Search in sources :

Example 1 with TableGenerator

use of com.github.drinkjava2.jdialects.model.TableGenerator in project jDialects by drinkjava2.

the class TableTest method tableGeneratorModel2.

private static Table tableGeneratorModel2() {
    // tableGenerator
    Table t = new Table("testTable2");
    t.addTableGenerator("tbgen3", "tb1", "pkcol3", "valcol", "pkval", 1, 10);
    t.addTableGenerator("tbgen4", "tb1", "pkcol3", "valcol", "pkval2", 1, 10);
    t.addTableGenerator("tbgen5", "tb1", "pkcol4", "valcol", "pkval3", 1, 10);
    t.addTableGenerator("tbgen6", "tb1", "pkcol4", "valcol", "pkval4", 1, 10);
    t.column("i1").INTEGER().pkey().tableGenerator("tbgen1");
    t.column("i2").INTEGER().pkey().tableGenerator("tbgen2");
    return t;
}
Also used : Table(com.github.drinkjava2.jdialects.model.Table)

Example 2 with TableGenerator

use of com.github.drinkjava2.jdialects.model.TableGenerator in project jDialects by drinkjava2.

the class DDLTest method sampleTest.

@Test
public void sampleTest() {
    // An example used to put on README.md
    TableModel t1 = new TableModel("customers");
    t1.column("name").STRING(20).pkey();
    t1.column("email").STRING(20).pkey().entityField("email").updatable(true).insertable(false);
    t1.column("address").VARCHAR(50).defaultValue("'Beijing'").comment("address comment");
    t1.column("phoneNumber").VARCHAR(50).singleIndex("IDX2");
    t1.column("age").INTEGER().notNull().check("'>0'");
    t1.index("idx3").columns("address", "phoneNumber").unique();
    TableModel t2 = new TableModel("orders").comment("order comment");
    t2.column("id").LONG().autoId().pkey();
    t2.column("name").STRING(20);
    t2.column("email").STRING(20);
    t2.column("name2").STRING(20).pkey().tail(" default 'Sam'");
    t2.column("email2").STRING(20);
    t2.fkey().columns("name2", "email2").refs("customers", "name", "email");
    t2.fkey("fk1").columns("name", "email").refs("customers", "name", "email");
    t2.unique("uk1").columns("name2", "email2");
    TableModel t3 = new TableModel("sampletable");
    t3.column("id").LONG().identityId().pkey();
    t3.tableGenerator("table_gen1", "tb1", "pkcol2", "valcol", "pkval", 1, 10);
    t3.column("id1").INTEGER().idGenerator("table_gen1");
    t3.sequenceGenerator("seq1", "seq_1", 1, 1);
    t3.column("id2").INTEGER().idGenerator("seq1");
    t3.engineTail(" DEFAULT CHARSET=utf8");
    String[] dropAndCreateDDL = Dialect.H2Dialect.toDropAndCreateDDL(t1, t2, t3);
    for (String ddl : dropAndCreateDDL) System.out.println(ddl);
    testOnCurrentRealDatabase(t1, t2, t3);
}
Also used : TableModel(com.github.drinkjava2.jdialects.model.TableModel) Test(org.junit.Test)

Example 3 with TableGenerator

use of com.github.drinkjava2.jdialects.model.TableGenerator in project jDialects by drinkjava2.

the class DDLUtils method buildTableGeneratorDDL.

private static void buildTableGeneratorDDL(Dialect dialect, List<String> stringList, List<TableGenerator> tbGeneratorList) {
    for (TableGenerator tg : tbGeneratorList) {
        //@formatter:off
        DialectException.assureNotEmpty(tg.getName(), "TableGenerator name can not be empty");
        DialectException.assureNotEmpty(tg.getTableName(), "TableGenerator tableName can not be empty of \"" + tg.getName() + "\"");
        DialectException.assureNotEmpty(tg.getPkColumnName(), "TableGenerator pkColumnName can not be empty of \"" + tg.getName() + "\"");
        DialectException.assureNotEmpty(tg.getPkColumnValue(), "TableGenerator pkColumnValue can not be empty of \"" + tg.getName() + "\"");
        DialectException.assureNotEmpty(tg.getValueColumnName(), "TableGenerator valueColumnName can not be empty of \"" + tg.getName() + "\"");
    //@formatter:on
    }
    for (TableGenerator tg : tbGeneratorList) {
        for (TableGenerator tg2 : tbGeneratorList) {
            if (tg != tg2 && (tg2.getAllocationSize() != 0)) {
                if (tg.getName().equalsIgnoreCase(tg2.getName())) {
                    // set to 0 to skip repeated
                    tg.setAllocationSize(0);
                } else {
                    if (tg.getTableName().equalsIgnoreCase(tg2.getTableName()) && tg.getPkColumnName().equalsIgnoreCase(tg2.getPkColumnName()) && tg.getPkColumnValue().equalsIgnoreCase(tg2.getPkColumnValue()) && tg.getValueColumnName().equalsIgnoreCase(tg2.getValueColumnName()))
                        DialectException.throwEX("Dulplicated tableGenerator setting \"" + tg.getName() + "\" and \"" + tg2.getName() + "\" found.");
                }
            }
        }
    }
    Set<String> tableExisted = new HashSet<>();
    Set<String> columnExisted = new HashSet<>();
    for (TableGenerator tg : tbGeneratorList) if (tg.getAllocationSize() != 0) {
        String tableName = tg.getTableName().toLowerCase();
        String tableAndPKColumn = tg.getTableName().toLowerCase() + "..XXOO.." + tg.getPkColumnName();
        String tableAndValColumn = tg.getTableName().toLowerCase() + "..XXOO.." + tg.getValueColumnName();
        if (!tableExisted.contains(tableName)) {
            String s = dialect.ddlFeatures.createTableString + " " + tableName + " (";
            s += tg.getPkColumnName() + " " + dialect.translateToDDLType(Type.VARCHAR, 100) + ",";
            s += tg.getValueColumnName() + " " + dialect.translateToDDLType(Type.BIGINT) + " )";
            stringList.add(s);
            tableExisted.add(tableName);
            columnExisted.add(tableAndPKColumn);
            columnExisted.add(tableAndValColumn);
        } else {
            if (!columnExisted.contains(tableAndPKColumn)) {
                stringList.add("alter table " + tableName + " " + dialect.ddlFeatures.addColumnString + " " + tg.getPkColumnName() + dialect.ddlFeatures.addColumnSuffixString);
                columnExisted.add(tableAndPKColumn);
            }
            if (!columnExisted.contains(tableAndValColumn)) {
                stringList.add("alter table " + tableName + " " + dialect.ddlFeatures.addColumnString + " " + tg.getValueColumnName() + dialect.ddlFeatures.addColumnSuffixString);
                columnExisted.add(tableAndValColumn);
            }
        }
    }
}
Also used : TableGenerator(com.github.drinkjava2.jdialects.model.TableGenerator) HashSet(java.util.HashSet)

Example 4 with TableGenerator

use of com.github.drinkjava2.jdialects.model.TableGenerator in project jDialects by drinkjava2.

the class DDLUtils method toCreateDDLwithoutFormat.

/**
	 * Transfer table to DDL by given dialect and without format it
	 */
public static String[] toCreateDDLwithoutFormat(Dialect dialect, Table... tables) {
    // resultList store mixed DDL String + TableGenerator + Sequence
    List<Object> objectResultList = new ArrayList<>();
    for (Table table : tables) transferTableToObjectList(dialect, table, objectResultList);
    List<String> stringResultList = new ArrayList<>();
    List<TableGenerator> tbGeneratorList = new ArrayList<>();
    List<Sequence> sequenceList = new ArrayList<>();
    List<GlobalIdGenerator> globalIdGeneratorList = new ArrayList<>();
    List<FKeyConstraint> fKeyConstraintList = new ArrayList<>();
    for (Object ddl : objectResultList) {
        if (!StrUtils.isEmpty(ddl)) {
            if (ddl instanceof String)
                stringResultList.add((String) ddl);
            else if (ddl instanceof TableGenerator)
                tbGeneratorList.add((TableGenerator) ddl);
            else if (ddl instanceof Sequence)
                sequenceList.add((Sequence) ddl);
            else if (ddl instanceof GlobalIdGenerator)
                globalIdGeneratorList.add((GlobalIdGenerator) ddl);
            else if (ddl instanceof FKeyConstraint)
                fKeyConstraintList.add((FKeyConstraint) ddl);
        }
    }
    buildSequenceDDL(dialect, stringResultList, sequenceList);
    buildTableGeneratorDDL(dialect, stringResultList, tbGeneratorList);
    buildGolbalIDGeneratorDDL(dialect, stringResultList, globalIdGeneratorList);
    buildFKeyConstraintDDL(dialect, stringResultList, fKeyConstraintList);
    return stringResultList.toArray(new String[stringResultList.size()]);
}
Also used : Table(com.github.drinkjava2.jdialects.model.Table) ArrayList(java.util.ArrayList) TableGenerator(com.github.drinkjava2.jdialects.model.TableGenerator) Sequence(com.github.drinkjava2.jdialects.model.Sequence) GlobalIdGenerator(com.github.drinkjava2.jdialects.model.GlobalIdGenerator) FKeyConstraint(com.github.drinkjava2.jdialects.model.FKeyConstraint)

Example 5 with TableGenerator

use of com.github.drinkjava2.jdialects.model.TableGenerator in project jDialects by drinkjava2.

the class TableModelUtilsOfEntity method entity2ModelIgnoreConfigMethod.

/**
 * Convert a Java entity class or JPA annotated entity classes to
 * "TableModel" Object, ignore config method
 */
private static TableModel entity2ModelIgnoreConfigMethod(Class<?> entityClass) {
    DialectException.assureNotNull(entityClass, "entity2Model method does not accept a null class");
    // Entity
    String tableName = null;
    Map<String, Object> entityMap = getFirstEntityAnno(entityClass, "Entity");
    tableName = (String) entityMap.get("name");
    // Table
    Map<String, Object> tableMap = getFirstEntityAnno(entityClass, "Table");
    if (!StrUtils.isEmpty(tableMap.get("name")))
        tableName = (String) tableMap.get("name");
    if (StrUtils.isEmpty(tableName))
        tableName = entityClass.getSimpleName();
    // Build the tableModel
    TableModel model = new TableModel(tableName);
    if (!tableMap.isEmpty()) {
        // Index
        Annotation[] indexes = (Annotation[]) tableMap.get("indexes");
        if (indexes != null && indexes.length > 0)
            for (Annotation anno : indexes) {
                Map<String, Object> mp = changeAnnotationValuesToMap(anno, anno.annotationType());
                String columnListString = (String) mp.get("columnList");
                String[] columns;
                if (columnListString.indexOf(',') >= 0)
                    columns = columnListString.split(",");
                else
                    columns = new String[] { columnListString };
                if (columns.length > 0)
                    model.index((String) mp.get("name")).columns(columns).setUnique((Boolean) mp.get("unique"));
            }
        // Unique
        Annotation[] uniques = (Annotation[]) tableMap.get("uniqueConstraints");
        if (uniques != null && uniques.length > 0)
            for (Annotation anno : uniques) {
                Map<String, Object> mp = changeAnnotationValuesToMap(anno, anno.annotationType());
                String[] columnNames = (String[]) mp.get("columnNames");
                if (columnNames != null && columnNames.length > 0)
                    model.unique((String) mp.get("name")).columns(columnNames);
            }
    }
    // SequenceGenerator
    Map<String, Object> seqMap = getFirstEntityAnno(entityClass, "SequenceGenerator");
    if (!seqMap.isEmpty()) {
        model.sequenceGenerator((String) seqMap.get("name"), (String) seqMap.get("sequenceName"), (Integer) seqMap.get("initialValue"), (Integer) seqMap.get("allocationSize"));
    }
    // TableGenerator
    Map<String, Object> tableGenMap = getFirstEntityAnno(entityClass, "TableGenerator");
    if (!tableGenMap.isEmpty()) {
        model.tableGenerator((String) tableGenMap.get("name"), (String) tableGenMap.get("table"), (String) tableGenMap.get("pkColumnName"), (String) tableGenMap.get("valueColumnName"), (String) tableGenMap.get("pkColumnValue"), (Integer) tableGenMap.get("initialValue"), (Integer) tableGenMap.get("allocationSize"));
    }
    // UUIDAny
    Map<String, Object> uuidAnyMp = getFirstEntityAnno(entityClass, "UUIDAny");
    if (!uuidAnyMp.isEmpty()) {
        model.uuidAny((String) uuidAnyMp.get("name"), (Integer) uuidAnyMp.get("length"));
    }
    // FKey
    List<Map<String, Object>> fkeys = getEntityAnnos(entityClass, "FKey");
    for (Map<String, Object> map : fkeys) {
        Boolean ddl = (Boolean) map.get("ddl");
        if (ddl == null)
            ddl = true;
        model.fkey((String) map.get("name")).columns((String[]) map.get("columns")).refs((String[]) map.get("refs")).ddl(ddl);
    }
    BeanInfo beanInfo = null;
    PropertyDescriptor[] pds = null;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
        pds = beanInfo.getPropertyDescriptors();
    } catch (Exception e) {
        DialectException.throwEX("entity2Model can not get bean info", e);
    }
    for (PropertyDescriptor pd : pds) {
        String entityfieldName = pd.getName();
        if ("class".equals(entityfieldName) || "simpleName".equals(entityfieldName) || "canonicalName".equals(entityfieldName) || "box".equals(entityfieldName))
            continue;
        Class<?> propertyClass = pd.getPropertyType();
        if (TypeUtils.canMapToSqlType(propertyClass)) {
            Field field = ReflectionUtils.findField(entityClass, entityfieldName);
            if (field == null)
                continue;
            if (!getFirstEntityAnno(field, "Transient").isEmpty()) {
                ColumnModel col = new ColumnModel(entityfieldName);
                col.setColumnType(TypeUtils.toType(propertyClass));
                col.setLengths(new Integer[] { 255, 0, 0 });
                col.setTransientable(true);
                col.setTableModel(model);
                model.addColumn(col);
            } else {
                // SequenceGenerator
                Map<String, Object> map = getFirstEntityAnno(field, "SequenceGenerator");
                if (!map.isEmpty()) {
                    model.sequenceGenerator((String) map.get("name"), (String) map.get("sequenceName"), (Integer) map.get("initialValue"), (Integer) map.get("allocationSize"));
                }
                // TableGenerator
                map = getFirstEntityAnno(field, "TableGenerator");
                if (!map.isEmpty()) {
                    model.tableGenerator((String) map.get("name"), (String) map.get("table"), (String) map.get("pkColumnName"), (String) map.get("valueColumnName"), (String) map.get("pkColumnValue"), (Integer) map.get("initialValue"), (Integer) map.get("allocationSize"));
                }
                // UUIDAny
                map = getFirstEntityAnno(field, "UUIDAny");
                if (!map.isEmpty()) {
                    model.uuidAny((String) map.get("name"), (Integer) map.get("length"));
                }
                ColumnModel col = new ColumnModel(entityfieldName);
                col.entityField(entityfieldName);
                // Column
                Map<String, Object> colMap = getFirstEntityAnno(field, "Column");
                if (!colMap.isEmpty()) {
                    if (!(Boolean) colMap.get("nullable"))
                        col.setNullable(false);
                    if (!StrUtils.isEmpty(colMap.get("name")))
                        col.setColumnName((String) colMap.get("name"));
                    col.setLength((Integer) colMap.get("length"));
                    col.setPrecision((Integer) colMap.get("precision"));
                    col.setScale((Integer) colMap.get("scale"));
                    col.setLengths(new Integer[] { col.getLength(), col.getPrecision(), col.getScale() });
                    if (!StrUtils.isEmpty(colMap.get("columnDefinition")))
                        col.setColumnType(TypeUtils.toType((String) colMap.get("columnDefinition")));
                    else
                        col.setColumnType(TypeUtils.toType(propertyClass));
                    col.setInsertable((Boolean) colMap.get("insertable"));
                    col.setUpdatable((Boolean) colMap.get("updatable"));
                } else {
                    col.setColumnType(TypeUtils.toType(propertyClass));
                    col.setLengths(new Integer[] { 255, 0, 0 });
                }
                // Id
                if (!getFirstEntityAnno(field, "Id").isEmpty() || !getFirstEntityAnno(field, "PKey").isEmpty())
                    col.pkey();
                col.setEntityField(entityfieldName);
                col.setTableModel(model);
                // col will also set TableModel field point to its owner
                model.addColumn(col);
                // shortcut Id generator annotations
                if (existEntityAnno(field, "AutoId"))
                    col.autoId();
                if (existEntityAnno(field, "IdentityId"))
                    col.identityId();
                if (existEntityAnno(field, "TimeStampId"))
                    col.timeStampId();
                if (existEntityAnno(field, "UUID25"))
                    col.uuid25();
                if (existEntityAnno(field, "UUID32"))
                    col.uuid32();
                if (existEntityAnno(field, "UUID36"))
                    col.uuid36();
                // GeneratedValue
                Map<String, Object> gvMap = getFirstEntityAnno(field, "GeneratedValue");
                if (!gvMap.isEmpty()) {
                    Object strategy = gvMap.get("strategy");
                    if (strategy != null) {
                        String strategyStr = strategy.toString();
                        if ("AUTO".equals(strategyStr))
                            col.autoId();
                        else if ("IDENTITY".equals(strategyStr))
                            col.identityId();
                        else if ("UUID25".equals(strategyStr))
                            col.uuid25();
                        else if ("UUID32".equals(strategyStr))
                            col.uuid32();
                        else if ("UUID36".equals(strategyStr))
                            col.uuid36();
                        else if ("TIMESTAMP".equals(strategyStr))
                            col.timeStampId();
                        else {
                            String generator = (String) gvMap.get("generator");
                            if (StrUtils.isEmpty(generator))
                                throw new DialectException("GeneratedValue strategy '" + strategyStr + "' can not find a generator");
                            col.idGenerator(generator);
                        }
                    }
                }
                // SingleFKey is a shortcut format of FKey, only for 1
                // column
                Map<String, Object> refMap = getFirstEntityAnno(field, "SingleFKey");
                if (!refMap.isEmpty()) {
                    Boolean ddl = (Boolean) refMap.get("ddl");
                    if (ddl == null)
                        ddl = true;
                    model.fkey((String) refMap.get("name")).columns(col.getColumnName()).refs((String[]) refMap.get("refs")).ddl(ddl);
                }
                // SingleIndex is a ShortCut format of Index, only for 1
                // column
                Map<String, Object> idxMap = getFirstEntityAnno(field, "SingleIndex");
                if (!idxMap.isEmpty())
                    model.index((String) idxMap.get("name")).columns(col.getColumnName());
                // SingleUnique is a ShortCut format of Unique, only for 1
                // column
                Map<String, Object> uniMap = getFirstEntityAnno(field, "SingleUnique");
                if (!uniMap.isEmpty())
                    model.unique((String) uniMap.get("name")).columns(col.getColumnName());
            }
        }
    }
    // End of columns loop
    return model;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) Annotation(java.lang.annotation.Annotation) Field(java.lang.reflect.Field) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Aggregations

TableModel (com.github.drinkjava2.jdialects.model.TableModel)5 Table (com.github.drinkjava2.jdialects.model.Table)3 TableGenerator (com.github.drinkjava2.jdialects.model.TableGenerator)3 FKeyConstraint (com.github.drinkjava2.jdialects.model.FKeyConstraint)2 GlobalIdGenerator (com.github.drinkjava2.jdialects.model.GlobalIdGenerator)2 Sequence (com.github.drinkjava2.jdialects.model.Sequence)2 Test (org.junit.Test)2 AutoIdGenerator (com.github.drinkjava2.jdialects.id.AutoIdGenerator)1 IdGenerator (com.github.drinkjava2.jdialects.id.IdGenerator)1 Column (com.github.drinkjava2.jdialects.model.Column)1 ColumnModel (com.github.drinkjava2.jdialects.model.ColumnModel)1 BeanInfo (java.beans.BeanInfo)1 PropertyDescriptor (java.beans.PropertyDescriptor)1 Annotation (java.lang.annotation.Annotation)1 Field (java.lang.reflect.Field)1 ArrayList (java.util.ArrayList)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1