Example usage for java.sql Types TIMESTAMP

List of usage examples for java.sql Types TIMESTAMP

Introduction

In this page you can find the example usage for java.sql Types TIMESTAMP.

Prototype

int TIMESTAMP

To view the source code for java.sql Types TIMESTAMP.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type TIMESTAMP.

Usage

From source file:org.jumpmind.symmetric.db.AbstractTriggerTemplate.java

protected ColumnString fillOutColumnTemplate(String origTableAlias, String tableAlias, String columnPrefix,
        Column column, DataEventType dml, boolean isOld, Channel channel, Trigger trigger) {
    boolean isLob = symmetricDialect.getPlatform().isLob(column.getMappedTypeCode());
    String templateToUse = null;//ww  w . ja  v a2 s . c o m
    if (column.getJdbcTypeName() != null && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOMETRY))
            && StringUtils.isNotBlank(geometryColumnTemplate)) {
        templateToUse = geometryColumnTemplate;
    } else if (column.getJdbcTypeName() != null
            && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.GEOGRAPHY))
            && StringUtils.isNotBlank(geographyColumnTemplate)) {
        templateToUse = geographyColumnTemplate;
    } else {
        switch (column.getMappedTypeCode()) {
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
        case Types.NUMERIC:
        case Types.DECIMAL:
            templateToUse = numberColumnTemplate;
            break;
        case Types.CHAR:
        case Types.NCHAR:
        case Types.VARCHAR:
        case ColumnTypes.NVARCHAR:
            templateToUse = stringColumnTemplate;
            break;
        case ColumnTypes.SQLXML:
            templateToUse = xmlColumnTemplate;
            break;
        case Types.ARRAY:
            templateToUse = arrayColumnTemplate;
            break;
        case Types.LONGVARCHAR:
        case ColumnTypes.LONGNVARCHAR:
            if (!isLob) {
                templateToUse = stringColumnTemplate;
                break;
            }
        case Types.CLOB:
            if (isOld && symmetricDialect.needsToSelectLobData()) {
                templateToUse = emptyColumnTemplate;
            } else {
                templateToUse = clobColumnTemplate;
            }
            break;
        case Types.BINARY:
        case Types.VARBINARY:
            if (isNotBlank(binaryColumnTemplate)) {
                templateToUse = binaryColumnTemplate;
                break;
            }
        case Types.BLOB:
            if (requiresWrappedBlobTemplateForBlobType()) {
                templateToUse = wrappedBlobColumnTemplate;
                break;
            }
        case Types.LONGVARBINARY:
        case -10: // SQL-Server ntext binary type
            if (column.getJdbcTypeName() != null
                    && (column.getJdbcTypeName().toUpperCase().contains(TypeMap.IMAGE))
                    && StringUtils.isNotBlank(imageColumnTemplate)) {
                if (isOld) {
                    templateToUse = emptyColumnTemplate;
                } else {
                    templateToUse = imageColumnTemplate;
                }
            } else if (isOld && symmetricDialect.needsToSelectLobData()) {
                templateToUse = emptyColumnTemplate;
            } else {
                templateToUse = blobColumnTemplate;
            }
            break;
        case Types.DATE:
            if (noDateColumnTemplate()) {
                templateToUse = datetimeColumnTemplate;
                break;
            }
            templateToUse = dateColumnTemplate;
            break;
        case Types.TIME:
            if (noTimeColumnTemplate()) {
                templateToUse = datetimeColumnTemplate;
                break;
            }
            templateToUse = timeColumnTemplate;
            break;
        case Types.TIMESTAMP:
            templateToUse = datetimeColumnTemplate;
            break;
        case Types.BOOLEAN:
        case Types.BIT:
            templateToUse = booleanColumnTemplate;
            break;
        default:
            if (column.getJdbcTypeName() != null) {
                if (column.getJdbcTypeName().toUpperCase().equals(TypeMap.INTERVAL)) {
                    templateToUse = numberColumnTemplate;
                    break;
                } else if (column.getMappedType().equals(TypeMap.TIMESTAMPTZ)
                        && StringUtils.isNotBlank(this.dateTimeWithTimeZoneColumnTemplate)) {
                    templateToUse = this.dateTimeWithTimeZoneColumnTemplate;
                    break;
                } else if (column.getMappedType().equals(TypeMap.TIMESTAMPLTZ)
                        && StringUtils.isNotBlank(this.dateTimeWithLocalTimeZoneColumnTemplate)) {
                    templateToUse = this.dateTimeWithLocalTimeZoneColumnTemplate;
                    break;
                }

            }

            if (StringUtils.isBlank(templateToUse) && StringUtils.isNotBlank(this.otherColumnTemplate)) {
                templateToUse = this.otherColumnTemplate;
                break;
            }

            throw new NotImplementedException(column.getName() + " is of type " + column.getMappedType()
                    + " with JDBC type of " + column.getJdbcTypeName());
        }
    }

    if (dml == DataEventType.DELETE && isLob && requiresEmptyLobTemplateForDeletes()) {
        templateToUse = emptyColumnTemplate;
    } else if (isLob && trigger.isUseStreamLobs()) {
        templateToUse = emptyColumnTemplate;
    }

    if (templateToUse != null) {
        templateToUse = templateToUse.trim();
    } else {
        throw new NotImplementedException();
    }

    String formattedColumnText = FormatUtils.replace("columnName",
            String.format("%s%s", columnPrefix, column.getName()), templateToUse);

    formattedColumnText = FormatUtils.replace("columnSize", column.getSize(), formattedColumnText);

    formattedColumnText = FormatUtils.replace("masterCollation", symmetricDialect.getMasterCollation(),
            formattedColumnText);

    if (isLob) {
        formattedColumnText = symmetricDialect.massageForLob(formattedColumnText, channel);
    }

    formattedColumnText = FormatUtils.replace("origTableAlias", origTableAlias, formattedColumnText);
    formattedColumnText = FormatUtils.replace("tableAlias", tableAlias, formattedColumnText);
    formattedColumnText = FormatUtils.replace("prefixName", symmetricDialect.getTablePrefix(),
            formattedColumnText);

    return new ColumnString(formattedColumnText, isLob);

}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private static int getColumnType(Class<?> javaType, Method method, ColumnMetadata foreignReference) {
    final int dimensions = ReflectionUtils.getArrayDimensions(javaType);
    javaType = ReflectionUtils.mapType(ReflectionUtils.getComponentType(javaType));
    if (dimensions > 1) {
        throw new UnsupportedColumnTypeError("Arrays of dimension > 1 are not supported");
    }/*from w  w  w.j a  va  2s .co m*/
    if (Byte.class.equals(javaType) && dimensions == 0) {
        return Types.TINYINT;
    } else if (Short.class.equals(javaType)) {
        return Types.SMALLINT;
    } else if (Integer.class.equals(javaType)) {
        return Types.INTEGER;
    } else if (Long.class.equals(javaType)) {
        return Types.BIGINT;
    } else if (Float.class.equals(javaType)) {
        return Types.FLOAT;
    } else if (Double.class.equals(javaType)) {
        return Types.DOUBLE;
    } else if (BigDecimal.class.equals(javaType)) {
        return Types.DECIMAL;
    } else if (BigInteger.class.equals(javaType)) {
        return Types.NUMERIC;
    } else if (Character.class.equals(javaType)) {
        return Types.CHAR;
    } else if (String.class.equals(javaType) || Class.class.equals(javaType)) {
        if (method != null && method.isAnnotationPresent(Column.class)
                && method.getAnnotation(Column.class).length() > 0) {
            return Types.VARCHAR;
        } else {
            return Types.LONGVARCHAR;
        }
    } else if (Date.class.isAssignableFrom(javaType)) {
        if (javaType.equals(java.sql.Date.class)) {
            return Types.DATE;
        } else if (javaType.equals(Time.class)) {
            return Types.TIME;
        } else if (javaType.equals(java.sql.Timestamp.class)) {
            return Types.TIMESTAMP;
        }
        final TemporalType temporalType = method != null && method.isAnnotationPresent(Temporal.class)
                ? method.getAnnotation(Temporal.class).value()
                : null;
        return (temporalType == null || temporalType.equals(TemporalType.TIMESTAMP)) ? Types.TIMESTAMP
                : (temporalType.equals(TemporalType.DATE) ? Types.DATE : Types.TIME);
    } else if (Byte.class.equals(javaType) && dimensions > 0) {
        return Types.VARBINARY;
    } else if (Enum.class.isAssignableFrom(javaType)) {
        return Types.VARCHAR;
    } else if (Boolean.class.equals(javaType)) {
        return Types.BOOLEAN;
    } else if (Collection.class.isAssignableFrom(javaType)
            && method.isAnnotationPresent(BasicCollection.class)) {
        return Types.LONGVARCHAR;
    }
    if (foreignReference != null) {
        return Integer.MIN_VALUE;
    }
    return Types.LONGVARCHAR;
}

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

private String getValueFromResultSet(int columnType, String column, ResultSet resultSet) throws SQLException {
    String paramValue;/* w  w  w. j  av  a 2  s  . c  om*/
    switch (columnType) {
    case Types.INTEGER:
        /* fall through */
    case Types.TINYINT:
        /* fall through */
    case Types.SMALLINT:
        paramValue = ConverterUtil.convertToString(resultSet.getInt(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.DOUBLE:
        paramValue = ConverterUtil.convertToString(resultSet.getDouble(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.VARCHAR:
        /* fall through */
    case Types.CHAR:
        /* fall through */
    case Types.CLOB:
        /* fall through */
    case Types.LONGVARCHAR:
        paramValue = resultSet.getString(column);
        break;
    case Types.BOOLEAN:
        /* fall through */
    case Types.BIT:
        paramValue = ConverterUtil.convertToString(resultSet.getBoolean(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.BLOB:
        Blob sqlBlob = resultSet.getBlob(column);
        if (sqlBlob != null) {
            paramValue = this.getBase64StringFromInputStream(sqlBlob.getBinaryStream());
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.BINARY:
        /* fall through */
    case Types.LONGVARBINARY:
        /* fall through */
    case Types.VARBINARY:
        InputStream binInStream = resultSet.getBinaryStream(column);
        if (binInStream != null) {
            paramValue = this.getBase64StringFromInputStream(binInStream);
        } else {
            paramValue = null;
        }
        break;
    case Types.DATE:
        Date sqlDate = resultSet.getDate(column);
        if (sqlDate != null) {
            paramValue = ConverterUtil.convertToString(sqlDate);
        } else {
            paramValue = null;
        }
        break;
    case Types.DECIMAL:
        /* fall through */
    case Types.NUMERIC:
        BigDecimal bigDecimal = resultSet.getBigDecimal(column);
        if (bigDecimal != null) {
            paramValue = ConverterUtil.convertToString(bigDecimal);
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.FLOAT:
        paramValue = ConverterUtil.convertToString(resultSet.getFloat(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.TIME:
        Time sqlTime = resultSet.getTime(column);
        if (sqlTime != null) {
            paramValue = this.convertToTimeString(sqlTime);
        } else {
            paramValue = null;
        }
        break;
    case Types.LONGNVARCHAR:
        /* fall through */
    case Types.NCHAR:
        /* fall through */
    case Types.NCLOB:
        /* fall through */
    case Types.NVARCHAR:
        paramValue = resultSet.getNString(column);
        break;
    case Types.BIGINT:
        paramValue = ConverterUtil.convertToString(resultSet.getLong(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.TIMESTAMP:
        Timestamp sqlTimestamp = resultSet.getTimestamp(column);
        if (sqlTimestamp != null) {
            paramValue = this.convertToTimestampString(sqlTimestamp);
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    /* handle all other types as strings */
    default:
        paramValue = resultSet.getString(column);
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    }
    return paramValue;
}

From source file:org.jumpmind.symmetric.io.data.writer.DefaultDatabaseWriter.java

@Override
protected Table lookupTableAtTarget(Table sourceTable) {
    String tableNameKey = sourceTable.getTableKey();
    Table table = targetTables.get(tableNameKey);
    if (table == null) {
        table = platform.getTableFromCache(sourceTable.getCatalog(), sourceTable.getSchema(),
                sourceTable.getName(), false);
        if (table != null) {
            table = table.copyAndFilterColumns(sourceTable.getColumnNames(),
                    sourceTable.getPrimaryKeyColumnNames(), this.writerSettings.isUsePrimaryKeysFromSource());

            Column[] columns = table.getColumns();
            for (Column column : columns) {
                if (column != null) {
                    int typeCode = column.getMappedTypeCode();
                    if (this.writerSettings.isTreatDateTimeFieldsAsVarchar() && (typeCode == Types.DATE
                            || typeCode == Types.TIME || typeCode == Types.TIMESTAMP)) {
                        column.setMappedTypeCode(Types.VARCHAR);
                    }/*  ww w.j  a v a 2s . c om*/
                }
            }

            targetTables.put(tableNameKey, table);
        }
    }
    return table;
}

From source file:nl.ordina.bag.etl.dao.AbstractBAGDAO.java

@Override
public void insertNummeraanduidingen(final List<Nummeraanduiding> nummeraanduidingen) throws DAOException {
    try {/*from w ww . j  a  v  a2  s. c o m*/
        jdbcTemplate.batchUpdate("insert into bag_nummeraanduiding (" + "bag_nummeraanduiding_id,"
                + "aanduiding_record_inactief," + "aanduiding_record_correctie," + "huisnummer," + "officieel,"
                + "huisletter," + "huisnummertoevoeging," + "postcode," + "begindatum_tijdvak_geldigheid,"
                + "einddatum_tijdvak_geldigheid," + "in_onderzoek," + "type_adresseerbaar_object,"
                + "bron_documentdatum," + "bron_documentnummer," + "nummeraanduiding_status,"
                + "bag_woonplaats_id," + "bag_openbare_ruimte_id"
                + ") values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int i) throws SQLException {
                        ps.setLong(1, nummeraanduidingen.get(i).getIdentificatie());
                        ps.setInt(2, nummeraanduidingen.get(i).getAanduidingRecordInactief().ordinal());
                        ps.setLong(3, nummeraanduidingen.get(i).getAanduidingRecordCorrectie());
                        ps.setInt(4, nummeraanduidingen.get(i).getHuisnummer());
                        ps.setInt(5, nummeraanduidingen.get(i).getOfficieel().ordinal());
                        if (nummeraanduidingen.get(i).getHuisletter() == null)
                            ps.setNull(6, Types.VARCHAR);
                        else
                            ps.setString(6, nummeraanduidingen.get(i).getHuisletter());
                        if (nummeraanduidingen.get(i).getHuisnummertoevoeging() == null)
                            ps.setNull(7, Types.VARCHAR);
                        else
                            ps.setString(7, nummeraanduidingen.get(i).getHuisnummertoevoeging());
                        if (nummeraanduidingen.get(i).getPostcode() == null)
                            ps.setNull(8, Types.VARCHAR);
                        else
                            ps.setString(8, nummeraanduidingen.get(i).getPostcode());
                        ps.setTimestamp(9, new Timestamp(
                                nummeraanduidingen.get(i).getBegindatumTijdvakGeldigheid().getTime()));
                        if (nummeraanduidingen.get(i).getEinddatumTijdvakGeldigheid() == null)
                            ps.setNull(10, Types.TIMESTAMP);
                        else
                            ps.setTimestamp(10, new Timestamp(
                                    nummeraanduidingen.get(i).getEinddatumTijdvakGeldigheid().getTime()));
                        ps.setInt(11, nummeraanduidingen.get(i).getInOnderzoek().ordinal());
                        ps.setInt(12, nummeraanduidingen.get(i).getTypeAdresseerbaarObject().ordinal());
                        ps.setDate(13, new Date(nummeraanduidingen.get(i).getDocumentdatum().getTime()));
                        ps.setString(14, nummeraanduidingen.get(i).getDocumentnummer());
                        ps.setInt(15, nummeraanduidingen.get(i).getNummeraanduidingStatus().ordinal());
                        if (nummeraanduidingen.get(i).getGerelateerdeWoonplaats() == null)
                            ps.setNull(16, Types.INTEGER);
                        else
                            ps.setLong(16, nummeraanduidingen.get(i).getGerelateerdeWoonplaats());
                        ps.setLong(17, nummeraanduidingen.get(i).getGerelateerdeOpenbareRuimte());
                    }

                    @Override
                    public int getBatchSize() {
                        return nummeraanduidingen.size();
                    }
                });
    } catch (DataAccessException e) {
        throw new DAOException("Error inserting nummeraanduidingen", e);
    }
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results/*from  www.j av a 2 s  .c  om*/
 *            A ResultSet to process
 * @param table
 *            The name of the table
 * @param pColumnNames
 *            The name of the columns in this resultset
 * @return A TableRow object with the data from the ResultSet
 * @exception SQLException
 *                If a database error occurs
 */
@Mock
static TableRow process(ResultSet results, String table, List<String> pColumnNames) throws SQLException {
    String dbName = ConfigurationManager.getProperty("db.name");
    ResultSetMetaData meta = results.getMetaData();
    int columns = meta.getColumnCount() + 1;

    // If we haven't been passed the column names try to generate them from the metadata / table
    List<String> columnNames = pColumnNames != null ? pColumnNames
            : ((table == null) ? getColumnNames(meta) : getColumnNames(table));

    TableRow row = new TableRow(canonicalize(table), columnNames);

    // Process the columns in order
    // (This ensures maximum backwards compatibility with
    // old JDBC drivers)
    for (int i = 1; i < columns; i++) {
        String name = meta.getColumnName(i);
        int jdbctype = meta.getColumnType(i);

        if (jdbctype == Types.BIT || jdbctype == Types.BOOLEAN) {
            row.setColumn(name, results.getBoolean(i));
        } else if ((jdbctype == Types.INTEGER) || (jdbctype == Types.NUMERIC) || (jdbctype == Types.DECIMAL)) {
            // If we are using oracle
            if ("oracle".equals(dbName)) {
                // Test the value from the record set. If it can be represented using an int, do so.
                // Otherwise, store it as long
                long longValue = results.getLong(i);
                if (longValue <= (long) Integer.MAX_VALUE)
                    row.setColumn(name, (int) longValue);
                else
                    row.setColumn(name, longValue);
            } else
                row.setColumn(name, results.getInt(i));
        } else if (jdbctype == Types.BIGINT) {
            row.setColumn(name, results.getLong(i));
        } else if (jdbctype == Types.DOUBLE) {
            row.setColumn(name, results.getDouble(i));
        } else if (jdbctype == Types.CLOB && "oracle".equals(dbName)) {
            // Support CLOBs in place of TEXT columns in Oracle
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.VARCHAR) {
            /*try
            {
            byte[] bytes = results.getBytes(i);
                    
            if (bytes != null)
            {
                String mystring = new String(results.getBytes(i),
                        "UTF-8");
                row.setColumn(name, mystring);
            }
            else
            {
                row.setColumn(name, results.getString(i));
            }
                    
            }
            catch (UnsupportedEncodingException e)
            {
            // do nothing, UTF-8 is built in!
            }*/
            //removing issue with H2 and getBytes
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.DATE) {
            row.setColumn(name, results.getDate(i));
        } else if (jdbctype == Types.TIME) {
            row.setColumn(name, results.getTime(i));
        } else if (jdbctype == Types.TIMESTAMP) {
            row.setColumn(name, results.getTimestamp(i));
        } else {
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype + " (" + name + ")");
        }

        if (results.wasNull()) {
            row.setColumnNull(name);
        }
    }

    // Now that we've prepped the TableRow, reset the flags so that we can detect which columns have changed
    row.resetChanged();
    return row;
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Generates the string representation of the given value.
 * /*from  w w  w .jav a 2s  .c  o  m*/
 * @param column The column
 * @param value  The value
 * @return The string representation
 */
protected String getValueAsString(Column column, Object value) {
    if (value == null) {
        return "NULL";
    }

    StringBuffer result = new StringBuffer();

    // TODO: Handle binary types (BINARY, VARBINARY, LONGVARBINARY, BLOB)
    switch (column.getTypeCode()) {
    case Types.DATE:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueDateFormat() != null)) {
            // TODO: Can the format method handle java.sql.Date properly ?
            result.append(getValueDateFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.TIME:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueTimeFormat() != null)) {
            // TODO: Can the format method handle java.sql.Date properly ?
            result.append(getValueTimeFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.TIMESTAMP:
        result.append(getPlatformInfo().getValueQuoteToken());
        // TODO: SimpleDateFormat does not support nano seconds so we would
        //       need a custom date formatter for timestamps
        result.append(value.toString());
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.REAL:
    case Types.NUMERIC:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueNumberFormat() != null)) {
            result.append(getValueNumberFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    default:
        result.append(getPlatformInfo().getValueQuoteToken());
        result.append(escapeStringValue(value.toString()));
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    }
    return result.toString();
}

From source file:org.jumpmind.vaadin.ui.sqlexplorer.TabularResultLayout.java

private void initCommit() {
    grid.getEditorFieldGroup().addCommitHandler(new CommitHandler() {

        private static final long serialVersionUID = 1L;

        Map<Object, Object> unchangedValues;
        Object[] params;/*from w w w. j  a  v a2s. c  o  m*/
        int[] types;

        @Override
        public void preCommit(CommitEvent commitEvent) throws CommitException {
            Item row = commitEvent.getFieldBinder().getItemDataSource();
            unchangedValues = new HashMap<Object, Object>();
            params = new Object[resultTable.getPrimaryKeyColumnCount() + 1];
            types = new int[params.length];
            int paramCount = 1;
            for (Object id : row.getItemPropertyIds()) {
                unchangedValues.put(id, row.getItemProperty(id).getValue());
                if (resultTable.getPrimaryKeyColumnIndex(id.toString()) >= 0) {
                    params[paramCount] = commitEvent.getFieldBinder().getItemDataSource().getItemProperty(id)
                            .getValue();
                    types[paramCount] = resultTable.getColumnWithName(id.toString()).getMappedTypeCode();
                    paramCount++;
                }
            }
        }

        @Override
        public void postCommit(CommitEvent commitEvent) throws CommitException {
            Item row = commitEvent.getFieldBinder().getItemDataSource();
            for (Object id : row.getItemPropertyIds()) {
                if (grid.getColumn(id).isEditable() && !db.getPlatform()
                        .isLob(resultTable.getColumnWithName(id.toString()).getMappedTypeCode())) {
                    String sql = buildUpdate(resultTable, id.toString(),
                            resultTable.getPrimaryKeyColumnNames());
                    params[0] = row.getItemProperty(id).getValue();
                    if ((params[0] == null && unchangedValues.get(id) == null)
                            || (params[0] != null && params[0].equals(unchangedValues.get(id)))) {
                        continue;
                    }
                    types[0] = resultTable.getColumnWithName(id.toString()).getMappedTypeCode();
                    for (int i = 0; i < types.length; i++) {
                        if (types[i] == Types.DATE && db.getPlatform().getDdlBuilder().getDatabaseInfo()
                                .isDateOverridesToTimestamp()) {
                            types[i] = Types.TIMESTAMP;
                        }
                    }
                    try {
                        long startTime = System.nanoTime();
                        db.getPlatform().getSqlTemplate().update(sql, params, types);
                        new LogSqlBuilder().logSql(log, sql, params, types, System.nanoTime() - startTime);
                    } catch (SqlException e) {
                        NotifyDialog.show("Error",
                                "<b>The table could not be updated.</b><br>"
                                        + "Cause: the sql update statement failed to execute.<br><br>"
                                        + "To view the <b>Stack Trace</b>, click <b>\"Details\"</b>.",
                                e, Type.ERROR_MESSAGE);
                    }
                }
            }
            listener.reExecute(sql);
        }
    });
}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

public void exportChildDB(String uuidForChild, OutputStream os) throws DAOException {
    PrintStream out = new PrintStream(os);
    Set<String> tablesToSkip = new HashSet<String>();
    {//from   w  ww  .  java 2  s  .  co m
        tablesToSkip.add("hl7_in_archive");
        tablesToSkip.add("hl7_in_queue");
        tablesToSkip.add("hl7_in_error");
        tablesToSkip.add("formentry_archive");
        tablesToSkip.add("formentry_queue");
        tablesToSkip.add("formentry_error");
        tablesToSkip.add("sync_class");
        tablesToSkip.add("sync_import");
        tablesToSkip.add("sync_record");
        tablesToSkip.add("sync_server");
        tablesToSkip.add("sync_server_class");
        tablesToSkip.add("sync_server_record");
        // TODO: figure out which other tables to skip
        // tablesToSkip.add("obs");
        // tablesToSkip.add("concept");
        // tablesToSkip.add("patient");
    }
    List<String> tablesToDump = new ArrayList<String>();
    Session session = sessionFactory.getCurrentSession();
    String schema = (String) session.createSQLQuery("SELECT schema()").uniqueResult();
    log.warn("schema: " + schema);
    // Get all tables that we'll need to dump
    {
        Query query = session.createSQLQuery(
                "SELECT tabs.table_name FROM INFORMATION_SCHEMA.TABLES tabs WHERE tabs.table_schema = '"
                        + schema + "'");
        for (Object tn : query.list()) {
            String tableName = (String) tn;
            if (!tablesToSkip.contains(tableName.toLowerCase()))
                tablesToDump.add(tableName);
        }
    }
    log.warn("tables to dump: " + tablesToDump);

    String thisServerGuid = getGlobalProperty(SyncConstants.PROPERTY_SERVER_UUID);

    // Write the DDL Header as mysqldump does
    {
        out.println("-- ------------------------------------------------------");
        out.println("-- Database dump to create an openmrs child server");
        out.println("-- Schema: " + schema);
        out.println("-- Parent GUID: " + thisServerGuid);
        out.println("-- Parent version: " + OpenmrsConstants.OPENMRS_VERSION);
        out.println("-- ------------------------------------------------------");
        out.println("");
        out.println("/*!40101 SET CHARACTER_SET_CLIENT=utf8 */;");
        out.println("/*!40101 SET NAMES utf8 */;");
        out.println("/*!40103 SET TIME_ZONE='+00:00' */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;");
        out.println("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;");
        out.println("/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;");
        out.println("/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;");
        out.println("/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;");
        out.println("/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;");
        out.println("/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;");
        out.println("");
    }
    try {
        // JDBC way of doing this
        // Connection conn =
        // DriverManager.getConnection("jdbc:mysql://localhost/" + schema,
        // "test", "test");
        Connection conn = sessionFactory.getCurrentSession().connection();
        try {
            Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            // Get the create database statement
            ResultSet rs = st.executeQuery("SHOW CREATE DATABASE " + schema);
            for (String tableName : tablesToDump) {
                out.println();
                out.println("--");
                out.println("-- Table structure for table `" + tableName + "`");
                out.println("--");
                out.println("DROP TABLE IF EXISTS `" + tableName + "`;");
                out.println("SET @saved_cs_client     = @@character_set_client;");
                out.println("SET character_set_client = utf8;");
                rs = st.executeQuery("SHOW CREATE TABLE " + tableName);
                while (rs.next()) {
                    out.println(rs.getString("Create Table") + ";");
                }
                out.println("SET character_set_client = @saved_cs_client;");
                out.println();

                {
                    out.println("-- Dumping data for table `" + tableName + "`");
                    out.println("LOCK TABLES `" + tableName + "` WRITE;");
                    out.println("/*!40000 ALTER TABLE `" + tableName + "` DISABLE KEYS */;");
                    boolean first = true;

                    rs = st.executeQuery("select * from " + tableName);
                    ResultSetMetaData md = rs.getMetaData();
                    int numColumns = md.getColumnCount();
                    int rowNum = 0;
                    boolean insert = false;

                    while (rs.next()) {
                        if (rowNum == 0) {
                            insert = true;
                            out.print("INSERT INTO `" + tableName + "` VALUES ");
                        }
                        ++rowNum;
                        if (first) {
                            first = false;
                        } else {
                            out.print(", ");
                        }
                        if (rowNum % 20 == 0) {
                            out.println();
                        }
                        out.print("(");
                        for (int i = 1; i <= numColumns; ++i) {
                            if (i != 1) {
                                out.print(",");
                            }
                            if (rs.getObject(i) == null) {
                                out.print("NULL");
                            } else {
                                switch (md.getColumnType(i)) {
                                case Types.VARCHAR:
                                case Types.CHAR:
                                case Types.LONGVARCHAR:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.BIGINT:
                                case Types.DECIMAL:
                                case Types.NUMERIC:
                                    out.print(rs.getBigDecimal(i));
                                    break;
                                case Types.BIT:
                                    out.print(rs.getBoolean(i));
                                    break;
                                case Types.INTEGER:
                                case Types.SMALLINT:
                                case Types.TINYINT:
                                    out.print(rs.getInt(i));
                                    break;
                                case Types.REAL:
                                case Types.FLOAT:
                                case Types.DOUBLE:
                                    out.print(rs.getDouble(i));
                                    break;
                                case Types.BLOB:
                                case Types.VARBINARY:
                                case Types.LONGVARBINARY:
                                    Blob blob = rs.getBlob(i);
                                    out.print("'");
                                    InputStream in = blob.getBinaryStream();
                                    while (true) {
                                        int b = in.read();
                                        if (b < 0) {
                                            break;
                                        }
                                        char c = (char) b;
                                        if (c == '\'') {
                                            out.print("\'");
                                        } else {
                                            out.print(c);
                                        }
                                    }
                                    out.print("'");
                                    break;
                                case Types.CLOB:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.DATE:
                                    out.print("'" + rs.getDate(i) + "'");
                                    break;
                                case Types.TIMESTAMP:
                                    out.print("'" + rs.getTimestamp(i) + "'");
                                    break;
                                default:
                                    throw new RuntimeException("TODO: handle type code " + md.getColumnType(i)
                                            + " (name " + md.getColumnTypeName(i) + ")");
                                }
                            }
                        }
                        out.print(")");
                    }
                    if (insert) {
                        out.println(";");
                        insert = false;
                    }

                    out.println("/*!40000 ALTER TABLE `" + tableName + "` ENABLE KEYS */;");
                    out.println("UNLOCK TABLES;");
                    out.println();
                }
            }
        } finally {
            conn.close();
        }

        // Now we mark this as a child
        out.println("-- Now mark this as a child database");
        if (uuidForChild == null)
            uuidForChild = SyncUtil.generateUuid();
        out.println("update global_property set property_value = '" + uuidForChild + "' where property = '"
                + SyncConstants.PROPERTY_SERVER_UUID + "';");

        // Write the footer of the DDL script
        {
            out.println("/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;");
            out.println("/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;");
            out.println("/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;");
            out.println("/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;");
            out.println("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;");
            out.println("/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;");
            out.println("/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;");
            out.println("/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;");
        }
        out.flush();
        out.close();
    } catch (IOException ex) {
        log.error("IOException", ex);

    } catch (SQLException ex) {
        log.error("SQLException", ex);
    }
}

From source file:org.seasar.dbflute.logic.replaceschema.loaddata.impl.DfAbsractDataWriter.java

/**
 * Get the bind type to find a value type.
 * @param tableName The name of table corresponding to column. (NotNull)
 * @param columnMeta The meta info of column. (NotNull)
 * @return The type of column. (NullAllowed: However Basically NotNull)
 *///  w  ww.  ja v  a  2 s.  co  m
protected Class<?> getBindType(String tableName, DfColumnMeta columnMeta) {
    Map<String, Class<?>> cacheMap = _bindTypeCacheMap.get(tableName);
    if (cacheMap == null) {
        cacheMap = StringKeyMap.createAsFlexibleOrdered();
        _bindTypeCacheMap.put(tableName, cacheMap);
    }
    final String columnName = columnMeta.getColumnName();
    Class<?> bindType = cacheMap.get(columnName);
    if (bindType != null) { // cache hit
        return bindType;
    }

    // use mapped JDBC defined value if found (basically found)
    // because it has already been resolved about JDBC specification per DBMS
    final String jdbcType = _columnHandler.getColumnJdbcType(columnMeta);
    Integer jdbcDefValue = TypeMap.getJdbcDefValueByJdbcType(jdbcType);
    if (jdbcDefValue == null) { // basically no way
        jdbcDefValue = columnMeta.getJdbcDefValue(); // as plain
    }

    // ReplaceSchema uses an own original mapping way
    // (not uses Generate mapping)
    // it's simple mapping (for string processor)
    if (jdbcDefValue == Types.CHAR || jdbcDefValue == Types.VARCHAR || jdbcDefValue == Types.LONGVARCHAR
            || jdbcDefValue == Types.CLOB) {
        bindType = String.class;
    } else if (jdbcDefValue == Types.TINYINT || jdbcDefValue == Types.SMALLINT
            || jdbcDefValue == Types.INTEGER) {
        bindType = Integer.class;
    } else if (jdbcDefValue == Types.BIGINT) {
        bindType = Long.class;
    } else if (jdbcDefValue == Types.DECIMAL || jdbcDefValue == Types.NUMERIC) {
        bindType = BigDecimal.class;
    } else if (jdbcDefValue == Types.TIMESTAMP) {
        bindType = Timestamp.class;
    } else if (jdbcDefValue == Types.TIME) {
        bindType = Time.class;
    } else if (jdbcDefValue == Types.DATE) {
        // it depends on value type settings
        // that which is bound java.sql.Date or java.sql.Timestamp
        bindType = java.util.Date.class;
    } else if (jdbcDefValue == Types.BIT || jdbcDefValue == Types.BOOLEAN) {
        bindType = Boolean.class;
    } else if (jdbcDefValue == Types.BINARY || jdbcDefValue == Types.VARBINARY
            || jdbcDefValue == Types.LONGVARBINARY || jdbcDefValue == Types.BLOB) {
        bindType = byte[].class;
    } else if (jdbcDefValue == Types.OTHER && TypeMap.UUID.equalsIgnoreCase(jdbcType)) {
        // [UUID Headache]: The reason why UUID type has not been supported yet on JDBC.
        bindType = UUID.class;
    } else {
        bindType = Object.class;
    }
    cacheMap.put(columnName, bindType);
    return bindType;
}