Search in sources :

Example 6 with DialectException

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

the class TableModelUtilsOfDb method db2Model.

/**
 * Convert JDBC connected database structure to TableModels, note: <br/>
 * 1)This method does not close connection <br/>
 * 2)This method does not support sequence, foreign keys, primary keys...,
 * but will improve later.
 */
public static TableModel[] db2Model(Connection con, Dialect dialect) {
    // NOSONAR
    List<String> tableNames = new ArrayList<String>();
    List<TableModel> tableModels = new ArrayList<TableModel>();
    SQLException sqlException = null;
    ResultSet rs = null;
    PreparedStatement pst = null;
    try {
        DatabaseMetaData meta = con.getMetaData();
        if (dialect.isOracleFamily()) {
            // NOSONAR
            pst = con.prepareStatement("SELECT TABLE_NAME FROM USER_TABLES");
            rs = pst.executeQuery();
            while (rs.next()) tableNames.add(rs.getString(TABLE_NAME));
            rs.close();
            pst.close();
        // } else if (dialect.isSQLServerFamily()) {
        // pst = con.prepareStatement("select name from sysobjects where
        // xtype='U'");
        // rs = pst.executeQuery();
        // while (rs.next())
        // tableNames.add(rs.getString(TABLE_NAME));
        // rs.close();
        // pst.close();
        } else {
            rs = meta.getTables(null, null, null, new String[] { "TABLE" });
            while (rs.next()) tableNames.add(rs.getString(TABLE_NAME));
            rs.close();
        }
        for (String dbTableName : tableNames) {
            rs = con.getMetaData().getColumns(null, null, dbTableName, null);
            TableModel oneTable = new TableModel(dbTableName);
            while (rs.next()) {
                // NOSONAR
                String colName = rs.getString("COLUMN_NAME");
                oneTable.column(colName);
                ColumnModel col = oneTable.getColumn(colName);
                int javaSqlType = rs.getInt("DATA_TYPE");
                try {
                    col.setColumnType(TypeUtils.javaSqlTypeToDialectType(javaSqlType));
                } catch (Exception e1) {
                    throw new DialectException("jDialect does not supported java.sql.types value " + javaSqlType, e1);
                }
                col.setLength(rs.getInt("COLUMN_SIZE"));
                col.setNullable(rs.getInt("NULLABLE") > 0);
                col.setPrecision(rs.getInt("DECIMAL_DIGITS"));
                try {
                    if (((Boolean) (true)).equals(rs.getBoolean("IS_AUTOINCREMENT")))
                        col.identityId();
                } catch (Exception e) {
                }
                try {
                    if ("YES".equalsIgnoreCase(rs.getString("IS_AUTOINCREMENT")))
                        col.identityId();
                } catch (Exception e) {
                }
            }
            tableModels.add(oneTable);
            rs.close();
        }
    } catch (SQLException e) {
        e.printStackTrace();
        sqlException = e;
    } finally {
        if (pst != null)
            try {
                pst.close();
            } catch (SQLException e1) {
                if (sqlException != null)
                    sqlException.setNextException(e1);
                else
                    sqlException = e1;
            }
        try {
            if (rs != null)
                rs.close();
        } catch (SQLException e2) {
            if (sqlException != null)
                sqlException.setNextException(e2);
            else
                sqlException = e2;
        }
    }
    if (sqlException != null)
        throw new DialectException(sqlException);
    return tableModels.toArray(new TableModel[tableModels.size()]);
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) PreparedStatement(java.sql.PreparedStatement) DatabaseMetaData(java.sql.DatabaseMetaData) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 7 with DialectException

use of com.github.drinkjava2.jdialects.DialectException 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)

Example 8 with DialectException

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

the class TableModelUtilsOfEntity method oneEntity2Model.

/**
 * Convert a Java entity class or JPA annotated entity classes to
 * "TableModel" Object, if this class has a "config(TableModel tableModel)"
 * method, will also call it
 */
public static TableModel oneEntity2Model(Class<?> entityClass) {
    DialectException.assureNotNull(entityClass, "Entity class can not be null");
    TableModel model = tableModelCache.get(entityClass);
    if (model != null)
        return model.newCopy();
    model = entity2ModelIgnoreConfigMethod(entityClass);
    Method method = null;
    try {
        method = entityClass.getMethod("config", TableModel.class);
    } catch (Exception e) {
    // NOSONAR
    }
    if (method != null)
        try {
            method.invoke(null, model);
        } catch (Exception e) {
            throw new DialectException(e);
        }
    if (model != null)
        tableModelCache.put(entityClass, model);
    return model.newCopy();
}
Also used : Method(java.lang.reflect.Method) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 9 with DialectException

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

the class TableModel method sortedUUIDGenerator.

/**
 * Add a Sequence Generator, note: not all database support sequence
 */
public void sortedUUIDGenerator(String name, Integer sortedLength, Integer uuidLength) {
    DialectException.assureNotNull(name);
    if (this.getIdGenerator(GenerationType.SORTED_UUID, name) != null)
        throw new DialectException("Duplicated sortedUUIDGenerator name '" + name + "'");
    idGenerators.add(new SortedUUIDGenerator(name, sortedLength, uuidLength));
}
Also used : DialectException(com.github.drinkjava2.jdialects.DialectException) SortedUUIDGenerator(com.github.drinkjava2.jdialects.id.SortedUUIDGenerator)

Example 10 with DialectException

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

the class DDLCreateUtils method toCreateDDL.

/**
 * Transfer tables to DDL by given dialect and without format it, if want get a
 * formatted DDL, use DDLFormatter.format(DDLs) method to format it
 */
public static String[] toCreateDDL(Dialect dialect, TableModel... tables) {
    // Store mixed DDL String, TableGen Object, SequenceGen Object ...
    List<Object> objectResultList = new ArrayList<Object>();
    for (TableModel table : tables) transferTableToObjectList(dialect, table, objectResultList);
    boolean hasAutoIdGenerator = false;
    for (TableModel table : tables) {
        for (ColumnModel column : table.getColumns()) if (GenerationType.AUTO.equals(column.getIdGenerationType())) {
            hasAutoIdGenerator = true;
            break;
        }
        for (IdGenerator idGens : table.getIdGenerators()) if (hasAutoIdGenerator || idGens.dependOnAutoIdGenerator()) {
            hasAutoIdGenerator = true;
            break;
        }
    }
    List<String> stringResultList = new ArrayList<String>();
    List<TableIdGenerator> tbGeneratorList = new ArrayList<TableIdGenerator>();
    List<SequenceIdGenerator> sequenceList = new ArrayList<SequenceIdGenerator>();
    List<FKeyModel> fKeyConstraintList = new ArrayList<FKeyModel>();
    for (Object strOrObj : objectResultList) {
        if (!StrUtils.isEmpty(strOrObj)) {
            if (strOrObj instanceof String)
                stringResultList.add((String) strOrObj);
            else if (strOrObj instanceof TableIdGenerator)
                tbGeneratorList.add((TableIdGenerator) strOrObj);
            else if (strOrObj instanceof SequenceIdGenerator)
                sequenceList.add((SequenceIdGenerator) strOrObj);
            else if (strOrObj instanceof FKeyModel)
                fKeyConstraintList.add((FKeyModel) strOrObj);
        }
    }
    if (hasAutoIdGenerator) {
        IdGenerator realIdGen = AutoIdGenerator.INSTANCE.getSequenceOrTableIdGenerator(dialect);
        if (realIdGen instanceof TableIdGenerator)
            tbGeneratorList.add((TableIdGenerator) realIdGen);
        else if (realIdGen instanceof SequenceIdGenerator)
            sequenceList.add((SequenceIdGenerator) realIdGen);
        else
            throw new DialectException("Unknow exception happen for realIdGen, please report this bug");
    }
    buildSequenceDDL(dialect, stringResultList, sequenceList);
    buildTableGeneratorDDL(dialect, stringResultList, tbGeneratorList);
    outputFKeyConstraintDDL(dialect, stringResultList, fKeyConstraintList);
    String[] result = stringResultList.toArray(new String[stringResultList.size()]);
    if (Dialect.getGlobalAllowShowSql())
        Dialect.logger.info("Create DDL:\r" + StrUtils.arrayToString(result, "\r"));
    return result;
}
Also used : ArrayList(java.util.ArrayList) TableIdGenerator(com.github.drinkjava2.jdialects.id.TableIdGenerator) AutoIdGenerator(com.github.drinkjava2.jdialects.id.AutoIdGenerator) SequenceIdGenerator(com.github.drinkjava2.jdialects.id.SequenceIdGenerator) IdGenerator(com.github.drinkjava2.jdialects.id.IdGenerator) TableIdGenerator(com.github.drinkjava2.jdialects.id.TableIdGenerator) SequenceIdGenerator(com.github.drinkjava2.jdialects.id.SequenceIdGenerator) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel) FKeyModel(com.github.drinkjava2.jdialects.model.FKeyModel)

Aggregations

DialectException (com.github.drinkjava2.jdialects.DialectException)6 TableModel (com.github.drinkjava2.jdialects.model.TableModel)5 Dialect (com.github.drinkjava2.jdialects.Dialect)4 DB2400Dialect (com.github.drinkjava2.jdialects.Dialect.DB2400Dialect)4 DB2Dialect (com.github.drinkjava2.jdialects.Dialect.DB2Dialect)4 DerbyDialect (com.github.drinkjava2.jdialects.Dialect.DerbyDialect)4 DerbyTenFiveDialect (com.github.drinkjava2.jdialects.Dialect.DerbyTenFiveDialect)4 DerbyTenSevenDialect (com.github.drinkjava2.jdialects.Dialect.DerbyTenSevenDialect)4 DerbyTenSixDialect (com.github.drinkjava2.jdialects.Dialect.DerbyTenSixDialect)4 H2Dialect (com.github.drinkjava2.jdialects.Dialect.H2Dialect)4 HSQLDialect (com.github.drinkjava2.jdialects.Dialect.HSQLDialect)4 InformixDialect (com.github.drinkjava2.jdialects.Dialect.InformixDialect)4 IngresDialect (com.github.drinkjava2.jdialects.Dialect.IngresDialect)4 Oracle10gDialect (com.github.drinkjava2.jdialects.Dialect.Oracle10gDialect)4 Oracle8iDialect (com.github.drinkjava2.jdialects.Dialect.Oracle8iDialect)4 Oracle9iDialect (com.github.drinkjava2.jdialects.Dialect.Oracle9iDialect)4 PostgreSQL81Dialect (com.github.drinkjava2.jdialects.Dialect.PostgreSQL81Dialect)4 PostgreSQL82Dialect (com.github.drinkjava2.jdialects.Dialect.PostgreSQL82Dialect)4 PostgreSQL9Dialect (com.github.drinkjava2.jdialects.Dialect.PostgreSQL9Dialect)4 PostgresPlusDialect (com.github.drinkjava2.jdialects.Dialect.PostgresPlusDialect)4