Search in sources :

Example 1 with Type

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

the class ImprovedQueryRunner method batchFlush.

// === Batch execute methods======
/**
 * Force flush cached SQLs
 */
public void batchFlush() throws SQLException {
    List<Object[]> sqlCacheList = sqlBatchCache.get();
    if (sqlCacheList.isEmpty())
        return;
    // first row
    Object[] f = sqlCacheList.get(0);
    if (f.length != 6)
        throw new DbProRuntimeException("Unexpected batch cached SQL format");
    int paramLenth = 0;
    if ("i1".equals(f[0]) || "i3".equals(f[0]) || "u1".equals(f[0]) || "u4".equals(f[0]))
        paramLenth = 0;
    if ("u2".equals(f[0]) || "u5".equals(f[0]))
        paramLenth = 1;
    else
        paramLenth = ((Object[]) sqlCacheList.get(0)[5]).length;
    Object[][] allParams = new Object[sqlCacheList.size()][paramLenth];
    int i = 0;
    for (Object[] c : sqlCacheList) {
        // cached parameters
        Object param = c[2];
        Object[] params = (Object[]) c[5];
        if ("i1".equals(f[0]) || "i3".equals(f[0]) || "u1".equals(f[0]) || "u4".equals(f[0]))
            allParams[i] = new Object[0];
        if ("u2".equals(f[0]) || "u5".equals(f[0]))
            allParams[i] = new Object[] { param };
        else
            allParams[i] = params;
        i++;
    }
    String sql = (String) f[3];
    Connection conn = (Connection) f[4];
    ResultSetHandler rsh = (ResultSetHandler) f[1];
    if (this.getAllowShowSQL()) {
        logger.info("Batch execute " + sqlCacheList.size() + " SQLs");
        logger.info(formatSqlForLoggerOutput(sql));
        logger.info("First row " + formatParametersForLoggerOutput(allParams[0]));
        logger.info("Last row " + formatParametersForLoggerOutput(allParams[allParams.length - 1]));
    }
    if ("e1".equals(f[0]) || "i1".equals(f[0]) || "u1".equals(f[0]) || "u2".equals(f[0]) || "u3".equals(f[0]))
        super.batch(conn, sql, allParams);
    else if ("e3".equals(f[0]) || "i3".equals(f[0]) || "u4".equals(f[0]) || "u5".equals(f[0]) || "u6".equals(f[0]))
        super.batch(sql, allParams);
    else if ("e2".equals(f[0]) || "i2".equals(f[0]))
        super.insertBatch(conn, sql, rsh, allParams);
    else if ("e4".equals(f[0]) || "i4".equals(f[0]))
        super.insertBatch(sql, rsh, allParams);
    else
        throw new DbProRuntimeException("unknow batch sql operation type +'" + f[0] + "'");
    sqlBatchCache.get().clear();
}
Also used : DbProRuntimeException(com.github.drinkjava2.jdbpro.DbProRuntimeException) Connection(java.sql.Connection) ResultSetHandler(org.apache.commons.dbutils.ResultSetHandler)

Example 2 with Type

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

the class EntityNet method findNodeSetforNodes.

/**
 * According given path and input Node Set, find related node set
 *
 * @param level
 *            search level, start from 0
 * @param path
 *            The Path
 * @param input
 *            The input node collection
 * @param output
 *            The output node collection
 * @return Related node set
 */
private void findNodeSetforNodes(Integer level, Path path, Collection<Node> input, Map<Class<?>, Set<Node>> result) {
    if (level > 1000)
        throw new EntityNetException("Search level beyond 1000, this may caused by a circular reference path chain.");
    TableModel model = path.getTargetModel();
    String type0 = path.getType().substring(0, 1);
    String type1 = path.getType().substring(1, 2);
    Class<?> targetClass = model.getEntityClass();
    Set<Node> selected = new LinkedHashSet<Node>();
    String pathUniqueString = path.getUniqueIdString();
    Integer pathId = pathIdCache.get(pathUniqueString);
    // Start
    if ("S".equalsIgnoreCase(type0)) {
        if (level != 0)
            throw new EntityNetException("'S' type can only be used on path start");
        // Check if cached
        Map<Integer, Set<Node>> rootCache = queryCache.get("ROOT");
        if (this.allowQueryCache && path.getCacheable() && pathId != null && (rootCache != null)) {
            Set<Node> cachedNodes = rootCache.get(pathId);
            if (cachedNodes != null)
                selected = cachedNodes;
        } else {
            // check all targetClass
            Collection<Node> nodesToCheck = getAllNodeSet(targetClass);
            validateSelected(level, path, selected, nodesToCheck);
            // cache it if allow cache
            if (this.allowQueryCache && path.getCacheable() && !StrUtils.isEmpty(pathUniqueString)) {
                cacheSelected("ROOT", pathUniqueString, selected);
            }
        }
    } else // Child
    if ("C".equalsIgnoreCase(type0) && input != null && !input.isEmpty()) {
        for (Node inputNode : input) {
            Map<Integer, Set<Node>> childCache = queryCache.get(inputNode.getId());
            if (this.allowQueryCache && path.getCacheable() && pathId != null && childCache != null) {
                Set<Node> cachedNodes = childCache.get(pathId);
                if (cachedNodes != null)
                    selected.addAll(cachedNodes);
            } else {
                // Find childNodes meat class/columns/id condition
                Set<Node> nodesToCheck = new LinkedHashSet<Node>();
                for (Entry<String, Node> cNode : body.get(targetClass).entrySet()) {
                    List<ParentRelation> prs = cNode.getValue().getParentRelations();
                    if (prs != null)
                        for (ParentRelation pr : prs) {
                            if (inputNode.getId().equals(pr.getParentId()) && pr.getRefColumns().equalsIgnoreCase(path.getRefColumns())) {
                                nodesToCheck.add(cNode.getValue());
                                break;
                            }
                        }
                }
                validateSelected(level, path, selected, nodesToCheck);
                // now cached childNodes on parentNode
                if (this.allowQueryCache && path.getCacheable() && !StrUtils.isEmpty(pathUniqueString)) {
                    cacheSelected(inputNode.getId(), pathUniqueString, selected);
                }
            }
        }
    } else // Parent
    if ("P".equalsIgnoreCase(type0) && input != null && !input.isEmpty()) {
        String targetTableName = model.getTableName();
        EntityNetException.assureNotEmpty(targetTableName, "targetTableName can not be null");
        for (Node inputNode : input) {
            // Find parent nodes meat tableName/refColumns/nodeId condition
            Set<Node> nodesToCheck = new LinkedHashSet<Node>();
            List<ParentRelation> prs = inputNode.getParentRelations();
            if (prs != null)
                for (ParentRelation pr : prs) {
                    if (targetTableName.equalsIgnoreCase(pr.getParentTable()) && path.getRefColumns().equalsIgnoreCase(pr.getRefColumns())) {
                        Node node = this.getOneNode(targetClass, pr.getParentId());
                        if (node != null)
                            nodesToCheck.add(node);
                    }
                }
            validateSelected(level, path, selected, nodesToCheck);
            // now cached childNodes on parentNode
            if (this.allowQueryCache && path.getCacheable() && !StrUtils.isEmpty(pathUniqueString)) {
                cacheSelected(inputNode.getId(), pathUniqueString, selected);
            }
        }
    }
    Set<Node> nodes = result.get(targetClass);
    if (nodes == null) {
        nodes = new LinkedHashSet<Node>();
        result.put(targetClass, nodes);
    }
    if ("+".equals(type1) || "*".equals(type1))
        nodes.addAll(selected);
    if (!(path.getCacheable() && StrUtils.isEmpty(path.getUniqueIdString()))) {
        if (selected.size() > 100000)
            throw new EntityNetException("Query result return more than 100000 records to cache in memory, this may caused by careless programming.");
    }
    if (level > 10000)
        throw new EntityNetException("Search depth >10000, this may caused by careless programming.");
    if ("*".equals(type1) && !selected.isEmpty())
        findNodeSetforNodes(level + 1, path, selected, result);
    if (path.getNextPath() != null) {
        findNodeSetforNodes(level + 1, path.getNextPath(), selected, result);
    }
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) Entry(java.util.Map.Entry) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 3 with Type

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

the class TableModelUtilsOfDb method doCompareDB.

private static void doCompareDB(Connection con1, Connection con2, boolean ignoreLength) {
    TableModel[] models1 = TableModelUtils.db2Models(con1, Dialect.guessDialect(con1));
    TableModel[] models2 = TableModelUtils.db2Models(con2, Dialect.guessDialect(con2));
    for (TableModel model1 : models1) {
        String tableName1 = model1.getTableName();
        boolean foundTable = false;
        List<ColumnModel> cols1 = model1.getColumns();
        for (TableModel model2 : models2) {
            if (tableName1.equalsIgnoreCase(model2.getTableName())) {
                String tableName2 = model2.getTableName();
                foundTable = true;
                List<ColumnModel> cols2 = model2.getColumns();
                for (ColumnModel col1 : cols1) {
                    for (ColumnModel col2 : cols2) {
                        if (col1.getColumnName().equalsIgnoreCase(col2.getColumnName())) {
                            if (!("" + col1.getColumnType()).equalsIgnoreCase("" + col2.getColumnType())) {
                                print("DB1 column " + tableName1 + "." + col1.getColumnName() + " type is " + col1.getColumnType() + ", but " + "DB2 column " + tableName2 + "." + col2.getColumnName() + " type is " + col2.getColumnType());
                            }
                            if (!ignoreLength) {
                                // if ignore length check?
                                if (!("" + col1.getLength()).equalsIgnoreCase("" + col2.getLength())) {
                                    print("DB1 column " + tableName1 + "." + col1.getColumnName() + " length is " + col1.getLength() + ", but " + "DB2 column " + tableName2 + "." + col2.getColumnName() + " length is " + col2.getLength());
                                }
                                if (!("" + col1.getPrecision()).equalsIgnoreCase("" + col2.getPrecision())) {
                                    print("DB1 column " + tableName1 + "." + col1.getColumnName() + " precision is " + col1.getPrecision() + ", but " + "DB2 column " + tableName2 + "." + col2.getColumnName() + " precision is " + col2.getPrecision());
                                }
                                if (!("" + col1.getScale()).equalsIgnoreCase("" + col2.getScale())) {
                                    print("DB1 column " + tableName1 + "." + col1.getColumnName() + " scale is " + col1.getScale() + ", but " + "DB2 column " + tableName2 + "." + col2.getColumnName() + " scale is " + col2.getScale());
                                }
                            }
                            break;
                        }
                    }
                }
                for (ColumnModel col1 : cols1) {
                    boolean found = false;
                    for (ColumnModel col2 : cols2) if (col1.getColumnName().equalsIgnoreCase(col2.getColumnName())) {
                        found = true;
                        break;
                    }
                    if (!found)
                        print("DB1 column " + tableName1 + "." + col1.getColumnName() + " not found in " + "DB2 table " + tableName2);
                }
                for (ColumnModel col2 : cols2) {
                    boolean found = false;
                    for (ColumnModel col1 : cols1) if (col2.getColumnName().equalsIgnoreCase(col1.getColumnName())) {
                        found = true;
                        break;
                    }
                    if (!found)
                        print("DB2 column " + tableName1 + "." + col2.getColumnName() + " not found in " + "DB1 table " + tableName1);
                }
                break;
            }
        }
        if (!foundTable)
            print("DB1 table" + tableName1 + " not found in " + "DB2 ");
    }
    for (TableModel model2 : models1) {
        String tableName2 = model2.getTableName();
        boolean foundTable = false;
        for (TableModel model1 : models1) {
            if (tableName2.equalsIgnoreCase(model1.getTableName())) {
                foundTable = true;
                break;
            }
        }
        if (!foundTable)
            print("DB2 table " + tableName2 + " not found in " + "DB1 ");
    }
}
Also used : ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) TableModel(com.github.drinkjava2.jdialects.model.TableModel)

Example 4 with Type

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

the class DDLCreateUtils method transferTableToObjectList.

/**
 * Transfer table to a mixed DDL String or TableGen Object list
 */
/**
 * @param dialect
 * @param t
 * @param objectResultList
 */
private static void transferTableToObjectList(Dialect dialect, TableModel t, List<Object> objectResultList) {
    DDLFeatures features = dialect.ddlFeatures;
    StringBuilder buf = new StringBuilder();
    boolean hasPkey = false;
    String pkeys = "";
    String tableName = t.getTableName();
    List<ColumnModel> columns = t.getColumns();
    // Reserved words check
    dialect.checkNotEmptyReservedWords(tableName, "Table name", tableName);
    // check index names
    List<IndexModel> idexChks = t.getIndexConsts();
    if (idexChks != null && !idexChks.isEmpty())
        for (IndexModel index : idexChks) dialect.checkReservedWords(index.getName());
    // check unique names
    List<UniqueModel> ukChks = t.getUniqueConsts();
    if (ukChks != null && !ukChks.isEmpty())
        for (UniqueModel unique : ukChks) dialect.checkReservedWords(unique.getName());
    // check Fkey names
    List<FKeyModel> fkeyChks = t.getFkeyConstraints();
    if (fkeyChks != null && !fkeyChks.isEmpty())
        for (FKeyModel fkey : fkeyChks) dialect.checkReservedWords(fkey.getFkeyName());
    for (// check column names
    ColumnModel col : // check column names
    columns) if (!col.getTransientable())
        dialect.checkNotEmptyReservedWords(col.getColumnName(), "Column name", tableName);
    // idGenerator
    for (IdGenerator idGen : t.getIdGenerators()) objectResultList.add(idGen);
    // Foreign key
    for (FKeyModel fkey : t.getFkeyConstraints()) objectResultList.add(fkey);
    // check and cache prime keys
    for (ColumnModel col : columns) {
        if (col.getTransientable())
            continue;
        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 (ColumnModel c : columns) {
        if (c.getTransientable())
            continue;
        if (c.getColumnType() == null)
            DialectException.throwEX("Type not set on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
        // column definition
        buf.append(c.getColumnName()).append(" ");
        // Identity
        if (GenerationType.IDENTITY.equals(c.getIdGenerationType()) && !features.supportsIdentityColumns)
            DialectException.throwEX("Unsupported identity setting for dialect \"" + dialect + "\" on column \"" + c.getColumnName() + "\" at table \"" + tableName + "\"");
        // Column type definition
        if (!StrUtils.isEmpty(c.getColumnDefinition()))
            buf.append(c.getColumnDefinition());
        else if (GenerationType.IDENTITY.equals(c.getIdGenerationType())) {
            if (features.hasDataTypeInIdentityColumn)
                buf.append(dialect.translateToDDLType(c));
            buf.append(' ');
            if (Type.BIGINT.equals(c.getColumnType()))
                buf.append(features.identityColumnStringBigINT);
            else
                buf.append(features.identityColumnString);
        } else {
            buf.append(dialect.translateToDDLType(c));
            // Default
            String defaultValue = c.getDefaultValue();
            if (defaultValue != null) {
                buf.append(" default ").append(defaultValue);
            }
            // Not null
            if (!c.getNullable())
                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 (!StrUtils.isEmpty(c.getComment())) {
            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()));
        }
        // tail String
        if (!StrUtils.isEmpty(c.getTail()))
            buf.append(c.getTail());
        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(")");
    // Engine for MariaDB & MySql only, for example "engine=innoDB"
    String tableTypeString = features.tableTypeString;
    if (!StrUtils.isEmpty(tableTypeString) && !DDLFeatures.NOT_SUPPORT.equals(tableTypeString)) {
        buf.append(tableTypeString);
        // EngineTail, for example:" DEFAULT CHARSET=utf8"
        if (!StrUtils.isEmpty(t.getEngineTail()))
            buf.append(t.getEngineTail());
    }
    objectResultList.add(buf.toString());
    // table comment on
    if (!StrUtils.isEmpty(t.getComment())) {
        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 (ColumnModel c : columns) {
        if (!c.getTransientable() && features.supportsCommentOn && c.getComment() != null && StrUtils.isEmpty(features.columnComment))
            objectResultList.add("comment on column " + tableName + '.' + c.getColumnName() + " is '" + c.getComment() + "'");
    }
    // index
    buildIndexDLL(dialect, objectResultList, t);
    // unique
    buildUniqueDLL(dialect, objectResultList, t);
}
Also used : 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) IndexModel(com.github.drinkjava2.jdialects.model.IndexModel) UniqueModel(com.github.drinkjava2.jdialects.model.UniqueModel) ColumnModel(com.github.drinkjava2.jdialects.model.ColumnModel) FKeyModel(com.github.drinkjava2.jdialects.model.FKeyModel)

Example 5 with Type

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

the class IdentityIdGenerator method getNextID.

@Override
public Object getNextID(NormalJdbcTool jdbc, Dialect dialect, Type dataType) {
    if (!dialect.ddlFeatures.getSupportsIdentityColumns())
        throw new DialectException("Dialect '" + dialect + "' does not support identity type");
    String sql = null;
    if (Type.BIGINT.equals(dataType))
        sql = dialect.ddlFeatures.getIdentitySelectStringBigINT();
    else
        sql = dialect.ddlFeatures.getIdentitySelectString();
    if (StrUtils.isEmpty(sql) || DDLFeatures.NOT_SUPPORT.equals(sql))
        throw new DialectException("Dialect '" + dialect + "' does not support identity type");
    sql = StrUtils.replaceFirst(sql, "_table__col", new StringBuilder(table).append("_").append(column).toString());
    return jdbc.jdbcQueryForObject(sql);
}
Also used : DialectException(com.github.drinkjava2.jdialects.DialectException)

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