Search in sources :

Example 81 with Column

use of org.h2.table.Column in project h2database by h2database.

the class TableFilter method getSystemColumns.

/**
 * Get the system columns that this table understands. This is used for
 * compatibility with other databases. The columns are only returned if the
 * current mode supports system columns.
 *
 * @return the system columns
 */
@Override
public Column[] getSystemColumns() {
    if (!session.getDatabase().getMode().systemColumns) {
        return null;
    }
    Column[] sys = new Column[3];
    sys[0] = new Column("oid", Value.INT);
    sys[0].setTable(table, 0);
    sys[1] = new Column("ctid", Value.STRING);
    sys[1].setTable(table, 0);
    sys[2] = new Column("CTID", Value.STRING);
    sys[2].setTable(table, 0);
    return sys;
}
Also used : ExpressionColumn(org.h2.expression.ExpressionColumn)

Example 82 with Column

use of org.h2.table.Column in project h2database by h2database.

the class TableLink method readMetaData.

private void readMetaData() throws SQLException {
    DatabaseMetaData meta = conn.getConnection().getMetaData();
    storesLowerCase = meta.storesLowerCaseIdentifiers();
    storesMixedCase = meta.storesMixedCaseIdentifiers();
    storesMixedCaseQuoted = meta.storesMixedCaseQuotedIdentifiers();
    supportsMixedCaseIdentifiers = meta.supportsMixedCaseIdentifiers();
    ResultSet rs = meta.getTables(null, originalSchema, originalTable, null);
    if (rs.next() && rs.next()) {
        throw DbException.get(ErrorCode.SCHEMA_NAME_MUST_MATCH, originalTable);
    }
    rs.close();
    rs = meta.getColumns(null, originalSchema, originalTable, null);
    int i = 0;
    ArrayList<Column> columnList = New.arrayList();
    HashMap<String, Column> columnMap = new HashMap<>();
    String catalog = null, schema = null;
    while (rs.next()) {
        String thisCatalog = rs.getString("TABLE_CAT");
        if (catalog == null) {
            catalog = thisCatalog;
        }
        String thisSchema = rs.getString("TABLE_SCHEM");
        if (schema == null) {
            schema = thisSchema;
        }
        if (!Objects.equals(catalog, thisCatalog) || !Objects.equals(schema, thisSchema)) {
            // if the table exists in multiple schemas or tables,
            // use the alternative solution
            columnMap.clear();
            columnList.clear();
            break;
        }
        String n = rs.getString("COLUMN_NAME");
        n = convertColumnName(n);
        int sqlType = rs.getInt("DATA_TYPE");
        String sqlTypeName = rs.getString("TYPE_NAME");
        long precision = rs.getInt("COLUMN_SIZE");
        precision = convertPrecision(sqlType, precision);
        int scale = rs.getInt("DECIMAL_DIGITS");
        scale = convertScale(sqlType, scale);
        int displaySize = MathUtils.convertLongToInt(precision);
        int type = DataType.convertSQLTypeToValueType(sqlType, sqlTypeName);
        Column col = new Column(n, type, precision, scale, displaySize);
        col.setTable(this, i++);
        columnList.add(col);
        columnMap.put(n, col);
    }
    rs.close();
    if (originalTable.indexOf('.') < 0 && !StringUtils.isNullOrEmpty(schema)) {
        qualifiedTableName = schema + "." + originalTable;
    } else {
        qualifiedTableName = originalTable;
    }
    try (Statement stat = conn.getConnection().createStatement()) {
        rs = stat.executeQuery("SELECT * FROM " + qualifiedTableName + " T WHERE 1=0");
        if (columnList.isEmpty()) {
            // alternative solution
            ResultSetMetaData rsMeta = rs.getMetaData();
            for (i = 0; i < rsMeta.getColumnCount(); ) {
                String n = rsMeta.getColumnName(i + 1);
                n = convertColumnName(n);
                int sqlType = rsMeta.getColumnType(i + 1);
                long precision = rsMeta.getPrecision(i + 1);
                precision = convertPrecision(sqlType, precision);
                int scale = rsMeta.getScale(i + 1);
                scale = convertScale(sqlType, scale);
                int displaySize = rsMeta.getColumnDisplaySize(i + 1);
                int type = DataType.getValueTypeFromResultSet(rsMeta, i + 1);
                Column col = new Column(n, type, precision, scale, displaySize);
                col.setTable(this, i++);
                columnList.add(col);
                columnMap.put(n, col);
            }
        }
        rs.close();
    } catch (Exception e) {
        throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, e, originalTable + "(" + e.toString() + ")");
    }
    Column[] cols = columnList.toArray(new Column[0]);
    setColumns(cols);
    int id = getId();
    linkedIndex = new LinkedIndex(this, id, IndexColumn.wrap(cols), IndexType.createNonUnique(false));
    indexes.add(linkedIndex);
    try {
        rs = meta.getPrimaryKeys(null, originalSchema, originalTable);
    } catch (Exception e) {
        // Some ODBC bridge drivers don't support it:
        // some combinations of "DataDirect SequeLink(R) for JDBC"
        // http://www.datadirect.com/index.ssp
        rs = null;
    }
    String pkName = "";
    ArrayList<Column> list;
    if (rs != null && rs.next()) {
        // the problem is, the rows are not sorted by KEY_SEQ
        list = New.arrayList();
        do {
            int idx = rs.getInt("KEY_SEQ");
            if (pkName == null) {
                pkName = rs.getString("PK_NAME");
            }
            while (list.size() < idx) {
                list.add(null);
            }
            String col = rs.getString("COLUMN_NAME");
            col = convertColumnName(col);
            Column column = columnMap.get(col);
            if (idx == 0) {
                // workaround for a bug in the SQLite JDBC driver
                list.add(column);
            } else {
                list.set(idx - 1, column);
            }
        } while (rs.next());
        addIndex(list, IndexType.createPrimaryKey(false, false));
        rs.close();
    }
    try {
        rs = meta.getIndexInfo(null, originalSchema, originalTable, false, true);
    } catch (Exception e) {
        // Oracle throws an exception if the table is not found or is a
        // SYNONYM
        rs = null;
    }
    String indexName = null;
    list = New.arrayList();
    IndexType indexType = null;
    if (rs != null) {
        while (rs.next()) {
            if (rs.getShort("TYPE") == DatabaseMetaData.tableIndexStatistic) {
                // ignore index statistics
                continue;
            }
            String newIndex = rs.getString("INDEX_NAME");
            if (pkName.equals(newIndex)) {
                continue;
            }
            if (indexName != null && !indexName.equals(newIndex)) {
                addIndex(list, indexType);
                indexName = null;
            }
            if (indexName == null) {
                indexName = newIndex;
                list.clear();
            }
            boolean unique = !rs.getBoolean("NON_UNIQUE");
            indexType = unique ? IndexType.createUnique(false, false) : IndexType.createNonUnique(false);
            String col = rs.getString("COLUMN_NAME");
            col = convertColumnName(col);
            Column column = columnMap.get(col);
            list.add(column);
        }
        rs.close();
    }
    if (indexName != null) {
        addIndex(list, indexType);
    }
}
Also used : HashMap(java.util.HashMap) LinkedIndex(org.h2.index.LinkedIndex) PreparedStatement(java.sql.PreparedStatement) Statement(java.sql.Statement) DatabaseMetaData(java.sql.DatabaseMetaData) DbException(org.h2.message.DbException) SQLException(java.sql.SQLException) JdbcSQLException(org.h2.jdbc.JdbcSQLException) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) IndexType(org.h2.index.IndexType)

Example 83 with Column

use of org.h2.table.Column in project h2database by h2database.

the class TableLink method validateConvertUpdateSequence.

/**
 * Convert the values if required. Default values are not set (kept as
 * null).
 *
 * @param session the session
 * @param row the row
 */
@Override
public void validateConvertUpdateSequence(Session session, Row row) {
    for (int i = 0; i < columns.length; i++) {
        Value value = row.getValue(i);
        if (value != null) {
            // null means use the default value
            Column column = columns[i];
            Value v2 = column.validateConvertUpdateSequence(session, value);
            if (v2 != value) {
                row.setValue(i, v2);
            }
        }
    }
}
Also used : Value(org.h2.value.Value)

Example 84 with Column

use of org.h2.table.Column in project h2database by h2database.

the class TableView method getCreateSQL.

private String getCreateSQL(boolean orReplace, boolean force, String quotedName) {
    StatementBuilder buff = new StatementBuilder("CREATE ");
    if (orReplace) {
        buff.append("OR REPLACE ");
    }
    if (force) {
        buff.append("FORCE ");
    }
    buff.append("VIEW ");
    if (isTableExpression) {
        buff.append("TABLE_EXPRESSION ");
    }
    buff.append(quotedName);
    if (comment != null) {
        buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
    }
    if (columns != null && columns.length > 0) {
        buff.append('(');
        for (Column c : columns) {
            buff.appendExceptFirst(", ");
            buff.append(c.getSQL());
        }
        buff.append(')');
    } else if (columnTemplates != null) {
        buff.append('(');
        for (Column c : columnTemplates) {
            buff.appendExceptFirst(", ");
            buff.append(c.getName());
        }
        buff.append(')');
    }
    return buff.append(" AS\n").append(querySQL).toString();
}
Also used : ExpressionColumn(org.h2.expression.ExpressionColumn) StatementBuilder(org.h2.util.StatementBuilder)

Example 85 with Column

use of org.h2.table.Column in project h2database by h2database.

the class TableView method createTempView.

/**
 * Create a temporary view out of the given query.
 *
 * @param session the session
 * @param owner the owner of the query
 * @param name the view name
 * @param query the query
 * @param topQuery the top level query
 * @return the view table
 */
public static TableView createTempView(Session session, User owner, String name, Query query, Query topQuery) {
    Schema mainSchema = session.getDatabase().getSchema(Constants.SCHEMA_MAIN);
    String querySQL = query.getPlanSQL();
    TableView v = new TableView(mainSchema, 0, name, querySQL, query.getParameters(), null, /* column templates */
    session, false, /* allow recursive */
    true, /* literals have already been checked when parsing original query */
    false, /* is table expression */
    false);
    if (v.createException != null) {
        throw v.createException;
    }
    v.setTopQuery(topQuery);
    v.setOwner(owner);
    v.setTemporary(true);
    return v;
}
Also used : Schema(org.h2.schema.Schema)

Aggregations

Column (org.h2.table.Column)146 Value (org.h2.value.Value)83 IndexColumn (org.h2.table.IndexColumn)79 DbException (org.h2.message.DbException)64 SQLException (java.sql.SQLException)60 Expression (org.h2.expression.Expression)55 ExpressionColumn (org.h2.expression.ExpressionColumn)51 ValueString (org.h2.value.ValueString)34 AlterTableAlterColumn (org.h2.command.ddl.AlterTableAlterColumn)32 ValueExpression (org.h2.expression.ValueExpression)30 ArrayList (java.util.ArrayList)27 PreparedStatement (java.sql.PreparedStatement)26 Index (org.h2.index.Index)26 IgniteSQLException (org.apache.ignite.internal.processors.query.IgniteSQLException)25 Table (org.h2.table.Table)25 AlterTableRenameColumn (org.h2.command.ddl.AlterTableRenameColumn)22 GridH2Table (org.apache.ignite.internal.processors.query.h2.opt.GridH2Table)21 AlterTableAddConstraint (org.h2.command.ddl.AlterTableAddConstraint)21 StatementBuilder (org.h2.util.StatementBuilder)19 Constraint (org.h2.constraint.Constraint)18