Search in sources :

Example 6 with Type

use of com.github.drinkjava2.jdialects.Type in project jDialects by drinkjava2.

the class SortedUUIDGenerator method getNextID.

@Override
public Object getNextID(NormalJdbcTool jdbc, Dialect dialect, Type dataType) {
    String s = "" + AutoIdGenerator.INSTANCE.getNextID(jdbc, dialect, dataType);
    if (s.length() > (sortedLength - 1))
        throw new DialectException("SortedLength should set bigger than auto generated ID length");
    StringBuilder sb = new StringBuilder("1");
    for (int i = 1; i < sortedLength - s.length(); i++) sb.append("0");
    sb.append(s);
    sb.append(UUIDAnyGenerator.getAnyLengthRadix36UUID(uuidLength));
    return sb.toString();
}
Also used : DialectException(com.github.drinkjava2.jdialects.DialectException)

Example 7 with Type

use of com.github.drinkjava2.jdialects.Type in project jDialects by drinkjava2.

the class DDLUtils method transferTableToObjectList.

/**
	 * Transfer table to a mixed DDL String or TableGenerator Object list
	 */
private static void transferTableToObjectList(Dialect dialect, Table t, List<Object> objectResultList) {
    DDLFeatures features = dialect.ddlFeatures;
    StringBuilder buf = new StringBuilder();
    boolean hasPkey = false;
    String pkeys = "";
    String tableName = t.getTableName();
    Map<String, Column> columns = t.getColumns();
    // Reserved words check
    dialect.checkNotEmptyReservedWords(tableName, "Table name can not be empty");
    for (Column col : columns.values()) {
        dialect.checkNotEmptyReservedWords(col.getColumnName(), "Column name can not be empty");
        dialect.checkReservedWords(col.getPkeyName());
        dialect.checkReservedWords(col.getUniqueConstraintName());
    }
    for (Column col : columns.values()) {
        // autoGenerator, only support sequence or table for "Auto" type
        if (col.getAutoGenerator()) {
            if (features.supportsSequences || features.supportsPooledSequences) {
                objectResultList.add(new Sequence(GlobalIdGenerator.JDIALECTS_IDGEN_TABLE, GlobalIdGenerator.JDIALECTS_IDGEN_TABLE, 1, 1));
            } else {
                // GlobalIdGenerator
                objectResultList.add(new GlobalIdGenerator());
            }
        }
        // foreign keys
        if (!StrUtils.isEmpty(col.getFkeyReferenceTable()))
            objectResultList.add(new FKeyConstraint(tableName, col.getColumnName(), col.getFkeyReferenceTable(), col.getFkeyReferenceColumns()));
    }
    // sequence
    for (Sequence seq : t.getSequences().values()) objectResultList.add(seq);
    // tableGenerator
    for (TableGenerator tg : t.getTableGenerators().values()) objectResultList.add(tg);
    // check and cache prime keys
    for (Column col : columns.values()) {
        if (col.getPkey()) {
            hasPkey = true;
            if (StrUtils.isEmpty(pkeys))
                pkeys = col.getColumnName();
            else
                pkeys += "," + col.getColumnName();
        }
    }
    // create table
    buf.append(hasPkey ? dialect.ddlFeatures.createTableString : dialect.ddlFeatures.createMultisetTableString).append(" ").append(tableName).append(" (");
    for (Column c : columns.values()) {
        if (c.getColumnType() == null)
            DialectException.throwEX("Type not set on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
        // column definition
        buf.append(c.getColumnName()).append(" ");
        // Identity or autoGenerator+supportIdentity
        if (c.getIdentity() && !features.supportsIdentityColumns)
            DialectException.throwEX("Unsupported identity setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
        if (c.getIdentity()) {
            if (features.hasDataTypeInIdentityColumn)
                buf.append(dialect.translateToDDLType(c.getColumnType(), c.getLengths()));
            buf.append(' ');
            if (Type.BIGINT.equals(c.getColumnType()))
                buf.append(features.identityColumnStringBigINT);
            else
                buf.append(features.identityColumnString);
        } else {
            buf.append(dialect.translateToDDLType(c.getColumnType(), c.getLengths()));
            // Default
            String defaultValue = c.getDefaultValue();
            if (defaultValue != null) {
                buf.append(" default ").append(defaultValue);
            }
            // Not null
            if (c.getNotNull())
                buf.append(" not null");
            else
                buf.append(features.nullColumnString);
        }
        // Check
        if (!StrUtils.isEmpty(c.getCheck())) {
            if (features.supportsColumnCheck)
                buf.append(" check (").append(c.getCheck()).append(")");
            else
                logger.warn("Ignore unsupported check setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\" with value: " + c.getCheck());
        }
        // Comments
        if (c.getComment() != null) {
            if (StrUtils.isEmpty(features.columnComment) && !features.supportsCommentOn)
                logger.warn("Ignore unsupported comment setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\" with value: " + c.getComment());
            else
                buf.append(StrUtils.replace(features.columnComment, "_COMMENT", c.getComment()));
        }
        buf.append(",");
    }
    // PKEY
    if (!StrUtils.isEmpty(pkeys)) {
        buf.append(" primary key (").append(pkeys).append("),");
    }
    // Table Check
    if (!StrUtils.isEmpty(t.getCheck())) {
        if (features.supportsTableCheck)
            buf.append(" check (").append(t.getCheck()).append("),");
        else
            logger.warn("Ignore unsupported table check setting for dialect \"" + dialect + "\" on table \"" + tableName + "\" with value: " + t.getCheck());
    }
    buf.setLength(buf.length() - 1);
    buf.append(")");
    // type or engine for MariaDB & MySql
    buf.append(dialect.engine());
    objectResultList.add(buf.toString());
    // unique constraint
    for (Column column : columns.values()) addUniqueConstraintDDL(objectResultList, dialect, tableName, column);
    // table comment on
    if (t.getComment() != null) {
        if (features.supportsCommentOn)
            objectResultList.add("comment on table " + t.getTableName() + " is '" + t.getComment() + "'");
        else
            logger.warn("Ignore unsupported table comment setting for dialect \"" + dialect + "\" on table \"" + tableName + "\" with value: " + t.getComment());
    }
    // column comment on
    for (Column c : columns.values()) {
        if (features.supportsCommentOn && c.getComment() != null && StrUtils.isEmpty(features.columnComment))
            objectResultList.add("comment on column " + tableName + '.' + c.getColumnName() + " is '" + c.getComment() + "'");
    }
}
Also used : Column(com.github.drinkjava2.jdialects.model.Column) FKeyConstraint(com.github.drinkjava2.jdialects.model.FKeyConstraint) Sequence(com.github.drinkjava2.jdialects.model.Sequence) TableGenerator(com.github.drinkjava2.jdialects.model.TableGenerator) GlobalIdGenerator(com.github.drinkjava2.jdialects.model.GlobalIdGenerator)

Example 8 with Type

use of com.github.drinkjava2.jdialects.Type in project jDialects by drinkjava2.

the class BasicJavaConverter method convert.

@Override
public Object convert(Object value, Class<?> targetType) {
    if (value == null)
        return null;
    if (targetType == String.class)
        return value.toString();
    Class<?> vType = value.getClass();
    if (targetType.isAssignableFrom(vType))
        return value;
    if (vType == BigDecimal.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((BigDecimal) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((BigDecimal) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((BigDecimal) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((BigDecimal) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((BigDecimal) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((BigDecimal) value).shortValue();
        if (targetType == Boolean.class || targetType == boolean.class)
            return ((BigDecimal) value).byteValue() != 0;
    }
    if (vType == BigInteger.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((BigInteger) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((BigInteger) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((BigInteger) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((BigInteger) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((BigInteger) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((BigInteger) value).shortValue();
        if (targetType == Boolean.class || targetType == boolean.class)
            return ((BigInteger) value).byteValue() != 0;
    } else if (vType == Integer.class) {
        if (targetType == int.class)
            return ((Integer) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((Integer) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((Integer) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((Integer) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((Integer) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((Integer) value).shortValue();
    } else if (vType == Long.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((Long) value).intValue();
        if (targetType == long.class)
            return ((Long) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((Long) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((Long) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((Long) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((Long) value).shortValue();
        if (targetType == BigInteger.class)
            return BigInteger.valueOf((Long) value);
    } else if (vType == Double.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((Double) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((Double) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((Double) value).byteValue();
        if (targetType == double.class)
            return ((Double) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((Double) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((Double) value).shortValue();
    } else if (vType == Float.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((Float) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((Float) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((Float) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((Float) value).doubleValue();
        if (targetType == float.class)
            return ((Float) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((Float) value).shortValue();
    } else if (vType == Short.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((Short) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((Short) value).longValue();
        if (targetType == Byte.class || targetType == byte.class)
            return ((Short) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((Short) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((Short) value).floatValue();
        if (targetType == short.class)
            return ((Short) value).shortValue();
    } else if (vType == Byte.class) {
        if (targetType == Integer.class || targetType == int.class)
            return ((Byte) value).intValue();
        if (targetType == Long.class || targetType == long.class)
            return ((Byte) value).longValue();
        if (targetType == byte.class)
            return ((Byte) value).byteValue();
        if (targetType == Double.class || targetType == double.class)
            return ((Byte) value).doubleValue();
        if (targetType == Float.class || targetType == float.class)
            return ((Byte) value).floatValue();
        if (targetType == Short.class || targetType == short.class)
            return ((Byte) value).shortValue();
    } else if (vType == java.sql.Date.class) {
        // no need convert java.util.Date
        if (targetType == Timestamp.class)
            return new Timestamp(((java.sql.Date) value).getTime());
        if (targetType == java.sql.Time.class)
            return new java.sql.Time(((java.sql.Date) value).getTime());
        if (targetType == Calendar.class) {
            Calendar c = Calendar.getInstance();
            c.setTime((java.sql.Date) value);
            return c;
        }
    } else if (vType == java.sql.Time.class) {
        if (targetType == Timestamp.class)
            return new Timestamp(((java.sql.Time) value).getTime());
        if (targetType == java.sql.Date.class)
            return new java.sql.Date(((java.sql.Time) value).getTime());
    } else if (vType == Timestamp.class) {
        if (targetType == java.sql.Date.class)
            return new java.sql.Date(((Timestamp) value).getTime());
        if (targetType == java.sql.Time.class)
            return new java.sql.Time(((Timestamp) value).getTime());
        if (targetType == Calendar.class) {
            Calendar c = Calendar.getInstance();
            c.setTime(new java.util.Date(((Timestamp) value).getTime()));
            return c;
        }
    } else if (vType == java.util.Date.class) {
        if (targetType == Timestamp.class)
            return new Timestamp(((java.util.Date) value).getTime());
        if (targetType == java.sql.Date.class)
            return new java.util.Date(((java.util.Date) value).getTime());
        if (targetType == java.sql.Time.class)
            return new java.sql.Time(((java.util.Date) value).getTime());
        if (targetType == Calendar.class) {
            Calendar c = Calendar.getInstance();
            c.setTime((java.util.Date) value);
            return c;
        }
    } else if (vType == String.class) {
        if (targetType == char.class || targetType == Character.class) {
            return ((String) value).length() > 0 ? ((String) value).charAt(0) : '\u0000';
        }
    } else if (vType == Boolean.class) {
        return ((Boolean) value).booleanValue();
    }
    /*- JAVA8_BEGIN */
    if (vType == java.sql.Date.class) {
        if (targetType == java.time.LocalDate.class)
            return Java8DateUtils.sqlDate2localDate((java.sql.Date) value);
        if (targetType == java.time.LocalDateTime.class)
            return Java8DateUtils.sqlDate2localDateTime((java.sql.Date) value);
    } else if (vType == java.sql.Time.class) {
        if (targetType == java.time.LocalTime.class)
            return Java8DateUtils.sqlTime2LocalTime((java.sql.Time) value);
        if (targetType == java.time.OffsetTime.class)
            return Java8DateUtils.sqlTime2OffsetTime((java.sql.Time) value);
    } else if (vType == Timestamp.class) {
        if (targetType == java.time.LocalDate.class)
            return Java8DateUtils.sqlTimestamp2LocalDate((Timestamp) value);
        if (targetType == java.time.LocalTime.class)
            return Java8DateUtils.sqlTimestamp2LocalTime((Timestamp) value);
        if (targetType == java.time.Instant.class)
            return Java8DateUtils.sqlTimestamp2instant((Timestamp) value);
        if (targetType == java.time.LocalDateTime.class)
            return Java8DateUtils.sqlTimestamp2LocalDateTime((Timestamp) value);
        if (targetType == java.time.OffsetDateTime.class)
            return Java8DateUtils.sqlTimestamp2OffsetDateTime((Timestamp) value);
        if (targetType == java.time.ZonedDateTime.class)
            return Java8DateUtils.sqlTimestamp2ZonedDateTime((Timestamp) value);
        if (targetType == java.time.OffsetTime.class)
            return Java8DateUtils.sqlTimestamp2OffsetTime((Timestamp) value);
    } else if (vType == Date.class) {
        if (targetType == java.time.LocalDate.class)
            return Java8DateUtils.date2LocalDate((Date) value);
        if (targetType == java.time.LocalDateTime.class)
            return Java8DateUtils.date2LocalDateTime((Date) value);
    }
    /* JAVA8_END */
    String oracleTip = // NOSONAR
    "oracle.sql.TIMESTAMP".equals(vType.getName()) ? "\nBelow setting may solve this Oracle JDBC compliant issue:\n" + "System.getProperties().setProperty(\"oracle.jdbc.J2EE13Compliant\", \"true\");" : "";
    throw new DialectException("Can not convert jdbc type: '" + value.getClass() + "' with value '" + value + "' to jave type:" + targetType + oracleTip);
}
Also used : Date(java.util.Date) Timestamp(java.sql.Timestamp) Calendar(java.util.Calendar) BigDecimal(java.math.BigDecimal) Date(java.util.Date) BigInteger(java.math.BigInteger) DialectException(com.github.drinkjava2.jdialects.DialectException) BigInteger(java.math.BigInteger)

Example 9 with Type

use of com.github.drinkjava2.jdialects.Type in project jSqlBox by drinkjava2.

the class SqlBoxContextUtils method insert.

/**
 * Insert entityBean into database, and change ID fields to values generated by
 * IdGenerator (identity or sequence or UUID...)
 */
public static void insert(SqlBoxContext ctx, Object entityBean) {
    SqlBox box = SqlBoxUtils.findAndBindSqlBox(ctx, entityBean);
    checkBeanAndBoxExist(entityBean, box);
    TableModel tableModel = box.getTableModel();
    StringBuilder sb = new StringBuilder();
    sb.append("insert into ").append(tableModel.getTableName()).append(" (");
    List<Object> params = new ArrayList<Object>();
    String identityFieldName = null;
    Type identityType = null;
    Map<String, Method> readMethods = ClassCacheUtils.getClassReadMethods(entityBean.getClass());
    for (String fieldName : readMethods.keySet()) {
        ColumnModel col = findMatchColumnForJavaField(fieldName, box);
        if (!col.getTransientable() && col.getInsertable()) {
            if (col.getIdGenerationType() != null || !StrUtils.isEmpty(col.getIdGeneratorName())) {
                IdGenerator idGen = col.getIdGenerator();
                if (GenerationType.IDENTITY.equals(idGen.getGenerationType())) {
                    if (identityFieldName != null)
                        throw new SqlBoxException("More than 1 identity field found for model '" + tableModel.getTableName() + "'");
                    identityFieldName = fieldName;
                } else {
                    sb.append(col.getColumnName()).append(", ");
                    Object id = idGen.getNextID(ctx, ctx.getDialect(), col.getColumnType());
                    params.add(id);
                    ClassCacheUtils.writeValueToBeanField(entityBean, fieldName, id);
                }
            } else {
                Object value = ClassCacheUtils.readValueFromBeanField(entityBean, fieldName);
                sb.append(col.getColumnName()).append(", ");
                params.add(value);
            }
        }
    }
    if (!params.isEmpty())
        // delete the last ", " character
        sb.setLength(sb.length() - 2);
    sb.append(") values(").append(SqlBoxStrUtils.getQuestionsStr(params.size())).append(")");
    int result = ctx.nExecute(sb.toString(), params.toArray(new Object[params.size()]));
    if (ctx.isBatchEnabled())
        return;
    if (result != 1)
        throw new SqlBoxException(result + " row record be inserted.");
    if (identityFieldName != null) {
        // write identity id to Bean field
        Object identityId = IdentityIdGenerator.INSTANCE.getNextID(ctx, ctx.getDialect(), identityType);
        ClassCacheUtils.writeValueToBeanField(entityBean, identityFieldName, identityId);
    }
}
Also used : ArrayList(java.util.ArrayList) Method(java.lang.reflect.Method) IdentityIdGenerator(com.github.drinkjava2.jdialects.id.IdentityIdGenerator) IdGenerator(com.github.drinkjava2.jdialects.id.IdGenerator) Type(com.github.drinkjava2.jdialects.Type) GenerationType(com.github.drinkjava2.jdialects.annotation.jpa.GenerationType) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Aggregations

DialectException (com.github.drinkjava2.jdialects.DialectException)3 ColumnModel (com.github.drinkjava2.jdialects.model.ColumnModel)3 TableModel (com.github.drinkjava2.jdialects.model.TableModel)3 IdGenerator (com.github.drinkjava2.jdialects.id.IdGenerator)2 ArrayList (java.util.ArrayList)2 DbProRuntimeException (com.github.drinkjava2.jdbpro.DbProRuntimeException)1 Type (com.github.drinkjava2.jdialects.Type)1 GenerationType (com.github.drinkjava2.jdialects.annotation.jpa.GenerationType)1 AutoIdGenerator (com.github.drinkjava2.jdialects.id.AutoIdGenerator)1 IdentityIdGenerator (com.github.drinkjava2.jdialects.id.IdentityIdGenerator)1 SequenceIdGenerator (com.github.drinkjava2.jdialects.id.SequenceIdGenerator)1 TableIdGenerator (com.github.drinkjava2.jdialects.id.TableIdGenerator)1 Column (com.github.drinkjava2.jdialects.model.Column)1 FKeyConstraint (com.github.drinkjava2.jdialects.model.FKeyConstraint)1 FKeyModel (com.github.drinkjava2.jdialects.model.FKeyModel)1 GlobalIdGenerator (com.github.drinkjava2.jdialects.model.GlobalIdGenerator)1 IndexModel (com.github.drinkjava2.jdialects.model.IndexModel)1 Sequence (com.github.drinkjava2.jdialects.model.Sequence)1 TableGenerator (com.github.drinkjava2.jdialects.model.TableGenerator)1 UniqueModel (com.github.drinkjava2.jdialects.model.UniqueModel)1