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

--no commit message

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