提交 1452e9ba authored 作者: Thomas Mueller's avatar Thomas Mueller

--no commit message

--no commit message
上级 dd7fba44
...@@ -4166,9 +4166,9 @@ public class Parser { ...@@ -4166,9 +4166,9 @@ public class Parser {
} }
private Prepared parseAlterTableAddConstraintIf(String tableName, Schema schema) throws SQLException { private Prepared parseAlterTableAddConstraintIf(String tableName, Schema schema) throws SQLException {
String name = null, comment = null; String constraintName = null, comment = null;
if (readIf("CONSTRAINT")) { if (readIf("CONSTRAINT")) {
name = readIdentifierWithSchema(schema.getName()); constraintName = readIdentifierWithSchema(schema.getName());
checkSchema(schema); checkSchema(schema);
comment = readCommentIf(); comment = readCommentIf();
} }
...@@ -4176,6 +4176,7 @@ public class Parser { ...@@ -4176,6 +4176,7 @@ public class Parser {
read("KEY"); read("KEY");
CreateIndex command = new CreateIndex(session, schema); CreateIndex command = new CreateIndex(session, schema);
command.setComment(comment); command.setComment(comment);
command.setConstraintName(constraintName);
command.setTableName(tableName); command.setTableName(tableName);
command.setPrimaryKey(true); command.setPrimaryKey(true);
if (readIf("HASH")) { if (readIf("HASH")) {
...@@ -4206,10 +4207,10 @@ public class Parser { ...@@ -4206,10 +4207,10 @@ public class Parser {
command = new AlterTableAddConstraint(session, schema); command = new AlterTableAddConstraint(session, schema);
command.setType(AlterTableAddConstraint.UNIQUE); command.setType(AlterTableAddConstraint.UNIQUE);
if (!readIf("(")) { if (!readIf("(")) {
name = readUniqueIdentifier(); constraintName = readUniqueIdentifier();
read("("); read("(");
} }
command.setColumnNames(parseColumnList()); command.setIndexColumns(parseIndexColumnList());
if (readIf("INDEX")) { if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema(); String indexName = readIdentifierWithSchema();
command.setIndex(getSchema().findIndex(indexName)); command.setIndex(getSchema().findIndex(indexName));
...@@ -4219,8 +4220,7 @@ public class Parser { ...@@ -4219,8 +4220,7 @@ public class Parser {
command.setType(AlterTableAddConstraint.REFERENTIAL); command.setType(AlterTableAddConstraint.REFERENTIAL);
read("KEY"); read("KEY");
read("("); read("(");
String[] cols = parseColumnList(); command.setIndexColumns(parseIndexColumnList());
command.setColumnNames(cols);
if (readIf("INDEX")) { if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema(); String indexName = readIdentifierWithSchema();
command.setIndex(schema.findIndex(indexName)); command.setIndex(schema.findIndex(indexName));
...@@ -4228,7 +4228,7 @@ public class Parser { ...@@ -4228,7 +4228,7 @@ public class Parser {
read("REFERENCES"); read("REFERENCES");
parseReferences(command, schema, tableName); parseReferences(command, schema, tableName);
} else { } else {
if (name != null) { if (constraintName != null) {
throw getSyntaxError(); throw getSyntaxError();
} }
return null; return null;
...@@ -4240,23 +4240,20 @@ public class Parser { ...@@ -4240,23 +4240,20 @@ public class Parser {
command.setCheckExisting(true); command.setCheckExisting(true);
} }
command.setTableName(tableName); command.setTableName(tableName);
command.setConstraintName(name); command.setConstraintName(constraintName);
command.setComment(comment); command.setComment(comment);
return command; return command;
} }
private void parseReferences(AlterTableAddConstraint command, Schema schema, String tableName) throws SQLException { private void parseReferences(AlterTableAddConstraint command, Schema schema, String tableName) throws SQLException {
String[] cols;
if (readIf("(")) { if (readIf("(")) {
command.setRefTableName(schema, tableName); command.setRefTableName(schema, tableName);
cols = parseColumnList(); command.setRefIndexColumns(parseIndexColumnList());
command.setRefColumnNames(cols);
} else { } else {
String refTableName = readIdentifierWithSchema(schema.getName()); String refTableName = readIdentifierWithSchema(schema.getName());
command.setRefTableName(getSchema(), refTableName); command.setRefTableName(getSchema(), refTableName);
if (readIf("(")) { if (readIf("(")) {
cols = parseColumnList(); command.setRefIndexColumns(parseIndexColumnList());
command.setRefColumnNames(cols);
} }
} }
if (readIf("INDEX")) { if (readIf("INDEX")) {
...@@ -4357,7 +4354,9 @@ public class Parser { ...@@ -4357,7 +4354,9 @@ public class Parser {
AlterTableAddConstraint unique = new AlterTableAddConstraint(session, schema); AlterTableAddConstraint unique = new AlterTableAddConstraint(session, schema);
unique.setConstraintName(constraintName); unique.setConstraintName(constraintName);
unique.setType(AlterTableAddConstraint.UNIQUE); unique.setType(AlterTableAddConstraint.UNIQUE);
unique.setColumnNames(new String[] { columnName }); IndexColumn[] cols = new IndexColumn[]{new IndexColumn()};
cols[0].columnName = columnName;
unique.setIndexColumns(cols);
unique.setTableName(tableName); unique.setTableName(tableName);
command.addConstraintCommand(unique); command.addConstraintCommand(unique);
} }
...@@ -4369,7 +4368,9 @@ public class Parser { ...@@ -4369,7 +4368,9 @@ public class Parser {
AlterTableAddConstraint ref = new AlterTableAddConstraint(session, schema); AlterTableAddConstraint ref = new AlterTableAddConstraint(session, schema);
ref.setConstraintName(constraintName); ref.setConstraintName(constraintName);
ref.setType(AlterTableAddConstraint.REFERENTIAL); ref.setType(AlterTableAddConstraint.REFERENTIAL);
ref.setColumnNames(new String[] { columnName }); IndexColumn[] cols = new IndexColumn[]{new IndexColumn()};
cols[0].columnName = columnName;
ref.setIndexColumns(cols);
ref.setTableName(tableName); ref.setTableName(tableName);
parseReferences(ref, schema, tableName); parseReferences(ref, schema, tableName);
command.addConstraintCommand(ref); command.addConstraintCommand(ref);
......
...@@ -38,12 +38,12 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -38,12 +38,12 @@ public class AlterTableAddConstraint extends SchemaCommand {
private int type; private int type;
private String constraintName; private String constraintName;
private String tableName; private String tableName;
private String[] columnNames; private IndexColumn[] indexColumns;
private int deleteAction; private int deleteAction;
private int updateAction; private int updateAction;
private Schema refSchema; private Schema refSchema;
private String refTableName; private String refTableName;
private String[] refColumnNames; private IndexColumn[] refIndexColumns;
private Expression checkExpression; private Expression checkExpression;
private Index index, refIndex; private Index index, refIndex;
private String comment; private String comment;
...@@ -87,22 +87,22 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -87,22 +87,22 @@ public class AlterTableAddConstraint extends SchemaCommand {
break; break;
} }
case UNIQUE: { case UNIQUE: {
Column[] columns = table.getColumns(columnNames); IndexColumn.mapColumns(indexColumns, table);
boolean isOwner = false; boolean isOwner = false;
if (index != null && canUseUniqueIndex(index, table, columns)) { if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
isOwner = true; isOwner = true;
index.getIndexType().setBelongsToConstraint(true); index.getIndexType().setBelongsToConstraint(true);
} else { } else {
index = getUniqueIndex(table, columns); index = getUniqueIndex(table, indexColumns);
if (index == null) { if (index == null) {
index = createIndex(table, columns, true); index = createIndex(table, indexColumns, true);
isOwner = true; isOwner = true;
} }
} }
int id = getObjectId(true, true); int id = getObjectId(true, true);
String name = generateConstraintName(table, id); String name = generateConstraintName(table, id);
ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table); ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
unique.setColumns(columns); unique.setColumns(indexColumns);
unique.setIndex(index, isOwner); unique.setIndex(index, isOwner);
constraint = unique; constraint = unique;
break; break;
...@@ -111,25 +111,24 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -111,25 +111,24 @@ public class AlterTableAddConstraint extends SchemaCommand {
Table refTable = refSchema.getTableOrView(session, refTableName); Table refTable = refSchema.getTableOrView(session, refTableName);
session.getUser().checkRight(refTable, Right.ALL); session.getUser().checkRight(refTable, Right.ALL);
boolean isOwner = false; boolean isOwner = false;
Column[] columns = table.getColumns(columnNames); IndexColumn.mapColumns(indexColumns, table);
if (index != null && canUseIndex(index, table, columns)) { if (index != null && canUseIndex(index, table, indexColumns)) {
isOwner = true; isOwner = true;
index.getIndexType().setBelongsToConstraint(true); index.getIndexType().setBelongsToConstraint(true);
} else { } else {
index = getIndex(table, columns); index = getIndex(table, indexColumns);
if (index == null) { if (index == null) {
index = createIndex(table, columns, false); index = createIndex(table, indexColumns, false);
isOwner = true; isOwner = true;
} }
} }
Column[] refColumns; if (refIndexColumns == null) {
if (refColumnNames == null) {
Index refIdx = refTable.getPrimaryKey(); Index refIdx = refTable.getPrimaryKey();
refColumns = refIdx.getColumns(); refIndexColumns = refIdx.getIndexColumns();
} else { } else {
refColumns = refTable.getColumns(refColumnNames); IndexColumn.mapColumns(refIndexColumns, refTable);
} }
if (refColumns.length != columns.length) { if (refIndexColumns.length != indexColumns.length) {
throw Message.getSQLException(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH); throw Message.getSQLException(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
} }
boolean isRefOwner = false; boolean isRefOwner = false;
...@@ -140,19 +139,19 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -140,19 +139,19 @@ public class AlterTableAddConstraint extends SchemaCommand {
refIndex = null; refIndex = null;
} }
if (refIndex == null) { if (refIndex == null) {
refIndex = getUniqueIndex(refTable, refColumns); refIndex = getUniqueIndex(refTable, refIndexColumns);
if (refIndex == null) { if (refIndex == null) {
refIndex = createIndex(refTable, refColumns, true); refIndex = createIndex(refTable, refIndexColumns, true);
isRefOwner = true; isRefOwner = true;
} }
} }
int id = getObjectId(true, true); int id = getObjectId(true, true);
String name = generateConstraintName(table, id); String name = generateConstraintName(table, id);
ConstraintReferential ref = new ConstraintReferential(getSchema(), id, name, table); ConstraintReferential ref = new ConstraintReferential(getSchema(), id, name, table);
ref.setColumns(columns); ref.setColumns(indexColumns);
ref.setIndex(index, isOwner); ref.setIndex(index, isOwner);
ref.setRefTable(refTable); ref.setRefTable(refTable);
ref.setRefColumns(refColumns); ref.setRefColumns(refIndexColumns);
ref.setRefIndex(refIndex, isRefOwner); ref.setRefIndex(refIndex, isRefOwner);
if (checkExisting) { if (checkExisting) {
ref.checkExistingData(session); ref.checkExistingData(session);
...@@ -173,7 +172,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -173,7 +172,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
return 0; return 0;
} }
private Index createIndex(Table t, Column[] cols, boolean unique) throws SQLException { private Index createIndex(Table t, IndexColumn[] cols, boolean unique) throws SQLException {
int indexId = getObjectId(true, false); int indexId = getObjectId(true, false);
IndexType indexType; IndexType indexType;
if (unique) { if (unique) {
...@@ -188,8 +187,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -188,8 +187,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
indexType.setBelongsToConstraint(true); indexType.setBelongsToConstraint(true);
String prefix = constraintName == null ? "CONSTRAINT" : constraintName; String prefix = constraintName == null ? "CONSTRAINT" : constraintName;
String indexName = getSchema().getUniqueIndexName(t, prefix + "_INDEX_"); String indexName = getSchema().getUniqueIndexName(t, prefix + "_INDEX_");
IndexColumn[] idxCols = IndexColumn.wrap(cols); return t.addIndex(session, indexName, indexId, cols, indexType, Index.EMPTY_HEAD, null);
return t.addIndex(session, indexName, indexId, idxCols, indexType, Index.EMPTY_HEAD, null);
} }
public void setDeleteAction(int action) { public void setDeleteAction(int action) {
...@@ -200,7 +198,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -200,7 +198,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
this.updateAction = action; this.updateAction = action;
} }
private Index getUniqueIndex(Table t, Column[] cols) { private Index getUniqueIndex(Table t, IndexColumn[] cols) {
ObjectArray list = t.getIndexes(); ObjectArray list = t.getIndexes();
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
Index index = (Index) list.get(i); Index index = (Index) list.get(i);
...@@ -211,7 +209,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -211,7 +209,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
return null; return null;
} }
private Index getIndex(Table t, Column[] cols) { private Index getIndex(Table t, IndexColumn[] cols) {
ObjectArray list = t.getIndexes(); ObjectArray list = t.getIndexes();
for (int i = 0; i < list.size(); i++) { for (int i = 0; i < list.size(); i++) {
Index index = (Index) list.get(i); Index index = (Index) list.get(i);
...@@ -222,7 +220,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -222,7 +220,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
return null; return null;
} }
private boolean canUseUniqueIndex(Index index, Table table, Column[] cols) { private boolean canUseUniqueIndex(Index index, Table table, IndexColumn[] cols) {
if (index.getTable() != table || !index.getIndexType().isUnique()) { if (index.getTable() != table || !index.getIndexType().isUnique()) {
return false; return false;
} }
...@@ -235,7 +233,10 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -235,7 +233,10 @@ public class AlterTableAddConstraint extends SchemaCommand {
if (indexCols.length > cols.length) { if (indexCols.length > cols.length) {
return false; return false;
} }
HashSet set = new HashSet(Arrays.asList(cols)); HashSet set = new HashSet();
for (int i = 0; i < cols.length; i++) {
set.add(cols[i].column);
}
for (int j = 0; j < indexCols.length; j++) { for (int j = 0; j < indexCols.length; j++) {
// all columns of the index must be part of the list, // all columns of the index must be part of the list,
// but not all columns of the list need to be part of the index // but not all columns of the list need to be part of the index
...@@ -246,7 +247,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -246,7 +247,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
return true; return true;
} }
private boolean canUseIndex(Index index, Table table, Column[] cols) { private boolean canUseIndex(Index index, Table table, IndexColumn[] cols) {
if (index.getTable() != table || index.getCreateSQL() == null) { if (index.getTable() != table || index.getCreateSQL() == null) {
// can't use the scan index or index of another table // can't use the scan index or index of another table
return false; return false;
...@@ -265,7 +266,7 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -265,7 +266,7 @@ public class AlterTableAddConstraint extends SchemaCommand {
// but not all columns of the index need to be part of the list // but not all columns of the index need to be part of the list
// holes are not allowed (index=a,b,c & list=a,b is ok; but list=a,c // holes are not allowed (index=a,b,c & list=a,b is ok; but list=a,c
// is not) // is not)
int idx = index.getColumnIndex(cols[j]); int idx = index.getColumnIndex(cols[j].column);
if (idx < 0 || idx >= cols.length) { if (idx < 0 || idx >= cols.length) {
return false; return false;
} }
...@@ -289,8 +290,8 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -289,8 +290,8 @@ public class AlterTableAddConstraint extends SchemaCommand {
this.tableName = tableName; this.tableName = tableName;
} }
public void setColumnNames(String[] columnNames) { public void setIndexColumns(IndexColumn[] indexColumns) {
this.columnNames = columnNames; this.indexColumns = indexColumns;
} }
public void setRefTableName(Schema refSchema, String ref) { public void setRefTableName(Schema refSchema, String ref) {
...@@ -298,8 +299,8 @@ public class AlterTableAddConstraint extends SchemaCommand { ...@@ -298,8 +299,8 @@ public class AlterTableAddConstraint extends SchemaCommand {
this.refTableName = ref; this.refTableName = ref;
} }
public void setRefColumnNames(String[] cols) { public void setRefIndexColumns(IndexColumn[] indexColumns) {
this.refColumnNames = cols; this.refIndexColumns = indexColumns;
} }
public void setIndex(Index index) { public void setIndex(Index index) {
......
...@@ -7,9 +7,12 @@ package org.h2.command.ddl; ...@@ -7,9 +7,12 @@ package org.h2.command.ddl;
import java.sql.SQLException; import java.sql.SQLException;
import org.h2.constant.ErrorCode; import org.h2.constant.ErrorCode;
import org.h2.constraint.ConstraintUnique;
import org.h2.engine.Database; import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Right; import org.h2.engine.Right;
import org.h2.engine.Session; import org.h2.engine.Session;
import org.h2.index.Index;
import org.h2.index.IndexType; import org.h2.index.IndexType;
import org.h2.message.Message; import org.h2.message.Message;
import org.h2.schema.Schema; import org.h2.schema.Schema;
...@@ -28,6 +31,7 @@ public class CreateIndex extends SchemaCommand { ...@@ -28,6 +31,7 @@ public class CreateIndex extends SchemaCommand {
private boolean primaryKey, unique, hash; private boolean primaryKey, unique, hash;
private boolean ifNotExists; private boolean ifNotExists;
private String comment; private String comment;
private String constraintName;
public CreateIndex(Session session, Schema schema) { public CreateIndex(Session session, Schema schema) {
super(session, schema); super(session, schema);
...@@ -57,6 +61,13 @@ public class CreateIndex extends SchemaCommand { ...@@ -57,6 +61,13 @@ public class CreateIndex extends SchemaCommand {
return indexColumns; return indexColumns;
} }
private String generateConstraintName(DbObject obj, int id) throws SQLException {
if (constraintName == null) {
constraintName = getSchema().getUniqueConstraintName(obj);
}
return constraintName;
}
public int update() throws SQLException { public int update() throws SQLException {
// TODO cancel: may support for index creation // TODO cancel: may support for index creation
session.commit(true); session.commit(true);
...@@ -90,7 +101,20 @@ public class CreateIndex extends SchemaCommand { ...@@ -90,7 +101,20 @@ public class CreateIndex extends SchemaCommand {
indexType = IndexType.createNonUnique(persistent); indexType = IndexType.createNonUnique(persistent);
} }
IndexColumn.mapColumns(indexColumns, table); IndexColumn.mapColumns(indexColumns, table);
table.addIndex(session, indexName, id, indexColumns, indexType, headPos, comment); Index index = table.addIndex(session, indexName, id, indexColumns, indexType, headPos, comment);
int todo;
// if (primaryKey) {
// // TODO this code is a copy of CreateTable (primaryKey creation)
// // for primary keys, create a constraint as well
// String name = generateConstraintName(table, id);
// int constraintId = getObjectId(true, true);
// ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
// pk.setColumns(index.getIndexColumns());
// pk.setIndex(index, true);
// pk.setComment(comment);
// db.addSchemaObject(session, pk);
// table.addConstraint(pk);
// }
return 0; return 0;
} }
...@@ -114,4 +138,8 @@ public class CreateIndex extends SchemaCommand { ...@@ -114,4 +138,8 @@ public class CreateIndex extends SchemaCommand {
this.comment = comment; this.comment = comment;
} }
public void setConstraintName(String constraintName) {
this.constraintName = constraintName;
}
} }
...@@ -10,6 +10,7 @@ import org.h2.command.Prepared; ...@@ -10,6 +10,7 @@ import org.h2.command.Prepared;
import org.h2.command.dml.Insert; import org.h2.command.dml.Insert;
import org.h2.command.dml.Query; import org.h2.command.dml.Query;
import org.h2.constant.ErrorCode; import org.h2.constant.ErrorCode;
import org.h2.constraint.ConstraintUnique;
import org.h2.engine.Database; import org.h2.engine.Database;
import org.h2.engine.Session; import org.h2.engine.Session;
import org.h2.expression.Expression; import org.h2.expression.Expression;
...@@ -146,8 +147,18 @@ public class CreateTable extends SchemaCommand { ...@@ -146,8 +147,18 @@ public class CreateTable extends SchemaCommand {
if (pkColumns != null) { if (pkColumns != null) {
IndexColumn.mapColumns(pkColumns, table); IndexColumn.mapColumns(pkColumns, table);
int indexId = getObjectId(true, false); int indexId = getObjectId(true, false);
table.addIndex(session, null, indexId, pkColumns, IndexType.createPrimaryKey(persistent, hashPrimaryKey), Index index = table.addIndex(session, null, indexId, pkColumns, IndexType.createPrimaryKey(persistent, hashPrimaryKey),
Index.EMPTY_HEAD, null); Index.EMPTY_HEAD, null);
// TODO this code is a copy of CreateIndex (if primaryKey)
int todo;
// String name = getSchema().getUniqueConstraintName(table);
// int constraintId = getObjectId(true, true);
// ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
// pk.setColumns(index.getIndexColumns());
// pk.setIndex(index, true);
// pk.setComment(comment);
// db.addSchemaObject(session, pk);
// table.addConstraint(pk);
} }
for (int i = 0; i < sequences.size(); i++) { for (int i = 0; i < sequences.size(); i++) {
Sequence sequence = (Sequence) sequences.get(i); Sequence sequence = (Sequence) sequences.get(i);
......
...@@ -36,6 +36,11 @@ public abstract class Constraint extends SchemaObjectBase { ...@@ -36,6 +36,11 @@ public abstract class Constraint extends SchemaObjectBase {
*/ */
public static final String UNIQUE = "UNIQUE"; public static final String UNIQUE = "UNIQUE";
/**
* The constraint type name for primary key constraints.
*/
public static final String PRIMARY_KEY = "PRIMARY KEY";
/** /**
* The table for which this constraint is defined. * The table for which this constraint is defined.
*/ */
......
...@@ -20,6 +20,7 @@ import org.h2.result.Row; ...@@ -20,6 +20,7 @@ import org.h2.result.Row;
import org.h2.result.SearchRow; import org.h2.result.SearchRow;
import org.h2.schema.Schema; import org.h2.schema.Schema;
import org.h2.table.Column; import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table; import org.h2.table.Table;
import org.h2.util.ObjectArray; import org.h2.util.ObjectArray;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
...@@ -39,8 +40,8 @@ public class ConstraintReferential extends Constraint { ...@@ -39,8 +40,8 @@ public class ConstraintReferential extends Constraint {
private Index refIndex; private Index refIndex;
private boolean indexOwner; private boolean indexOwner;
private boolean refIndexOwner; private boolean refIndexOwner;
protected Column[] columns; protected IndexColumn[] columns;
protected Column[] refColumns; protected IndexColumn[] refColumns;
private String deleteSQL, updateSQL; private String deleteSQL, updateSQL;
private boolean skipOwnTable; private boolean skipOwnTable;
...@@ -83,8 +84,8 @@ public class ConstraintReferential extends Constraint { ...@@ -83,8 +84,8 @@ public class ConstraintReferential extends Constraint {
buff.append(" COMMENT "); buff.append(" COMMENT ");
buff.append(StringUtils.quoteStringSQL(comment)); buff.append(StringUtils.quoteStringSQL(comment));
} }
Column[] cols = columns; IndexColumn[] cols = columns;
Column[] refCols = refColumns; IndexColumn[] refCols = refColumns;
buff.append(" FOREIGN KEY("); buff.append(" FOREIGN KEY(");
for (int i = 0; i < cols.length; i++) { for (int i = 0; i < cols.length; i++) {
if (i > 0) { if (i > 0) {
...@@ -164,19 +165,19 @@ public class ConstraintReferential extends Constraint { ...@@ -164,19 +165,19 @@ public class ConstraintReferential extends Constraint {
return getCreateSQLForCopy(table, getSQL()); return getCreateSQLForCopy(table, getSQL());
} }
public void setColumns(Column[] cols) { public void setColumns(IndexColumn[] cols) {
columns = cols; columns = cols;
} }
public Column[] getColumns() { public IndexColumn[] getColumns() {
return columns; return columns;
} }
public void setRefColumns(Column[] refCols) { public void setRefColumns(IndexColumn[] refCols) {
refColumns = refCols; refColumns = refCols;
} }
public Column[] getRefColumns() { public IndexColumn[] getRefColumns() {
return refColumns; return refColumns;
} }
...@@ -240,7 +241,7 @@ public class ConstraintReferential extends Constraint { ...@@ -240,7 +241,7 @@ public class ConstraintReferential extends Constraint {
} }
boolean containsNull = false; boolean containsNull = false;
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
int idx = columns[i].getColumnId(); int idx = columns[i].column.getColumnId();
Value v = newRow.getValue(idx); Value v = newRow.getValue(idx);
if (v == ValueNull.INSTANCE) { if (v == ValueNull.INSTANCE) {
containsNull = true; containsNull = true;
...@@ -255,9 +256,9 @@ public class ConstraintReferential extends Constraint { ...@@ -255,9 +256,9 @@ public class ConstraintReferential extends Constraint {
// first // first
boolean self = true; boolean self = true;
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
int idx = columns[i].getColumnId(); int idx = columns[i].column.getColumnId();
Value v = newRow.getValue(idx); Value v = newRow.getValue(idx);
Column refCol = refColumns[i]; Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId(); int refIdx = refCol.getColumnId();
Value r = newRow.getValue(refIdx); Value r = newRow.getValue(refIdx);
if (!database.areEqual(r, v)) { if (!database.areEqual(r, v)) {
...@@ -271,9 +272,9 @@ public class ConstraintReferential extends Constraint { ...@@ -271,9 +272,9 @@ public class ConstraintReferential extends Constraint {
} }
Row check = refTable.getTemplateRow(); Row check = refTable.getTemplateRow();
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
int idx = columns[i].getColumnId(); int idx = columns[i].column.getColumnId();
Value v = newRow.getValue(idx); Value v = newRow.getValue(idx);
Column refCol = refColumns[i]; Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId(); int refIdx = refCol.getColumnId();
check.setValue(refIdx, v.convertTo(refCol.getType())); check.setValue(refIdx, v.convertTo(refCol.getType()));
} }
...@@ -317,10 +318,10 @@ public class ConstraintReferential extends Constraint { ...@@ -317,10 +318,10 @@ public class ConstraintReferential extends Constraint {
// first // first
boolean self = true; boolean self = true;
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
Column refCol = refColumns[i]; Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId(); int refIdx = refCol.getColumnId();
Value v = oldRow.getValue(refIdx); Value v = oldRow.getValue(refIdx);
int idx = columns[i].getColumnId(); int idx = columns[i].column.getColumnId();
Value r = oldRow.getValue(idx); Value r = oldRow.getValue(idx);
if (!database.areEqual(r, v)) { if (!database.areEqual(r, v)) {
self = false; self = false;
...@@ -333,9 +334,9 @@ public class ConstraintReferential extends Constraint { ...@@ -333,9 +334,9 @@ public class ConstraintReferential extends Constraint {
} }
SearchRow check = table.getTemplateSimpleRow(false); SearchRow check = table.getTemplateSimpleRow(false);
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
Column refCol = refColumns[i]; Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId(); int refIdx = refCol.getColumnId();
Column col = columns[i]; Column col = columns[i].column;
int idx = col.getColumnId(); int idx = col.getColumnId();
Value v = oldRow.getValue(refIdx).convertTo(col.getType()); Value v = oldRow.getValue(refIdx).convertTo(col.getType());
check.setValue(idx, v); check.setValue(idx, v);
...@@ -375,7 +376,7 @@ public class ConstraintReferential extends Constraint { ...@@ -375,7 +376,7 @@ public class ConstraintReferential extends Constraint {
ObjectArray params = updateCommand.getParameters(); ObjectArray params = updateCommand.getParameters();
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
Parameter param = (Parameter) params.get(i); Parameter param = (Parameter) params.get(i);
Column refCol = refColumns[i]; Column refCol = refColumns[i].column;
param.setValue(newRow.getValue(refCol.getColumnId())); param.setValue(newRow.getValue(refCol.getColumnId()));
} }
} }
...@@ -400,7 +401,7 @@ public class ConstraintReferential extends Constraint { ...@@ -400,7 +401,7 @@ public class ConstraintReferential extends Constraint {
void setWhere(Prepared command, int pos, Row row) { void setWhere(Prepared command, int pos, Row row) {
for (int i = 0; i < refColumns.length; i++) { for (int i = 0; i < refColumns.length; i++) {
int idx = refColumns[i].getColumnId(); int idx = refColumns[i].column.getColumnId();
Value v = row.getValue(idx); Value v = row.getValue(idx);
ObjectArray params = command.getParameters(); ObjectArray params = command.getParameters();
Parameter param = (Parameter) params.get(pos + i); Parameter param = (Parameter) params.get(pos + i);
...@@ -462,7 +463,7 @@ public class ConstraintReferential extends Constraint { ...@@ -462,7 +463,7 @@ public class ConstraintReferential extends Constraint {
if (action != CASCADE) { if (action != CASCADE) {
ObjectArray params = command.getParameters(); ObjectArray params = command.getParameters();
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
Column column = columns[i]; Column column = columns[i].column;
Parameter param = (Parameter) params.get(i); Parameter param = (Parameter) params.get(i);
Value value; Value value;
if (action == SET_NULL) { if (action == SET_NULL) {
...@@ -488,7 +489,7 @@ public class ConstraintReferential extends Constraint { ...@@ -488,7 +489,7 @@ public class ConstraintReferential extends Constraint {
if (i > 0) { if (i > 0) {
buff.append(" , "); buff.append(" , ");
} }
Column column = columns[i]; Column column = columns[i].column;
buff.append(Parser.quoteIdentifier(column.getName())); buff.append(Parser.quoteIdentifier(column.getName()));
buff.append("=?"); buff.append("=?");
} }
...@@ -500,7 +501,7 @@ public class ConstraintReferential extends Constraint { ...@@ -500,7 +501,7 @@ public class ConstraintReferential extends Constraint {
if (i > 0) { if (i > 0) {
buff.append(" AND "); buff.append(" AND ");
} }
Column column = columns[i]; Column column = columns[i].column;
buff.append(Parser.quoteIdentifier(column.getName())); buff.append(Parser.quoteIdentifier(column.getName()));
buff.append("=?"); buff.append("=?");
} }
...@@ -516,12 +517,12 @@ public class ConstraintReferential extends Constraint { ...@@ -516,12 +517,12 @@ public class ConstraintReferential extends Constraint {
public boolean containsColumn(Column col) { public boolean containsColumn(Column col) {
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
if (columns[i] == col) { if (columns[i].column == col) {
return true; return true;
} }
} }
for (int i = 0; i < refColumns.length; i++) { for (int i = 0; i < refColumns.length; i++) {
if (refColumns[i] == col) { if (refColumns[i].column == col) {
return true; return true;
} }
} }
......
...@@ -11,6 +11,7 @@ import org.h2.index.Index; ...@@ -11,6 +11,7 @@ import org.h2.index.Index;
import org.h2.result.Row; import org.h2.result.Row;
import org.h2.schema.Schema; import org.h2.schema.Schema;
import org.h2.table.Column; import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table; import org.h2.table.Table;
import org.h2.util.StringUtils; import org.h2.util.StringUtils;
...@@ -21,14 +22,16 @@ public class ConstraintUnique extends Constraint { ...@@ -21,14 +22,16 @@ public class ConstraintUnique extends Constraint {
private Index index; private Index index;
private boolean indexOwner; private boolean indexOwner;
private Column[] columns; private IndexColumn[] columns;
private boolean primaryKey;
public ConstraintUnique(Schema schema, int id, String name, Table table) { public ConstraintUnique(Schema schema, int id, String name, Table table, boolean primaryKey) {
super(schema, id, name, table); super(schema, id, name, table);
this.primaryKey = primaryKey;
} }
public String getConstraintType() { public String getConstraintType() {
return Constraint.UNIQUE; return primaryKey ? Constraint.PRIMARY_KEY : Constraint.UNIQUE;
} }
public String getCreateSQLForCopy(Table table, String quotedName) { public String getCreateSQLForCopy(Table table, String quotedName) {
...@@ -45,14 +48,16 @@ public class ConstraintUnique extends Constraint { ...@@ -45,14 +48,16 @@ public class ConstraintUnique extends Constraint {
buff.append(" COMMENT "); buff.append(" COMMENT ");
buff.append(StringUtils.quoteStringSQL(comment)); buff.append(StringUtils.quoteStringSQL(comment));
} }
buff.append(" UNIQUE("); buff.append(' ');
buff.append(getTypeName());
buff.append('(');
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
if (i > 0) { if (i > 0) {
buff.append(", "); buff.append(", ");
} }
buff.append(Parser.quoteIdentifier(columns[i].getName())); buff.append(Parser.quoteIdentifier(columns[i].column.getName()));
} }
buff.append(")"); buff.append(')');
if (internalIndex && indexOwner && table == this.table) { if (internalIndex && indexOwner && table == this.table) {
buff.append(" INDEX "); buff.append(" INDEX ");
buff.append(index.getSQL()); buff.append(index.getSQL());
...@@ -60,16 +65,25 @@ public class ConstraintUnique extends Constraint { ...@@ -60,16 +65,25 @@ public class ConstraintUnique extends Constraint {
return buff.toString(); return buff.toString();
} }
private String getTypeName() {
if (primaryKey) {
return "PRIMARY KEY";
} else {
return "UNIQUE";
}
}
public String getShortDescription() { public String getShortDescription() {
StringBuffer buff = new StringBuffer(); StringBuffer buff = new StringBuffer();
buff.append(getName()); buff.append(getName());
buff.append(": "); buff.append(": ");
buff.append("UNIQUE("); buff.append(getTypeName());
buff.append('(');
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
if (i > 0) { if (i > 0) {
buff.append(", "); buff.append(", ");
} }
buff.append(Parser.quoteIdentifier(columns[i].getName())); buff.append(Parser.quoteIdentifier(columns[i].column.getName()));
} }
buff.append(")"); buff.append(")");
return buff.toString(); return buff.toString();
...@@ -83,11 +97,11 @@ public class ConstraintUnique extends Constraint { ...@@ -83,11 +97,11 @@ public class ConstraintUnique extends Constraint {
return getCreateSQLForCopy(table, getSQL()); return getCreateSQLForCopy(table, getSQL());
} }
public void setColumns(Column[] columns) { public void setColumns(IndexColumn[] columns) {
this.columns = columns; this.columns = columns;
} }
public Column[] getColumns() { public IndexColumn[] getColumns() {
return columns; return columns;
} }
...@@ -117,7 +131,7 @@ public class ConstraintUnique extends Constraint { ...@@ -117,7 +131,7 @@ public class ConstraintUnique extends Constraint {
public boolean containsColumn(Column col) { public boolean containsColumn(Column col) {
for (int i = 0; i < columns.length; i++) { for (int i = 0; i < columns.length; i++) {
if (columns[i] == col) { if (columns[i].column == col) {
return true; return true;
} }
} }
......
...@@ -10,6 +10,7 @@ import java.sql.SQLException; ...@@ -10,6 +10,7 @@ import java.sql.SQLException;
import org.h2.constant.SysProperties; import org.h2.constant.SysProperties;
import org.h2.engine.SessionRemote; import org.h2.engine.SessionRemote;
import org.h2.message.Message; import org.h2.message.Message;
import org.h2.message.Trace;
import org.h2.util.ObjectArray; import org.h2.util.ObjectArray;
import org.h2.value.Transfer; import org.h2.value.Transfer;
import org.h2.value.Value; import org.h2.value.Value;
...@@ -163,7 +164,11 @@ public class ResultRemote implements ResultInterface { ...@@ -163,7 +164,11 @@ public class ResultRemote implements ResultInterface {
} }
public void close() { public void close() {
if (session == null) {
return;
}
result = null; result = null;
Trace trace = session.getTrace();
sendClose(); sendClose();
if (lobValues != null) { if (lobValues != null) {
for (int i = 0; i < lobValues.size(); i++) { for (int i = 0; i < lobValues.size(); i++) {
...@@ -171,7 +176,7 @@ public class ResultRemote implements ResultInterface { ...@@ -171,7 +176,7 @@ public class ResultRemote implements ResultInterface {
try { try {
v.close(); v.close();
} catch (SQLException e) { } catch (SQLException e) {
session.getTrace().error("delete lob " + v.getSQL(), e); trace.error("delete lob " + v.getSQL(), e);
} }
} }
lobValues = null; lobValues = null;
......
...@@ -9,14 +9,14 @@ import java.sql.SQLException; ...@@ -9,14 +9,14 @@ import java.sql.SQLException;
import org.h2.result.SortOrder; import org.h2.result.SortOrder;
/** /**
* This represents a column item of an index. This is required because some * This represents a column item of an index. This is required because some
* indexes support descending sorted columns. * indexes support descending sorted columns.
*/ */
public class IndexColumn { public class IndexColumn {
public String columnName; public String columnName;
public Column column; public Column column;
public int sortType = SortOrder.ASCENDING; public int sortType = SortOrder.ASCENDING;
public String getSQL() { public String getSQL() {
StringBuffer buff = new StringBuffer(column.getSQL()); StringBuffer buff = new StringBuffer(column.getSQL());
if ((sortType & SortOrder.DESCENDING) != 0) { if ((sortType & SortOrder.DESCENDING) != 0) {
...@@ -29,8 +29,9 @@ public class IndexColumn { ...@@ -29,8 +29,9 @@ public class IndexColumn {
} }
return buff.toString(); return buff.toString();
} }
public static IndexColumn[] wrap(Column[] columns) { public static IndexColumn[] wrap(Column[] columns) {
int testDelete_;
IndexColumn[] list = new IndexColumn[columns.length]; IndexColumn[] list = new IndexColumn[columns.length];
for (int i = 0; i < list.length; i++) { for (int i = 0; i < list.length; i++) {
list[i] = new IndexColumn(); list[i] = new IndexColumn();
......
...@@ -1060,8 +1060,8 @@ public class MetaTable extends Table { ...@@ -1060,8 +1060,8 @@ public class MetaTable extends Table {
continue; continue;
} }
ConstraintReferential ref = (ConstraintReferential) constraint; ConstraintReferential ref = (ConstraintReferential) constraint;
Column[] cols = ref.getColumns(); IndexColumn[] cols = ref.getColumns();
Column[] refCols = ref.getRefColumns(); IndexColumn[] refCols = ref.getRefColumns();
Table tab = ref.getTable(); Table tab = ref.getTable();
Table refTab = ref.getRefTable(); Table refTab = ref.getRefTable();
String tableName = identifier(refTab.getName()); String tableName = identifier(refTab.getName());
...@@ -1075,11 +1075,11 @@ public class MetaTable extends Table { ...@@ -1075,11 +1075,11 @@ public class MetaTable extends Table {
catalog, // PKTABLE_CATALOG catalog, // PKTABLE_CATALOG
identifier(refTab.getSchema().getName()), // PKTABLE_SCHEMA identifier(refTab.getSchema().getName()), // PKTABLE_SCHEMA
identifier(refTab.getName()), // PKTABLE_NAME identifier(refTab.getName()), // PKTABLE_NAME
identifier(refCols[j].getName()), // PKCOLUMN_NAME identifier(refCols[j].column.getName()), // PKCOLUMN_NAME
catalog, // FKTABLE_CATALOG catalog, // FKTABLE_CATALOG
identifier(tab.getSchema().getName()), // FKTABLE_SCHEMA identifier(tab.getSchema().getName()), // FKTABLE_SCHEMA
identifier(tab.getName()), // FKTABLE_NAME identifier(tab.getName()), // FKTABLE_NAME
identifier(cols[j].getName()), // FKCOLUMN_NAME identifier(cols[j].column.getName()), // FKCOLUMN_NAME
String.valueOf(j + 1), // ORDINAL_POSITION String.valueOf(j + 1), // ORDINAL_POSITION
String.valueOf(update), // UPDATE_RULE SMALLINT String.valueOf(update), // UPDATE_RULE SMALLINT
String.valueOf(delete), // DELETE_RULE SMALLINT String.valueOf(delete), // DELETE_RULE SMALLINT
...@@ -1097,7 +1097,7 @@ public class MetaTable extends Table { ...@@ -1097,7 +1097,7 @@ public class MetaTable extends Table {
Constraint constraint = (Constraint) constraints.get(i); Constraint constraint = (Constraint) constraints.get(i);
String type = constraint.getConstraintType(); String type = constraint.getConstraintType();
String checkExpression = null; String checkExpression = null;
Column[] columns = null; IndexColumn[] columns = null;
Table table = constraint.getTable(); Table table = constraint.getTable();
String tableName = identifier(table.getName()); String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) { if (!checkIndex(session, tableName, indexFrom, indexTo)) {
...@@ -1105,7 +1105,7 @@ public class MetaTable extends Table { ...@@ -1105,7 +1105,7 @@ public class MetaTable extends Table {
} }
if (type.equals(Constraint.CHECK)) { if (type.equals(Constraint.CHECK)) {
checkExpression = ((ConstraintCheck) constraint).getExpression().getSQL(); checkExpression = ((ConstraintCheck) constraint).getExpression().getSQL();
} else if (type.equals(Constraint.UNIQUE)) { } else if (type.equals(Constraint.UNIQUE) || type.equals(Constraint.PRIMARY_KEY)) {
columns = ((ConstraintUnique) constraint).getColumns(); columns = ((ConstraintUnique) constraint).getColumns();
} else if (type.equals(Constraint.REFERENTIAL)) { } else if (type.equals(Constraint.REFERENTIAL)) {
columns = ((ConstraintReferential) constraint).getColumns(); columns = ((ConstraintReferential) constraint).getColumns();
...@@ -1117,7 +1117,7 @@ public class MetaTable extends Table { ...@@ -1117,7 +1117,7 @@ public class MetaTable extends Table {
if (j > 0) { if (j > 0) {
buff.append(','); buff.append(',');
} }
buff.append(columns[j].getName()); buff.append(columns[j].column.getName());
} }
columnList = buff.toString(); columnList = buff.toString();
} }
......
...@@ -68,6 +68,7 @@ public class TableData extends Table implements RecordReader { ...@@ -68,6 +68,7 @@ public class TableData extends Table implements RecordReader {
for (int i = 0; i < cols.length; i++) { for (int i = 0; i < cols.length; i++) {
if (DataType.isLargeObject(cols[i].getType())) { if (DataType.isLargeObject(cols[i].getType())) {
containsLargeObject = true; containsLargeObject = true;
memoryPerRow = Row.MEMORY_CALCULATE;
} }
} }
traceLock = database.getTrace(Trace.LOCK); traceLock = database.getTrace(Trace.LOCK);
...@@ -464,8 +465,7 @@ public class TableData extends Table implements RecordReader { ...@@ -464,8 +465,7 @@ public class TableData extends Table implements RecordReader {
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
data[i] = s.readValue(); data[i] = s.readValue();
} }
int memory = containsLargeObject ? Row.MEMORY_CALCULATE : memoryPerRow; Row row = new Row(data, memoryPerRow);
Row row = new Row(data, memory);
return row; return row;
} }
......
...@@ -138,6 +138,12 @@ public class Recover implements DataHandler { ...@@ -138,6 +138,12 @@ public class Recover implements DataHandler {
} }
} }
private void log(String message) {
if (log) {
System.out.println(message);
}
}
private void logError(String message, Throwable t) { private void logError(String message, Throwable t) {
System.out.println(message + ": " + t.toString()); System.out.println(message + ": " + t.toString());
if (log) { if (log) {
...@@ -289,10 +295,10 @@ public class Recover implements DataHandler { ...@@ -289,10 +295,10 @@ public class Recover implements DataHandler {
} }
} }
private static PrintWriter getWriter(String fileName, String suffix) throws IOException, SQLException { private PrintWriter getWriter(String fileName, String suffix) throws IOException, SQLException {
fileName = fileName.substring(0, fileName.length() - 3); fileName = fileName.substring(0, fileName.length() - 3);
String outputFile = fileName + suffix; String outputFile = fileName + suffix;
System.out.println("Created file: " + outputFile); log("Created file: " + outputFile);
return new PrintWriter(FileUtils.openFileWriter(outputFile, false)); return new PrintWriter(FileUtils.openFileWriter(outputFile, false));
} }
......
...@@ -203,9 +203,9 @@ public class Cache2Q implements Cache { ...@@ -203,9 +203,9 @@ public class Cache2Q implements Cache {
removeCacheObject(r.getPos()); removeCacheObject(r.getPos());
removeFromList(r); removeFromList(r);
} }
} else { } else if (sizeMain > 0) {
CacheObject r = headMain.next; CacheObject r = headMain.next;
if (!r.canRemove()) { if (!r.canRemove() && !(r instanceof CacheHead)) {
removeFromList(r); removeFromList(r);
addToFront(headMain, r); addToFront(headMain, r);
continue; continue;
......
...@@ -151,60 +151,21 @@ java org.h2.test.TestAll timer ...@@ -151,60 +151,21 @@ java org.h2.test.TestAll timer
/* /*
adjust cache memory usage
simple pure java config file (interpreted)
not done yet:
DROP ALL OBJECTS;
SET MAX_LENGTH_INPLACE_LOB 32768;
CREATE TABLE TEST(ID IDENTITY, DATA CLOB);
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
@LOOP 1000 INSERT INTO TEST(DATA) VALUES(SPACE(32000));
CALL MEMORY_USED();
ResultRemote.close()
public void close() {
result = null;
// NULL OUT THE SESSION REFERENCE
sendClose();
if (lobValues != null) {
for (int i = 0; i < lobValues.size(); i++) {
Value v = (Value) lobValues.get(i);
try {
v.close();
} catch (SQLException e) {
// BANG NullPointerException
session.getTrace().error("delete lob " + v.getSQL(), e);
}
}
lobValues = null;
}
}
create table bla (id integer not null); create table bla (id integer not null);
alter table bla add constraint pk primary key (id); alter table bla add constraint pk primary key (id);
-- doesn't create a constraint!
alter table bla drop constraint pk; alter table bla drop constraint pk;
alter table bla drop primary key; alter table bla drop primary key;
drop table bla; drop table bla;
-- PostgreSQL, Derby, HSQLDB: works
-- MySQL: does not work
implement max_query_time and use it for TestCrashAPI implement max_query_time and use it for TestCrashAPI
adjust cache memory usage
simple pure java config file (interpreted)
orphan? orphan?
javadoc: design patterns javadoc: design patterns
...@@ -401,7 +362,6 @@ Features of H2 ...@@ -401,7 +362,6 @@ Features of H2
deleteIndex = (a & 128) != 0; deleteIndex = (a & 128) != 0;
for (logMode = 0; logMode < 3; logMode++) { for (logMode = 0; logMode < 3; logMode++) {
traceLevelFile = logMode; traceLevelFile = logMode;
TestBase.printTime("cipher:" + cipher +" a:" +a+" logMode:"+logMode);
test(); test();
} }
} }
...@@ -542,7 +502,8 @@ Features of H2 ...@@ -542,7 +502,8 @@ Features of H2
* Run all tests with the current settings. * Run all tests with the current settings.
*/ */
private void test() throws Exception { private void test() throws Exception {
System.out.println("test big:"+big+" net:"+networked+" cipher:"+cipher+" memory:"+memory+" log:"+logMode+" diskResult:"+diskResult + " mvcc:" + mvcc); System.out.println();
System.out.println("Test big:"+big+" net:"+networked+" cipher:"+cipher+" memory:"+memory+" log:"+logMode+" diskResult:"+diskResult + " mvcc:" + mvcc);
beforeTest(); beforeTest();
// db // db
...@@ -552,7 +513,6 @@ Features of H2 ...@@ -552,7 +513,6 @@ Features of H2
new TestBackup().runTest(this); new TestBackup().runTest(this);
new TestBigDb().runTest(this); new TestBigDb().runTest(this);
new TestBigResult().runTest(this); new TestBigResult().runTest(this);
new TestCache().runTest(this);
new TestCases().runTest(this); new TestCases().runTest(this);
new TestCheckpoint().runTest(this); new TestCheckpoint().runTest(this);
new TestCluster().runTest(this); new TestCluster().runTest(this);
...@@ -623,6 +583,7 @@ Features of H2 ...@@ -623,6 +583,7 @@ Features of H2
// unit // unit
new TestBitField().runTest(this); new TestBitField().runTest(this);
new TestCache().runTest(this);
new TestCompress().runTest(this); new TestCompress().runTest(this);
new TestDataPage().runTest(this); new TestDataPage().runTest(this);
new TestDate().runTest(this); new TestDate().runTest(this);
......
...@@ -51,9 +51,8 @@ public abstract class TestBase { ...@@ -51,9 +51,8 @@ public abstract class TestBase {
try { try {
init(conf); init(conf);
start = System.currentTimeMillis(); start = System.currentTimeMillis();
printlnWithTime("start");
test(); test();
println("done "); println("");
} catch (Exception e) { } catch (Exception e) {
fail("FAIL " + e.toString(), e); fail("FAIL " + e.toString(), e);
if (config.stopOnError) { if (config.stopOnError) {
...@@ -193,7 +192,7 @@ public abstract class TestBase { ...@@ -193,7 +192,7 @@ public abstract class TestBase {
public void printTimeMemory(String s, long time) { public void printTimeMemory(String s, long time) {
if (config.big) { if (config.big) {
println(time + " ms; " + getMemoryUsed() + " MB: " + s); println(getMemoryUsed() + " MB: " + s);
} }
} }
...@@ -244,19 +243,19 @@ public abstract class TestBase { ...@@ -244,19 +243,19 @@ public abstract class TestBase {
} }
protected void println(String s) { protected void println(String s) {
printlnWithTime(s); long time = System.currentTimeMillis() - start;
printlnWithTime(time, getClass().getName() + " " + s);
} }
private void printlnWithTime(String s) { private static void printlnWithTime(long time, String s) {
long time = System.currentTimeMillis() - start; String t = "0000000000" + time;
String t = " " + time;
t = t.substring(t.length() - 6); t = t.substring(t.length() - 6);
System.out.println(s + " (" + t + " ms) " + getClass().getName()); System.out.println(t + " " + s);
} }
protected static void printTime(String s) { protected void printTime(String s) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
System.out.println(dateFormat.format(new java.util.Date()) + " " + s); println(dateFormat.format(new java.util.Date()) + " " + s);
} }
protected void deleteDb(String name) throws Exception { protected void deleteDb(String name) throws Exception {
......
...@@ -64,7 +64,7 @@ public class TestBigDb extends TestBase { ...@@ -64,7 +64,7 @@ public class TestBigDb extends TestBase {
if (t - time > 1000) { if (t - time > 1000) {
time = t; time = t;
int free = MemoryUtils.getMemoryFree(); int free = MemoryUtils.getMemoryFree();
System.out.println("i: " + i + " free: " + free + " used: " + MemoryUtils.getMemoryUsed()); println("i: " + i + " free: " + free + " used: " + MemoryUtils.getMemoryUsed());
} }
} }
prep.setInt(1, i); prep.setInt(1, i);
...@@ -118,12 +118,9 @@ public class TestBigDb extends TestBase { ...@@ -118,12 +118,9 @@ public class TestBigDb extends TestBase {
stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)"); stat.execute("CREATE TABLE TEST(ID IDENTITY, NAME VARCHAR)");
PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES('Hello World')"); PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST(NAME) VALUES('Hello World')");
int len = getSize(1000, 10000); int len = getSize(1000, 10000);
long time = System.currentTimeMillis();
for (int i = 0; i < len; i++) { for (int i = 0; i < len; i++) {
if (i % 1000 == 0) { if (i % 1000 == 0) {
long t = System.currentTimeMillis(); println("rows: " + i);
time = t;
trace("rows:" + i + " time:" + (t - time));
Thread.yield(); Thread.yield();
} }
prep.execute(); prep.execute();
......
...@@ -49,7 +49,7 @@ public class TestFullText extends TestBase { ...@@ -49,7 +49,7 @@ public class TestFullText extends TestBase {
stat.execute("CREATE PRIMARY KEY ON TEST(ID)"); stat.execute("CREATE PRIMARY KEY ON TEST(ID)");
long time = System.currentTimeMillis(); long time = System.currentTimeMillis();
stat.execute("CALL " + prefix + "_CREATE_INDEX('PUBLIC', 'TEST', NULL)"); stat.execute("CALL " + prefix + "_CREATE_INDEX('PUBLIC', 'TEST', NULL)");
println("Create index " + prefix + ": " + (System.currentTimeMillis() - time) + " ms"); println("create " + prefix + ": " + (System.currentTimeMillis() - time));
PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + prefix + "_SEARCH(?, 0, 0)"); PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + prefix + "_SEARCH(?, 0, 0)");
time = System.currentTimeMillis(); time = System.currentTimeMillis();
ResultSet rs = stat.executeQuery("SELECT TEXT FROM TEST"); ResultSet rs = stat.executeQuery("SELECT TEXT FROM TEST");
...@@ -70,7 +70,7 @@ public class TestFullText extends TestBase { ...@@ -70,7 +70,7 @@ public class TestFullText extends TestBase {
} }
} }
} }
println("Search " + prefix + ": " + (System.currentTimeMillis() - time) + " ms, count: " + count); println("search " + prefix + ": " + (System.currentTimeMillis() - time) + " count: " + count);
stat.execute("CALL " + prefix + "_DROP_ALL()"); stat.execute("CALL " + prefix + "_DROP_ALL()");
conn.close(); conn.close();
} }
......
...@@ -49,7 +49,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -49,7 +49,7 @@ public class TestListener extends TestBase implements DatabaseEventListener {
} }
public void diskSpaceIsLow(long stillAvailable) throws SQLException { public void diskSpaceIsLow(long stillAvailable) throws SQLException {
System.out.println("diskSpaceIsLow stillAvailable=" + stillAvailable); printTime("diskSpaceIsLow stillAvailable=" + stillAvailable);
} }
public void exceptionThrown(SQLException e, String sql) { public void exceptionThrown(SQLException e, String sql) {
...@@ -81,7 +81,7 @@ public class TestListener extends TestBase implements DatabaseEventListener { ...@@ -81,7 +81,7 @@ public class TestListener extends TestBase implements DatabaseEventListener {
Thread.sleep(1); Thread.sleep(1);
} catch (InterruptedException e) { } catch (InterruptedException e) {
} }
System.out.println("state: " + stateName + " " + (100 * current / max) + " " + (time - start)); printTime("state: " + stateName + " " + (100 * current / max) + " " + (time - start));
} }
public void closingDatabase() { public void closingDatabase() {
......
...@@ -11,6 +11,7 @@ import java.sql.Statement; ...@@ -11,6 +11,7 @@ import java.sql.Statement;
import java.util.Random; import java.util.Random;
import org.h2.test.TestBase; import org.h2.test.TestBase;
import org.h2.util.MemoryUtils;
/** /**
* Tests the memory usage of the cache. * Tests the memory usage of the cache.
...@@ -29,6 +30,8 @@ public class TestMemoryUsage extends TestBase { ...@@ -29,6 +30,8 @@ public class TestMemoryUsage extends TestBase {
} }
public void test() throws Exception { public void test() throws Exception {
deleteDb("memoryUsage");
testClob();
deleteDb("memoryUsage"); deleteDb("memoryUsage");
testReconnectOften(); testReconnectOften();
deleteDb("memoryUsage"); deleteDb("memoryUsage");
...@@ -39,6 +42,30 @@ public class TestMemoryUsage extends TestBase { ...@@ -39,6 +42,30 @@ public class TestMemoryUsage extends TestBase {
conn.close(); conn.close();
} }
private void testClob() throws Exception {
if (config.memory || !config.big) {
return;
}
Connection conn = getConnection("memoryUsage");
Statement stat = conn.createStatement();
stat.execute("SET MAX_LENGTH_INPLACE_LOB 32768");
stat.execute("SET CACHE_SIZE 8000");
stat.execute("CREATE TABLE TEST(ID IDENTITY, DATA CLOB)");
System.gc();
System.gc();
int start = MemoryUtils.getMemoryUsed();
for (int i = 0; i < 4; i++) {
stat.execute("INSERT INTO TEST(DATA) SELECT SPACE(32000) FROM SYSTEM_RANGE(1, 200)");
System.gc();
System.gc();
int used = MemoryUtils.getMemoryUsed();
if ((used - start) > 16000) {
error("Used: " + (used - start));
}
}
conn.close();
}
private void testReconnectOften() throws Exception { private void testReconnectOften() throws Exception {
int len = getSize(1, 2000); int len = getSize(1, 2000);
Connection conn1 = getConnection("memoryUsage"); Connection conn1 = getConnection("memoryUsage");
......
...@@ -133,7 +133,7 @@ public class TestCrashAPI extends TestBase { ...@@ -133,7 +133,7 @@ public class TestCrashAPI extends TestBase {
} }
private void testOne(int seed) throws Exception { private void testOne(int seed) throws Exception {
printTime("TestCrashAPI " + seed); printTime("seed: " + seed);
callCount = 0; callCount = 0;
openCount = 0; openCount = 0;
random = new RandomGen(null); random = new RandomGen(null);
......
...@@ -49,7 +49,7 @@ public class TestKillRestart extends TestBase { ...@@ -49,7 +49,7 @@ public class TestKillRestart extends TestBase {
error("Expected: #..., got: " + s); error("Expected: #..., got: " + s);
} else if (s.startsWith("#Running")) { } else if (s.startsWith("#Running")) {
Thread.sleep(100); Thread.sleep(100);
printTime("Killing..." + i); printTime("killing: " + i);
p.destroy(); p.destroy();
break; break;
} else if (s.startsWith("#Fail")) { } else if (s.startsWith("#Fail")) {
......
...@@ -162,7 +162,7 @@ public class TestRandomSQL extends TestBase { ...@@ -162,7 +162,7 @@ public class TestRandomSQL extends TestBase {
String old = SysProperties.scriptDirectory; String old = SysProperties.scriptDirectory;
SysProperties.scriptDirectory = "dataScript/"; SysProperties.scriptDirectory = "dataScript/";
seed = i; seed = i;
printTime("TestRandomSQL " + seed); printTime("seed: " + seed);
try { try {
deleteDb(); deleteDb();
} catch (SQLException e) { } catch (SQLException e) {
......
...@@ -60,7 +60,7 @@ public class TestValueMemory extends TestBase implements DataHandler { ...@@ -60,7 +60,7 @@ public class TestValueMemory extends TestBase implements DataHandler {
System.gc(); System.gc();
long used = MemoryUtils.getMemoryUsed() - first; long used = MemoryUtils.getMemoryUsed() - first;
memory /= 1024; memory /= 1024;
if (used > memory * 2) { if (used > memory * 3) {
error("Type: " + type + " Used memory: " + used + " calculated: " + memory + " " + array.length); error("Type: " + type + " Used memory: " + used + " calculated: " + memory + " " + array.length);
} }
} }
......
...@@ -40,6 +40,7 @@ import oracle.toplink.essentials.internal.sessions.AbstractSession; ...@@ -40,6 +40,7 @@ import oracle.toplink.essentials.internal.sessions.AbstractSession;
* name="toplink.platform.class.name" * name="toplink.platform.class.name"
* value="oracle.toplink.essentials.platform.database.H2Platform"/> * value="oracle.toplink.essentials.platform.database.H2Platform"/>
* </pre> * </pre>
* See also: https://glassfish.dev.java.net/issues/show_bug.cgi?id=4042
*/ */
public class H2Platform extends DatabasePlatform { public class H2Platform extends DatabasePlatform {
public H2Platform() { public H2Platform() {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论