Search in sources :

Example 1 with QueryFactory

use of org.sql.generation.api.grammar.factories.QueryFactory in project qi4j-sdk by Qi4j.

the class AbstractSQLIndexing method createQueryEntityPkByIdentityStatement.

protected QueryExpression createQueryEntityPkByIdentityStatement(String schemaName, SQLVendor vendor) {
    BooleanFactory b = vendor.getBooleanFactory();
    LiteralFactory l = vendor.getLiteralFactory();
    ColumnsFactory c = vendor.getColumnsFactory();
    TableReferenceFactory t = vendor.getTableReferenceFactory();
    QueryFactory q = vendor.getQueryFactory();
    // "SELECT " + ENTITY_TABLE_PK_COLUMN_NAME + "\n" + //
    // "FROM " + "%s" + "." + ENTITY_TABLE_NAME + "\n" + //
    // "WHERE " + ENTITY_TABLE_IDENTITY_COLUMN_NAME + " = ?" + "\n" + //
    // ";" //
    QuerySpecificationBuilder query = q.querySpecificationBuilder();
    query.getSelect().addUnnamedColumns(c.colName(DBNames.ENTITY_TABLE_PK_COLUMN_NAME));
    query.getFrom().addTableReferences(t.tableBuilder(t.table(t.tableName(schemaName, DBNames.ENTITY_TABLE_NAME))));
    query.getWhere().reset(b.eq(c.colName(DBNames.ENTITY_TABLE_IDENTITY_COLUMN_NAME), l.param()));
    return q.createQuery(query.createExpression());
}
Also used : TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory) QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) ColumnsFactory(org.sql.generation.api.grammar.factories.ColumnsFactory) QuerySpecificationBuilder(org.sql.generation.api.grammar.builders.query.QuerySpecificationBuilder) BooleanFactory(org.sql.generation.api.grammar.factories.BooleanFactory) LiteralFactory(org.sql.generation.api.grammar.factories.LiteralFactory)

Example 2 with QueryFactory

use of org.sql.generation.api.grammar.factories.QueryFactory in project qi4j-sdk by Qi4j.

the class AbstractSQLStartup method readAppMetadataFromDB.

private void readAppMetadataFromDB(Connection connection, Map<String, EntityDescriptor> entityDescriptors) throws SQLException {
    String schemaName = this._state.schemaName().get();
    Statement stmt = connection.createStatement();
    SQLVendor vendor = this._vendor;
    QueryFactory q = vendor.getQueryFactory();
    TableReferenceFactory t = vendor.getTableReferenceFactory();
    try {
        // @formatter:off
        q.simpleQueryBuilder().select(ENTITY_TYPES_TABLE_PK_COLUMN_NAME, ENTITY_TYPES_TABLE_TYPE_NAME_COLUMN_NAME).from(t.tableName(schemaName, ENTITY_TYPES_TABLE_NAME)).createExpression();
        ResultSet rs = stmt.executeQuery(vendor.toString(q.simpleQueryBuilder().select(ENTITY_TYPES_TABLE_PK_COLUMN_NAME, ENTITY_TYPES_TABLE_TYPE_NAME_COLUMN_NAME).from(t.tableName(schemaName, ENTITY_TYPES_TABLE_NAME)).createExpression()));
        long pk = 0L;
        try {
            while (rs.next()) {
                pk = rs.getInt(1);
                String entityTypeName = rs.getString(2);
                this._state.entityTypePKs().get().put(entityTypeName, (int) pk);
            // this._state.entityTypeInfos().get()
            // .put( entityTypeName, new EntityTypeInfo( entityDescriptors.get( entityTypeName ), (int) pk ) );
            }
        } finally {
            SQLUtil.closeQuietly(rs);
        }
        rs = stmt.executeQuery(vendor.toString(q.simpleQueryBuilder().select(USED_CLASSES_TABLE_PK_COLUMN_NAME, USED_CLASSES_TABLE_CLASS_NAME_COLUMN_NAME).from(t.tableName(schemaName, USED_CLASSES_TABLE_NAME)).createExpression()));
        try {
            while (rs.next()) {
                pk = rs.getInt(1);
                String descriptorTextualFormat = rs.getString(2);
                this._state.usedClassesPKs().get().put(stringToCompositeDescriptor(ValueDescriptor.class, this._app.descriptor(), descriptorTextualFormat), (int) pk);
            }
        } finally {
            SQLUtil.closeQuietly(rs);
        }
        rs = stmt.executeQuery(vendor.toString(q.simpleQueryBuilder().select(ENUM_LOOKUP_TABLE_PK_COLUMN_NAME, ENUM_LOOKUP_TABLE_ENUM_VALUE_NAME).from(t.tableName(schemaName, ENUM_LOOKUP_TABLE_NAME)).createExpression()));
        try {
            while (rs.next()) {
                pk = rs.getInt(1);
                String enumName = rs.getString(2);
                this._state.enumPKs().get().put(enumName, (int) pk);
            }
        } finally {
            SQLUtil.closeQuietly(rs);
        }
        rs = stmt.executeQuery(q.simpleQueryBuilder().select(USED_QNAMES_TABLE_QNAME_COLUMN_NAME, USED_QNAMES_TABLE_TABLE_NAME_COLUMN_NAME).from(t.tableName(schemaName, USED_QNAMES_TABLE_NAME)).createExpression().toString());
        try {
            while (rs.next()) {
                String qName = rs.getString(1);
                String tableName = rs.getString(2);
                this._state.qNameInfos().get().get(QualifiedName.fromFQN(qName)).setTableName(tableName);
            }
        } finally {
            SQLUtil.closeQuietly(rs);
        }
    // @formatter:on
    } finally {
        SQLUtil.closeQuietly(stmt);
    }
}
Also used : TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory) QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) InsertStatement(org.sql.generation.api.grammar.modification.InsertStatement) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) ValueDescriptor(org.qi4j.api.value.ValueDescriptor) ResultSet(java.sql.ResultSet) SQLVendor(org.sql.generation.api.vendor.SQLVendor)

Example 3 with QueryFactory

use of org.sql.generation.api.grammar.factories.QueryFactory in project qi4j-sdk by Qi4j.

the class AbstractSQLQuerying method modifyFromClauseAndWhereClauseToGetValue.

// TODO refactor this monster of a method to something more understandable
protected Integer modifyFromClauseAndWhereClauseToGetValue(final QualifiedName qName, Object value, final Specification<Composite> predicate, final Boolean negationActive, final Integer currentTableIndex, final ModifiableInt maxTableIndex, final String columnName, final String collectionPath, final SQLVendor vendor, final BooleanBuilder whereClause, final BooleanBuilder afterWhere, final TableReferenceBuilder fromClause, final GroupByBuilder groupBy, final BooleanBuilder having, final List<QNameJoin> qNameJoins, Map<String, Object> variables, final List<Object> values, final List<Integer> valueSQLTypes) {
    if (value instanceof Variable) {
        value = variables.get(((Variable) value).variableName());
    }
    final String schemaName = this._state.schemaName().get();
    Integer result = 1;
    final BooleanFactory b = vendor.getBooleanFactory();
    final LiteralFactory l = vendor.getLiteralFactory();
    final ColumnsFactory c = vendor.getColumnsFactory();
    final QueryFactory q = vendor.getQueryFactory();
    final TableReferenceFactory t = vendor.getTableReferenceFactory();
    if (value instanceof Collection<?>) {
        // Collection
        Integer collectionIndex = 0;
        Boolean collectionIsSet = value instanceof Set<?>;
        Boolean topLevel = collectionPath.equals(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME);
        String collTable = TABLE_NAME_PREFIX + currentTableIndex;
        String collCol = DBNames.QNAME_TABLE_COLLECTION_PATH_COLUMN_NAME;
        ColumnReferenceByName collColExp = c.colName(collTable, collCol);
        BooleanBuilder collectionCondition = b.booleanBuilder();
        if (topLevel && negationActive) {
            afterWhere.and(b.booleanBuilder(b.neq(collColExp, l.s(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME))).or(b.isNull(collColExp)).createExpression());
        }
        Integer totalItemsProcessed = 0;
        for (Object item : (Collection<?>) value) {
            String path = collectionPath + DBNames.QNAME_TABLE_COLLECTION_PATH_SEPARATOR + (collectionIsSet ? "*{1,}" : collectionIndex);
            Boolean isCollection = (item instanceof Collection<?>);
            BooleanBuilder newWhere = b.booleanBuilder();
            if (!isCollection) {
                newWhere.reset(b.regexp(collColExp, l.s(path)));
            }
            totalItemsProcessed = totalItemsProcessed + modifyFromClauseAndWhereClauseToGetValue(qName, item, predicate, negationActive, currentTableIndex, maxTableIndex, columnName, path, vendor, newWhere, afterWhere, fromClause, groupBy, having, qNameJoins, variables, values, valueSQLTypes);
            ++collectionIndex;
            collectionCondition.or(newWhere.createExpression());
        }
        result = totalItemsProcessed;
        if (topLevel) {
            if (totalItemsProcessed == 0) {
                collectionCondition.and(b.isNotNull(collColExp)).and(b.eq(collColExp, l.l(DBNames.QNAME_TABLE_COLLECTION_PATH_TOP_LEVEL_NAME)));
            } else if (!negationActive) {
                groupBy.addGroupingElements(q.groupingElement(c.colName(TABLE_NAME_PREFIX + currentTableIndex, DBNames.ENTITY_TABLE_PK_COLUMN_NAME)));
                having.and(b.eq(l.func(SQLFunctions.COUNT, c.colName(TABLE_NAME_PREFIX + currentTableIndex, DBNames.QNAME_TABLE_VALUE_COLUMN_NAME)), l.n(totalItemsProcessed)));
            }
        }
        whereClause.and(collectionCondition.createExpression());
    } else if (value instanceof ValueComposite) {
        // @formatter:off
        for (Property<?> property : Qi4j.FUNCTION_COMPOSITE_INSTANCE_OF.map((ValueComposite) value).state().properties()) {
            Boolean qNameJoinDone = false;
            Integer sourceIndex = maxTableIndex.getInt();
            Integer targetIndex = sourceIndex + 1;
            for (QNameJoin join : qNameJoins) {
                if (join.getSourceQName().equals(qName)) {
                    sourceIndex = join.getSourceTableIndex();
                    if (join.getTargetQName().equals(spi.propertyDescriptorFor(property).qualifiedName())) {
                        // This join has already been done once
                        qNameJoinDone = true;
                        targetIndex = join.getTargetTableIndex();
                        break;
                    }
                }
            }
            if (!qNameJoinDone) {
                // @formatter:off
                QNameInfo info = _state.qNameInfos().get().get(spi.propertyDescriptorFor(property).qualifiedName());
                String prevTableName = TABLE_NAME_PREFIX + sourceIndex;
                String nextTableName = TABLE_NAME_PREFIX + targetIndex;
                fromClause.addQualifiedJoin(JoinType.LEFT_OUTER, t.table(t.tableName(schemaName, info.getTableName()), t.tableAlias(TABLE_NAME_PREFIX + targetIndex)), t.jc(b.booleanBuilder(b.eq(c.colName(prevTableName, DBNames.ALL_QNAMES_TABLE_PK_COLUMN_NAME), c.colName(nextTableName, DBNames.QNAME_TABLE_PARENT_QNAME_COLUMN_NAME))).and(b.eq(c.colName(prevTableName, DBNames.ENTITY_TABLE_PK_COLUMN_NAME), c.colName(nextTableName, DBNames.ENTITY_TABLE_PK_COLUMN_NAME))).createExpression()));
                // @formatter:on
                qNameJoins.add(new QNameJoin(qName, spi.propertyDescriptorFor(property).qualifiedName(), sourceIndex, targetIndex));
                maxTableIndex.setInt(maxTableIndex.getInt() + 1);
            }
            modifyFromClauseAndWhereClauseToGetValue(spi.propertyDescriptorFor(property).qualifiedName(), property.get(), predicate, negationActive, targetIndex, maxTableIndex, columnName, collectionPath, vendor, whereClause, afterWhere, fromClause, groupBy, having, qNameJoins, variables, values, valueSQLTypes);
        }
    // @formatter:on
    } else {
        // Primitive
        ColumnReferenceByName valueCol = c.colName(TABLE_NAME_PREFIX + currentTableIndex, columnName);
        if (value == null) {
            whereClause.and(b.isNull(valueCol));
        } else {
            Object dbValue = value;
            if (Enum.class.isAssignableFrom(value.getClass())) {
                dbValue = this._state.enumPKs().get().get(value.getClass().getName());
            }
            whereClause.and(b.and(b.isNotNull(valueCol), this.getOperator(predicate).getExpression(b, valueCol, l.param())));
            values.add(dbValue);
            valueSQLTypes.add(_typeHelper.getSQLType(value));
            _log.info(TABLE_NAME_PREFIX + currentTableIndex + "." + columnName + " is " + dbValue);
        }
    }
    return result;
}
Also used : QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) Variable(org.qi4j.api.query.grammar.Variable) ResultSet(java.sql.ResultSet) Set(java.util.Set) ColumnsFactory(org.sql.generation.api.grammar.factories.ColumnsFactory) ValueComposite(org.qi4j.api.value.ValueComposite) BooleanFactory(org.sql.generation.api.grammar.factories.BooleanFactory) LiteralFactory(org.sql.generation.api.grammar.factories.LiteralFactory) TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory) ColumnReferenceByName(org.sql.generation.api.grammar.query.ColumnReferenceByName) BooleanBuilder(org.sql.generation.api.grammar.builders.booleans.BooleanBuilder) Collection(java.util.Collection) AccessibleObject(java.lang.reflect.AccessibleObject) QNameInfo(org.qi4j.index.sql.support.common.QNameInfo) Property(org.qi4j.api.property.Property)

Example 4 with QueryFactory

use of org.sql.generation.api.grammar.factories.QueryFactory in project qi4j-sdk by Qi4j.

the class AbstractSQLQuerying method processOrderBySegments.

protected void processOrderBySegments(OrderBy[] orderBy, SQLVendor vendor, QuerySpecificationBuilder builder) {
    if (orderBy != null) {
        QNameInfo[] qNames = new QNameInfo[orderBy.length];
        QueryFactory q = vendor.getQueryFactory();
        ColumnsFactory c = vendor.getColumnsFactory();
        Integer tableIndex = 0;
        for (Integer idx = 0; idx < orderBy.length; ++idx) {
            if (orderBy[idx] != null) {
                PropertyFunction<?> ref = orderBy[idx].property();
                QualifiedName qName = QualifiedName.fromAccessor(ref.accessor());
                QNameInfo info = this._state.qNameInfos().get().get(qName);
                qNames[idx] = info;
                if (info == null) {
                    throw new InternalError("No qName info found for qName [" + qName + "].");
                }
                tableIndex = this.traversePropertyPath(ref, 0, tableIndex + 1, vendor, builder.getFrom().getTableReferences().iterator().next(), JoinType.LEFT_OUTER);
                Class<?> declaringType = ((Member) ref.accessor()).getDeclaringClass();
                String colName = null;
                Integer tableIdx = null;
                if (Identity.class.equals(declaringType)) {
                    colName = DBNames.ENTITY_TABLE_IDENTITY_COLUMN_NAME;
                    tableIdx = tableIndex - 1;
                } else {
                    colName = DBNames.QNAME_TABLE_VALUE_COLUMN_NAME;
                    tableIdx = tableIndex;
                }
                Ordering ordering = Ordering.ASCENDING;
                if (orderBy[idx].order() == Order.DESCENDING) {
                    ordering = Ordering.DESCENDING;
                }
                builder.getOrderBy().addSortSpecs(q.sortSpec(c.colName(TABLE_NAME_PREFIX + tableIdx, colName), ordering));
            }
        }
    }
}
Also used : QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) ColumnsFactory(org.sql.generation.api.grammar.factories.ColumnsFactory) QualifiedName(org.qi4j.api.common.QualifiedName) Ordering(org.sql.generation.api.grammar.query.Ordering) QNameInfo(org.qi4j.index.sql.support.common.QNameInfo) Member(java.lang.reflect.Member)

Example 5 with QueryFactory

use of org.sql.generation.api.grammar.factories.QueryFactory in project qi4j-sdk by Qi4j.

the class GenericDatabaseExplorer method visitDatabaseTables.

public static void visitDatabaseTables(Connection connection, String catalogName, String schemaNamePattern, String tableNamePattern, DatabaseProcessor processor, SQLVendor sqlSyntaxVendor) throws SQLException {
    DatabaseMetaData metaData = connection.getMetaData();
    connection.setReadOnly(true);
    ResultSet rs = metaData.getTables(catalogName, schemaNamePattern, tableNamePattern, new String[] { "TABLE" });
    try {
        while (rs.next()) {
            String schemaName = rs.getString(2);
            try {
                processor.beginProcessSchemaInfo(schemaName);
                String tableName = rs.getString(3);
                String tableRemarks = rs.getString(5);
                try {
                    processor.beginProcessTableInfo(schemaName, tableName, tableRemarks);
                    List<ColumnInfo> colInfos = new ArrayList<ColumnInfo>();
                    ResultSet rsCols = metaData.getColumns(null, schemaName, tableName, null);
                    try {
                        while (rsCols.next()) {
                            String nullable = rsCols.getString(18);
                            colInfos.add(new ColumnInfo(rsCols.getString(4), rsCols.getInt(5), rsCols.getString(6), rsCols.getInt(7), rsCols.getInt(9), nullable.length() > 0 ? Boolean.toString(nullable.equals("YES")) : "unknown", rsCols.getString(13), rsCols.getString(12)));
                        }
                    } finally {
                        rsCols.close();
                    }
                    rsCols = metaData.getImportedKeys(null, schemaName, tableName);
                    Map<String, ForeignKeyInfo> fkInfos = new HashMap<String, ForeignKeyInfo>();
                    try {
                        while (rsCols.next()) {
                            fkInfos.put(// 
                            rsCols.getString(8), new ForeignKeyInfo(rsCols.getString(2), rsCols.getString(3), rsCols.getString(4), rsCols.getShort(10), rsCols.getShort(11), rsCols.getShort(14)));
                        }
                    } finally {
                        rsCols.close();
                    }
                    try {
                        processor.beginProcessColumns(schemaName, tableName, tableRemarks);
                        for (ColumnInfo colInfo : colInfos) {
                            try {
                                processor.beginProcessColumnInfo(schemaName, tableName, colInfo, fkInfos.get(colInfo._name));
                            } finally {
                                processor.endProcessColumnInfo(schemaName, tableName, colInfo, fkInfos.get(colInfo._name));
                            }
                        }
                    } finally {
                        processor.endProcessColumns(schemaName, tableName, tableRemarks);
                    }
                    QueryFactory q = sqlSyntaxVendor.getQueryFactory();
                    TableReferenceFactory t = sqlSyntaxVendor.getTableReferenceFactory();
                    QuerySpecificationBuilder builda = q.querySpecificationBuilder();
                    builda.getSelect().selectAll();
                    builda.getFrom().addTableReferences(t.tableBuilder(t.table(t.tableName(schemaName, tableName))));
                    String sql = sqlSyntaxVendor.toString(q.createQuery(builda.createExpression()));
                    Statement stmt = connection.createStatement();
                    ResultSet rowsRs = null;
                    try {
                        rowsRs = stmt.executeQuery(sql);
                        processor.beginProcessRows(schemaName, tableName, tableRemarks);
                        while (rowsRs.next()) {
                            Object[] rowContents = new Object[colInfos.size()];
                            for (Integer x = 0; x < rowContents.length; ++x) {
                                rowContents[x] = rowsRs.getObject(x + 1);
                            }
                            try {
                                processor.beginProcessRowInfo(schemaName, tableName, rowContents);
                            } finally {
                                processor.endProcessRowInfo(schemaName, tableName, rowContents);
                            }
                        }
                    } finally {
                        processor.endProcessRows(schemaName, tableName, tableRemarks);
                        if (rowsRs != null) {
                            rowsRs.close();
                        }
                        stmt.close();
                    }
                } finally {
                    processor.endProcessTableInfo(schemaName, tableName, tableRemarks);
                }
            } finally {
                processor.endProcessSchemaInfo(schemaName);
            }
        }
    } finally {
        SQLUtil.closeQuietly(rs);
    }
}
Also used : QueryFactory(org.sql.generation.api.grammar.factories.QueryFactory) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) QuerySpecificationBuilder(org.sql.generation.api.grammar.builders.query.QuerySpecificationBuilder) TableReferenceFactory(org.sql.generation.api.grammar.factories.TableReferenceFactory)

Aggregations

QueryFactory (org.sql.generation.api.grammar.factories.QueryFactory)11 ColumnsFactory (org.sql.generation.api.grammar.factories.ColumnsFactory)6 TableReferenceFactory (org.sql.generation.api.grammar.factories.TableReferenceFactory)6 QuerySpecificationBuilder (org.sql.generation.api.grammar.builders.query.QuerySpecificationBuilder)5 LiteralFactory (org.sql.generation.api.grammar.factories.LiteralFactory)4 ResultSet (java.sql.ResultSet)3 QueryBuilder (org.sql.generation.api.grammar.builders.query.QueryBuilder)3 BooleanFactory (org.sql.generation.api.grammar.factories.BooleanFactory)3 SQLVendor (org.sql.generation.api.vendor.SQLVendor)3 QNameInfo (org.qi4j.index.sql.support.common.QNameInfo)2 AccessibleObject (java.lang.reflect.AccessibleObject)1 Member (java.lang.reflect.Member)1 PreparedStatement (java.sql.PreparedStatement)1 Statement (java.sql.Statement)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 Set (java.util.Set)1 QualifiedName (org.qi4j.api.common.QualifiedName)1 Property (org.qi4j.api.property.Property)1