Search in sources :

Example 76 with StatementBuilder

use of org.h2.util.StatementBuilder in project h2database by h2database.

the class TableDefinition method update.

void update(Db db, Object obj) {
    if (primaryKeyColumnNames == null || primaryKeyColumnNames.size() == 0) {
        throw new IllegalStateException("No primary key columns defined " + "for table " + obj.getClass() + " - no update possible");
    }
    SQLStatement stat = new SQLStatement(db);
    StatementBuilder buff = new StatementBuilder("UPDATE ");
    buff.append(db.getDialect().getTableName(schemaName, tableName)).append(" SET ");
    buff.resetCount();
    for (FieldDefinition field : fields) {
        if (!field.isPrimaryKey) {
            buff.appendExceptFirst(", ");
            buff.append(field.columnName);
            buff.append(" = ?");
            Object value = getValue(obj, field);
            stat.addParameter(value);
        }
    }
    Object alias = ClassUtils.newObject(obj.getClass());
    Query<Object> query = Query.from(db, alias);
    boolean firstCondition = true;
    for (FieldDefinition field : fields) {
        if (field.isPrimaryKey) {
            Object aliasValue = field.getValue(alias);
            Object value = field.getValue(obj);
            if (!firstCondition) {
                query.addConditionToken(ConditionAndOr.AND);
            }
            firstCondition = false;
            query.addConditionToken(new Condition<>(aliasValue, value, CompareType.EQUAL));
        }
    }
    stat.setSQL(buff.toString());
    query.appendWhere(stat);
    StatementLogger.update(stat.getSQL());
    stat.executeUpdate();
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Example 77 with StatementBuilder

use of org.h2.util.StatementBuilder in project h2database by h2database.

the class TableDefinition method createTableIfRequired.

TableDefinition<T> createTableIfRequired(Db db) {
    if (!createTableIfRequired) {
        // skip table and index creation
        // but still check for upgrades
        db.upgradeTable(this);
        return this;
    }
    SQLDialect dialect = db.getDialect();
    SQLStatement stat = new SQLStatement(db);
    StatementBuilder buff;
    if (memoryTable && dialect.supportsMemoryTables()) {
        buff = new StatementBuilder("CREATE MEMORY TABLE IF NOT EXISTS ");
    } else {
        buff = new StatementBuilder("CREATE TABLE IF NOT EXISTS ");
    }
    buff.append(dialect.getTableName(schemaName, tableName)).append('(');
    for (FieldDefinition field : fields) {
        buff.appendExceptFirst(", ");
        buff.append(field.columnName).append(' ').append(field.dataType);
        if (field.maxLength > 0) {
            buff.append('(').append(field.maxLength).append(')');
        }
        if (field.isAutoIncrement) {
            buff.append(" AUTO_INCREMENT");
        }
        if (!field.allowNull) {
            buff.append(" NOT NULL");
        }
        // default values
        if (!field.isAutoIncrement && !field.isPrimaryKey) {
            String dv = field.defaultValue;
            if (!StringUtils.isNullOrEmpty(dv)) {
                if (ModelUtils.isProperlyFormattedDefaultValue(dv) && ModelUtils.isValidDefaultValue(field.field.getType(), dv)) {
                    buff.append(" DEFAULT " + dv);
                }
            }
        }
    }
    // primary key
    if (primaryKeyColumnNames != null && primaryKeyColumnNames.size() > 0) {
        buff.append(", PRIMARY KEY(");
        buff.resetCount();
        for (String n : primaryKeyColumnNames) {
            buff.appendExceptFirst(", ");
            buff.append(n);
        }
        buff.append(')');
    }
    buff.append(')');
    stat.setSQL(buff.toString());
    StatementLogger.create(stat.getSQL());
    stat.executeUpdate();
    // create indexes
    for (IndexDefinition index : indexes) {
        String sql = db.getDialect().getCreateIndex(schemaName, tableName, index);
        stat.setSQL(sql);
        StatementLogger.create(stat.getSQL());
        stat.executeUpdate();
    }
    // tables are created using IF NOT EXISTS
    // but we may still need to upgrade
    db.upgradeTable(this);
    return this;
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Example 78 with StatementBuilder

use of org.h2.util.StatementBuilder in project h2database by h2database.

the class TableInspector method generateColumn.

private StatementBuilder generateColumn(Set<String> imports, ColumnInspector col, boolean trimStrings) {
    StatementBuilder sb = new StatementBuilder();
    Class<?> clazz = col.clazz;
    String column = ModelUtils.convertColumnToFieldName(col.name.toLowerCase());
    sb.append('\t');
    if (clazz == null) {
        // unsupported type
        clazz = Object.class;
        sb.append("// unsupported type " + col.type);
    } else {
        // @JQColumn
        imports.add(clazz.getCanonicalName());
        sb.append('@').append(JQColumn.class.getSimpleName());
        // JQColumn annotation parameters
        AnnotationBuilder ap = new AnnotationBuilder();
        // JQColumn.name
        if (!col.name.equalsIgnoreCase(column)) {
            ap.addParameter("name", col.name);
        }
        // composite primary keys are annotated on the table
        if (col.isPrimaryKey && primaryKeys.size() == 1) {
            ap.addParameter("primaryKey=true");
        }
        // JQColumn.maxLength
        if ((clazz == String.class) && (col.size > 0) && (col.size < Integer.MAX_VALUE)) {
            ap.addParameter("maxLength", col.size);
            // JQColumn.trimStrings
            if (trimStrings) {
                ap.addParameter("trimString=true");
            }
        } else {
            // JQColumn.AutoIncrement
            if (col.isAutoIncrement) {
                ap.addParameter("autoIncrement=true");
            }
        }
        // JQColumn.allowNull
        if (!col.allowNull) {
            ap.addParameter("allowNull=false");
        }
        // JQColumn.defaultValue
        if (!StringUtils.isNullOrEmpty(col.defaultValue)) {
            ap.addParameter("defaultValue=\"" + col.defaultValue + "\"");
        }
        // add leading and trailing ()
        if (ap.length() > 0) {
            AnnotationBuilder b = new AnnotationBuilder();
            b.append('(').append(ap.toString()).append(')');
            ap = b;
        }
        sb.append(ap.toString());
    }
    sb.append(EOL);
    // variable declaration
    sb.append("\t" + "public ");
    sb.append(clazz.getSimpleName());
    sb.append(' ');
    sb.append(column);
    sb.append(';');
    sb.append(EOL).append(EOL);
    return sb;
}
Also used : StatementBuilder(org.h2.util.StatementBuilder) JQColumn(org.h2.jaqu.Table.JQColumn)

Example 79 with StatementBuilder

use of org.h2.util.StatementBuilder in project h2database by h2database.

the class TestOptimizerHints method checkPlanComma.

private void checkPlanComma(Statement s, String... t) throws SQLException {
    StatementBuilder from = new StatementBuilder();
    for (String table : t) {
        from.appendExceptFirst(", ");
        from.append(table);
    }
    String plan = plan(s, "select 1 from " + from.toString() + " where t1.id = t2.t1_id " + "and t2.id = t4.t2_id and t3.id = t4.t3_id");
    int prev = plan.indexOf("FROM PUBLIC." + t[0].toUpperCase());
    for (int i = 1; i < t.length; i++) {
        int next = plan.indexOf("INNER JOIN PUBLIC." + t[i].toUpperCase());
        assertTrue("Wrong plan for : " + Arrays.toString(t) + "\n" + plan, next > prev);
        prev = next;
    }
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Example 80 with StatementBuilder

use of org.h2.util.StatementBuilder in project h2database by h2database.

the class TestOptimizerHints method checkPlanJoin.

private void checkPlanJoin(Statement s, boolean on, boolean left, String... t) throws SQLException {
    StatementBuilder from = new StatementBuilder();
    for (int i = 0; i < t.length; i++) {
        if (i != 0) {
            if (left) {
                from.append(" left join ");
            } else {
                from.append(" inner join ");
            }
        }
        from.append(t[i]);
        if (on && i != 0) {
            from.append(" on 1=1 ");
        }
    }
    String plan = plan(s, "select 1 from " + from.toString() + " where t1.id = t2.t1_id " + "and t2.id = t4.t2_id and t3.id = t4.t3_id");
    int prev = plan.indexOf("FROM PUBLIC." + t[0].toUpperCase());
    for (int i = 1; i < t.length; i++) {
        int next = plan.indexOf((!left ? "INNER JOIN PUBLIC." : on ? "LEFT OUTER JOIN PUBLIC." : "PUBLIC.") + t[i].toUpperCase());
        if (prev > next) {
            System.err.println(plan);
            fail("Wrong plan for : " + Arrays.toString(t) + "\n" + plan);
        }
        prev = next;
    }
}
Also used : StatementBuilder(org.h2.util.StatementBuilder)

Aggregations

StatementBuilder (org.h2.util.StatementBuilder)82 Value (org.h2.value.Value)16 Column (org.h2.table.Column)15 IndexColumn (org.h2.table.IndexColumn)11 PreparedStatement (java.sql.PreparedStatement)9 Expression (org.h2.expression.Expression)9 ValueString (org.h2.value.ValueString)7 Index (org.h2.index.Index)6 DbException (org.h2.message.DbException)6 ResultSet (java.sql.ResultSet)5 Row (org.h2.result.Row)4 SQLException (java.sql.SQLException)3 ArrayList (java.util.ArrayList)3 Constraint (org.h2.constraint.Constraint)3 Database (org.h2.engine.Database)3 ExpressionColumn (org.h2.expression.ExpressionColumn)3 HashMap (java.util.HashMap)2 SelectOrderBy (org.h2.command.dml.SelectOrderBy)2 ResultInterface (org.h2.result.ResultInterface)2 SearchRow (org.h2.result.SearchRow)2