Search in sources :

Example 31 with Column

use of org.h2.table.Column in project ignite by apache.

the class DdlStatementsProcessor method toQueryEntity.

/**
 * Convert this statement to query entity and do Ignite specific sanity checks on the way.
 * @return Query entity mimicking this SQL statement.
 */
private static QueryEntity toQueryEntity(GridSqlCreateTable createTbl) {
    QueryEntity res = new QueryEntity();
    res.setTableName(createTbl.tableName());
    Set<String> notNullFields = null;
    HashMap<String, Object> dfltValues = new HashMap<>();
    for (Map.Entry<String, GridSqlColumn> e : createTbl.columns().entrySet()) {
        GridSqlColumn gridCol = e.getValue();
        Column col = gridCol.column();
        res.addQueryField(e.getKey(), DataType.getTypeClassName(col.getType()), null);
        if (!col.isNullable()) {
            if (notNullFields == null)
                notNullFields = new HashSet<>();
            notNullFields.add(e.getKey());
        }
        Object dfltVal = gridCol.defaultValue();
        if (dfltVal != null)
            dfltValues.put(e.getKey(), dfltVal);
    }
    if (!F.isEmpty(dfltValues))
        res.setDefaultFieldValues(dfltValues);
    String valTypeName = QueryUtils.createTableValueTypeName(createTbl.schemaName(), createTbl.tableName());
    String keyTypeName = QueryUtils.createTableKeyTypeName(valTypeName);
    if (!F.isEmpty(createTbl.keyTypeName()))
        keyTypeName = createTbl.keyTypeName();
    if (!F.isEmpty(createTbl.valueTypeName()))
        valTypeName = createTbl.valueTypeName();
    assert createTbl.wrapKey() != null;
    assert createTbl.wrapValue() != null;
    if (!createTbl.wrapKey()) {
        GridSqlColumn pkCol = createTbl.columns().get(createTbl.primaryKeyColumns().iterator().next());
        keyTypeName = DataType.getTypeClassName(pkCol.column().getType());
        res.setKeyFieldName(pkCol.columnName());
    } else
        res.setKeyFields(createTbl.primaryKeyColumns());
    if (!createTbl.wrapValue()) {
        GridSqlColumn valCol = null;
        for (Map.Entry<String, GridSqlColumn> e : createTbl.columns().entrySet()) {
            if (!createTbl.primaryKeyColumns().contains(e.getKey())) {
                valCol = e.getValue();
                break;
            }
        }
        assert valCol != null;
        valTypeName = DataType.getTypeClassName(valCol.column().getType());
        res.setValueFieldName(valCol.columnName());
    }
    res.setValueType(valTypeName);
    res.setKeyType(keyTypeName);
    if (!F.isEmpty(notNullFields)) {
        QueryEntityEx res0 = new QueryEntityEx(res);
        res0.setNotNullFields(notNullFields);
        res = res0;
    }
    return res;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) AlterTableAlterColumn(org.h2.command.ddl.AlterTableAlterColumn) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) Column(org.h2.table.Column) GridSqlAlterTableAddColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableAddColumn) SqlIndexColumn(org.apache.ignite.internal.sql.command.SqlIndexColumn) GridSqlAlterTableDropColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlterTableDropColumn) QueryEntityEx(org.apache.ignite.internal.processors.query.QueryEntityEx) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) QueryEntity(org.apache.ignite.cache.QueryEntity) Map(java.util.Map) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HashSet(java.util.HashSet)

Example 32 with Column

use of org.h2.table.Column in project ignite by apache.

the class DmlAstUtils method selectForUpdate.

/**
 * Generate SQL SELECT based on UPDATE's WHERE, LIMIT, etc.
 *
 * @param update Update statement.
 * @param keysParamIdx Index of new param for the array of keys.
 * @return SELECT statement.
 */
public static GridSqlSelect selectForUpdate(GridSqlUpdate update, @Nullable Integer keysParamIdx) {
    GridSqlSelect mapQry = new GridSqlSelect();
    mapQry.from(update.target());
    Set<GridSqlTable> tbls = new HashSet<>();
    collectAllGridTablesInTarget(update.target(), tbls);
    assert tbls.size() == 1 : "Failed to determine target table for UPDATE";
    GridSqlTable tbl = tbls.iterator().next();
    GridH2Table gridTbl = tbl.dataTable();
    assert gridTbl != null : "Failed to determine target grid table for UPDATE";
    Column h2KeyCol = gridTbl.getColumn(GridH2KeyValueRowOnheap.KEY_COL);
    Column h2ValCol = gridTbl.getColumn(GridH2KeyValueRowOnheap.VAL_COL);
    GridSqlColumn keyCol = new GridSqlColumn(h2KeyCol, tbl, h2KeyCol.getName());
    keyCol.resultType(GridSqlType.fromColumn(h2KeyCol));
    GridSqlColumn valCol = new GridSqlColumn(h2ValCol, tbl, h2ValCol.getName());
    valCol.resultType(GridSqlType.fromColumn(h2ValCol));
    mapQry.addColumn(keyCol, true);
    mapQry.addColumn(valCol, true);
    for (GridSqlColumn c : update.cols()) {
        String newColName = Parser.quoteIdentifier("_upd_" + c.columnName());
        // We have to use aliases to cover cases when the user
        // wants to update _val field directly (if it's a literal)
        GridSqlAlias alias = new GridSqlAlias(newColName, elementOrDefault(update.set().get(c.columnName()), c), true);
        alias.resultType(c.resultType());
        mapQry.addColumn(alias, true);
    }
    GridSqlElement where = update.where();
    if (keysParamIdx != null)
        where = injectKeysFilterParam(where, keyCol, keysParamIdx);
    mapQry.where(where);
    mapQry.limit(update.limit());
    return mapQry;
}
Also used : GridSqlAlias(org.apache.ignite.internal.processors.query.h2.sql.GridSqlAlias) Column(org.h2.table.Column) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlTable(org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable) GridH2Table(org.apache.ignite.internal.processors.query.h2.opt.GridH2Table) GridSqlColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn) GridSqlElement(org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement) ValueString(org.h2.value.ValueString) GridSqlSelect(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSelect) HashSet(java.util.HashSet)

Example 33 with Column

use of org.h2.table.Column in project elastic-core-maven by OrdinaryDude.

the class FullTextTrigger method init.

/**
 * Initialize the trigger (Trigger interface)
 *
 * @param   conn                Database connection
 * @param   schema              Database schema name
 * @param   trigger             Database trigger name
 * @param   table               Database table name
 * @param   before              TRUE if trigger is called before database operation
 * @param   type                Trigger type
 * @throws  SQLException        A SQL error occurred
 */
@Override
public void init(Connection conn, String schema, String trigger, String table, boolean before, int type) throws SQLException {
    // 
    if (!isActive || table.contains("_COPY_")) {
        return;
    }
    // 
    // Access the Lucene index
    // 
    // We need to get the access just once, either in a trigger or in a function alias
    // 
    getIndexAccess(conn);
    // 
    // Get table and index information
    // 
    tableName = schema + "." + table;
    try (Statement stmt = conn.createStatement()) {
        // 
        try (ResultSet rs = stmt.executeQuery("SHOW COLUMNS FROM " + table + " FROM " + schema)) {
            int index = 0;
            while (rs.next()) {
                String columnName = rs.getString("FIELD");
                String columnType = rs.getString("TYPE");
                columnType = columnType.substring(0, columnType.indexOf('('));
                columnNames.add(columnName);
                columnTypes.add(columnType);
                if (columnName.equals("DB_ID")) {
                    dbColumn = index;
                }
                index++;
            }
        }
        if (dbColumn < 0) {
            Logger.logErrorMessage("DB_ID column not found for table " + tableName);
            return;
        }
        // 
        try (ResultSet rs = stmt.executeQuery(String.format("SELECT COLUMNS FROM FTL.INDEXES WHERE SCHEMA = '%s' AND TABLE = '%s'", schema, table))) {
            if (rs.next()) {
                String[] columns = rs.getString(1).split(",");
                for (String column : columns) {
                    int pos = columnNames.indexOf(column);
                    if (pos >= 0) {
                        if (columnTypes.get(pos).equals("VARCHAR")) {
                            indexColumns.add(pos);
                        } else {
                            Logger.logErrorMessage("Indexed column " + column + " in table " + tableName + " is not a string");
                        }
                    } else {
                        Logger.logErrorMessage("Indexed column " + column + " not found in table " + tableName);
                    }
                }
            }
        }
        if (indexColumns.isEmpty()) {
            Logger.logErrorMessage("No indexed columns found for table " + tableName);
            return;
        }
        // 
        // Trigger is enabled
        // 
        isEnabled = true;
        indexTriggers.put(tableName, this);
    } catch (SQLException exc) {
        Logger.logErrorMessage("Unable to get table information", exc);
    }
}
Also used : SQLException(java.sql.SQLException) Statement(java.sql.Statement) SimpleResultSet(org.h2.tools.SimpleResultSet) ResultSet(java.sql.ResultSet)

Example 34 with Column

use of org.h2.table.Column in project ignite by apache.

the class GridQueryParsingTest method cn.

/**
 * Constructs non-nullable column.
 *
 * @param name Column name.
 * @param type Column data type.
 * @return {@link GridSqlColumn} with given name and type.
 */
private static GridSqlColumn cn(String name, int type) {
    Column col = new Column(name, type);
    col.setNullable(false);
    return new GridSqlColumn(col, null, name);
}
Also used : Column(org.h2.table.Column)

Example 35 with Column

use of org.h2.table.Column in project ignite by apache.

the class GridReduceQueryExecutor method createMergeTable.

/**
 * @param conn Connection.
 * @param qry Query.
 * @param explain Explain.
 * @return Table.
 * @throws IgniteCheckedException If failed.
 */
@SuppressWarnings("unchecked")
private GridMergeTable createMergeTable(JdbcConnection conn, GridCacheSqlQuery qry, boolean explain) throws IgniteCheckedException {
    try {
        Session ses = (Session) conn.getSession();
        CreateTableData data = new CreateTableData();
        data.tableName = "T___";
        data.schema = ses.getDatabase().getSchema(ses.getCurrentSchemaName());
        data.create = true;
        if (!explain) {
            LinkedHashMap<String, ?> colsMap = qry.columns();
            assert colsMap != null;
            ArrayList<Column> cols = new ArrayList<>(colsMap.size());
            for (Map.Entry<String, ?> e : colsMap.entrySet()) {
                String alias = e.getKey();
                GridSqlType t = (GridSqlType) e.getValue();
                assert !F.isEmpty(alias);
                Column c = new Column(alias, t.type(), t.precision(), t.scale(), t.displaySize());
                cols.add(c);
            }
            data.columns = cols;
        } else
            data.columns = planColumns();
        boolean sortedIndex = !F.isEmpty(qry.sortColumns());
        GridMergeTable tbl = new GridMergeTable(data);
        ArrayList<Index> idxs = new ArrayList<>(2);
        if (explain) {
            idxs.add(new GridMergeIndexUnsorted(ctx, tbl, sortedIndex ? MERGE_INDEX_SORTED : MERGE_INDEX_UNSORTED));
        } else if (sortedIndex) {
            List<GridSqlSortColumn> sortCols = (List<GridSqlSortColumn>) qry.sortColumns();
            GridMergeIndexSorted sortedMergeIdx = new GridMergeIndexSorted(ctx, tbl, MERGE_INDEX_SORTED, GridSqlSortColumn.toIndexColumns(tbl, sortCols));
            idxs.add(GridMergeTable.createScanIndex(sortedMergeIdx));
            idxs.add(sortedMergeIdx);
        } else
            idxs.add(new GridMergeIndexUnsorted(ctx, tbl, MERGE_INDEX_UNSORTED));
        tbl.indexes(idxs);
        return tbl;
    } catch (Exception e) {
        U.closeQuiet(conn);
        throw new IgniteCheckedException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) Index(org.h2.index.Index) CreateTableData(org.h2.command.ddl.CreateTableData) QueryCancelledException(org.apache.ignite.cache.query.QueryCancelledException) IgniteClientDisconnectedException(org.apache.ignite.IgniteClientDisconnectedException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IgniteException(org.apache.ignite.IgniteException) SQLException(java.sql.SQLException) IgniteInterruptedCheckedException(org.apache.ignite.internal.IgniteInterruptedCheckedException) CacheException(javax.cache.CacheException) TransactionException(org.apache.ignite.transactions.TransactionException) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) Column(org.h2.table.Column) GridSqlSortColumn(org.apache.ignite.internal.processors.query.h2.sql.GridSqlSortColumn) GridSqlType(org.apache.ignite.internal.processors.query.h2.sql.GridSqlType) Collections.singletonList(java.util.Collections.singletonList) GridIntList(org.apache.ignite.internal.util.GridIntList) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ConcurrentMap(java.util.concurrent.ConcurrentMap) LinkedHashMap(java.util.LinkedHashMap) Session(org.h2.engine.Session)

Aggregations

Column (org.h2.table.Column)29 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)16 IndexColumn (org.h2.table.IndexColumn)15 GridH2RowDescriptor (org.apache.ignite.internal.processors.query.h2.opt.GridH2RowDescriptor)12 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)11 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)8 ExpressionColumn (org.h2.expression.ExpressionColumn)8 ArrayList (java.util.ArrayList)7 GridSqlColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlColumn)7 GridSqlType.fromColumn (org.apache.ignite.internal.processors.query.h2.sql.GridSqlType.fromColumn)7 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)7 Expression (org.h2.expression.Expression)7 HashMap (java.util.HashMap)6 IgniteCheckedException (org.apache.ignite.IgniteCheckedException)6 HashSet (java.util.HashSet)5 LinkedHashMap (java.util.LinkedHashMap)5 IgniteException (org.apache.ignite.IgniteException)5 GridSqlElement (org.apache.ignite.internal.processors.query.h2.sql.GridSqlElement)5 GridSqlTable (org.apache.ignite.internal.processors.query.h2.sql.GridSqlTable)5 ValueExpression (org.h2.expression.ValueExpression)5