index
int64 | repo_id
string | file_path
string | content
string |
|---|---|---|---|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/compress/LZFInputStream.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.compress;
import java.io.IOException;
import java.io.InputStream;
import org.h2.message.DbException;
import org.h2.util.Utils;
/**
* An input stream to read from an LZF stream.
* The data is automatically expanded.
*/
public class LZFInputStream extends InputStream {
private final InputStream in;
private CompressLZF decompress = new CompressLZF();
private int pos;
private int bufferLength;
private byte[] inBuffer;
private byte[] buffer;
public LZFInputStream(InputStream in) throws IOException {
this.in = in;
if (readInt() != LZFOutputStream.MAGIC) {
throw new IOException("Not an LZFInputStream");
}
}
private static byte[] ensureSize(byte[] buff, int len) {
return buff == null || buff.length < len ? Utils.newBytes(len) : buff;
}
private void fillBuffer() throws IOException {
if (buffer != null && pos < bufferLength) {
return;
}
int len = readInt();
if (decompress == null) {
// EOF
this.bufferLength = 0;
} else if (len < 0) {
len = -len;
buffer = ensureSize(buffer, len);
readFully(buffer, len);
this.bufferLength = len;
} else {
inBuffer = ensureSize(inBuffer, len);
int size = readInt();
readFully(inBuffer, len);
buffer = ensureSize(buffer, size);
try {
decompress.expand(inBuffer, 0, len, buffer, 0, size);
} catch (ArrayIndexOutOfBoundsException e) {
DbException.convertToIOException(e);
}
this.bufferLength = size;
}
pos = 0;
}
private void readFully(byte[] buff, int len) throws IOException {
int off = 0;
while (len > 0) {
int l = in.read(buff, off, len);
len -= l;
off += l;
}
}
private int readInt() throws IOException {
int x = in.read();
if (x < 0) {
decompress = null;
return 0;
}
x = (x << 24) + (in.read() << 16) + (in.read() << 8) + in.read();
return x;
}
@Override
public int read() throws IOException {
fillBuffer();
if (pos >= bufferLength) {
return -1;
}
return buffer[pos++] & 255;
}
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
int read = 0;
while (len > 0) {
int r = readBlock(b, off, len);
if (r < 0) {
break;
}
read += r;
off += r;
len -= r;
}
return read == 0 ? -1 : read;
}
private int readBlock(byte[] b, int off, int len) throws IOException {
fillBuffer();
if (pos >= bufferLength) {
return -1;
}
int max = Math.min(len, bufferLength - pos);
max = Math.min(max, b.length - off);
System.arraycopy(buffer, pos, b, off, max);
pos += max;
return max;
}
@Override
public void close() throws IOException {
in.close();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/compress/LZFOutputStream.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.compress;
import java.io.IOException;
import java.io.OutputStream;
import org.h2.engine.Constants;
/**
* An output stream to write an LZF stream.
* The data is automatically compressed.
*/
public class LZFOutputStream extends OutputStream {
/**
* The file header of a LZF file.
*/
static final int MAGIC = ('H' << 24) | ('2' << 16) | ('I' << 8) | 'S';
private final OutputStream out;
private final CompressLZF compress = new CompressLZF();
private final byte[] buffer;
private int pos;
private byte[] outBuffer;
public LZFOutputStream(OutputStream out) throws IOException {
this.out = out;
int len = Constants.IO_BUFFER_SIZE_COMPRESS;
buffer = new byte[len];
ensureOutput(len);
writeInt(MAGIC);
}
private void ensureOutput(int len) {
// TODO calculate the maximum overhead (worst case) for the output
// buffer
int outputLen = (len < 100 ? len + 100 : len) * 2;
if (outBuffer == null || outBuffer.length < outputLen) {
outBuffer = new byte[outputLen];
}
}
@Override
public void write(int b) throws IOException {
if (pos >= buffer.length) {
flush();
}
buffer[pos++] = (byte) b;
}
private void compressAndWrite(byte[] buff, int len) throws IOException {
if (len > 0) {
ensureOutput(len);
int compressed = compress.compress(buff, len, outBuffer, 0);
if (compressed > len) {
writeInt(-len);
out.write(buff, 0, len);
} else {
writeInt(compressed);
writeInt(len);
out.write(outBuffer, 0, compressed);
}
}
}
private void writeInt(int x) throws IOException {
out.write((byte) (x >> 24));
out.write((byte) (x >> 16));
out.write((byte) (x >> 8));
out.write((byte) x);
}
@Override
public void write(byte[] buff, int off, int len) throws IOException {
while (len > 0) {
int copy = Math.min(buffer.length - pos, len);
System.arraycopy(buff, off, buffer, pos, copy);
pos += copy;
if (pos >= buffer.length) {
flush();
}
off += copy;
len -= copy;
}
}
@Override
public void flush() throws IOException {
compressAndWrite(buffer, pos);
pos = 0;
}
@Override
public void close() throws IOException {
flush();
out.close();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/constraint/Constraint.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.constraint;
import java.util.HashSet;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.expression.ExpressionVisitor;
import org.h2.index.Index;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObjectBase;
import org.h2.table.Column;
import org.h2.table.Table;
/**
* The base class for constraint checking.
*/
public abstract class Constraint extends SchemaObjectBase implements
Comparable<Constraint> {
public enum Type {
/**
* The constraint type for check constraints.
*/
CHECK,
/**
* The constraint type for primary key constraints.
*/
PRIMARY_KEY,
/**
* The constraint type for unique constraints.
*/
UNIQUE,
/**
* The constraint type for referential constraints.
*/
REFERENTIAL;
/**
* Get standard SQL type name.
*
* @return standard SQL type name
*/
public String getSqlName() {
if (this == Constraint.Type.PRIMARY_KEY) {
return "PRIMARY KEY";
}
if (this == Constraint.Type.REFERENTIAL) {
return "FOREIGN KEY";
}
return name();
}
}
/**
* The table for which this constraint is defined.
*/
protected Table table;
Constraint(Schema schema, int id, String name, Table table) {
initSchemaObjectBase(schema, id, name, Trace.CONSTRAINT);
this.table = table;
this.setTemporary(table.isTemporary());
}
/**
* The constraint type name
*
* @return the name
*/
public abstract Type getConstraintType();
/**
* Check if this row fulfils the constraint.
* This method throws an exception if not.
*
* @param session the session
* @param t the table
* @param oldRow the old row
* @param newRow the new row
*/
public abstract void checkRow(Session session, Table t, Row oldRow, Row newRow);
/**
* Check if this constraint needs the specified index.
*
* @param index the index
* @return true if the index is used
*/
public abstract boolean usesIndex(Index index);
/**
* This index is now the owner of the specified index.
*
* @param index the index
*/
public abstract void setIndexOwner(Index index);
/**
* Get all referenced columns.
*
* @param table the table
* @return the set of referenced columns
*/
public abstract HashSet<Column> getReferencedColumns(Table table);
/**
* Get the SQL statement to create this constraint.
*
* @return the SQL statement
*/
public abstract String getCreateSQLWithoutIndexes();
/**
* Check if this constraint needs to be checked before updating the data.
*
* @return true if it must be checked before updating
*/
public abstract boolean isBefore();
/**
* Check the existing data. This method is called if the constraint is added
* after data has been inserted into the table.
*
* @param session the session
*/
public abstract void checkExistingData(Session session);
/**
* This method is called after a related table has changed
* (the table was renamed, or columns have been renamed).
*/
public abstract void rebuild();
/**
* Get the unique index used to enforce this constraint, or null if no index
* is used.
*
* @return the index
*/
public abstract Index getUniqueIndex();
@Override
public void checkRename() {
// ok
}
@Override
public int getType() {
return DbObject.CONSTRAINT;
}
public Table getTable() {
return table;
}
public Table getRefTable() {
return table;
}
@Override
public String getDropSQL() {
return null;
}
@Override
public int compareTo(Constraint other) {
if (this == other) {
return 0;
}
return Integer.compare(getConstraintType().ordinal(), other.getConstraintType().ordinal());
}
@Override
public boolean isHidden() {
return table.isHidden();
}
/**
* Visit all elements in the constraint.
*
* @param visitor the visitor
* @return true if every visited expression returned true, or if there are
* no expressions
*/
public boolean isEverything(@SuppressWarnings("unused") ExpressionVisitor visitor) {
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/constraint/ConstraintActionType.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.constraint;
public enum ConstraintActionType {
/**
* The action is to restrict the operation.
*/
RESTRICT,
/**
* The action is to cascade the operation.
*/
CASCADE,
/**
* The action is to set the value to the default value.
*/
SET_DEFAULT,
/**
* The action is to set the value to NULL.
*/
SET_NULL;
/**
* Get standard SQL type name.
*
* @return standard SQL type name
*/
public String getSqlName() {
if (this == ConstraintActionType.SET_DEFAULT) {
return "SET DEFAULT";
}
if (this == SET_NULL) {
return "SET NULL";
}
return name();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/constraint/ConstraintCheck.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.constraint;
import java.util.HashSet;
import java.util.Iterator;
import org.h2.api.ErrorCode;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* A check constraint.
*/
public class ConstraintCheck extends Constraint {
private TableFilter filter;
private Expression expr;
public ConstraintCheck(Schema schema, int id, String name, Table table) {
super(schema, id, name, table);
}
@Override
public Type getConstraintType() {
return Constraint.Type.CHECK;
}
public void setTableFilter(TableFilter filter) {
this.filter = filter;
}
public void setExpression(Expression expr) {
this.expr = expr;
}
@Override
public String getCreateSQLForCopy(Table forTable, String quotedName) {
StringBuilder buff = new StringBuilder("ALTER TABLE ");
buff.append(forTable.getSQL()).append(" ADD CONSTRAINT ");
if (forTable.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(quotedName);
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append(" CHECK").append(StringUtils.enclose(expr.getSQL()))
.append(" NOCHECK");
return buff.toString();
}
private String getShortDescription() {
return getName() + ": " + expr.getSQL();
}
@Override
public String getCreateSQLWithoutIndexes() {
return getCreateSQL();
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(table, getSQL());
}
@Override
public void removeChildrenAndResources(Session session) {
table.removeConstraint(this);
database.removeMeta(session, getId());
filter = null;
expr = null;
table = null;
invalidate();
}
@Override
public void checkRow(Session session, Table t, Row oldRow, Row newRow) {
if (newRow == null) {
return;
}
filter.set(newRow);
boolean b;
try {
Value v = expr.getValue(session);
// Both TRUE and NULL are ok
b = v == ValueNull.INSTANCE || v.getBoolean();
} catch (DbException ex) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_INVALID, ex,
getShortDescription());
}
if (!b) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1,
getShortDescription());
}
}
@Override
public boolean usesIndex(Index index) {
return false;
}
@Override
public void setIndexOwner(Index index) {
DbException.throwInternalError(toString());
}
@Override
public HashSet<Column> getReferencedColumns(Table table) {
HashSet<Column> columns = new HashSet<>();
expr.isEverything(ExpressionVisitor.getColumnsVisitor(columns));
for (Iterator<Column> it = columns.iterator(); it.hasNext();) {
if (it.next().getTable() != table) {
it.remove();
}
}
return columns;
}
public Expression getExpression() {
return expr;
}
@Override
public boolean isBefore() {
return true;
}
@Override
public void checkExistingData(Session session) {
if (session.getDatabase().isStarting()) {
// don't check at startup
return;
}
String sql = "SELECT 1 FROM " + filter.getTable().getSQL() +
" WHERE NOT(" + expr.getSQL() + ")";
ResultInterface r = session.prepare(sql).query(1);
if (r.next()) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, getName());
}
}
@Override
public Index getUniqueIndex() {
return null;
}
@Override
public void rebuild() {
// nothing to do
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return expr.isEverything(visitor);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/constraint/ConstraintReferential.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.constraint;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.Parser;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.Parameter;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
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.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* A referential constraint.
*/
public class ConstraintReferential extends Constraint {
private IndexColumn[] columns;
private IndexColumn[] refColumns;
private ConstraintActionType deleteAction = ConstraintActionType.RESTRICT;
private ConstraintActionType updateAction = ConstraintActionType.RESTRICT;
private Table refTable;
private Index index;
private Index refIndex;
private boolean indexOwner;
private boolean refIndexOwner;
private String deleteSQL, updateSQL;
private boolean skipOwnTable;
public ConstraintReferential(Schema schema, int id, String name, Table table) {
super(schema, id, name, table);
}
@Override
public Type getConstraintType() {
return Constraint.Type.REFERENTIAL;
}
/**
* Create the SQL statement of this object so a copy of the table can be
* made.
*
* @param forTable the table to create the object for
* @param quotedName the name of this object (quoted if necessary)
* @return the SQL statement
*/
@Override
public String getCreateSQLForCopy(Table forTable, String quotedName) {
return getCreateSQLForCopy(forTable, refTable, quotedName, true);
}
/**
* Create the SQL statement of this object so a copy of the table can be
* made.
*
* @param forTable the table to create the object for
* @param forRefTable the referenced table
* @param quotedName the name of this object (quoted if necessary)
* @param internalIndex add the index name to the statement
* @return the SQL statement
*/
public String getCreateSQLForCopy(Table forTable, Table forRefTable,
String quotedName, boolean internalIndex) {
StatementBuilder buff = new StatementBuilder("ALTER TABLE ");
String mainTable = forTable.getSQL();
buff.append(mainTable).append(" ADD CONSTRAINT ");
if (forTable.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(quotedName);
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
IndexColumn[] cols = columns;
IndexColumn[] refCols = refColumns;
buff.append(" FOREIGN KEY(");
for (IndexColumn c : cols) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
if (internalIndex && indexOwner && forTable == this.table) {
buff.append(" INDEX ").append(index.getSQL());
}
buff.append(" REFERENCES ");
String quotedRefTable;
if (this.table == this.refTable) {
// self-referencing constraints: need to use new table
quotedRefTable = forTable.getSQL();
} else {
quotedRefTable = forRefTable.getSQL();
}
buff.append(quotedRefTable).append('(');
buff.resetCount();
for (IndexColumn r : refCols) {
buff.appendExceptFirst(", ");
buff.append(r.getSQL());
}
buff.append(')');
if (internalIndex && refIndexOwner && forTable == this.table) {
buff.append(" INDEX ").append(refIndex.getSQL());
}
if (deleteAction != ConstraintActionType.RESTRICT) {
buff.append(" ON DELETE ").append(deleteAction.getSqlName());
}
if (updateAction != ConstraintActionType.RESTRICT) {
buff.append(" ON UPDATE ").append(updateAction.getSqlName());
}
return buff.append(" NOCHECK").toString();
}
/**
* Get a short description of the constraint. This includes the constraint
* name (if set), and the constraint expression.
*
* @param searchIndex the index, or null
* @param check the row, or null
* @return the description
*/
private String getShortDescription(Index searchIndex, SearchRow check) {
StatementBuilder buff = new StatementBuilder(getName());
buff.append(": ").append(table.getSQL()).append(" FOREIGN KEY(");
for (IndexColumn c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(") REFERENCES ").append(refTable.getSQL()).append('(');
buff.resetCount();
for (IndexColumn r : refColumns) {
buff.appendExceptFirst(", ");
buff.append(r.getSQL());
}
buff.append(')');
if (searchIndex != null && check != null) {
buff.append(" (");
buff.resetCount();
Column[] cols = searchIndex.getColumns();
int len = Math.min(columns.length, cols.length);
for (int i = 0; i < len; i++) {
int idx = cols[i].getColumnId();
Value c = check.getValue(idx);
buff.appendExceptFirst(", ");
buff.append(c == null ? "" : c.toString());
}
buff.append(')');
}
return buff.toString();
}
@Override
public String getCreateSQLWithoutIndexes() {
return getCreateSQLForCopy(table, refTable, getSQL(), false);
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(table, getSQL());
}
public void setColumns(IndexColumn[] cols) {
columns = cols;
}
public IndexColumn[] getColumns() {
return columns;
}
@Override
public HashSet<Column> getReferencedColumns(Table table) {
HashSet<Column> result = new HashSet<>();
if (table == this.table) {
for (IndexColumn c : columns) {
result.add(c.column);
}
} else if (table == this.refTable) {
for (IndexColumn c : refColumns) {
result.add(c.column);
}
}
return result;
}
public void setRefColumns(IndexColumn[] refCols) {
refColumns = refCols;
}
public IndexColumn[] getRefColumns() {
return refColumns;
}
public void setRefTable(Table refTable) {
this.refTable = refTable;
if (refTable.isTemporary()) {
setTemporary(true);
}
}
/**
* Set the index to use for this constraint.
*
* @param index the index
* @param isOwner true if the index is generated by the system and belongs
* to this constraint
*/
public void setIndex(Index index, boolean isOwner) {
this.index = index;
this.indexOwner = isOwner;
}
/**
* Set the index of the referenced table to use for this constraint.
*
* @param refIndex the index
* @param isRefOwner true if the index is generated by the system and
* belongs to this constraint
*/
public void setRefIndex(Index refIndex, boolean isRefOwner) {
this.refIndex = refIndex;
this.refIndexOwner = isRefOwner;
}
@Override
public void removeChildrenAndResources(Session session) {
table.removeConstraint(this);
refTable.removeConstraint(this);
if (indexOwner) {
table.removeIndexOrTransferOwnership(session, index);
}
if (refIndexOwner) {
refTable.removeIndexOrTransferOwnership(session, refIndex);
}
database.removeMeta(session, getId());
refTable = null;
index = null;
refIndex = null;
columns = null;
refColumns = null;
deleteSQL = null;
updateSQL = null;
table = null;
invalidate();
}
@Override
public void checkRow(Session session, Table t, Row oldRow, Row newRow) {
if (!database.getReferentialIntegrity()) {
return;
}
if (!table.getCheckForeignKeyConstraints() ||
!refTable.getCheckForeignKeyConstraints()) {
return;
}
if (t == table) {
if (!skipOwnTable) {
checkRowOwnTable(session, oldRow, newRow);
}
}
if (t == refTable) {
checkRowRefTable(session, oldRow, newRow);
}
}
private void checkRowOwnTable(Session session, Row oldRow, Row newRow) {
if (newRow == null) {
return;
}
boolean constraintColumnsEqual = oldRow != null;
for (IndexColumn col : columns) {
int idx = col.column.getColumnId();
Value v = newRow.getValue(idx);
if (v == ValueNull.INSTANCE) {
// return early if one of the columns is NULL
return;
}
if (constraintColumnsEqual) {
if (!database.areEqual(v, oldRow.getValue(idx))) {
constraintColumnsEqual = false;
}
}
}
if (constraintColumnsEqual) {
// return early if the key columns didn't change
return;
}
if (refTable == table) {
// special case self referencing constraints:
// check the inserted row first
boolean self = true;
for (int i = 0, len = columns.length; i < len; i++) {
int idx = columns[i].column.getColumnId();
Value v = newRow.getValue(idx);
Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId();
Value r = newRow.getValue(refIdx);
if (!database.areEqual(r, v)) {
self = false;
break;
}
}
if (self) {
return;
}
}
Row check = refTable.getTemplateRow();
for (int i = 0, len = columns.length; i < len; i++) {
int idx = columns[i].column.getColumnId();
Value v = newRow.getValue(idx);
Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId();
check.setValue(refIdx, refCol.convert(v));
}
if (!existsRow(session, refIndex, check, null)) {
throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1,
getShortDescription(refIndex, check));
}
}
private boolean existsRow(Session session, Index searchIndex,
SearchRow check, Row excluding) {
Table searchTable = searchIndex.getTable();
searchTable.lock(session, false, false);
Cursor cursor = searchIndex.find(session, check, check);
while (cursor.next()) {
SearchRow found;
found = cursor.getSearchRow();
if (excluding != null && found.getKey() == excluding.getKey()) {
continue;
}
Column[] cols = searchIndex.getColumns();
boolean allEqual = true;
int len = Math.min(columns.length, cols.length);
for (int i = 0; i < len; i++) {
int idx = cols[i].getColumnId();
Value c = check.getValue(idx);
Value f = found.getValue(idx);
if (searchTable.compareTypeSafe(c, f) != 0) {
allEqual = false;
break;
}
}
if (allEqual) {
return true;
}
}
return false;
}
private boolean isEqual(Row oldRow, Row newRow) {
return refIndex.compareRows(oldRow, newRow) == 0;
}
private void checkRow(Session session, Row oldRow) {
SearchRow check = table.getTemplateSimpleRow(false);
for (int i = 0, len = columns.length; i < len; i++) {
Column refCol = refColumns[i].column;
int refIdx = refCol.getColumnId();
Column col = columns[i].column;
Value v = col.convert(oldRow.getValue(refIdx));
if (v == ValueNull.INSTANCE) {
return;
}
check.setValue(col.getColumnId(), v);
}
// exclude the row only for self-referencing constraints
Row excluding = (refTable == table) ? oldRow : null;
if (existsRow(session, index, check, excluding)) {
throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_CHILD_EXISTS_1,
getShortDescription(index, check));
}
}
private void checkRowRefTable(Session session, Row oldRow, Row newRow) {
if (oldRow == null) {
// this is an insert
return;
}
if (newRow != null && isEqual(oldRow, newRow)) {
// on an update, if both old and new are the same, don't do anything
return;
}
if (newRow == null) {
// this is a delete
if (deleteAction == ConstraintActionType.RESTRICT) {
checkRow(session, oldRow);
} else {
int i = deleteAction == ConstraintActionType.CASCADE ? 0 : columns.length;
Prepared deleteCommand = getDelete(session);
setWhere(deleteCommand, i, oldRow);
updateWithSkipCheck(deleteCommand);
}
} else {
// this is an update
if (updateAction == ConstraintActionType.RESTRICT) {
checkRow(session, oldRow);
} else {
Prepared updateCommand = getUpdate(session);
if (updateAction == ConstraintActionType.CASCADE) {
ArrayList<Parameter> params = updateCommand.getParameters();
for (int i = 0, len = columns.length; i < len; i++) {
Parameter param = params.get(i);
Column refCol = refColumns[i].column;
param.setValue(newRow.getValue(refCol.getColumnId()));
}
}
setWhere(updateCommand, columns.length, oldRow);
updateWithSkipCheck(updateCommand);
}
}
}
private void updateWithSkipCheck(Prepared prep) {
// TODO constraints: maybe delay the update or support delayed checks
// (until commit)
try {
// TODO multithreaded kernel: this works only if nobody else updates
// this or the ref table at the same time
skipOwnTable = true;
prep.update();
} finally {
skipOwnTable = false;
}
}
private void setWhere(Prepared command, int pos, Row row) {
for (int i = 0, len = refColumns.length; i < len; i++) {
int idx = refColumns[i].column.getColumnId();
Value v = row.getValue(idx);
ArrayList<Parameter> params = command.getParameters();
Parameter param = params.get(pos + i);
param.setValue(v);
}
}
public ConstraintActionType getDeleteAction() {
return deleteAction;
}
/**
* Set the action to apply (restrict, cascade,...) on a delete.
*
* @param action the action
*/
public void setDeleteAction(ConstraintActionType action) {
if (action == deleteAction && deleteSQL == null) {
return;
}
if (deleteAction != ConstraintActionType.RESTRICT) {
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, "ON DELETE");
}
this.deleteAction = action;
buildDeleteSQL();
}
private void buildDeleteSQL() {
if (deleteAction == ConstraintActionType.RESTRICT) {
return;
}
StatementBuilder buff = new StatementBuilder();
if (deleteAction == ConstraintActionType.CASCADE) {
buff.append("DELETE FROM ").append(table.getSQL());
} else {
appendUpdate(buff);
}
appendWhere(buff);
deleteSQL = buff.toString();
}
private Prepared getUpdate(Session session) {
return prepare(session, updateSQL, updateAction);
}
private Prepared getDelete(Session session) {
return prepare(session, deleteSQL, deleteAction);
}
public ConstraintActionType getUpdateAction() {
return updateAction;
}
/**
* Set the action to apply (restrict, cascade,...) on an update.
*
* @param action the action
*/
public void setUpdateAction(ConstraintActionType action) {
if (action == updateAction && updateSQL == null) {
return;
}
if (updateAction != ConstraintActionType.RESTRICT) {
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, "ON UPDATE");
}
this.updateAction = action;
buildUpdateSQL();
}
private void buildUpdateSQL() {
if (updateAction == ConstraintActionType.RESTRICT) {
return;
}
StatementBuilder buff = new StatementBuilder();
appendUpdate(buff);
appendWhere(buff);
updateSQL = buff.toString();
}
@Override
public void rebuild() {
buildUpdateSQL();
buildDeleteSQL();
}
private Prepared prepare(Session session, String sql, ConstraintActionType action) {
Prepared command = session.prepare(sql);
if (action != ConstraintActionType.CASCADE) {
ArrayList<Parameter> params = command.getParameters();
for (int i = 0, len = columns.length; i < len; i++) {
Column column = columns[i].column;
Parameter param = params.get(i);
Value value;
if (action == ConstraintActionType.SET_NULL) {
value = ValueNull.INSTANCE;
} else {
Expression expr = column.getDefaultExpression();
if (expr == null) {
throw DbException.get(ErrorCode.NO_DEFAULT_SET_1, column.getName());
}
value = expr.getValue(session);
}
param.setValue(value);
}
}
return command;
}
private void appendUpdate(StatementBuilder buff) {
buff.append("UPDATE ").append(table.getSQL()).append(" SET ");
buff.resetCount();
for (IndexColumn c : columns) {
buff.appendExceptFirst(" , ");
buff.append(Parser.quoteIdentifier(c.column.getName())).append("=?");
}
}
private void appendWhere(StatementBuilder buff) {
buff.append(" WHERE ");
buff.resetCount();
for (IndexColumn c : columns) {
buff.appendExceptFirst(" AND ");
buff.append(Parser.quoteIdentifier(c.column.getName())).append("=?");
}
}
@Override
public Table getRefTable() {
return refTable;
}
@Override
public boolean usesIndex(Index idx) {
return idx == index || idx == refIndex;
}
@Override
public void setIndexOwner(Index index) {
if (this.index == index) {
indexOwner = true;
} else if (this.refIndex == index) {
refIndexOwner = true;
} else {
DbException.throwInternalError(index + " " + toString());
}
}
@Override
public boolean isBefore() {
return false;
}
@Override
public void checkExistingData(Session session) {
if (session.getDatabase().isStarting()) {
// don't check at startup
return;
}
session.startStatementWithinTransaction();
StatementBuilder buff = new StatementBuilder("SELECT 1 FROM (SELECT ");
for (IndexColumn c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(" FROM ").append(table.getSQL()).append(" WHERE ");
buff.resetCount();
for (IndexColumn c : columns) {
buff.appendExceptFirst(" AND ");
buff.append(c.getSQL()).append(" IS NOT NULL ");
}
buff.append(" ORDER BY ");
buff.resetCount();
for (IndexColumn c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(") C WHERE NOT EXISTS(SELECT 1 FROM ").
append(refTable.getSQL()).append(" P WHERE ");
buff.resetCount();
int i = 0;
for (IndexColumn c : columns) {
buff.appendExceptFirst(" AND ");
buff.append("C.").append(c.getSQL()).append('=').
append("P.").append(refColumns[i++].getSQL());
}
buff.append(')');
String sql = buff.toString();
ResultInterface r = session.prepare(sql).query(1);
if (r.next()) {
throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1,
getShortDescription(null, null));
}
}
@Override
public Index getUniqueIndex() {
return refIndex;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/constraint/ConstraintUnique.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.constraint;
import java.util.HashSet;
import org.h2.command.Parser;
import org.h2.engine.Session;
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.StatementBuilder;
import org.h2.util.StringUtils;
/**
* A unique constraint. This object always backed by a unique index.
*/
public class ConstraintUnique extends Constraint {
private Index index;
private boolean indexOwner;
private IndexColumn[] columns;
private final boolean primaryKey;
public ConstraintUnique(Schema schema, int id, String name, Table table,
boolean primaryKey) {
super(schema, id, name, table);
this.primaryKey = primaryKey;
}
@Override
public Type getConstraintType() {
return primaryKey ? Constraint.Type.PRIMARY_KEY : Constraint.Type.UNIQUE;
}
@Override
public String getCreateSQLForCopy(Table forTable, String quotedName) {
return getCreateSQLForCopy(forTable, quotedName, true);
}
private String getCreateSQLForCopy(Table forTable, String quotedName,
boolean internalIndex) {
StatementBuilder buff = new StatementBuilder("ALTER TABLE ");
buff.append(forTable.getSQL()).append(" ADD CONSTRAINT ");
if (forTable.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(quotedName);
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append(' ').append(getConstraintType().getSqlName()).append('(');
for (IndexColumn c : columns) {
buff.appendExceptFirst(", ");
buff.append(Parser.quoteIdentifier(c.column.getName()));
}
buff.append(')');
if (internalIndex && indexOwner && forTable == this.table) {
buff.append(" INDEX ").append(index.getSQL());
}
return buff.toString();
}
@Override
public String getCreateSQLWithoutIndexes() {
return getCreateSQLForCopy(table, getSQL(), false);
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(table, getSQL());
}
public void setColumns(IndexColumn[] columns) {
this.columns = columns;
}
public IndexColumn[] getColumns() {
return columns;
}
/**
* Set the index to use for this unique constraint.
*
* @param index the index
* @param isOwner true if the index is generated by the system and belongs
* to this constraint
*/
public void setIndex(Index index, boolean isOwner) {
this.index = index;
this.indexOwner = isOwner;
}
@Override
public void removeChildrenAndResources(Session session) {
table.removeConstraint(this);
if (indexOwner) {
table.removeIndexOrTransferOwnership(session, index);
}
database.removeMeta(session, getId());
index = null;
columns = null;
table = null;
invalidate();
}
@Override
public void checkRow(Session session, Table t, Row oldRow, Row newRow) {
// unique index check is enough
}
@Override
public boolean usesIndex(Index idx) {
return idx == index;
}
@Override
public void setIndexOwner(Index index) {
indexOwner = true;
}
@Override
public HashSet<Column> getReferencedColumns(Table table) {
HashSet<Column> result = new HashSet<>();
for (IndexColumn c : columns) {
result.add(c.column);
}
return result;
}
@Override
public boolean isBefore() {
return true;
}
@Override
public void checkExistingData(Session session) {
// no need to check: when creating the unique index any problems are
// found
}
@Override
public Index getUniqueIndex() {
return index;
}
@Override
public void rebuild() {
// nothing to do
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Comment.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.table.Table;
import org.h2.util.StringUtils;
/**
* Represents a database object comment.
*/
public class Comment extends DbObjectBase {
private final int objectType;
private final String objectName;
private String commentText;
public Comment(Database database, int id, DbObject obj) {
initDbObjectBase(database, id, getKey(obj), Trace.DATABASE);
this.objectType = obj.getType();
this.objectName = obj.getSQL();
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
private static String getTypeName(int type) {
switch (type) {
case DbObject.CONSTANT:
return "CONSTANT";
case DbObject.CONSTRAINT:
return "CONSTRAINT";
case DbObject.FUNCTION_ALIAS:
return "ALIAS";
case DbObject.INDEX:
return "INDEX";
case DbObject.ROLE:
return "ROLE";
case DbObject.SCHEMA:
return "SCHEMA";
case DbObject.SEQUENCE:
return "SEQUENCE";
case DbObject.TABLE_OR_VIEW:
return "TABLE";
case DbObject.TRIGGER:
return "TRIGGER";
case DbObject.USER:
return "USER";
case DbObject.USER_DATATYPE:
return "DOMAIN";
default:
// not supported by parser, but required when trying to find a
// comment
return "type" + type;
}
}
@Override
public String getDropSQL() {
return null;
}
@Override
public String getCreateSQL() {
StringBuilder buff = new StringBuilder("COMMENT ON ");
buff.append(getTypeName(objectType)).append(' ').
append(objectName).append(" IS ");
if (commentText == null) {
buff.append("NULL");
} else {
buff.append(StringUtils.quoteStringSQL(commentText));
}
return buff.toString();
}
@Override
public int getType() {
return DbObject.COMMENT;
}
@Override
public void removeChildrenAndResources(Session session) {
database.removeMeta(session, getId());
}
@Override
public void checkRename() {
DbException.throwInternalError();
}
/**
* Get the comment key name for the given database object. This key name is
* used internally to associate the comment to the object.
*
* @param obj the object
* @return the key name
*/
static String getKey(DbObject obj) {
return getTypeName(obj.getType()) + " " + obj.getSQL();
}
/**
* Set the comment text.
*
* @param comment the text
*/
public void setCommentText(String comment) {
this.commentText = comment;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/ConnectionInfo.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import org.h2.api.ErrorCode;
import org.h2.command.dml.SetTypes;
import org.h2.message.DbException;
import org.h2.security.SHA256;
import org.h2.store.fs.FilePathEncrypt;
import org.h2.store.fs.FilePathRec;
import org.h2.store.fs.FileUtils;
import org.h2.util.SortedProperties;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* Encapsulates the connection settings, including user name and password.
*/
public class ConnectionInfo implements Cloneable {
private static final HashSet<String> KNOWN_SETTINGS;
private Properties prop = new Properties();
private String originalURL;
private String url;
private String user;
private byte[] filePasswordHash;
private byte[] fileEncryptionKey;
private byte[] userPasswordHash;
/**
* The database name
*/
private String name;
private String nameNormalized;
private boolean remote;
private boolean ssl;
private boolean persistent;
private boolean unnamed;
/**
* Create a connection info object.
*
* @param name the database name (including tags), but without the
* "jdbc:h2:" prefix
*/
public ConnectionInfo(String name) {
this.name = name;
this.url = Constants.START_URL + name;
parseName();
}
/**
* Create a connection info object.
*
* @param u the database URL (must start with jdbc:h2:)
* @param info the connection properties
*/
public ConnectionInfo(String u, Properties info) {
u = remapURL(u);
this.originalURL = u;
if (!u.startsWith(Constants.START_URL)) {
throw DbException.getInvalidValueException("url", u);
}
this.url = u;
readProperties(info);
readSettingsFromURL();
setUserName(removeProperty("USER", ""));
convertPasswords();
name = url.substring(Constants.START_URL.length());
parseName();
String recoverTest = removeProperty("RECOVER_TEST", null);
if (recoverTest != null) {
FilePathRec.register();
try {
Utils.callStaticMethod("org.h2.store.RecoverTester.init", recoverTest);
} catch (Exception e) {
throw DbException.convert(e);
}
name = "rec:" + name;
}
}
static {
ArrayList<String> list = SetTypes.getTypes();
String[] connectionTime = { "ACCESS_MODE_DATA", "AUTOCOMMIT", "CIPHER",
"CREATE", "CACHE_TYPE", "FILE_LOCK", "IGNORE_UNKNOWN_SETTINGS",
"IFEXISTS", "INIT", "PASSWORD", "RECOVER", "RECOVER_TEST",
"USER", "AUTO_SERVER", "AUTO_SERVER_PORT", "NO_UPGRADE",
"AUTO_RECONNECT", "OPEN_NEW", "PAGE_SIZE", "PASSWORD_HASH", "JMX",
"SCOPE_GENERATED_KEYS" };
HashSet<String> set = new HashSet<>(list.size() + connectionTime.length);
set.addAll(list);
for (String key : connectionTime) {
if (!set.add(key) && SysProperties.CHECK) {
DbException.throwInternalError(key);
}
}
KNOWN_SETTINGS = set;
}
private static boolean isKnownSetting(String s) {
return KNOWN_SETTINGS.contains(s);
}
@Override
public ConnectionInfo clone() throws CloneNotSupportedException {
ConnectionInfo clone = (ConnectionInfo) super.clone();
clone.prop = (Properties) prop.clone();
clone.filePasswordHash = Utils.cloneByteArray(filePasswordHash);
clone.fileEncryptionKey = Utils.cloneByteArray(fileEncryptionKey);
clone.userPasswordHash = Utils.cloneByteArray(userPasswordHash);
return clone;
}
private void parseName() {
if (".".equals(name)) {
name = "mem:";
}
if (name.startsWith("tcp:")) {
remote = true;
name = name.substring("tcp:".length());
} else if (name.startsWith("ssl:")) {
remote = true;
ssl = true;
name = name.substring("ssl:".length());
} else if (name.startsWith("mem:")) {
persistent = false;
if ("mem:".equals(name)) {
unnamed = true;
}
} else if (name.startsWith("file:")) {
name = name.substring("file:".length());
persistent = true;
} else {
persistent = true;
}
if (persistent && !remote) {
if ("/".equals(SysProperties.FILE_SEPARATOR)) {
name = name.replace('\\', '/');
} else {
name = name.replace('/', '\\');
}
}
}
/**
* Set the base directory of persistent databases, unless the database is in
* the user home folder (~).
*
* @param dir the new base directory
*/
public void setBaseDir(String dir) {
if (persistent) {
String absDir = FileUtils.unwrap(FileUtils.toRealPath(dir));
boolean absolute = FileUtils.isAbsolute(name);
String n;
String prefix = null;
if (dir.endsWith(SysProperties.FILE_SEPARATOR)) {
dir = dir.substring(0, dir.length() - 1);
}
if (absolute) {
n = name;
} else {
n = FileUtils.unwrap(name);
prefix = name.substring(0, name.length() - n.length());
n = dir + SysProperties.FILE_SEPARATOR + n;
}
String normalizedName = FileUtils.unwrap(FileUtils.toRealPath(n));
if (normalizedName.equals(absDir) || !normalizedName.startsWith(absDir)) {
// database name matches the baseDir or
// database name is clearly outside of the baseDir
throw DbException.get(ErrorCode.IO_EXCEPTION_1, normalizedName + " outside " +
absDir);
}
if (absDir.endsWith("/") || absDir.endsWith("\\")) {
// no further checks are needed for C:/ and similar
} else if (normalizedName.charAt(absDir.length()) != '/') {
// database must be within the directory
// (with baseDir=/test, the database name must not be
// /test2/x and not /test2)
throw DbException.get(ErrorCode.IO_EXCEPTION_1, normalizedName + " outside " +
absDir);
}
if (!absolute) {
name = prefix + dir + SysProperties.FILE_SEPARATOR + FileUtils.unwrap(name);
}
}
}
/**
* Check if this is a remote connection.
*
* @return true if it is
*/
public boolean isRemote() {
return remote;
}
/**
* Check if the referenced database is persistent.
*
* @return true if it is
*/
public boolean isPersistent() {
return persistent;
}
/**
* Check if the referenced database is an unnamed in-memory database.
*
* @return true if it is
*/
boolean isUnnamedInMemory() {
return unnamed;
}
private void readProperties(Properties info) {
Object[] list = info.keySet().toArray();
DbSettings s = null;
for (Object k : list) {
String key = StringUtils.toUpperEnglish(k.toString());
if (prop.containsKey(key)) {
throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
}
Object value = info.get(k);
if (isKnownSetting(key)) {
prop.put(key, value);
} else {
if (s == null) {
s = getDbSettings();
}
if (s.containsKey(key)) {
prop.put(key, value);
}
}
}
}
private void readSettingsFromURL() {
DbSettings defaultSettings = DbSettings.getDefaultSettings();
int idx = url.indexOf(';');
if (idx >= 0) {
String settings = url.substring(idx + 1);
url = url.substring(0, idx);
String[] list = StringUtils.arraySplit(settings, ';', false);
for (String setting : list) {
if (setting.length() == 0) {
continue;
}
int equal = setting.indexOf('=');
if (equal < 0) {
throw getFormatException();
}
String value = setting.substring(equal + 1);
String key = setting.substring(0, equal);
key = StringUtils.toUpperEnglish(key);
if (!isKnownSetting(key) && !defaultSettings.containsKey(key)) {
throw DbException.get(ErrorCode.UNSUPPORTED_SETTING_1, key);
}
String old = prop.getProperty(key);
if (old != null && !old.equals(value)) {
throw DbException.get(ErrorCode.DUPLICATE_PROPERTY_1, key);
}
prop.setProperty(key, value);
}
}
}
private char[] removePassword() {
Object p = prop.remove("PASSWORD");
if (p == null) {
return new char[0];
} else if (p instanceof char[]) {
return (char[]) p;
} else {
return p.toString().toCharArray();
}
}
/**
* Split the password property into file password and user password if
* necessary, and convert them to the internal hash format.
*/
private void convertPasswords() {
char[] password = removePassword();
boolean passwordHash = removeProperty("PASSWORD_HASH", false);
if (getProperty("CIPHER", null) != null) {
// split password into (filePassword+' '+userPassword)
int space = -1;
for (int i = 0, len = password.length; i < len; i++) {
if (password[i] == ' ') {
space = i;
break;
}
}
if (space < 0) {
throw DbException.get(ErrorCode.WRONG_PASSWORD_FORMAT);
}
char[] np = Arrays.copyOfRange(password, space + 1, password.length);
char[] filePassword = Arrays.copyOf(password, space);
Arrays.fill(password, (char) 0);
password = np;
fileEncryptionKey = FilePathEncrypt.getPasswordBytes(filePassword);
filePasswordHash = hashPassword(passwordHash, "file", filePassword);
}
userPasswordHash = hashPassword(passwordHash, user, password);
}
private static byte[] hashPassword(boolean passwordHash, String userName,
char[] password) {
if (passwordHash) {
return StringUtils.convertHexToBytes(new String(password));
}
if (userName.length() == 0 && password.length == 0) {
return new byte[0];
}
return SHA256.getKeyPasswordHash(userName, password);
}
/**
* Get a boolean property if it is set and return the value.
*
* @param key the property name
* @param defaultValue the default value
* @return the value
*/
public boolean getProperty(String key, boolean defaultValue) {
return Utils.parseBoolean(getProperty(key, null), defaultValue, false);
}
/**
* Remove a boolean property if it is set and return the value.
*
* @param key the property name
* @param defaultValue the default value
* @return the value
*/
public boolean removeProperty(String key, boolean defaultValue) {
return Utils.parseBoolean(removeProperty(key, null), defaultValue, false);
}
/**
* Remove a String property if it is set and return the value.
*
* @param key the property name
* @param defaultValue the default value
* @return the value
*/
String removeProperty(String key, String defaultValue) {
if (SysProperties.CHECK && !isKnownSetting(key)) {
DbException.throwInternalError(key);
}
Object x = prop.remove(key);
return x == null ? defaultValue : x.toString();
}
/**
* Get the unique and normalized database name (excluding settings).
*
* @return the database name
*/
public String getName() {
if (!persistent) {
return name;
}
if (nameNormalized == null) {
if (!SysProperties.IMPLICIT_RELATIVE_PATH) {
if (!FileUtils.isAbsolute(name)) {
if (!name.contains("./") &&
!name.contains(".\\") &&
!name.contains(":/") &&
!name.contains(":\\")) {
// the name could start with "./", or
// it could start with a prefix such as "nio:./"
// for Windows, the path "\test" is not considered
// absolute as the drive letter is missing,
// but we consider it absolute
throw DbException.get(
ErrorCode.URL_RELATIVE_TO_CWD,
originalURL);
}
}
}
String suffix = Constants.SUFFIX_PAGE_FILE;
String n;
if (FileUtils.exists(name + suffix)) {
n = FileUtils.toRealPath(name + suffix);
} else {
suffix = Constants.SUFFIX_MV_FILE;
n = FileUtils.toRealPath(name + suffix);
}
String fileName = FileUtils.getName(n);
if (fileName.length() < suffix.length() + 1) {
throw DbException.get(ErrorCode.INVALID_DATABASE_NAME_1, name);
}
nameNormalized = n.substring(0, n.length() - suffix.length());
}
return nameNormalized;
}
/**
* Get the file password hash if it is set.
*
* @return the password hash or null
*/
public byte[] getFilePasswordHash() {
return filePasswordHash;
}
byte[] getFileEncryptionKey() {
return fileEncryptionKey;
}
/**
* Get the name of the user.
*
* @return the user name
*/
public String getUserName() {
return user;
}
/**
* Get the user password hash.
*
* @return the password hash
*/
byte[] getUserPasswordHash() {
return userPasswordHash;
}
/**
* Get the property keys.
*
* @return the property keys
*/
String[] getKeys() {
return prop.keySet().toArray(new String[prop.size()]);
}
/**
* Get the value of the given property.
*
* @param key the property key
* @return the value as a String
*/
String getProperty(String key) {
Object value = prop.get(key);
if (!(value instanceof String)) {
return null;
}
return value.toString();
}
/**
* Get the value of the given property.
*
* @param key the property key
* @param defaultValue the default value
* @return the value as a String
*/
int getProperty(String key, int defaultValue) {
if (SysProperties.CHECK && !isKnownSetting(key)) {
DbException.throwInternalError(key);
}
String s = getProperty(key);
return s == null ? defaultValue : Integer.parseInt(s);
}
/**
* Get the value of the given property.
*
* @param key the property key
* @param defaultValue the default value
* @return the value as a String
*/
public String getProperty(String key, String defaultValue) {
if (SysProperties.CHECK && !isKnownSetting(key)) {
DbException.throwInternalError(key);
}
String s = getProperty(key);
return s == null ? defaultValue : s;
}
/**
* Get the value of the given property.
*
* @param setting the setting id
* @param defaultValue the default value
* @return the value as a String
*/
String getProperty(int setting, String defaultValue) {
String key = SetTypes.getTypeName(setting);
String s = getProperty(key);
return s == null ? defaultValue : s;
}
/**
* Get the value of the given property.
*
* @param setting the setting id
* @param defaultValue the default value
* @return the value as an integer
*/
int getIntProperty(int setting, int defaultValue) {
String key = SetTypes.getTypeName(setting);
String s = getProperty(key, null);
try {
return s == null ? defaultValue : Integer.decode(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
/**
* Check if this is a remote connection with SSL enabled.
*
* @return true if it is
*/
boolean isSSL() {
return ssl;
}
/**
* Overwrite the user name. The user name is case-insensitive and stored in
* uppercase. English conversion is used.
*
* @param name the user name
*/
public void setUserName(String name) {
this.user = StringUtils.toUpperEnglish(name);
}
/**
* Set the user password hash.
*
* @param hash the new hash value
*/
public void setUserPasswordHash(byte[] hash) {
this.userPasswordHash = hash;
}
/**
* Set the file password hash.
*
* @param hash the new hash value
*/
public void setFilePasswordHash(byte[] hash) {
this.filePasswordHash = hash;
}
public void setFileEncryptionKey(byte[] key) {
this.fileEncryptionKey = key;
}
/**
* Overwrite a property.
*
* @param key the property name
* @param value the value
*/
public void setProperty(String key, String value) {
// value is null if the value is an object
if (value != null) {
prop.setProperty(key, value);
}
}
/**
* Get the database URL.
*
* @return the URL
*/
public String getURL() {
return url;
}
/**
* Get the complete original database URL.
*
* @return the database URL
*/
public String getOriginalURL() {
return originalURL;
}
/**
* Set the original database URL.
*
* @param url the database url
*/
public void setOriginalURL(String url) {
originalURL = url;
}
/**
* Generate an URL format exception.
*
* @return the exception
*/
DbException getFormatException() {
String format = Constants.URL_FORMAT;
return DbException.get(ErrorCode.URL_FORMAT_ERROR_2, format, url);
}
/**
* Switch to server mode, and set the server name and database key.
*
* @param serverKey the server name, '/', and the security key
*/
public void setServerKey(String serverKey) {
remote = true;
persistent = false;
this.name = serverKey;
}
public DbSettings getDbSettings() {
DbSettings defaultSettings = DbSettings.getDefaultSettings();
HashMap<String, String> s = new HashMap<>();
for (Object k : prop.keySet()) {
String key = k.toString();
if (!isKnownSetting(key) && defaultSettings.containsKey(key)) {
s.put(key, prop.getProperty(key));
}
}
return DbSettings.getInstance(s);
}
private static String remapURL(String url) {
String urlMap = SysProperties.URL_MAP;
if (urlMap != null && urlMap.length() > 0) {
try {
SortedProperties prop;
prop = SortedProperties.loadProperties(urlMap);
String url2 = prop.getProperty(url);
if (url2 == null) {
prop.put(url, "");
prop.store(urlMap);
} else {
url2 = url2.trim();
if (url2.length() > 0) {
return url2;
}
}
} catch (IOException e) {
throw DbException.convert(e);
}
}
return url;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Constants.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.sql.ResultSet;
/**
* Constants are fixed values that are used in the whole database code.
*/
public class Constants {
/**
* The build date is updated for each public release.
*/
public static final String BUILD_DATE = "2018-03-18";
/**
* The build date of the last stable release.
*/
public static final String BUILD_DATE_STABLE = "2017-06-10";
/**
* The build id is incremented for each public release.
*/
public static final int BUILD_ID = 197;
/**
* The build id of the last stable release.
*/
public static final int BUILD_ID_STABLE = 196;
/**
* Whether this is a snapshot version.
*/
public static final boolean BUILD_SNAPSHOT = false;
/**
* If H2 is compiled to be included in a product, this should be set to
* a unique vendor id (to distinguish from official releases).
* Additionally, a version number should be set to distinguish releases.
* Example: ACME_SVN1651_BUILD3
*/
public static final String BUILD_VENDOR_AND_VERSION = null;
/**
* The TCP protocol version number 8.
* @since 1.2.143 (2010-09-18)
*/
public static final int TCP_PROTOCOL_VERSION_8 = 8;
/**
* The TCP protocol version number 9.
* @since 1.3.158 (2011-07-17)
*/
public static final int TCP_PROTOCOL_VERSION_9 = 9;
/**
* The TCP protocol version number 10.
* @since 1.3.162 (2011-11-26)
*/
public static final int TCP_PROTOCOL_VERSION_10 = 10;
/**
* The TCP protocol version number 11.
* @since 1.3.163 (2011-12-30)
*/
public static final int TCP_PROTOCOL_VERSION_11 = 11;
/**
* The TCP protocol version number 12.
* @since 1.3.168 (2012-07-13)
*/
public static final int TCP_PROTOCOL_VERSION_12 = 12;
/**
* The TCP protocol version number 13.
* @since 1.3.174 (2013-10-19)
*/
public static final int TCP_PROTOCOL_VERSION_13 = 13;
/**
* The TCP protocol version number 14.
* @since 1.3.176 (2014-04-05)
*/
public static final int TCP_PROTOCOL_VERSION_14 = 14;
/**
* The TCP protocol version number 15.
* @since 1.4.178 Beta (2014-05-02)
*/
public static final int TCP_PROTOCOL_VERSION_15 = 15;
/**
* The TCP protocol version number 16.
* @since 1.4.194 (2017-03-10)
*/
public static final int TCP_PROTOCOL_VERSION_16 = 16;
/**
* The TCP protocol version number 17.
* @since 1.4.197 (TODO)
*/
public static final int TCP_PROTOCOL_VERSION_17 = 17;
/**
* Minimum supported version of TCP protocol.
*/
public static final int TCP_PROTOCOL_VERSION_MIN_SUPPORTED = TCP_PROTOCOL_VERSION_8;
/**
* Maximum supported version of TCP protocol.
*/
public static final int TCP_PROTOCOL_VERSION_MAX_SUPPORTED = TCP_PROTOCOL_VERSION_17;
/**
* The major version of this database.
*/
public static final int VERSION_MAJOR = 1;
/**
* The minor version of this database.
*/
public static final int VERSION_MINOR = 4;
/**
* The lock mode that means no locking is used at all.
*/
public static final int LOCK_MODE_OFF = 0;
/**
* The lock mode that means read locks are acquired, but they are released
* immediately after the statement is executed.
*/
public static final int LOCK_MODE_READ_COMMITTED = 3;
/**
* The lock mode that means table level locking is used for reads and
* writes.
*/
public static final int LOCK_MODE_TABLE = 1;
/**
* The lock mode that means table level locking is used for reads and
* writes. If a table is locked, System.gc is called to close forgotten
* connections.
*/
public static final int LOCK_MODE_TABLE_GC = 2;
/**
* Constant meaning both numbers and text is allowed in SQL statements.
*/
public static final int ALLOW_LITERALS_ALL = 2;
/**
* Constant meaning no literals are allowed in SQL statements.
*/
public static final int ALLOW_LITERALS_NONE = 0;
/**
* Constant meaning only numbers are allowed in SQL statements (but no
* texts).
*/
public static final int ALLOW_LITERALS_NUMBERS = 1;
/**
* Whether searching in Blob values should be supported.
*/
public static final boolean BLOB_SEARCH = false;
/**
* The minimum number of entries to keep in the cache.
*/
public static final int CACHE_MIN_RECORDS = 16;
/**
* The default cache size in KB for each GB of RAM.
*/
public static final int CACHE_SIZE_DEFAULT = 64 * 1024;
/**
* The default cache type.
*/
public static final String CACHE_TYPE_DEFAULT = "LRU";
/**
* The value of the cluster setting if clustering is disabled.
*/
public static final String CLUSTERING_DISABLED = "''";
/**
* The value of the cluster setting if clustering is enabled (the actual
* value is checked later).
*/
public static final String CLUSTERING_ENABLED = "TRUE";
/**
* The database URL used when calling a function if only the column list
* should be returned.
*/
public static final String CONN_URL_COLUMNLIST = "jdbc:columnlist:connection";
/**
* The database URL used when calling a function if the data should be
* returned.
*/
public static final String CONN_URL_INTERNAL = "jdbc:default:connection";
/**
* The cost is calculated on rowcount + this offset,
* to avoid using the wrong or no index if the table
* contains no rows _currently_ (when preparing the statement)
*/
public static final int COST_ROW_OFFSET = 1000;
/**
* The number of milliseconds after which to check for a deadlock if locking
* is not successful.
*/
public static final int DEADLOCK_CHECK = 100;
/**
* The default port number of the HTTP server (for the H2 Console).
* This value is also in the documentation and in the Server javadoc.
*/
public static final int DEFAULT_HTTP_PORT = 8082;
/**
* The default value for the LOCK_MODE setting.
*/
public static final int DEFAULT_LOCK_MODE = LOCK_MODE_READ_COMMITTED;
/**
* The default maximum length of an LOB that is stored with the record
* itself, and not in a separate place.
*/
public static final int DEFAULT_MAX_LENGTH_INPLACE_LOB = 256;
/**
* The default value for the maximum transaction log size.
*/
public static final long DEFAULT_MAX_LOG_SIZE = 16 * 1024 * 1024;
/**
* The default value for the MAX_MEMORY_UNDO setting.
*/
public static final int DEFAULT_MAX_MEMORY_UNDO = 50_000;
/**
* The default for the setting MAX_OPERATION_MEMORY.
*/
public static final int DEFAULT_MAX_OPERATION_MEMORY = 100_000;
/**
* The default page size to use for new databases.
*/
public static final int DEFAULT_PAGE_SIZE = 4096;
/**
* The default result set concurrency for statements created with
* Connection.createStatement() or prepareStatement(String sql).
*/
public static final int DEFAULT_RESULT_SET_CONCURRENCY =
ResultSet.CONCUR_READ_ONLY;
/**
* The default port of the TCP server.
* This port is also used in the documentation and in the Server javadoc.
*/
public static final int DEFAULT_TCP_PORT = 9092;
/**
* The default delay in milliseconds before the transaction log is written.
*/
public static final int DEFAULT_WRITE_DELAY = 500;
/**
* The password is hashed this many times
* to slow down dictionary attacks.
*/
public static final int ENCRYPTION_KEY_HASH_ITERATIONS = 1024;
/**
* The block of a file. It is also the encryption block size.
*/
public static final int FILE_BLOCK_SIZE = 16;
/**
* For testing, the lock timeout is smaller than for interactive use cases.
* This value could be increased to about 5 or 10 seconds.
*/
public static final int INITIAL_LOCK_TIMEOUT = 2000;
/**
* The block size for I/O operations.
*/
public static final int IO_BUFFER_SIZE = 4 * 1024;
/**
* The block size used to compress data in the LZFOutputStream.
*/
public static final int IO_BUFFER_SIZE_COMPRESS = 128 * 1024;
/**
* The number of milliseconds to wait between checking the .lock.db file
* still exists once a database is locked.
*/
public static final int LOCK_SLEEP = 1000;
/**
* The highest possible parameter index.
*/
public static final int MAX_PARAMETER_INDEX = 100_000;
/**
* The memory needed by a object of class Data
*/
public static final int MEMORY_DATA = 24;
/**
* This value is used to calculate the average memory usage.
*/
public static final int MEMORY_FACTOR = 64;
/**
* The memory needed by a regular object with at least one field.
*/
// Java 6, 64 bit: 24
// Java 6, 32 bit: 12
public static final int MEMORY_OBJECT = 24;
/**
* The memory needed by an object of class PageBtree.
*/
public static final int MEMORY_PAGE_BTREE =
112 + MEMORY_DATA + 2 * MEMORY_OBJECT;
/**
* The memory needed by an object of class PageData.
*/
public static final int MEMORY_PAGE_DATA =
144 + MEMORY_DATA + 3 * MEMORY_OBJECT;
/**
* The memory needed by an object of class PageDataOverflow.
*/
public static final int MEMORY_PAGE_DATA_OVERFLOW = 96 + MEMORY_DATA;
/**
* The memory needed by a pointer.
*/
// Java 6, 64 bit: 8
// Java 6, 32 bit: 4
public static final int MEMORY_POINTER = 8;
/**
* The memory needed by a Row.
*/
public static final int MEMORY_ROW = 40;
/**
* The minimum write delay that causes commits to be delayed.
*/
public static final int MIN_WRITE_DELAY = 5;
/**
* The name prefix used for indexes that are not explicitly named.
*/
public static final String PREFIX_INDEX = "INDEX_";
/**
* The name prefix used for synthetic nested join tables.
*/
public static final String PREFIX_JOIN = "SYSTEM_JOIN_";
/**
* The name prefix used for primary key constraints that are not explicitly
* named.
*/
public static final String PREFIX_PRIMARY_KEY = "PRIMARY_KEY_";
/**
* Every user belongs to this role.
*/
public static final String PUBLIC_ROLE_NAME = "PUBLIC";
/**
* The number of bytes in random salt that is used to hash passwords.
*/
public static final int SALT_LEN = 8;
/**
* The name of the default schema.
*/
public static final String SCHEMA_MAIN = "PUBLIC";
/**
* The default selectivity (used if the selectivity is not calculated).
*/
public static final int SELECTIVITY_DEFAULT = 50;
/**
* The number of distinct values to keep in memory when running ANALYZE.
*/
public static final int SELECTIVITY_DISTINCT_COUNT = 10_000;
/**
* The default directory name of the server properties file for the H2
* Console.
*/
public static final String SERVER_PROPERTIES_DIR = "~";
/**
* The name of the server properties file for the H2 Console.
*/
public static final String SERVER_PROPERTIES_NAME = ".h2.server.properties";
/**
* Queries that take longer than this number of milliseconds are written to
* the trace file with the level info.
*/
public static final long SLOW_QUERY_LIMIT_MS = 100;
/**
* The database URL prefix of this database.
*/
public static final String START_URL = "jdbc:h2:";
/**
* The file name suffix of all database files.
*/
public static final String SUFFIX_DB_FILE = ".db";
/**
* The file name suffix of large object files.
*/
public static final String SUFFIX_LOB_FILE = ".lob.db";
/**
* The suffix of the directory name used if LOB objects are stored in a
* directory.
*/
public static final String SUFFIX_LOBS_DIRECTORY = ".lobs.db";
/**
* The file name suffix of file lock files that are used to make sure a
* database is open by only one process at any time.
*/
public static final String SUFFIX_LOCK_FILE = ".lock.db";
/**
* The file name suffix of a H2 version 1.1 database file.
*/
public static final String SUFFIX_OLD_DATABASE_FILE = ".data.db";
/**
* The file name suffix of page files.
*/
public static final String SUFFIX_PAGE_FILE = ".h2.db";
/**
* The file name suffix of a MVStore file.
*/
public static final String SUFFIX_MV_FILE = ".mv.db";
/**
* The file name suffix of a new MVStore file, used when compacting a store.
*/
public static final String SUFFIX_MV_STORE_NEW_FILE = ".newFile";
/**
* The file name suffix of a temporary MVStore file, used when compacting a
* store.
*/
public static final String SUFFIX_MV_STORE_TEMP_FILE = ".tempFile";
/**
* The file name suffix of temporary files.
*/
public static final String SUFFIX_TEMP_FILE = ".temp.db";
/**
* The file name suffix of trace files.
*/
public static final String SUFFIX_TRACE_FILE = ".trace.db";
/**
* How often we check to see if we need to apply a throttling delay if SET
* THROTTLE has been used.
*/
public static final int THROTTLE_DELAY = 50;
/**
* The maximum size of an undo log block.
*/
public static final int UNDO_BLOCK_SIZE = 1024 * 1024;
/**
* The database URL format in simplified Backus-Naur form.
*/
public static final String URL_FORMAT = START_URL +
"{ {.|mem:}[name] | [file:]fileName | " +
"{tcp|ssl}:[//]server[:port][,server2[:port]]/name }[;key=value...]";
/**
* The package name of user defined classes.
*/
public static final String USER_PACKAGE = "org.h2.dynamic";
/**
* The maximum time in milliseconds to keep the cost of a view.
* 10000 means 10 seconds.
*/
public static final int VIEW_COST_CACHE_MAX_AGE = 10_000;
/**
* The name of the index cache that is used for temporary view (subqueries
* used as tables).
*/
public static final int VIEW_INDEX_CACHE_SIZE = 64;
/**
* The maximum number of entries in query statistics.
*/
public static final int QUERY_STATISTICS_MAX_ENTRIES = 100;
/**
* Announced version for PgServer.
*/
public static final String PG_VERSION = "8.2.23";
private Constants() {
// utility class
}
/**
* Get the version of this product, consisting of major version, minor
* version, and build id.
*
* @return the version number
*/
public static String getVersion() {
String version = VERSION_MAJOR + "." + VERSION_MINOR + "." + BUILD_ID;
if (BUILD_VENDOR_AND_VERSION != null) {
version += "_" + BUILD_VENDOR_AND_VERSION;
}
if (BUILD_SNAPSHOT) {
version += "-SNAPSHOT";
}
return version;
}
/**
* Get the last stable version name.
*
* @return the version number
*/
public static Object getVersionStable() {
return "1.4." + BUILD_ID_STABLE;
}
/**
* Get the complete version number of this database, consisting of
* the major version, the minor version, the build id, and the build date.
*
* @return the complete version
*/
public static String getFullVersion() {
return getVersion() + " (" + BUILD_DATE + ")";
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Database.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import org.h2.api.DatabaseEventListener;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.api.TableEngine;
import org.h2.command.CommandInterface;
import org.h2.command.ddl.CreateTableData;
import org.h2.command.dml.SetTypes;
import org.h2.constraint.Constraint;
import org.h2.ext.pulsar.PulsarExtension;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.message.TraceSystem;
import org.h2.mvstore.db.MVTableEngine;
import org.h2.result.Row;
import org.h2.result.RowFactory;
import org.h2.result.SearchRow;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.schema.Sequence;
import org.h2.schema.TriggerObject;
import org.h2.store.DataHandler;
import org.h2.store.FileLock;
import org.h2.store.FileLockMethod;
import org.h2.store.FileStore;
import org.h2.store.InDoubtTransaction;
import org.h2.store.LobStorageBackend;
import org.h2.store.LobStorageFrontend;
import org.h2.store.LobStorageInterface;
import org.h2.store.LobStorageMap;
import org.h2.store.PageStore;
import org.h2.store.WriterThread;
import org.h2.store.fs.FileUtils;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.MetaTable;
import org.h2.table.Table;
import org.h2.table.TableLinkConnection;
import org.h2.table.TableSynonym;
import org.h2.table.TableType;
import org.h2.table.TableView;
import org.h2.tools.DeleteDbFiles;
import org.h2.tools.Server;
import org.h2.util.BitField;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.NetUtils;
import org.h2.util.New;
import org.h2.util.SmallLRUCache;
import org.h2.util.SourceCompiler;
import org.h2.util.StringUtils;
import org.h2.util.TempFileDeleter;
import org.h2.util.Utils;
import org.h2.value.CaseInsensitiveConcurrentMap;
import org.h2.value.CaseInsensitiveMap;
import org.h2.value.CompareMode;
import org.h2.value.NullableKeyConcurrentMap;
import org.h2.value.Value;
import org.h2.value.ValueInt;
/**
* There is one database object per open database.
*
* The format of the meta data table is:
* id int, 0, objectType int, sql varchar
*
* @since 2004-04-15 22:49
*/
public class Database implements DataHandler {
private static int initialPowerOffCount;
private static final ThreadLocal<Session> META_LOCK_DEBUGGING = new ThreadLocal<>();
private static final ThreadLocal<Throwable> META_LOCK_DEBUGGING_STACK = new ThreadLocal<>();
/**
* The default name of the system user. This name is only used as long as
* there is no administrator user registered.
*/
private static final String SYSTEM_USER_NAME = "DBA";
private final boolean persistent;
private final String databaseName;
private final String databaseShortName;
private final String databaseURL;
private final String cipher;
private final byte[] filePasswordHash;
private final byte[] fileEncryptionKey;
private final HashMap<String, Role> roles = new HashMap<>();
private final HashMap<String, User> users = new HashMap<>();
private final HashMap<String, Setting> settings = new HashMap<>();
private final HashMap<String, Schema> schemas = new HashMap<>();
private final HashMap<String, Right> rights = new HashMap<>();
private final HashMap<String, UserDataType> userDataTypes = new HashMap<>();
private final HashMap<String, UserAggregate> aggregates = new HashMap<>();
private final HashMap<String, Comment> comments = new HashMap<>();
private final HashMap<String, TableEngine> tableEngines = new HashMap<>();
private final Set<Session> userSessions =
Collections.synchronizedSet(new HashSet<Session>());
private final AtomicReference<Session> exclusiveSession = new AtomicReference<>();
private final BitField objectIds = new BitField();
private final Object lobSyncObject = new Object();
private Schema mainSchema;
private Schema infoSchema;
private int nextSessionId;
private int nextTempTableId;
private User systemUser;
private Session systemSession;
private Session lobSession;
private Table meta;
private Index metaIdIndex;
private FileLock lock;
private WriterThread writer;
private boolean starting;
private TraceSystem traceSystem;
private Trace trace;
private final FileLockMethod fileLockMethod;
private Role publicRole;
private final AtomicLong modificationDataId = new AtomicLong();
private final AtomicLong modificationMetaId = new AtomicLong();
private CompareMode compareMode;
private String cluster = Constants.CLUSTERING_DISABLED;
private boolean readOnly;
private int writeDelay = Constants.DEFAULT_WRITE_DELAY;
private DatabaseEventListener eventListener;
private int maxMemoryRows = SysProperties.MAX_MEMORY_ROWS;
private int maxMemoryUndo = Constants.DEFAULT_MAX_MEMORY_UNDO;
private int lockMode = Constants.DEFAULT_LOCK_MODE;
private int maxLengthInplaceLob;
private int allowLiterals = Constants.ALLOW_LITERALS_ALL;
private int powerOffCount = initialPowerOffCount;
private int closeDelay;
private DatabaseCloser delayedCloser;
private volatile boolean closing;
private boolean ignoreCase;
private boolean deleteFilesOnDisconnect;
private String lobCompressionAlgorithm;
private boolean optimizeReuseResults = true;
private final String cacheType;
private final String accessModeData;
private boolean referentialIntegrity = true;
private boolean multiVersion;
private DatabaseCloser closeOnExit;
private Mode mode = Mode.getRegular();
private boolean multiThreaded;
private int maxOperationMemory =
Constants.DEFAULT_MAX_OPERATION_MEMORY;
private SmallLRUCache<String, String[]> lobFileListCache;
private final boolean autoServerMode;
private final int autoServerPort;
private Server server;
private HashMap<TableLinkConnection, TableLinkConnection> linkConnections;
private final TempFileDeleter tempFileDeleter = TempFileDeleter.getInstance();
private PageStore pageStore;
private Properties reconnectLastLock;
private volatile long reconnectCheckNext;
private volatile boolean reconnectChangePending;
private volatile int checkpointAllowed;
private volatile boolean checkpointRunning;
private final Object reconnectSync = new Object();
private int cacheSize;
private int compactMode;
private SourceCompiler compiler;
private volatile boolean metaTablesInitialized;
private boolean flushOnEachCommit;
private LobStorageInterface lobStorage;
private final int pageSize;
private int defaultTableType = Table.TYPE_CACHED;
private final DbSettings dbSettings;
private final long reconnectCheckDelayNs;
private int logMode;
private MVTableEngine.Store mvStore;
private int retentionTime;
private boolean allowBuiltinAliasOverride;
private DbException backgroundException;
private JavaObjectSerializer javaObjectSerializer;
private String javaObjectSerializerName;
private volatile boolean javaObjectSerializerInitialized;
private boolean queryStatistics;
private int queryStatisticsMaxEntries = Constants.QUERY_STATISTICS_MAX_ENTRIES;
private QueryStatisticsData queryStatisticsData;
private RowFactory rowFactory = RowFactory.DEFAULT;
public Database(ConnectionInfo ci, String cipher) {
META_LOCK_DEBUGGING.set(null);
META_LOCK_DEBUGGING_STACK.set(null);
String name = ci.getName();
this.dbSettings = ci.getDbSettings();
this.reconnectCheckDelayNs = TimeUnit.MILLISECONDS.toNanos(dbSettings.reconnectCheckDelay);
this.compareMode = CompareMode.getInstance(null, 0);
this.persistent = ci.isPersistent();
this.filePasswordHash = ci.getFilePasswordHash();
this.fileEncryptionKey = ci.getFileEncryptionKey();
this.databaseName = name;
this.databaseShortName = parseDatabaseShortName();
this.maxLengthInplaceLob = Constants.DEFAULT_MAX_LENGTH_INPLACE_LOB;
this.cipher = cipher;
String lockMethodName = ci.getProperty("FILE_LOCK", null);
this.accessModeData = StringUtils.toLowerEnglish(
ci.getProperty("ACCESS_MODE_DATA", "rw"));
this.autoServerMode = ci.getProperty("AUTO_SERVER", false);
this.autoServerPort = ci.getProperty("AUTO_SERVER_PORT", 0);
int defaultCacheSize = Utils.scaleForAvailableMemory(
Constants.CACHE_SIZE_DEFAULT);
this.cacheSize =
ci.getProperty("CACHE_SIZE", defaultCacheSize);
this.pageSize = ci.getProperty("PAGE_SIZE",
Constants.DEFAULT_PAGE_SIZE);
if ("r".equals(accessModeData)) {
readOnly = true;
}
if (dbSettings.mvStore && lockMethodName == null) {
if (autoServerMode) {
fileLockMethod = FileLockMethod.FILE;
} else {
fileLockMethod = FileLockMethod.FS;
}
} else {
fileLockMethod = FileLock.getFileLockMethod(lockMethodName);
}
if (dbSettings.mvStore && fileLockMethod == FileLockMethod.SERIALIZED) {
throw DbException.getUnsupportedException(
"MV_STORE combined with FILE_LOCK=SERIALIZED");
}
this.databaseURL = ci.getURL();
String listener = ci.removeProperty("DATABASE_EVENT_LISTENER", null);
if (listener != null) {
listener = StringUtils.trim(listener, true, true, "'");
setEventListenerClass(listener);
}
String modeName = ci.removeProperty("MODE", null);
if (modeName != null) {
this.mode = Mode.getInstance(modeName);
}
this.multiVersion =
ci.getProperty("MVCC", dbSettings.mvStore);
this.logMode =
ci.getProperty("LOG", PageStore.LOG_MODE_SYNC);
this.javaObjectSerializerName =
ci.getProperty("JAVA_OBJECT_SERIALIZER", null);
this.multiThreaded =
ci.getProperty("MULTI_THREADED", false);
boolean closeAtVmShutdown =
dbSettings.dbCloseOnExit;
int traceLevelFile =
ci.getIntProperty(SetTypes.TRACE_LEVEL_FILE,
TraceSystem.DEFAULT_TRACE_LEVEL_FILE);
int traceLevelSystemOut =
ci.getIntProperty(SetTypes.TRACE_LEVEL_SYSTEM_OUT,
TraceSystem.DEFAULT_TRACE_LEVEL_SYSTEM_OUT);
this.cacheType = StringUtils.toUpperEnglish(
ci.removeProperty("CACHE_TYPE", Constants.CACHE_TYPE_DEFAULT));
openDatabase(traceLevelFile, traceLevelSystemOut, closeAtVmShutdown);
}
private void openDatabase(int traceLevelFile, int traceLevelSystemOut,
boolean closeAtVmShutdown) {
try {
open(traceLevelFile, traceLevelSystemOut);
if (closeAtVmShutdown) {
try {
closeOnExit = new DatabaseCloser(this, 0, true);
Runtime.getRuntime().addShutdownHook(closeOnExit);
} catch (IllegalStateException e) {
// shutdown in progress - just don't register the handler
// (maybe an application wants to write something into a
// database at shutdown time)
} catch (SecurityException e) {
// applets may not do that - ignore
// Google App Engine doesn't allow
// to instantiate classes that extend Thread
}
}
} catch (Throwable e) {
if (e instanceof OutOfMemoryError) {
e.fillInStackTrace();
}
boolean alreadyOpen = e instanceof DbException
&& ((DbException) e).getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1;
if (alreadyOpen) {
stopServer();
}
if (traceSystem != null) {
if (e instanceof DbException && !alreadyOpen) {
// only write if the database is not already in use
trace.error(e, "opening {0}", databaseName);
}
traceSystem.close();
}
closeOpenFilesAndUnlock(false);
throw DbException.convert(e);
}
}
/**
* Create a new row for a table.
*
* @param data the values
* @param memory whether the row is in memory
* @return the created row
*/
public Row createRow(Value[] data, int memory) {
return rowFactory.createRow(data, memory);
}
public RowFactory getRowFactory() {
return rowFactory;
}
public void setRowFactory(RowFactory rowFactory) {
this.rowFactory = rowFactory;
}
public static void setInitialPowerOffCount(int count) {
initialPowerOffCount = count;
}
public void setPowerOffCount(int count) {
if (powerOffCount == -1) {
return;
}
powerOffCount = count;
}
public MVTableEngine.Store getMvStore() {
return mvStore;
}
public void setMvStore(MVTableEngine.Store mvStore) {
this.mvStore = mvStore;
this.retentionTime = mvStore.getStore().getRetentionTime();
}
/**
* Check if two values are equal with the current comparison mode.
*
* @param a the first value
* @param b the second value
* @return true if both objects are equal
*/
public boolean areEqual(Value a, Value b) {
// can not use equals because ValueDecimal 0.0 is not equal to 0.00.
return a.compareTo(b, compareMode) == 0;
}
/**
* Compare two values with the current comparison mode. The values may not
* be of the same type.
*
* @param a the first value
* @param b the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and
* 1 otherwise
*/
public int compare(Value a, Value b) {
return a.compareTo(b, compareMode);
}
/**
* Compare two values with the current comparison mode. The values must be
* of the same type.
*
* @param a the first value
* @param b the second value
* @return 0 if both values are equal, -1 if the first value is smaller, and
* 1 otherwise
*/
public int compareTypeSafe(Value a, Value b) {
return a.compareTypeSafe(b, compareMode);
}
public long getModificationDataId() {
return modificationDataId.get();
}
/**
* Set or reset the pending change flag in the .lock.db file.
*
* @param pending the new value of the flag
* @return true if the call was successful,
* false if another connection was faster
*/
private synchronized boolean reconnectModified(boolean pending) {
if (readOnly || lock == null ||
fileLockMethod != FileLockMethod.SERIALIZED) {
return true;
}
try {
if (pending == reconnectChangePending) {
long now = System.nanoTime();
if (now > reconnectCheckNext) {
if (pending) {
String pos = pageStore == null ?
null : "" + pageStore.getWriteCountTotal();
lock.setProperty("logPos", pos);
lock.save();
}
reconnectCheckNext = now + reconnectCheckDelayNs;
}
return true;
}
Properties old = lock.load();
if (pending) {
if (old.getProperty("changePending") != null) {
return false;
}
trace.debug("wait before writing");
Thread.sleep(TimeUnit.NANOSECONDS.toMillis((long) (reconnectCheckDelayNs * 1.1)));
Properties now = lock.load();
if (!now.equals(old)) {
// somebody else was faster
return false;
}
}
String pos = pageStore == null ?
null : "" + pageStore.getWriteCountTotal();
lock.setProperty("logPos", pos);
if (pending) {
lock.setProperty("changePending", "true-" + Math.random());
} else {
lock.setProperty("changePending", null);
}
// ensure that the writer thread will
// not reset the flag before we are done
reconnectCheckNext = System.nanoTime() +
2 * reconnectCheckDelayNs;
old = lock.save();
if (pending) {
trace.debug("wait before writing again");
Thread.sleep(TimeUnit.NANOSECONDS.toMillis((long) (reconnectCheckDelayNs * 1.1)));
Properties now = lock.load();
if (!now.equals(old)) {
// somebody else was faster
return false;
}
} else {
Thread.sleep(1);
}
reconnectLastLock = old;
reconnectChangePending = pending;
reconnectCheckNext = System.nanoTime() + reconnectCheckDelayNs;
return true;
} catch (Exception e) {
trace.error(e, "pending {0}", pending);
return false;
}
}
public long getNextModificationDataId() {
return modificationDataId.incrementAndGet();
}
public long getModificationMetaId() {
return modificationMetaId.get();
}
public long getNextModificationMetaId() {
// if the meta data has been modified, the data is modified as well
// (because MetaTable returns modificationDataId)
modificationDataId.incrementAndGet();
return modificationMetaId.incrementAndGet() - 1;
}
public int getPowerOffCount() {
return powerOffCount;
}
@Override
public void checkPowerOff() {
if (powerOffCount == 0) {
return;
}
if (powerOffCount > 1) {
powerOffCount--;
return;
}
if (powerOffCount != -1) {
try {
powerOffCount = -1;
stopWriter();
if (mvStore != null) {
mvStore.closeImmediately();
}
if (pageStore != null) {
try {
pageStore.close();
} catch (DbException e) {
// ignore
}
pageStore = null;
}
if (lock != null) {
stopServer();
if (fileLockMethod != FileLockMethod.SERIALIZED) {
// allow testing shutdown
lock.unlock();
}
lock = null;
}
if (traceSystem != null) {
traceSystem.close();
}
} catch (DbException e) {
DbException.traceThrowable(e);
}
}
Engine.getInstance().close(databaseName);
throw DbException.get(ErrorCode.DATABASE_IS_CLOSED);
}
/**
* Check if a database with the given name exists.
*
* @param name the name of the database (including path)
* @return true if one exists
*/
static boolean exists(String name) {
if (FileUtils.exists(name + Constants.SUFFIX_PAGE_FILE)) {
return true;
}
return FileUtils.exists(name + Constants.SUFFIX_MV_FILE);
}
/**
* Get the trace object for the given module id.
*
* @param moduleId the module id
* @return the trace object
*/
public Trace getTrace(int moduleId) {
return traceSystem.getTrace(moduleId);
}
@Override
public FileStore openFile(String name, String openMode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStore store = FileStore.open(this, name, openMode, cipher,
filePasswordHash);
try {
store.init();
} catch (DbException e) {
store.closeSilently();
throw e;
}
return store;
}
/**
* Check if the file password hash is correct.
*
* @param testCipher the cipher algorithm
* @param testHash the hash code
* @return true if the cipher algorithm and the password match
*/
boolean validateFilePasswordHash(String testCipher, byte[] testHash) {
if (!Objects.equals(testCipher, this.cipher)) {
return false;
}
return Utils.compareSecure(testHash, filePasswordHash);
}
private String parseDatabaseShortName() {
String n = databaseName;
if (n.endsWith(":")) {
n = null;
}
if (n != null) {
StringTokenizer tokenizer = new StringTokenizer(n, "/\\:,;");
while (tokenizer.hasMoreTokens()) {
n = tokenizer.nextToken();
}
}
if (n == null || n.length() == 0) {
n = "unnamed";
}
return dbSettings.databaseToUpper ? StringUtils.toUpperEnglish(n) : n;
}
private synchronized void open(int traceLevelFile, int traceLevelSystemOut) {
if (persistent) {
String dataFileName = databaseName + Constants.SUFFIX_OLD_DATABASE_FILE;
boolean existsData = FileUtils.exists(dataFileName);
String pageFileName = databaseName + Constants.SUFFIX_PAGE_FILE;
String mvFileName = databaseName + Constants.SUFFIX_MV_FILE;
boolean existsPage = FileUtils.exists(pageFileName);
boolean existsMv = FileUtils.exists(mvFileName);
if (existsData && (!existsPage && !existsMv)) {
throw DbException.get(
ErrorCode.FILE_VERSION_ERROR_1, "Old database: " +
dataFileName +
" - please convert the database " +
"to a SQL script and re-create it.");
}
if (existsPage && !FileUtils.canWrite(pageFileName)) {
readOnly = true;
}
if (existsMv && !FileUtils.canWrite(mvFileName)) {
readOnly = true;
}
if (existsPage && !existsMv) {
dbSettings.mvStore = false;
}
if (readOnly) {
if (traceLevelFile >= TraceSystem.DEBUG) {
String traceFile = Utils.getProperty("java.io.tmpdir", ".") +
"/" + "h2_" + System.currentTimeMillis();
traceSystem = new TraceSystem(traceFile +
Constants.SUFFIX_TRACE_FILE);
} else {
traceSystem = new TraceSystem(null);
}
} else {
traceSystem = new TraceSystem(databaseName +
Constants.SUFFIX_TRACE_FILE);
}
traceSystem.setLevelFile(traceLevelFile);
traceSystem.setLevelSystemOut(traceLevelSystemOut);
trace = traceSystem.getTrace(Trace.DATABASE);
trace.info("opening {0} (build {1})", databaseName, Constants.BUILD_ID);
if (autoServerMode) {
if (readOnly ||
fileLockMethod == FileLockMethod.NO ||
fileLockMethod == FileLockMethod.SERIALIZED ||
fileLockMethod == FileLockMethod.FS ||
!persistent) {
throw DbException.getUnsupportedException(
"autoServerMode && (readOnly || " +
"fileLockMethod == NO || " +
"fileLockMethod == SERIALIZED || " +
"fileLockMethod == FS || " +
"inMemory)");
}
}
String lockFileName = databaseName + Constants.SUFFIX_LOCK_FILE;
if (readOnly) {
if (FileUtils.exists(lockFileName)) {
throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1,
"Lock file exists: " + lockFileName);
}
}
if (!readOnly && fileLockMethod != FileLockMethod.NO) {
if (fileLockMethod != FileLockMethod.FS) {
lock = new FileLock(traceSystem, lockFileName, Constants.LOCK_SLEEP);
lock.lock(fileLockMethod);
if (autoServerMode) {
startServer(lock.getUniqueId());
}
}
}
if (SysProperties.MODIFY_ON_WRITE) {
while (isReconnectNeeded()) {
// wait until others stopped writing
}
} else {
while (isReconnectNeeded() && !beforeWriting()) {
// wait until others stopped writing and
// until we can write (the file is not yet open -
// no need to re-connect)
}
}
deleteOldTempFiles();
starting = true;
if (SysProperties.MODIFY_ON_WRITE) {
try {
getPageStore();
} catch (DbException e) {
if (e.getErrorCode() != ErrorCode.DATABASE_IS_READ_ONLY) {
throw e;
}
pageStore = null;
while (!beforeWriting()) {
// wait until others stopped writing and
// until we can write (the file is not yet open -
// no need to re-connect)
}
getPageStore();
}
} else {
getPageStore();
}
starting = false;
if (mvStore == null) {
writer = WriterThread.create(this, writeDelay);
} else {
setWriteDelay(writeDelay);
}
} else {
if (autoServerMode) {
throw DbException.getUnsupportedException(
"autoServerMode && inMemory");
}
traceSystem = new TraceSystem(null);
trace = traceSystem.getTrace(Trace.DATABASE);
if (dbSettings.mvStore) {
getPageStore();
}
}
systemUser = new User(this, 0, SYSTEM_USER_NAME, true);
mainSchema = new Schema(this, 0, Constants.SCHEMA_MAIN, systemUser, true);
infoSchema = new Schema(this, -1, "INFORMATION_SCHEMA", systemUser, true);
schemas.put(mainSchema.getName(), mainSchema);
schemas.put(infoSchema.getName(), infoSchema);
publicRole = new Role(this, 0, Constants.PUBLIC_ROLE_NAME, true);
roles.put(Constants.PUBLIC_ROLE_NAME, publicRole);
systemUser.setAdmin(true);
systemSession = new Session(this, systemUser, ++nextSessionId);
lobSession = new Session(this, systemUser, ++nextSessionId);
CreateTableData data = new CreateTableData();
ArrayList<Column> cols = data.columns;
Column columnId = new Column("ID", Value.INT);
columnId.setNullable(false);
cols.add(columnId);
cols.add(new Column("HEAD", Value.INT));
cols.add(new Column("TYPE", Value.INT));
cols.add(new Column("SQL", Value.STRING));
boolean create = true;
if (pageStore != null) {
create = pageStore.isNew();
}
data.tableName = "SYS";
data.id = 0;
data.temporary = false;
data.persistData = persistent;
data.persistIndexes = persistent;
data.create = create;
data.isHidden = true;
data.session = systemSession;
meta = mainSchema.createTable(data);
IndexColumn[] pkCols = IndexColumn.wrap(new Column[] { columnId });
metaIdIndex = meta.addIndex(systemSession, "SYS_ID",
0, pkCols, IndexType.createPrimaryKey(
false, false), true, null);
objectIds.set(0);
starting = true;
Cursor cursor = metaIdIndex.find(systemSession, null, null);
ArrayList<MetaRecord> records = New.arrayList();
while (cursor.next()) {
MetaRecord rec = new MetaRecord(cursor.get());
objectIds.set(rec.getId());
records.add(rec);
}
Collections.sort(records);
synchronized (systemSession) {
for (MetaRecord rec : records) {
rec.execute(this, systemSession, eventListener);
}
}
if (mvStore != null) {
mvStore.initTransactions();
mvStore.removeTemporaryMaps(objectIds);
}
recompileInvalidViews(systemSession);
starting = false;
if (!readOnly) {
// set CREATE_BUILD in a new database
String name = SetTypes.getTypeName(SetTypes.CREATE_BUILD);
if (settings.get(name) == null) {
Setting setting = new Setting(this, allocateObjectId(), name);
setting.setIntValue(Constants.BUILD_ID);
lockMeta(systemSession);
addDatabaseObject(systemSession, setting);
}
// mark all ids used in the page store
if (pageStore != null) {
BitField f = pageStore.getObjectIds();
for (int i = 0, len = f.length(); i < len; i++) {
if (f.get(i) && !objectIds.get(i)) {
trace.info("unused object id: " + i);
objectIds.set(i);
}
}
}
}
getLobStorage().init();
systemSession.commit(true);
trace.info("opened {0}", databaseName);
if (checkpointAllowed > 0) {
afterWriting();
}
}
private void startServer(String key) {
try {
server = Server.createTcpServer(
"-tcpPort", Integer.toString(autoServerPort),
"-tcpAllowOthers",
"-tcpDaemon",
"-key", key, databaseName);
server.start();
} catch (SQLException e) {
throw DbException.convert(e);
}
String localAddress = NetUtils.getLocalAddress();
String address = localAddress + ":" + server.getPort();
lock.setProperty("server", address);
String hostName = NetUtils.getHostName(localAddress);
lock.setProperty("hostName", hostName);
lock.save();
}
private void stopServer() {
if (server != null) {
Server s = server;
// avoid calling stop recursively
// because stopping the server will
// try to close the database as well
server = null;
s.stop();
}
}
private void recompileInvalidViews(Session session) {
boolean atLeastOneRecompiledSuccessfully;
do {
atLeastOneRecompiledSuccessfully = false;
for (Table obj : getAllTablesAndViews(false)) {
if (obj instanceof TableView) {
TableView view = (TableView) obj;
if (view.isInvalid()) {
view.recompile(session, true, false);
if (!view.isInvalid()) {
atLeastOneRecompiledSuccessfully = true;
}
}
}
}
} while (atLeastOneRecompiledSuccessfully);
TableView.clearIndexCaches(session.getDatabase());
}
private void initMetaTables() {
if (metaTablesInitialized) {
return;
}
synchronized (infoSchema) {
if (!metaTablesInitialized) {
for (int type = 0, count = MetaTable.getMetaTableTypeCount();
type < count; type++) {
MetaTable m = new MetaTable(infoSchema, -1 - type, type);
infoSchema.add(m);
}
metaTablesInitialized = true;
}
}
}
private synchronized void addMeta(Session session, DbObject obj) {
int id = obj.getId();
if (id > 0 && !starting && !obj.isTemporary()) {
Row r = meta.getTemplateRow();
MetaRecord rec = new MetaRecord(obj);
rec.setRecord(r);
objectIds.set(id);
if (SysProperties.CHECK) {
verifyMetaLocked(session);
}
meta.addRow(session, r);
if (isMultiVersion()) {
// TODO this should work without MVCC, but avoid risks at the
// moment
session.log(meta, UndoLogRecord.INSERT, r);
}
}
}
/**
* Verify the meta table is locked.
*
* @param session the session
*/
public void verifyMetaLocked(Session session) {
if (meta != null && !meta.isLockedExclusivelyBy(session)
&& lockMode != Constants.LOCK_MODE_OFF) {
throw DbException.throwInternalError();
}
}
/**
* Lock the metadata table for updates.
*
* @param session the session
* @return whether it was already locked before by this session
*/
public boolean lockMeta(Session session) {
// this method can not be synchronized on the database object,
// as unlocking is also synchronized on the database object -
// so if locking starts just before unlocking, locking could
// never be successful
if (meta == null) {
return true;
}
if (SysProperties.CHECK2) {
final Session prev = META_LOCK_DEBUGGING.get();
if (prev == null) {
META_LOCK_DEBUGGING.set(session);
META_LOCK_DEBUGGING_STACK.set(new Throwable("Last meta lock granted in this stack trace, "+
"this is debug information for following IllegalStateException"));
} else if (prev != session) {
META_LOCK_DEBUGGING_STACK.get().printStackTrace();
throw new IllegalStateException("meta currently locked by "
+ prev +", sessionid="+ prev.getId()
+ " and trying to be locked by different session, "
+ session +", sessionid="+ session.getId() + " on same thread");
}
}
return meta.lock(session, true, true);
}
/**
* Unlock the metadata table.
*
* @param session the session
*/
public void unlockMeta(Session session) {
unlockMetaDebug(session);
meta.unlock(session);
session.unlock(meta);
}
/**
* This method doesn't actually unlock the metadata table, all it does it
* reset the debugging flags.
*
* @param session the session
*/
public void unlockMetaDebug(Session session) {
if (SysProperties.CHECK2) {
if (META_LOCK_DEBUGGING.get() == session) {
META_LOCK_DEBUGGING.set(null);
META_LOCK_DEBUGGING_STACK.set(null);
}
}
}
/**
* Remove the given object from the meta data.
*
* @param session the session
* @param id the id of the object to remove
*/
public synchronized void removeMeta(Session session, int id) {
if (id > 0 && !starting) {
SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
boolean wasLocked = lockMeta(session);
Cursor cursor = metaIdIndex.find(session, r, r);
if (cursor.next()) {
if (SysProperties.CHECK) {
if (lockMode != Constants.LOCK_MODE_OFF && !wasLocked) {
throw DbException.throwInternalError();
}
}
Row found = cursor.get();
meta.removeRow(session, found);
if (isMultiVersion()) {
// TODO this should work without MVCC, but avoid risks at
// the moment
session.log(meta, UndoLogRecord.DELETE, found);
}
if (SysProperties.CHECK) {
checkMetaFree(session, id);
}
} else if (!wasLocked) {
unlockMetaDebug(session);
// must not keep the lock if it was not locked
// otherwise updating sequences may cause a deadlock
meta.unlock(session);
session.unlock(meta);
}
objectIds.clear(id);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, DbObject> getMap(int type) {
HashMap<String, ? extends DbObject> result;
switch (type) {
case DbObject.USER:
result = users;
break;
case DbObject.SETTING:
result = settings;
break;
case DbObject.ROLE:
result = roles;
break;
case DbObject.RIGHT:
result = rights;
break;
case DbObject.SCHEMA:
result = schemas;
break;
case DbObject.USER_DATATYPE:
result = userDataTypes;
break;
case DbObject.COMMENT:
result = comments;
break;
case DbObject.AGGREGATE:
result = aggregates;
break;
default:
throw DbException.throwInternalError("type=" + type);
}
return (HashMap<String, DbObject>) result;
}
/**
* Add a schema object to the database.
*
* @param session the session
* @param obj the object to add
*/
public void addSchemaObject(Session session, SchemaObject obj) {
int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
lockMeta(session);
synchronized (this) {
obj.getSchema().add(obj);
addMeta(session, obj);
}
}
/**
* Add an object to the database.
*
* @param session the session
* @param obj the object to add
*/
public synchronized void addDatabaseObject(Session session, DbObject obj) {
int id = obj.getId();
if (id > 0 && !starting) {
checkWritingAllowed();
}
HashMap<String, DbObject> map = getMap(obj.getType());
if (obj.getType() == DbObject.USER) {
User user = (User) obj;
if (user.isAdmin() && systemUser.getName().equals(SYSTEM_USER_NAME)) {
systemUser.rename(user.getName());
}
}
String name = obj.getName();
if (SysProperties.CHECK && map.get(name) != null) {
DbException.throwInternalError("object already exists");
}
lockMeta(session);
addMeta(session, obj);
map.put(name, obj);
}
/**
* Get the user defined aggregate function if it exists, or null if not.
*
* @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
*
* @param name the name of the user defined aggregate function
* @return the aggregate function or null
*/
public UserAggregate findAggregate(String name) {
// return aggregates.get(name);
return PulsarExtension.findAggregate(aggregates, name);
}
/**
* Get the comment for the given database object if one exists, or null if
* not.
*
* @param object the database object
* @return the comment or null
*/
public Comment findComment(DbObject object) {
if (object.getType() == DbObject.COMMENT) {
return null;
}
String key = Comment.getKey(object);
return comments.get(key);
}
/**
* Get the role if it exists, or null if not.
*
* @param roleName the name of the role
* @return the role or null
*/
public Role findRole(String roleName) {
return roles.get(roleName);
}
/**
* Get the schema if it exists, or null if not.
*
* @param schemaName the name of the schema
* @return the schema or null
*/
public Schema findSchema(String schemaName) {
Schema schema = schemas.get(schemaName);
if (schema == infoSchema) {
initMetaTables();
}
return schema;
}
/**
* Get the setting if it exists, or null if not.
*
* @param name the name of the setting
* @return the setting or null
*/
public Setting findSetting(String name) {
return settings.get(name);
}
/**
* Get the user if it exists, or null if not.
*
* @param name the name of the user
* @return the user or null
*/
public User findUser(String name) {
return users.get(name);
}
/**
* Get the user defined data type if it exists, or null if not.
*
* @param name the name of the user defined data type
* @return the user defined data type or null
*/
public UserDataType findUserDataType(String name) {
return userDataTypes.get(name);
}
/**
* Get user with the given name. This method throws an exception if the user
* does not exist.
*
* @param name the user name
* @return the user
* @throws DbException if the user does not exist
*/
public User getUser(String name) {
User user = findUser(name);
if (user == null) {
throw DbException.get(ErrorCode.USER_NOT_FOUND_1, name);
}
return user;
}
/**
* Create a session for the given user.
*
* @param user the user
* @return the session, or null if the database is currently closing
* @throws DbException if the database is in exclusive mode
*/
synchronized Session createSession(User user) {
if (closing) {
return null;
}
if (exclusiveSession.get() != null) {
throw DbException.get(ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE);
}
Session session = new Session(this, user, ++nextSessionId);
userSessions.add(session);
trace.info("connecting session #{0} to {1}", session.getId(), databaseName);
if (delayedCloser != null) {
delayedCloser.reset();
delayedCloser = null;
}
return session;
}
/**
* Remove a session. This method is called after the user has disconnected.
*
* @param session the session
*/
public synchronized void removeSession(Session session) {
if (session != null) {
exclusiveSession.compareAndSet(session, null);
userSessions.remove(session);
if (session != systemSession && session != lobSession) {
trace.info("disconnecting session #{0}", session.getId());
}
}
if (userSessions.isEmpty() &&
session != systemSession && session != lobSession) {
if (closeDelay == 0) {
close(false);
} else if (closeDelay < 0) {
return;
} else {
delayedCloser = new DatabaseCloser(this, closeDelay * 1000, false);
delayedCloser.setName("H2 Close Delay " + getShortName());
delayedCloser.setDaemon(true);
delayedCloser.start();
}
}
if (session != systemSession &&
session != lobSession && session != null) {
trace.info("disconnected session #{0}", session.getId());
}
}
private synchronized void closeAllSessionsException(Session except) {
Session[] all = userSessions.toArray(new Session[userSessions.size()]);
for (Session s : all) {
if (s != except) {
try {
// must roll back, otherwise the session is removed and
// the transaction log that contains its uncommitted
// operations as well
s.rollback();
s.close();
} catch (DbException e) {
trace.error(e, "disconnecting session #{0}", s.getId());
}
}
}
}
/**
* Close the database.
*
* @param fromShutdownHook true if this method is called from the shutdown
* hook
*/
void close(boolean fromShutdownHook) {
try {
synchronized (this) {
if (closing) {
return;
}
throwLastBackgroundException();
if (fileLockMethod == FileLockMethod.SERIALIZED &&
!reconnectChangePending) {
// another connection may have written something - don't write
try {
closeOpenFilesAndUnlock(false);
} catch (DbException e) {
// ignore
}
traceSystem.close();
return;
}
closing = true;
stopServer();
if (!userSessions.isEmpty()) {
if (!fromShutdownHook) {
return;
}
trace.info("closing {0} from shutdown hook", databaseName);
closeAllSessionsException(null);
}
trace.info("closing {0}", databaseName);
if (eventListener != null) {
// allow the event listener to connect to the database
closing = false;
DatabaseEventListener e = eventListener;
// set it to null, to make sure it's called only once
eventListener = null;
e.closingDatabase();
if (!userSessions.isEmpty()) {
// if a connection was opened, we can't close the database
return;
}
closing = true;
}
}
removeOrphanedLobs();
try {
if (systemSession != null) {
if (powerOffCount != -1) {
for (Table table : getAllTablesAndViews(false)) {
if (table.isGlobalTemporary()) {
table.removeChildrenAndResources(systemSession);
} else {
table.close(systemSession);
}
}
for (SchemaObject obj : getAllSchemaObjects(
DbObject.SEQUENCE)) {
Sequence sequence = (Sequence) obj;
sequence.close();
}
}
for (SchemaObject obj : getAllSchemaObjects(
DbObject.TRIGGER)) {
TriggerObject trigger = (TriggerObject) obj;
try {
trigger.close();
} catch (SQLException e) {
trace.error(e, "close");
}
}
if (powerOffCount != -1) {
meta.close(systemSession);
systemSession.commit(true);
}
}
} catch (DbException e) {
trace.error(e, "close");
}
tempFileDeleter.deleteAll();
try {
closeOpenFilesAndUnlock(true);
} catch (DbException e) {
trace.error(e, "close");
}
trace.info("closed");
traceSystem.close();
if (closeOnExit != null) {
closeOnExit.reset();
try {
Runtime.getRuntime().removeShutdownHook(closeOnExit);
} catch (IllegalStateException e) {
// ignore
} catch (SecurityException e) {
// applets may not do that - ignore
}
closeOnExit = null;
}
if (deleteFilesOnDisconnect && persistent) {
deleteFilesOnDisconnect = false;
try {
String directory = FileUtils.getParent(databaseName);
String name = FileUtils.getName(databaseName);
DeleteDbFiles.execute(directory, name, true);
} catch (Exception e) {
// ignore (the trace is closed already)
}
}
} finally {
Engine.getInstance().close(databaseName);
}
}
private void removeOrphanedLobs() {
// remove all session variables and temporary lobs
if (!persistent) {
return;
}
boolean lobStorageIsUsed = infoSchema.findTableOrView(
systemSession, LobStorageBackend.LOB_DATA_TABLE) != null;
lobStorageIsUsed |= mvStore != null;
if (!lobStorageIsUsed) {
return;
}
try {
getLobStorage();
lobStorage.removeAllForTable(
LobStorageFrontend.TABLE_ID_SESSION_VARIABLE);
} catch (DbException e) {
trace.error(e, "close");
}
}
private void stopWriter() {
if (writer != null) {
writer.stopThread();
writer = null;
}
}
/**
* Close all open files and unlock the database.
*
* @param flush whether writing is allowed
*/
private synchronized void closeOpenFilesAndUnlock(boolean flush) {
stopWriter();
if (pageStore != null) {
if (flush) {
try {
pageStore.checkpoint();
if (!readOnly) {
lockMeta(pageStore.getPageStoreSession());
pageStore.compact(compactMode);
unlockMeta(pageStore.getPageStoreSession());
}
} catch (DbException e) {
if (SysProperties.CHECK2) {
int code = e.getErrorCode();
if (code != ErrorCode.DATABASE_IS_CLOSED &&
code != ErrorCode.LOCK_TIMEOUT_1 &&
code != ErrorCode.IO_EXCEPTION_2) {
e.printStackTrace();
}
}
trace.error(e, "close");
} catch (Throwable t) {
if (SysProperties.CHECK2) {
t.printStackTrace();
}
trace.error(t, "close");
}
}
}
reconnectModified(false);
if (mvStore != null) {
long maxCompactTime = dbSettings.maxCompactTime;
if (compactMode == CommandInterface.SHUTDOWN_COMPACT) {
mvStore.compactFile(dbSettings.maxCompactTime);
} else if (compactMode == CommandInterface.SHUTDOWN_DEFRAG) {
maxCompactTime = Long.MAX_VALUE;
} else if (getSettings().defragAlways) {
maxCompactTime = Long.MAX_VALUE;
}
mvStore.close(maxCompactTime);
}
closeFiles();
if (persistent && lock == null &&
fileLockMethod != FileLockMethod.NO &&
fileLockMethod != FileLockMethod.FS) {
// everything already closed (maybe in checkPowerOff)
// don't delete temp files in this case because
// the database could be open now (even from within another process)
return;
}
if (persistent) {
deleteOldTempFiles();
}
if (systemSession != null) {
systemSession.close();
systemSession = null;
}
if (lobSession != null) {
lobSession.close();
lobSession = null;
}
if (lock != null) {
if (fileLockMethod == FileLockMethod.SERIALIZED) {
// wait before deleting the .lock file,
// otherwise other connections can not detect that
if (lock.load().containsKey("changePending")) {
try {
Thread.sleep(TimeUnit.NANOSECONDS
.toMillis((long) (reconnectCheckDelayNs * 1.1)));
} catch (InterruptedException e) {
trace.error(e, "close");
}
}
}
lock.unlock();
lock = null;
}
}
private synchronized void closeFiles() {
try {
if (mvStore != null) {
mvStore.closeImmediately();
}
if (pageStore != null) {
pageStore.close();
pageStore = null;
}
} catch (DbException e) {
trace.error(e, "close");
}
}
private void checkMetaFree(Session session, int id) {
SearchRow r = meta.getTemplateSimpleRow(false);
r.setValue(0, ValueInt.get(id));
Cursor cursor = metaIdIndex.find(session, r, r);
if (cursor.next()) {
DbException.throwInternalError();
}
}
/**
* Allocate a new object id.
*
* @return the id
*/
public synchronized int allocateObjectId() {
int i = objectIds.nextClearBit(0);
objectIds.set(i);
return i;
}
public ArrayList<UserAggregate> getAllAggregates() {
return new ArrayList<>(aggregates.values());
}
public ArrayList<Comment> getAllComments() {
return new ArrayList<>(comments.values());
}
public int getAllowLiterals() {
if (starting) {
return Constants.ALLOW_LITERALS_ALL;
}
return allowLiterals;
}
public ArrayList<Right> getAllRights() {
return new ArrayList<>(rights.values());
}
public ArrayList<Role> getAllRoles() {
return new ArrayList<>(roles.values());
}
/**
* Get all schema objects.
*
* @return all objects of all types
*/
public ArrayList<SchemaObject> getAllSchemaObjects() {
initMetaTables();
ArrayList<SchemaObject> list = New.arrayList();
for (Schema schema : schemas.values()) {
list.addAll(schema.getAll());
}
return list;
}
/**
* Get all schema objects of the given type.
*
* @param type the object type
* @return all objects of that type
*/
public ArrayList<SchemaObject> getAllSchemaObjects(int type) {
if (type == DbObject.TABLE_OR_VIEW) {
initMetaTables();
}
ArrayList<SchemaObject> list = New.arrayList();
for (Schema schema : schemas.values()) {
list.addAll(schema.getAll(type));
}
return list;
}
/**
* Get all tables and views.
*
* @param includeMeta whether to force including the meta data tables (if
* true, metadata tables are always included; if false, metadata
* tables are only included if they are already initialized)
* @return all objects of that type
*/
public ArrayList<Table> getAllTablesAndViews(boolean includeMeta) {
if (includeMeta) {
initMetaTables();
}
ArrayList<Table> list = New.arrayList();
for (Schema schema : schemas.values()) {
list.addAll(schema.getAllTablesAndViews());
}
return list;
}
/**
* Get all synonyms.
*
* @return all objects of that type
*/
public ArrayList<TableSynonym> getAllSynonyms() {
ArrayList<TableSynonym> list = New.arrayList();
for (Schema schema : schemas.values()) {
list.addAll(schema.getAllSynonyms());
}
return list;
}
/**
* Get the tables with the given name, if any.
*
* @param name the table name
* @return the list
*/
public ArrayList<Table> getTableOrViewByName(String name) {
ArrayList<Table> list = New.arrayList();
for (Schema schema : schemas.values()) {
Table table = schema.getTableOrViewByName(name);
if (table != null) {
list.add(table);
}
}
return list;
}
public ArrayList<Schema> getAllSchemas() {
initMetaTables();
return new ArrayList<>(schemas.values());
}
public ArrayList<Setting> getAllSettings() {
return new ArrayList<>(settings.values());
}
public ArrayList<UserDataType> getAllUserDataTypes() {
return new ArrayList<>(userDataTypes.values());
}
public ArrayList<User> getAllUsers() {
return new ArrayList<>(users.values());
}
public String getCacheType() {
return cacheType;
}
public String getCluster() {
return cluster;
}
@Override
public CompareMode getCompareMode() {
return compareMode;
}
@Override
public String getDatabasePath() {
if (persistent) {
return FileUtils.toRealPath(databaseName);
}
return null;
}
public String getShortName() {
return databaseShortName;
}
public String getName() {
return databaseName;
}
/**
* Get all sessions that are currently connected to the database.
*
* @param includingSystemSession if the system session should also be
* included
* @return the list of sessions
*/
public Session[] getSessions(boolean includingSystemSession) {
ArrayList<Session> list;
// need to synchronized on userSession, otherwise the list
// may contain null elements
synchronized (userSessions) {
list = new ArrayList<>(userSessions);
}
// copy, to ensure the reference is stable
Session sys = systemSession;
Session lob = lobSession;
if (includingSystemSession && sys != null) {
list.add(sys);
}
if (includingSystemSession && lob != null) {
list.add(lob);
}
return list.toArray(new Session[0]);
}
/**
* Update an object in the system table.
*
* @param session the session
* @param obj the database object
*/
public void updateMeta(Session session, DbObject obj) {
lockMeta(session);
synchronized (this) {
int id = obj.getId();
removeMeta(session, id);
addMeta(session, obj);
// for temporary objects
if (id > 0) {
objectIds.set(id);
}
}
}
/**
* Rename a schema object.
*
* @param session the session
* @param obj the object
* @param newName the new name
*/
public synchronized void renameSchemaObject(Session session,
SchemaObject obj, String newName) {
checkWritingAllowed();
obj.getSchema().rename(obj, newName);
updateMetaAndFirstLevelChildren(session, obj);
}
private synchronized void updateMetaAndFirstLevelChildren(Session session, DbObject obj) {
ArrayList<DbObject> list = obj.getChildren();
Comment comment = findComment(obj);
if (comment != null) {
DbException.throwInternalError(comment.toString());
}
updateMeta(session, obj);
// remember that this scans only one level deep!
if (list != null) {
for (DbObject o : list) {
if (o.getCreateSQL() != null) {
updateMeta(session, o);
}
}
}
}
/**
* Rename a database object.
*
* @param session the session
* @param obj the object
* @param newName the new name
*/
public synchronized void renameDatabaseObject(Session session,
DbObject obj, String newName) {
checkWritingAllowed();
int type = obj.getType();
HashMap<String, DbObject> map = getMap(type);
if (SysProperties.CHECK) {
if (!map.containsKey(obj.getName())) {
DbException.throwInternalError("not found: " + obj.getName());
}
if (obj.getName().equals(newName) || map.containsKey(newName)) {
DbException.throwInternalError("object already exists: " + newName);
}
}
obj.checkRename();
int id = obj.getId();
lockMeta(session);
removeMeta(session, id);
map.remove(obj.getName());
obj.rename(newName);
map.put(newName, obj);
updateMetaAndFirstLevelChildren(session, obj);
}
/**
* Create a temporary file in the database folder.
*
* @return the file name
*/
public String createTempFile() {
try {
boolean inTempDir = readOnly;
String name = databaseName;
if (!persistent) {
name = "memFS:" + name;
}
return FileUtils.createTempFile(name,
Constants.SUFFIX_TEMP_FILE, true, inTempDir);
} catch (IOException e) {
throw DbException.convertIOException(e, databaseName);
}
}
private void deleteOldTempFiles() {
String path = FileUtils.getParent(databaseName);
for (String name : FileUtils.newDirectoryStream(path)) {
if (name.endsWith(Constants.SUFFIX_TEMP_FILE) &&
name.startsWith(databaseName)) {
// can't always delete the files, they may still be open
FileUtils.tryDelete(name);
}
}
}
/**
* Get the schema. If the schema does not exist, an exception is thrown.
*
* @param schemaName the name of the schema
* @return the schema
* @throws DbException no schema with that name exists
*/
public Schema getSchema(String schemaName) {
Schema schema = findSchema(schemaName);
if (schema == null) {
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
}
return schema;
}
/**
* Remove the object from the database.
*
* @param session the session
* @param obj the object to remove
*/
public synchronized void removeDatabaseObject(Session session, DbObject obj) {
checkWritingAllowed();
String objName = obj.getName();
int type = obj.getType();
HashMap<String, DbObject> map = getMap(type);
if (SysProperties.CHECK && !map.containsKey(objName)) {
DbException.throwInternalError("not found: " + objName);
}
Comment comment = findComment(obj);
lockMeta(session);
if (comment != null) {
removeDatabaseObject(session, comment);
}
int id = obj.getId();
obj.removeChildrenAndResources(session);
map.remove(objName);
removeMeta(session, id);
}
/**
* Get the first table that depends on this object.
*
* @param obj the object to find
* @param except the table to exclude (or null)
* @return the first dependent table, or null
*/
public Table getDependentTable(SchemaObject obj, Table except) {
switch (obj.getType()) {
case DbObject.COMMENT:
case DbObject.CONSTRAINT:
case DbObject.INDEX:
case DbObject.RIGHT:
case DbObject.TRIGGER:
case DbObject.USER:
return null;
default:
}
HashSet<DbObject> set = new HashSet<>();
for (Table t : getAllTablesAndViews(false)) {
if (except == t) {
continue;
} else if (TableType.VIEW == t.getTableType()) {
continue;
}
set.clear();
t.addDependencies(set);
if (set.contains(obj)) {
return t;
}
}
return null;
}
/**
* Remove an object from the system table.
*
* @param session the session
* @param obj the object to be removed
*/
public void removeSchemaObject(Session session,
SchemaObject obj) {
int type = obj.getType();
if (type == DbObject.TABLE_OR_VIEW) {
Table table = (Table) obj;
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.removeLocalTempTable(table);
return;
}
} else if (type == DbObject.INDEX) {
Index index = (Index) obj;
Table table = index.getTable();
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.removeLocalTempTableIndex(index);
return;
}
} else if (type == DbObject.CONSTRAINT) {
Constraint constraint = (Constraint) obj;
Table table = constraint.getTable();
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.removeLocalTempTableConstraint(constraint);
return;
}
}
checkWritingAllowed();
lockMeta(session);
synchronized (this) {
Comment comment = findComment(obj);
if (comment != null) {
removeDatabaseObject(session, comment);
}
obj.getSchema().remove(obj);
int id = obj.getId();
if (!starting) {
Table t = getDependentTable(obj, null);
if (t != null) {
obj.getSchema().add(obj);
throw DbException.get(ErrorCode.CANNOT_DROP_2, obj.getSQL(),
t.getSQL());
}
obj.removeChildrenAndResources(session);
}
removeMeta(session, id);
}
}
/**
* Check if this database is disk-based.
*
* @return true if it is disk-based, false it it is in-memory only.
*/
public boolean isPersistent() {
return persistent;
}
public TraceSystem getTraceSystem() {
return traceSystem;
}
public synchronized void setCacheSize(int kb) {
if (starting) {
int max = MathUtils.convertLongToInt(Utils.getMemoryMax()) / 2;
kb = Math.min(kb, max);
}
cacheSize = kb;
if (pageStore != null) {
pageStore.getCache().setMaxMemory(kb);
}
if (mvStore != null) {
mvStore.setCacheSize(Math.max(1, kb));
}
}
public synchronized void setMasterUser(User user) {
lockMeta(systemSession);
addDatabaseObject(systemSession, user);
systemSession.commit(true);
}
public Role getPublicRole() {
return publicRole;
}
/**
* Get a unique temporary table name.
*
* @param baseName the prefix of the returned name
* @param session the session
* @return a unique name
*/
public synchronized String getTempTableName(String baseName, Session session) {
String tempName;
do {
tempName = baseName + "_COPY_" + session.getId() +
"_" + nextTempTableId++;
} while (mainSchema.findTableOrView(session, tempName) != null);
return tempName;
}
public void setCompareMode(CompareMode compareMode) {
this.compareMode = compareMode;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
@Override
public void checkWritingAllowed() {
if (readOnly) {
throw DbException.get(ErrorCode.DATABASE_IS_READ_ONLY);
}
if (fileLockMethod == FileLockMethod.SERIALIZED) {
if (!reconnectChangePending) {
throw DbException.get(ErrorCode.DATABASE_IS_READ_ONLY);
}
}
}
public boolean isReadOnly() {
return readOnly;
}
public void setWriteDelay(int value) {
writeDelay = value;
if (writer != null) {
writer.setWriteDelay(value);
// TODO check if MIN_WRITE_DELAY is a good value
flushOnEachCommit = writeDelay < Constants.MIN_WRITE_DELAY;
}
if (mvStore != null) {
int millis = value < 0 ? 0 : value;
mvStore.getStore().setAutoCommitDelay(millis);
}
}
public int getRetentionTime() {
return retentionTime;
}
public void setRetentionTime(int value) {
retentionTime = value;
if (mvStore != null) {
mvStore.getStore().setRetentionTime(value);
}
}
public void setAllowBuiltinAliasOverride(boolean b) {
allowBuiltinAliasOverride = b;
}
public boolean isAllowBuiltinAliasOverride() {
return allowBuiltinAliasOverride;
}
/**
* Check if flush-on-each-commit is enabled.
*
* @return true if it is
*/
public boolean getFlushOnEachCommit() {
return flushOnEachCommit;
}
/**
* Get the list of in-doubt transactions.
*
* @return the list
*/
public ArrayList<InDoubtTransaction> getInDoubtTransactions() {
if (mvStore != null) {
return mvStore.getInDoubtTransactions();
}
return pageStore == null ? null : pageStore.getInDoubtTransactions();
}
/**
* Prepare a transaction.
*
* @param session the session
* @param transaction the name of the transaction
*/
synchronized void prepareCommit(Session session, String transaction) {
if (readOnly) {
return;
}
if (mvStore != null) {
mvStore.prepareCommit(session, transaction);
return;
}
if (pageStore != null) {
pageStore.flushLog();
pageStore.prepareCommit(session, transaction);
}
}
/**
* Commit the current transaction of the given session.
*
* @param session the session
*/
synchronized void commit(Session session) {
throwLastBackgroundException();
if (readOnly) {
return;
}
if (pageStore != null) {
pageStore.commit(session);
}
session.setAllCommitted();
}
private void throwLastBackgroundException() {
if (backgroundException != null) {
// we don't care too much about concurrency here,
// we just want to make sure the exception is _normally_
// not just logged to the .trace.db file
DbException b = backgroundException;
backgroundException = null;
if (b != null) {
// wrap the exception, so we see it was thrown here
throw DbException.get(b.getErrorCode(), b, b.getMessage());
}
}
}
public void setBackgroundException(DbException e) {
if (backgroundException == null) {
backgroundException = e;
TraceSystem t = getTraceSystem();
if (t != null) {
t.getTrace(Trace.DATABASE).error(e, "flush");
}
}
}
/**
* Flush all pending changes to the transaction log.
*/
public synchronized void flush() {
if (readOnly) {
return;
}
if (pageStore != null) {
pageStore.flushLog();
}
if (mvStore != null) {
try {
mvStore.flush();
} catch (RuntimeException e) {
backgroundException = DbException.convert(e);
throw e;
}
}
}
public void setEventListener(DatabaseEventListener eventListener) {
this.eventListener = eventListener;
}
public void setEventListenerClass(String className) {
if (className == null || className.length() == 0) {
eventListener = null;
} else {
try {
eventListener = (DatabaseEventListener)
JdbcUtils.loadUserClass(className).newInstance();
String url = databaseURL;
if (cipher != null) {
url += ";CIPHER=" + cipher;
}
eventListener.init(url);
} catch (Throwable e) {
throw DbException.get(
ErrorCode.ERROR_SETTING_DATABASE_EVENT_LISTENER_2, e,
className, e.toString());
}
}
}
/**
* Set the progress of a long running operation.
* This method calls the {@link DatabaseEventListener} if one is registered.
*
* @param state the {@link DatabaseEventListener} state
* @param name the object name
* @param x the current position
* @param max the highest value
*/
public void setProgress(int state, String name, int x, int max) {
if (eventListener != null) {
try {
eventListener.setProgress(state, name, x, max);
} catch (Exception e2) {
// ignore this (user made) exception
}
}
}
/**
* This method is called after an exception occurred, to inform the database
* event listener (if one is set).
*
* @param e the exception
* @param sql the SQL statement
*/
public void exceptionThrown(SQLException e, String sql) {
if (eventListener != null) {
try {
eventListener.exceptionThrown(e, sql);
} catch (Exception e2) {
// ignore this (user made) exception
}
}
}
/**
* Synchronize the files with the file system. This method is called when
* executing the SQL statement CHECKPOINT SYNC.
*/
public synchronized void sync() {
if (readOnly) {
return;
}
if (mvStore != null) {
mvStore.sync();
}
if (pageStore != null) {
pageStore.sync();
}
}
public int getMaxMemoryRows() {
return maxMemoryRows;
}
public void setMaxMemoryRows(int value) {
this.maxMemoryRows = value;
}
public void setMaxMemoryUndo(int value) {
this.maxMemoryUndo = value;
}
public int getMaxMemoryUndo() {
return maxMemoryUndo;
}
public void setLockMode(int lockMode) {
switch (lockMode) {
case Constants.LOCK_MODE_OFF:
if (multiThreaded) {
// currently the combination of LOCK_MODE=0 and MULTI_THREADED
// is not supported. also see code in
// JdbcDatabaseMetaData#supportsTransactionIsolationLevel(int)
throw DbException.get(
ErrorCode.UNSUPPORTED_SETTING_COMBINATION,
"LOCK_MODE=0 & MULTI_THREADED");
}
break;
case Constants.LOCK_MODE_READ_COMMITTED:
case Constants.LOCK_MODE_TABLE:
case Constants.LOCK_MODE_TABLE_GC:
break;
default:
throw DbException.getInvalidValueException("lock mode", lockMode);
}
this.lockMode = lockMode;
}
public int getLockMode() {
return lockMode;
}
public synchronized void setCloseDelay(int value) {
this.closeDelay = value;
}
public Session getSystemSession() {
return systemSession;
}
/**
* Check if the database is in the process of closing.
*
* @return true if the database is closing
*/
public boolean isClosing() {
return closing;
}
public void setMaxLengthInplaceLob(int value) {
this.maxLengthInplaceLob = value;
}
@Override
public int getMaxLengthInplaceLob() {
return maxLengthInplaceLob;
}
public void setIgnoreCase(boolean b) {
ignoreCase = b;
}
public boolean getIgnoreCase() {
if (starting) {
// tables created at startup must not be converted to ignorecase
return false;
}
return ignoreCase;
}
public synchronized void setDeleteFilesOnDisconnect(boolean b) {
this.deleteFilesOnDisconnect = b;
}
@Override
public String getLobCompressionAlgorithm(int type) {
return lobCompressionAlgorithm;
}
public void setLobCompressionAlgorithm(String stringValue) {
this.lobCompressionAlgorithm = stringValue;
}
public synchronized void setMaxLogSize(long value) {
if (pageStore != null) {
pageStore.setMaxLogSize(value);
}
}
public void setAllowLiterals(int value) {
this.allowLiterals = value;
}
public boolean getOptimizeReuseResults() {
return optimizeReuseResults;
}
public void setOptimizeReuseResults(boolean b) {
optimizeReuseResults = b;
}
@Override
public Object getLobSyncObject() {
return lobSyncObject;
}
public int getSessionCount() {
return userSessions.size();
}
public void setReferentialIntegrity(boolean b) {
referentialIntegrity = b;
}
public boolean getReferentialIntegrity() {
return referentialIntegrity;
}
public void setQueryStatistics(boolean b) {
queryStatistics = b;
synchronized (this) {
if (!b) {
queryStatisticsData = null;
}
}
}
public boolean getQueryStatistics() {
return queryStatistics;
}
public void setQueryStatisticsMaxEntries(int n) {
queryStatisticsMaxEntries = n;
if (queryStatisticsData != null) {
synchronized (this) {
if (queryStatisticsData != null) {
queryStatisticsData.setMaxQueryEntries(queryStatisticsMaxEntries);
}
}
}
}
public QueryStatisticsData getQueryStatisticsData() {
if (!queryStatistics) {
return null;
}
if (queryStatisticsData == null) {
synchronized (this) {
if (queryStatisticsData == null) {
queryStatisticsData = new QueryStatisticsData(queryStatisticsMaxEntries);
}
}
}
return queryStatisticsData;
}
/**
* Check if the database is currently opening. This is true until all stored
* SQL statements have been executed.
*
* @return true if the database is still starting
*/
public boolean isStarting() {
return starting;
}
/**
* Check if multi version concurrency is enabled for this database.
*
* @return true if it is enabled
*/
public boolean isMultiVersion() {
return multiVersion;
}
/**
* Called after the database has been opened and initialized. This method
* notifies the event listener if one has been set.
*/
void opened() {
if (eventListener != null) {
eventListener.opened();
}
if (writer != null) {
writer.startThread();
}
}
public void setMode(Mode mode) {
this.mode = mode;
}
public Mode getMode() {
return mode;
}
public boolean isMultiThreaded() {
return multiThreaded;
}
public void setMultiThreaded(boolean multiThreaded) {
if (multiThreaded && this.multiThreaded != multiThreaded) {
if (multiVersion && mvStore == null) {
// currently the combination of MVCC and MULTI_THREADED is not
// supported
throw DbException.get(
ErrorCode.UNSUPPORTED_SETTING_COMBINATION,
"MVCC & MULTI_THREADED");
}
if (lockMode == 0) {
// currently the combination of LOCK_MODE=0 and MULTI_THREADED
// is not supported
throw DbException.get(
ErrorCode.UNSUPPORTED_SETTING_COMBINATION,
"LOCK_MODE=0 & MULTI_THREADED");
}
}
this.multiThreaded = multiThreaded;
}
public void setMaxOperationMemory(int maxOperationMemory) {
this.maxOperationMemory = maxOperationMemory;
}
public int getMaxOperationMemory() {
return maxOperationMemory;
}
public Session getExclusiveSession() {
return exclusiveSession.get();
}
/**
* Set the session that can exclusively access the database.
*
* @param session the session
* @param closeOthers whether other sessions are closed
*/
public void setExclusiveSession(Session session, boolean closeOthers) {
this.exclusiveSession.set(session);
if (closeOthers) {
closeAllSessionsException(session);
}
}
@Override
public SmallLRUCache<String, String[]> getLobFileListCache() {
if (lobFileListCache == null) {
lobFileListCache = SmallLRUCache.newInstance(128);
}
return lobFileListCache;
}
/**
* Checks if the system table (containing the catalog) is locked.
*
* @return true if it is currently locked
*/
public boolean isSysTableLocked() {
return meta == null || meta.isLockedExclusively();
}
/**
* Checks if the system table (containing the catalog) is locked by the
* given session.
*
* @param session the session
* @return true if it is currently locked
*/
public boolean isSysTableLockedBy(Session session) {
return meta == null || meta.isLockedExclusivelyBy(session);
}
/**
* Open a new connection or get an existing connection to another database.
*
* @param driver the database driver or null
* @param url the database URL
* @param user the user name
* @param password the password
* @return the connection
*/
public TableLinkConnection getLinkConnection(String driver, String url,
String user, String password) {
if (linkConnections == null) {
linkConnections = new HashMap<>();
}
return TableLinkConnection.open(linkConnections, driver, url, user,
password, dbSettings.shareLinkedConnections);
}
@Override
public String toString() {
return databaseShortName + ":" + super.toString();
}
/**
* Immediately close the database.
*/
public void shutdownImmediately() {
setPowerOffCount(1);
try {
checkPowerOff();
} catch (DbException e) {
// ignore
}
closeFiles();
}
@Override
public TempFileDeleter getTempFileDeleter() {
return tempFileDeleter;
}
public PageStore getPageStore() {
if (dbSettings.mvStore) {
if (mvStore == null) {
mvStore = MVTableEngine.init(this);
}
return null;
}
if (pageStore == null) {
pageStore = new PageStore(this, databaseName +
Constants.SUFFIX_PAGE_FILE, accessModeData, cacheSize);
if (pageSize != Constants.DEFAULT_PAGE_SIZE) {
pageStore.setPageSize(pageSize);
}
if (!readOnly && fileLockMethod == FileLockMethod.FS) {
pageStore.setLockFile(true);
}
pageStore.setLogMode(logMode);
pageStore.open();
}
return pageStore;
}
/**
* Get the first user defined table.
*
* @return the table or null if no table is defined
*/
public Table getFirstUserTable() {
for (Table table : getAllTablesAndViews(false)) {
if (table.getCreateSQL() != null) {
if (table.isHidden()) {
// LOB tables
continue;
}
return table;
}
}
return null;
}
/**
* Check if the contents of the database was changed and therefore it is
* required to re-connect. This method waits until pending changes are
* completed. If a pending change takes too long (more than 2 seconds), the
* pending change is broken (removed from the properties file).
*
* @return true if reconnecting is required
*/
public boolean isReconnectNeeded() {
if (fileLockMethod != FileLockMethod.SERIALIZED) {
return false;
}
if (reconnectChangePending) {
return false;
}
long now = System.nanoTime();
if (now < reconnectCheckNext) {
return false;
}
reconnectCheckNext = now + reconnectCheckDelayNs;
if (lock == null) {
lock = new FileLock(traceSystem, databaseName +
Constants.SUFFIX_LOCK_FILE, Constants.LOCK_SLEEP);
}
try {
Properties prop = lock.load(), first = prop;
while (true) {
if (prop.equals(reconnectLastLock)) {
return false;
}
if (prop.getProperty("changePending", null) == null) {
break;
}
if (System.nanoTime() >
now + reconnectCheckDelayNs * 10) {
if (first.equals(prop)) {
// the writing process didn't update the file -
// it may have terminated
lock.setProperty("changePending", null);
lock.save();
break;
}
}
trace.debug("delay (change pending)");
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(reconnectCheckDelayNs));
prop = lock.load();
}
reconnectLastLock = prop;
} catch (Exception e) {
// DbException, InterruptedException
trace.error(e, "readOnly {0}", readOnly);
// ignore
}
return true;
}
/**
* Flush all changes when using the serialized mode, and if there are
* pending changes, and some time has passed. This switches to a new
* transaction log and resets the change pending flag in
* the .lock.db file.
*/
public void checkpointIfRequired() {
if (fileLockMethod != FileLockMethod.SERIALIZED ||
readOnly || !reconnectChangePending || closing) {
return;
}
long now = System.nanoTime();
if (now > reconnectCheckNext + reconnectCheckDelayNs) {
if (SysProperties.CHECK && checkpointAllowed < 0) {
DbException.throwInternalError("" + checkpointAllowed);
}
synchronized (reconnectSync) {
if (checkpointAllowed > 0) {
return;
}
checkpointRunning = true;
}
synchronized (this) {
trace.debug("checkpoint start");
flushSequences();
checkpoint();
reconnectModified(false);
trace.debug("checkpoint end");
}
synchronized (reconnectSync) {
checkpointRunning = false;
}
}
}
public boolean isFileLockSerialized() {
return fileLockMethod == FileLockMethod.SERIALIZED;
}
private void flushSequences() {
for (SchemaObject obj : getAllSchemaObjects(DbObject.SEQUENCE)) {
Sequence sequence = (Sequence) obj;
sequence.flushWithoutMargin();
}
}
/**
* Flush all changes and open a new transaction log.
*/
public void checkpoint() {
if (persistent) {
synchronized (this) {
if (pageStore != null) {
pageStore.checkpoint();
}
}
if (mvStore != null) {
mvStore.flush();
}
}
getTempFileDeleter().deleteUnused();
}
/**
* This method is called before writing to the transaction log.
*
* @return true if the call was successful and writing is allowed,
* false if another connection was faster
*/
public boolean beforeWriting() {
if (fileLockMethod != FileLockMethod.SERIALIZED) {
return true;
}
while (checkpointRunning) {
try {
Thread.sleep(10 + (int) (Math.random() * 10));
} catch (Exception e) {
// ignore InterruptedException
}
}
synchronized (reconnectSync) {
if (reconnectModified(true)) {
checkpointAllowed++;
if (SysProperties.CHECK && checkpointAllowed > 20) {
throw DbException.throwInternalError("" + checkpointAllowed);
}
return true;
}
}
// make sure the next call to isReconnectNeeded() returns true
reconnectCheckNext = System.nanoTime() - 1;
reconnectLastLock = null;
return false;
}
/**
* This method is called after updates are finished.
*/
public void afterWriting() {
if (fileLockMethod != FileLockMethod.SERIALIZED) {
return;
}
synchronized (reconnectSync) {
checkpointAllowed--;
}
if (SysProperties.CHECK && checkpointAllowed < 0) {
throw DbException.throwInternalError("" + checkpointAllowed);
}
}
/**
* Switch the database to read-only mode.
*
* @param readOnly the new value
*/
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public void setCompactMode(int compactMode) {
this.compactMode = compactMode;
}
public SourceCompiler getCompiler() {
if (compiler == null) {
compiler = new SourceCompiler();
}
return compiler;
}
@Override
public LobStorageInterface getLobStorage() {
if (lobStorage == null) {
if (dbSettings.mvStore) {
lobStorage = new LobStorageMap(this);
} else {
lobStorage = new LobStorageBackend(this);
}
}
return lobStorage;
}
public JdbcConnection getLobConnectionForInit() {
String url = Constants.CONN_URL_INTERNAL;
JdbcConnection conn = new JdbcConnection(
systemSession, systemUser.getName(), url);
conn.setTraceLevel(TraceSystem.OFF);
return conn;
}
public JdbcConnection getLobConnectionForRegularUse() {
String url = Constants.CONN_URL_INTERNAL;
JdbcConnection conn = new JdbcConnection(
lobSession, systemUser.getName(), url);
conn.setTraceLevel(TraceSystem.OFF);
return conn;
}
public Session getLobSession() {
return lobSession;
}
public void setLogMode(int log) {
if (log < 0 || log > 2) {
throw DbException.getInvalidValueException("LOG", log);
}
if (pageStore != null) {
if (log != PageStore.LOG_MODE_SYNC ||
pageStore.getLogMode() != PageStore.LOG_MODE_SYNC) {
// write the log mode in the trace file when enabling or
// disabling a dangerous mode
trace.error(null, "log {0}", log);
}
this.logMode = log;
pageStore.setLogMode(log);
}
if (mvStore != null) {
this.logMode = log;
}
}
public int getLogMode() {
if (pageStore != null) {
return pageStore.getLogMode();
}
if (mvStore != null) {
return logMode;
}
return PageStore.LOG_MODE_OFF;
}
public int getDefaultTableType() {
return defaultTableType;
}
public void setDefaultTableType(int defaultTableType) {
this.defaultTableType = defaultTableType;
}
public void setMultiVersion(boolean multiVersion) {
this.multiVersion = multiVersion;
}
public DbSettings getSettings() {
return dbSettings;
}
/**
* Create a new hash map. Depending on the configuration, the key is case
* sensitive or case insensitive.
*
* @param <V> the value type
* @return the hash map
*/
public <V> HashMap<String, V> newStringMap() {
return dbSettings.databaseToUpper ?
new HashMap<String, V>() :
new CaseInsensitiveMap<V>();
}
/**
* Create a new hash map. Depending on the configuration, the key is case
* sensitive or case insensitive.
*
* @param <V> the value type
* @return the hash map
*/
public <V> ConcurrentHashMap<String, V> newConcurrentStringMap() {
return dbSettings.databaseToUpper ?
new NullableKeyConcurrentMap<V>() :
new CaseInsensitiveConcurrentMap<V>();
}
/**
* Compare two identifiers (table names, column names,...) and verify they
* are equal. Case sensitivity depends on the configuration.
*
* @param a the first identifier
* @param b the second identifier
* @return true if they match
*/
public boolean equalsIdentifiers(String a, String b) {
return a.equals(b) || (!dbSettings.databaseToUpper && a.equalsIgnoreCase(b));
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
throw DbException.throwInternalError();
}
public byte[] getFileEncryptionKey() {
return fileEncryptionKey;
}
public int getPageSize() {
return pageSize;
}
@Override
public JavaObjectSerializer getJavaObjectSerializer() {
initJavaObjectSerializer();
return javaObjectSerializer;
}
private void initJavaObjectSerializer() {
if (javaObjectSerializerInitialized) {
return;
}
synchronized (this) {
if (javaObjectSerializerInitialized) {
return;
}
String serializerName = javaObjectSerializerName;
if (serializerName != null) {
serializerName = serializerName.trim();
if (!serializerName.isEmpty() &&
!serializerName.equals("null")) {
try {
javaObjectSerializer = (JavaObjectSerializer)
JdbcUtils.loadUserClass(serializerName).newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
javaObjectSerializerInitialized = true;
}
}
public void setJavaObjectSerializerName(String serializerName) {
synchronized (this) {
javaObjectSerializerInitialized = false;
javaObjectSerializerName = serializerName;
}
}
/**
* Get the table engine class, loading it if needed.
*
* @param tableEngine the table engine name
* @return the class
*/
public TableEngine getTableEngine(String tableEngine) {
assert Thread.holdsLock(this);
TableEngine engine = tableEngines.get(tableEngine);
if (engine == null) {
try {
engine = (TableEngine) JdbcUtils.loadUserClass(tableEngine).newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
tableEngines.put(tableEngine, engine);
}
return engine;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/DatabaseCloser.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.lang.ref.WeakReference;
import org.h2.message.Trace;
/**
* This class is responsible to close a database if the application did not
* close a connection. A database closer object only exists if there is no user
* connected to the database.
*/
class DatabaseCloser extends Thread {
private final boolean shutdownHook;
private final Trace trace;
private volatile WeakReference<Database> databaseRef;
private int delayInMillis;
DatabaseCloser(Database db, int delayInMillis, boolean shutdownHook) {
this.databaseRef = new WeakReference<>(db);
this.delayInMillis = delayInMillis;
this.shutdownHook = shutdownHook;
trace = db.getTrace(Trace.DATABASE);
}
/**
* Stop and disable the database closer. This method is called after the
* database has been closed, or after a session has been created.
*/
void reset() {
synchronized (this) {
databaseRef = null;
}
}
@Override
public void run() {
while (delayInMillis > 0) {
try {
int step = 100;
Thread.sleep(step);
delayInMillis -= step;
} catch (Exception e) {
// ignore InterruptedException
}
if (databaseRef == null) {
return;
}
}
Database database = null;
synchronized (this) {
if (databaseRef != null) {
database = databaseRef.get();
}
}
if (database != null) {
try {
database.close(shutdownHook);
} catch (RuntimeException e) {
// this can happen when stopping a web application,
// if loading classes is no longer allowed
// it would throw an IllegalStateException
try {
trace.error(e, "could not close the database");
// if this was successful, we ignore the exception
// otherwise not
} catch (Throwable e2) {
e.addSuppressed(e2);
throw e;
}
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/DbObject.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import org.h2.table.Table;
/**
* A database object such as a table, an index, or a user.
*/
public interface DbObject {
/**
* The object is of the type table or view.
*/
int TABLE_OR_VIEW = 0;
/**
* This object is an index.
*/
int INDEX = 1;
/**
* This object is a user.
*/
int USER = 2;
/**
* This object is a sequence.
*/
int SEQUENCE = 3;
/**
* This object is a trigger.
*/
int TRIGGER = 4;
/**
* This object is a constraint (check constraint, unique constraint, or
* referential constraint).
*/
int CONSTRAINT = 5;
/**
* This object is a setting.
*/
int SETTING = 6;
/**
* This object is a role.
*/
int ROLE = 7;
/**
* This object is a right.
*/
int RIGHT = 8;
/**
* This object is an alias for a Java function.
*/
int FUNCTION_ALIAS = 9;
/**
* This object is a schema.
*/
int SCHEMA = 10;
/**
* This object is a constant.
*/
int CONSTANT = 11;
/**
* This object is a user data type (domain).
*/
int USER_DATATYPE = 12;
/**
* This object is a comment.
*/
int COMMENT = 13;
/**
* This object is a user-defined aggregate function.
*/
int AGGREGATE = 14;
/**
* This object is a synonym.
*/
int SYNONYM = 15;
/**
* Get the SQL name of this object (may be quoted).
*
* @return the SQL name
*/
String getSQL();
/**
* Get the list of dependent children (for tables, this includes indexes and
* so on).
*
* @return the list of children
*/
ArrayList<DbObject> getChildren();
/**
* Get the database.
*
* @return the database
*/
Database getDatabase();
/**
* Get the unique object id.
*
* @return the object id
*/
int getId();
/**
* Get the name.
*
* @return the name
*/
String getName();
/**
* Build a SQL statement to re-create the object, or to create a copy of the
* object with a different name or referencing a different table
*
* @param table the new table
* @param quotedName the quoted name
* @return the SQL statement
*/
String getCreateSQLForCopy(Table table, String quotedName);
/**
* Construct the original CREATE ... SQL statement for this object.
*
* @return the SQL statement
*/
String getCreateSQL();
/**
* Construct a DROP ... SQL statement for this object.
*
* @return the SQL statement
*/
String getDropSQL();
/**
* Get the object type.
*
* @return the object type
*/
int getType();
/**
* Delete all dependent children objects and resources of this object.
*
* @param session the session
*/
void removeChildrenAndResources(Session session);
/**
* Check if renaming is allowed. Does nothing when allowed.
*/
void checkRename();
/**
* Rename the object.
*
* @param newName the new name
*/
void rename(String newName);
/**
* Check if this object is temporary (for example, a temporary table).
*
* @return true if is temporary
*/
boolean isTemporary();
/**
* Tell this object that it is temporary or not.
*
* @param temporary the new value
*/
void setTemporary(boolean temporary);
/**
* Change the comment of this object.
*
* @param comment the new comment, or null for no comment
*/
void setComment(String comment);
/**
* Get the current comment of this object.
*
* @return the comment, or null if not set
*/
String getComment();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/DbObjectBase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import org.h2.command.Parser;
import org.h2.message.DbException;
import org.h2.message.Trace;
/**
* The base class for all database objects.
*/
public abstract class DbObjectBase implements DbObject {
/**
* The database.
*/
protected Database database;
/**
* The trace module.
*/
protected Trace trace;
/**
* The comment (if set).
*/
protected String comment;
private int id;
private String objectName;
private long modificationId;
private boolean temporary;
/**
* Initialize some attributes of this object.
*
* @param db the database
* @param objectId the object id
* @param name the name
* @param traceModuleId the trace module id
*/
protected void initDbObjectBase(Database db, int objectId, String name,
int traceModuleId) {
this.database = db;
this.trace = db.getTrace(traceModuleId);
this.id = objectId;
this.objectName = name;
this.modificationId = db.getModificationMetaId();
}
/**
* Build a SQL statement to re-create this object.
*
* @return the SQL statement
*/
@Override
public abstract String getCreateSQL();
/**
* Build a SQL statement to drop this object.
*
* @return the SQL statement
*/
@Override
public abstract String getDropSQL();
/**
* Remove all dependent objects and free all resources (files, blocks in
* files) of this object.
*
* @param session the session
*/
@Override
public abstract void removeChildrenAndResources(Session session);
/**
* Check if this object can be renamed. System objects may not be renamed.
*/
@Override
public abstract void checkRename();
/**
* Tell the object that is was modified.
*/
public void setModified() {
this.modificationId = database == null ?
-1 : database.getNextModificationMetaId();
}
public long getModificationId() {
return modificationId;
}
protected void setObjectName(String name) {
objectName = name;
}
@Override
public String getSQL() {
return Parser.quoteIdentifier(objectName);
}
@Override
public ArrayList<DbObject> getChildren() {
return null;
}
@Override
public Database getDatabase() {
return database;
}
@Override
public int getId() {
return id;
}
@Override
public String getName() {
return objectName;
}
/**
* Set the main attributes to null to make sure the object is no longer
* used.
*/
protected void invalidate() {
if (SysProperties.CHECK && id == -1) {
throw DbException.throwInternalError();
}
setModified();
id = -1;
database = null;
trace = null;
objectName = null;
}
public final boolean isValid() {
return id != -1;
}
@Override
public void rename(String newName) {
checkRename();
objectName = newName;
setModified();
}
@Override
public boolean isTemporary() {
return temporary;
}
@Override
public void setTemporary(boolean temporary) {
this.temporary = temporary;
}
@Override
public void setComment(String comment) {
this.comment = comment;
}
@Override
public String getComment() {
return comment;
}
@Override
public String toString() {
return objectName + ":" + id + ":" + super.toString();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/DbSettings.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.HashMap;
import org.h2.message.DbException;
import org.h2.util.Utils;
/**
* This class contains various database-level settings. To override the
* documented default value for a database, append the setting in the database
* URL: "jdbc:h2:test;ALIAS_COLUMN_NAME=TRUE" when opening the first connection
* to the database. The settings can not be changed once the database is open.
* <p>
* Some settings are a last resort and temporary solution to work around a
* problem in the application or database engine. Also, there are system
* properties to enable features that are not yet fully tested or that are not
* backward compatible.
* </p>
*/
public class DbSettings extends SettingsBase {
private static DbSettings defaultSettings;
/**
* Database setting <code>ALIAS_COLUMN_NAME</code> (default: false).<br />
* When enabled, aliased columns (as in SELECT ID AS I FROM TEST) return the
* alias (I in this case) in ResultSetMetaData.getColumnName() and 'null' in
* getTableName(). If disabled, the real column name (ID in this case) and
* table name is returned.
* <br />
* This setting only affects the default and the MySQL mode. When using
* any other mode, this feature is enabled for compatibility, even if this
* database setting is not enabled explicitly.
*/
public final boolean aliasColumnName = get("ALIAS_COLUMN_NAME", false);
/**
* Database setting <code>ANALYZE_AUTO</code> (default: 2000).<br />
* After changing this many rows, ANALYZE is automatically run for a table.
* Automatically running ANALYZE is disabled if set to 0. If set to 1000,
* then ANALYZE will run against each user table after about 1000 changes to
* that table. The time between running ANALYZE doubles each time since
* starting the database. It is not run on local temporary tables, and
* tables that have a trigger on SELECT.
*/
public final int analyzeAuto = get("ANALYZE_AUTO", 2000);
/**
* Database setting <code>ANALYZE_SAMPLE</code> (default: 10000).<br />
* The default sample size when analyzing a table.
*/
public final int analyzeSample = get("ANALYZE_SAMPLE", 10_000);
/**
* Database setting <code>DATABASE_TO_UPPER</code> (default: true).<br />
* Database short names are converted to uppercase for the DATABASE()
* function, and in the CATALOG column of all database meta data methods.
* Setting this to "false" is experimental. When set to false, all
* identifier names (table names, column names) are case sensitive (except
* aggregate, built-in functions, data types, and keywords).
*/
public final boolean databaseToUpper = get("DATABASE_TO_UPPER", true);
/**
* Database setting <code>DB_CLOSE_ON_EXIT</code> (default: true).<br />
* Close the database when the virtual machine exits normally, using a
* shutdown hook.
*/
public final boolean dbCloseOnExit = get("DB_CLOSE_ON_EXIT", true);
/**
* Database setting <code>DEFAULT_CONNECTION</code> (default: false).<br />
* Whether Java functions can use
* <code>DriverManager.getConnection("jdbc:default:connection")</code> to
* get a database connection. This feature is disabled by default for
* performance reasons. Please note the Oracle JDBC driver will try to
* resolve this database URL if it is loaded before the H2 driver.
*/
public final boolean defaultConnection = get("DEFAULT_CONNECTION", false);
/**
* Database setting <code>DEFAULT_ESCAPE</code> (default: \).<br />
* The default escape character for LIKE comparisons. To select no escape
* character, use an empty string.
*/
public final String defaultEscape = get("DEFAULT_ESCAPE", "\\");
/**
* Database setting <code>DEFRAG_ALWAYS</code> (default: false).<br />
* Each time the database is closed normally, it is fully defragmented (the
* same as SHUTDOWN DEFRAG). If you execute SHUTDOWN COMPACT, then this
* setting is ignored.
*/
public final boolean defragAlways = get("DEFRAG_ALWAYS", false);
/**
* Database setting <code>DROP_RESTRICT</code> (default: true).<br />
* Whether the default action for DROP TABLE, DROP VIEW, and DROP SCHEMA
* is RESTRICT.
*/
public final boolean dropRestrict = get("DROP_RESTRICT", true);
/**
* Database setting <code>EARLY_FILTER</code> (default: false).<br />
* This setting allows table implementations to apply filter conditions
* early on.
*/
public final boolean earlyFilter = get("EARLY_FILTER", false);
/**
* Database setting <code>ESTIMATED_FUNCTION_TABLE_ROWS</code> (default:
* 1000).<br />
* The estimated number of rows in a function table (for example, CSVREAD or
* FTL_SEARCH). This value is used by the optimizer.
*/
public final int estimatedFunctionTableRows = get(
"ESTIMATED_FUNCTION_TABLE_ROWS", 1000);
/**
* Database setting <code>FUNCTIONS_IN_SCHEMA</code>
* (default: true).<br />
* If set, all functions are stored in a schema. Specially, the SCRIPT
* statement will always include the schema name in the CREATE ALIAS
* statement. This is not backward compatible with H2 versions 1.2.134 and
* older.
*/
public final boolean functionsInSchema = get("FUNCTIONS_IN_SCHEMA", true);
/**
* Database setting <code>LARGE_TRANSACTIONS</code> (default: true).<br />
* Support very large transactions
*/
public final boolean largeTransactions = get("LARGE_TRANSACTIONS", true);
/**
* Database setting <code>LOB_TIMEOUT</code> (default: 300000,
* which means 5 minutes).<br />
* The number of milliseconds a temporary LOB reference is kept until it
* times out. After the timeout, the LOB is no longer accessible using this
* reference.
*/
public final int lobTimeout = get("LOB_TIMEOUT", 300_000);
/**
* Database setting <code>MAX_COMPACT_COUNT</code>
* (default: Integer.MAX_VALUE).<br />
* The maximum number of pages to move when closing a database.
*/
public final int maxCompactCount = get("MAX_COMPACT_COUNT",
Integer.MAX_VALUE);
/**
* Database setting <code>MAX_COMPACT_TIME</code> (default: 200).<br />
* The maximum time in milliseconds used to compact a database when closing.
*/
public final int maxCompactTime = get("MAX_COMPACT_TIME", 200);
/**
* Database setting <code>MAX_QUERY_TIMEOUT</code> (default: 0).<br />
* The maximum timeout of a query in milliseconds. The default is 0, meaning
* no limit. Please note the actual query timeout may be set to a lower
* value.
*/
public final int maxQueryTimeout = get("MAX_QUERY_TIMEOUT", 0);
/**
* Database setting <code>OPTIMIZE_DISTINCT</code> (default: true).<br />
* Improve the performance of simple DISTINCT queries if an index is
* available for the given column. The optimization is used if:
* <ul>
* <li>The select is a single column query without condition </li>
* <li>The query contains only one table, and no group by </li>
* <li>There is only one table involved </li>
* <li>There is an ascending index on the column </li>
* <li>The selectivity of the column is below 20 </li>
* </ul>
*/
public final boolean optimizeDistinct = get("OPTIMIZE_DISTINCT", true);
/**
* Database setting <code>OPTIMIZE_EVALUATABLE_SUBQUERIES</code> (default:
* true).<br />
* Optimize subqueries that are not dependent on the outer query.
*/
public final boolean optimizeEvaluatableSubqueries = get(
"OPTIMIZE_EVALUATABLE_SUBQUERIES", true);
/**
* Database setting <code>OPTIMIZE_INSERT_FROM_SELECT</code>
* (default: true).<br />
* Insert into table from query directly bypassing temporary disk storage.
* This also applies to create table as select.
*/
public final boolean optimizeInsertFromSelect = get(
"OPTIMIZE_INSERT_FROM_SELECT", true);
/**
* Database setting <code>OPTIMIZE_IN_LIST</code> (default: true).<br />
* Optimize IN(...) and IN(SELECT ...) comparisons. This includes
* optimization for SELECT, DELETE, and UPDATE.
*/
public final boolean optimizeInList = get("OPTIMIZE_IN_LIST", true);
/**
* Database setting <code>OPTIMIZE_IN_SELECT</code> (default: true).<br />
* Optimize IN(SELECT ...) comparisons. This includes
* optimization for SELECT, DELETE, and UPDATE.
*/
public final boolean optimizeInSelect = get("OPTIMIZE_IN_SELECT", true);
/**
* Database setting <code>OPTIMIZE_IS_NULL</code> (default: false).<br />
* Use an index for condition of the form columnName IS NULL.
*/
public final boolean optimizeIsNull = get("OPTIMIZE_IS_NULL", true);
/**
* Database setting <code>OPTIMIZE_OR</code> (default: true).<br />
* Convert (C=? OR C=?) to (C IN(?, ?)).
*/
public final boolean optimizeOr = get("OPTIMIZE_OR", true);
/**
* Database setting <code>OPTIMIZE_TWO_EQUALS</code> (default: true).<br />
* Optimize expressions of the form A=B AND B=1. In this case, AND A=1 is
* added so an index on A can be used.
*/
public final boolean optimizeTwoEquals = get("OPTIMIZE_TWO_EQUALS", true);
/**
* Database setting <code>OPTIMIZE_UPDATE</code> (default: true).<br />
* Speed up inserts, updates, and deletes by not reading all rows from a
* page unless necessary.
*/
public final boolean optimizeUpdate = get("OPTIMIZE_UPDATE", true);
/**
* Database setting <code>PAGE_STORE_MAX_GROWTH</code>
* (default: 128 * 1024).<br />
* The maximum number of pages the file grows at any time.
*/
public final int pageStoreMaxGrowth = get("PAGE_STORE_MAX_GROWTH",
128 * 1024);
/**
* Database setting <code>PAGE_STORE_INTERNAL_COUNT</code>
* (default: false).<br />
* Update the row counts on a node level.
*/
public final boolean pageStoreInternalCount = get(
"PAGE_STORE_INTERNAL_COUNT", false);
/**
* Database setting <code>PAGE_STORE_TRIM</code> (default: true).<br />
* Trim the database size when closing.
*/
public final boolean pageStoreTrim = get("PAGE_STORE_TRIM", true);
/**
* Database setting <code>QUERY_CACHE_SIZE</code> (default: 8).<br />
* The size of the query cache, in number of cached statements. Each session
* has it's own cache with the given size. The cache is only used if the SQL
* statement and all parameters match. Only the last returned result per
* query is cached. The following statement types are cached: SELECT
* statements are cached (excluding UNION and FOR UPDATE statements), CALL
* if it returns a single value, DELETE, INSERT, MERGE, UPDATE, and
* transactional statements such as COMMIT. This works for both statements
* and prepared statement.
*/
public final int queryCacheSize = get("QUERY_CACHE_SIZE", 8);
/**
* Database setting <code>RECOMPILE_ALWAYS</code> (default: false).<br />
* Always recompile prepared statements.
*/
public final boolean recompileAlways = get("RECOMPILE_ALWAYS", false);
/**
* Database setting <code>RECONNECT_CHECK_DELAY</code> (default: 200).<br />
* Check the .lock.db file every this many milliseconds to detect that the
* database was changed. The process writing to the database must first
* notify a change in the .lock.db file, then wait twice this many
* milliseconds before updating the database.
*/
public final int reconnectCheckDelay = get("RECONNECT_CHECK_DELAY", 200);
/**
* Database setting <code>REUSE_SPACE</code> (default: true).<br />
* If disabled, all changes are appended to the database file, and existing
* content is never overwritten. This setting has no effect if the database
* is already open.
*/
public final boolean reuseSpace = get("REUSE_SPACE", true);
/**
* Database setting <code>ROWID</code> (default: true).<br />
* If set, each table has a pseudo-column _ROWID_.
*/
public final boolean rowId = get("ROWID", true);
/**
* Database setting <code>SELECT_FOR_UPDATE_MVCC</code>
* (default: true).<br />
* If set, SELECT .. FOR UPDATE queries lock only the selected rows when
* using MVCC.
*/
public final boolean selectForUpdateMvcc = get("SELECT_FOR_UPDATE_MVCC", true);
/**
* Database setting <code>SHARE_LINKED_CONNECTIONS</code>
* (default: true).<br />
* Linked connections should be shared, that means connections to the same
* database should be used for all linked tables that connect to the same
* database.
*/
public final boolean shareLinkedConnections = get(
"SHARE_LINKED_CONNECTIONS", true);
/**
* Database setting <code>DEFAULT_TABLE_ENGINE</code>
* (default: null).<br />
* The default table engine to use for new tables.
*/
public final String defaultTableEngine = get("DEFAULT_TABLE_ENGINE", null);
/**
* Database setting <code>MV_STORE</code>
* (default: false for version 1.3, true for version 1.4).<br />
* Use the MVStore storage engine.
*/
public boolean mvStore = get("MV_STORE", Constants.VERSION_MINOR >= 4);
/**
* Database setting <code>COMPRESS</code>
* (default: false).<br />
* Compress data when storing.
*/
public final boolean compressData = get("COMPRESS", false);
/**
* Database setting <code>MULTI_THREADED</code>
* (default: false).<br />
*/
public final boolean multiThreaded = get("MULTI_THREADED", false);
/**
* Database setting <code>STANDARD_DROP_TABLE_RESTRICT</code> (default:
* false).<br />
* <code>true</code> if DROP TABLE RESTRICT should fail if there's any
* foreign key referencing the table to be dropped. <code>false</code> if
* foreign keys referencing the table to be dropped should be silently
* dropped as well.
*/
public final boolean standardDropTableRestrict = get(
"STANDARD_DROP_TABLE_RESTRICT", false);
private DbSettings(HashMap<String, String> s) {
super(s);
if (s.get("NESTED_JOINS") != null || Utils.getProperty("h2.nestedJoins", null) != null) {
throw DbException.getUnsupportedException("NESTED_JOINS setting is not available since 1.4.197");
}
}
/**
* INTERNAL.
* Get the settings for the given properties (may not be null).
*
* @param s the settings
* @return the settings
*/
public static DbSettings getInstance(HashMap<String, String> s) {
return new DbSettings(s);
}
/**
* INTERNAL.
* Get the default settings. Those must not be modified.
*
* @return the settings
*/
public static DbSettings getDefaultSettings() {
if (defaultSettings == null) {
defaultSettings = new DbSettings(new HashMap<String, String>());
}
return defaultSettings;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Engine.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Parser;
import org.h2.command.dml.SetTypes;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.store.FileLock;
import org.h2.store.FileLockMethod;
import org.h2.util.MathUtils;
import org.h2.util.ThreadDeadlockDetector;
import org.h2.util.Utils;
/**
* The engine contains a map of all open databases.
* It is also responsible for opening and creating new databases.
* This is a singleton class.
*/
public class Engine implements SessionFactory {
private static final Engine INSTANCE = new Engine();
private static final Map<String, Database> DATABASES = new HashMap<>();
private volatile long wrongPasswordDelay =
SysProperties.DELAY_WRONG_PASSWORD_MIN;
private boolean jmx;
private Engine() {
// use getInstance()
if (SysProperties.THREAD_DEADLOCK_DETECTOR) {
ThreadDeadlockDetector.init();
}
}
public static Engine getInstance() {
return INSTANCE;
}
private Session openSession(ConnectionInfo ci, boolean ifExists,
String cipher) {
String name = ci.getName();
Database database;
ci.removeProperty("NO_UPGRADE", false);
boolean openNew = ci.getProperty("OPEN_NEW", false);
boolean opened = false;
User user = null;
synchronized (DATABASES) {
if (openNew || ci.isUnnamedInMemory()) {
database = null;
} else {
database = DATABASES.get(name);
}
if (database == null) {
if (ifExists && !Database.exists(name)) {
throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1, name);
}
database = new Database(ci, cipher);
opened = true;
if (database.getAllUsers().isEmpty()) {
// users is the last thing we add, so if no user is around,
// the database is new (or not initialized correctly)
user = new User(database, database.allocateObjectId(),
ci.getUserName(), false);
user.setAdmin(true);
user.setUserPasswordHash(ci.getUserPasswordHash());
database.setMasterUser(user);
}
if (!ci.isUnnamedInMemory()) {
DATABASES.put(name, database);
}
}
}
if (opened) {
// start the thread when already synchronizing on the database
// otherwise a deadlock can occur when the writer thread
// opens a new database (as in recovery testing)
database.opened();
}
if (database.isClosing()) {
return null;
}
if (user == null) {
if (database.validateFilePasswordHash(cipher, ci.getFilePasswordHash())) {
user = database.findUser(ci.getUserName());
if (user != null) {
if (!user.validateUserPasswordHash(ci.getUserPasswordHash())) {
user = null;
}
}
}
if (opened && (user == null || !user.isAdmin())) {
// reset - because the user is not an admin, and has no
// right to listen to exceptions
database.setEventListener(null);
}
}
if (user == null) {
DbException er = DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
database.getTrace(Trace.DATABASE).error(er, "wrong user or password; user: \"" +
ci.getUserName() + "\"");
database.removeSession(null);
throw er;
}
checkClustering(ci, database);
Session session = database.createSession(user);
if (session == null) {
// concurrently closing
return null;
}
if (ci.getProperty("JMX", false)) {
try {
Utils.callStaticMethod(
"org.h2.jmx.DatabaseInfo.registerMBean", ci, database);
} catch (Exception e) {
database.removeSession(session);
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, e, "JMX");
}
jmx = true;
}
return session;
}
/**
* Open a database connection with the given connection information.
*
* @param ci the connection information
* @return the session
*/
@Override
public Session createSession(ConnectionInfo ci) {
return INSTANCE.createSessionAndValidate(ci);
}
private Session createSessionAndValidate(ConnectionInfo ci) {
try {
ConnectionInfo backup = null;
String lockMethodName = ci.getProperty("FILE_LOCK", null);
FileLockMethod fileLockMethod = FileLock.getFileLockMethod(lockMethodName);
if (fileLockMethod == FileLockMethod.SERIALIZED) {
// In serialized mode, database instance sharing is not possible
ci.setProperty("OPEN_NEW", "TRUE");
try {
backup = ci.clone();
} catch (CloneNotSupportedException e) {
throw DbException.convert(e);
}
}
Session session = openSession(ci);
validateUserAndPassword(true);
if (backup != null) {
session.setConnectionInfo(backup);
}
return session;
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.WRONG_USER_OR_PASSWORD) {
validateUserAndPassword(false);
}
throw e;
}
}
private synchronized Session openSession(ConnectionInfo ci) {
boolean ifExists = ci.removeProperty("IFEXISTS", false);
boolean ignoreUnknownSetting = ci.removeProperty(
"IGNORE_UNKNOWN_SETTINGS", false);
String cipher = ci.removeProperty("CIPHER", null);
String init = ci.removeProperty("INIT", null);
Session session;
for (int i = 0;; i++) {
session = openSession(ci, ifExists, cipher);
if (session != null) {
break;
}
// we found a database that is currently closing
// wait a bit to avoid a busy loop (the method is synchronized)
if (i > 60 * 1000) {
// retry at most 1 minute
throw DbException.get(ErrorCode.DATABASE_ALREADY_OPEN_1,
"Waited for database closing longer than 1 minute");
}
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// ignore
}
}
synchronized (session) {
session.setAllowLiterals(true);
DbSettings defaultSettings = DbSettings.getDefaultSettings();
for (String setting : ci.getKeys()) {
if (defaultSettings.containsKey(setting)) {
// database setting are only used when opening the database
continue;
}
String value = ci.getProperty(setting);
try {
CommandInterface command = session.prepareCommand(
"SET " + Parser.quoteIdentifier(setting) + " " + value,
Integer.MAX_VALUE);
command.executeUpdate(false);
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.ADMIN_RIGHTS_REQUIRED) {
session.getTrace().error(e, "admin rights required; user: \"" +
ci.getUserName() + "\"");
} else {
session.getTrace().error(e, "");
}
if (!ignoreUnknownSetting) {
session.close();
throw e;
}
}
}
if (init != null) {
try {
CommandInterface command = session.prepareCommand(init,
Integer.MAX_VALUE);
command.executeUpdate(false);
} catch (DbException e) {
if (!ignoreUnknownSetting) {
session.close();
throw e;
}
}
}
session.setAllowLiterals(false);
session.commit(true);
}
return session;
}
private static void checkClustering(ConnectionInfo ci, Database database) {
String clusterSession = ci.getProperty(SetTypes.CLUSTER, null);
if (Constants.CLUSTERING_DISABLED.equals(clusterSession)) {
// in this case, no checking is made
// (so that a connection can be made to disable/change clustering)
return;
}
String clusterDb = database.getCluster();
if (!Constants.CLUSTERING_DISABLED.equals(clusterDb)) {
if (!Constants.CLUSTERING_ENABLED.equals(clusterSession)) {
if (!Objects.equals(clusterSession, clusterDb)) {
if (clusterDb.equals(Constants.CLUSTERING_DISABLED)) {
throw DbException.get(
ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_ALONE);
}
throw DbException.get(
ErrorCode.CLUSTER_ERROR_DATABASE_RUNS_CLUSTERED_1,
clusterDb);
}
}
}
}
/**
* Called after a database has been closed, to remove the object from the
* list of open databases.
*
* @param name the database name
*/
void close(String name) {
if (jmx) {
try {
Utils.callStaticMethod("org.h2.jmx.DatabaseInfo.unregisterMBean", name);
} catch (Exception e) {
throw DbException.get(ErrorCode.FEATURE_NOT_SUPPORTED_1, e, "JMX");
}
}
synchronized (DATABASES) {
DATABASES.remove(name);
}
}
/**
* This method is called after validating user name and password. If user
* name and password were correct, the sleep time is reset, otherwise this
* method waits some time (to make brute force / rainbow table attacks
* harder) and then throws a 'wrong user or password' exception. The delay
* is a bit randomized to protect against timing attacks. Also the delay
* doubles after each unsuccessful logins, to make brute force attacks
* harder.
*
* There is only one exception message both for wrong user and for
* wrong password, to make it harder to get the list of user names. This
* method must only be called from one place, so it is not possible from the
* stack trace to see if the user name was wrong or the password.
*
* @param correct if the user name or the password was correct
* @throws DbException the exception 'wrong user or password'
*/
private void validateUserAndPassword(boolean correct) {
int min = SysProperties.DELAY_WRONG_PASSWORD_MIN;
if (correct) {
long delay = wrongPasswordDelay;
if (delay > min && delay > 0) {
// the first correct password must be blocked,
// otherwise parallel attacks are possible
synchronized (INSTANCE) {
// delay up to the last delay
// an attacker can't know how long it will be
delay = MathUtils.secureRandomInt((int) delay);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// ignore
}
wrongPasswordDelay = min;
}
}
} else {
// this method is not synchronized on the Engine, so that
// regular successful attempts are not blocked
synchronized (INSTANCE) {
long delay = wrongPasswordDelay;
int max = SysProperties.DELAY_WRONG_PASSWORD_MAX;
if (max <= 0) {
max = Integer.MAX_VALUE;
}
wrongPasswordDelay += wrongPasswordDelay;
if (wrongPasswordDelay > max || wrongPasswordDelay < 0) {
wrongPasswordDelay = max;
}
if (min > 0) {
// a bit more to protect against timing attacks
delay += Math.abs(MathUtils.secureRandomLong() % 100);
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
// ignore
}
}
throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD);
}
}
}
@Override
public void closeSession(int sessionId) throws SQLException {
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/FunctionAlias.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import org.h2.Driver;
import org.h2.api.ErrorCode;
import org.h2.command.Parser;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObjectBase;
import org.h2.table.Table;
import org.h2.util.JdbcUtils;
import org.h2.util.New;
import org.h2.util.SourceCompiler;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueNull;
/**
* Represents a user-defined function, or alias.
*
* @author Thomas Mueller
* @author Gary Tong
*/
public class FunctionAlias extends SchemaObjectBase {
private String className;
private String methodName;
private String source;
private JavaMethod[] javaMethods;
private boolean deterministic;
private boolean bufferResultSetToLocalTemp = true;
private FunctionAlias(Schema schema, int id, String name) {
initSchemaObjectBase(schema, id, name, Trace.FUNCTION);
}
/**
* Create a new alias based on a method name.
*
* @param schema the schema
* @param id the id
* @param name the name
* @param javaClassMethod the class and method name
* @param force create the object even if the class or method does not exist
* @param bufferResultSetToLocalTemp whether the result should be buffered
* @return the database object
*/
public static FunctionAlias newInstance(
Schema schema, int id, String name, String javaClassMethod,
boolean force, boolean bufferResultSetToLocalTemp) {
FunctionAlias alias = new FunctionAlias(schema, id, name);
int paren = javaClassMethod.indexOf('(');
int lastDot = javaClassMethod.lastIndexOf('.', paren < 0 ?
javaClassMethod.length() : paren);
if (lastDot < 0) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, javaClassMethod);
}
alias.className = javaClassMethod.substring(0, lastDot);
alias.methodName = javaClassMethod.substring(lastDot + 1);
alias.bufferResultSetToLocalTemp = bufferResultSetToLocalTemp;
alias.init(force);
return alias;
}
/**
* Create a new alias based on source code.
*
* @param schema the schema
* @param id the id
* @param name the name
* @param source the source code
* @param force create the object even if the class or method does not exist
* @param bufferResultSetToLocalTemp whether the result should be buffered
* @return the database object
*/
public static FunctionAlias newInstanceFromSource(
Schema schema, int id, String name, String source, boolean force,
boolean bufferResultSetToLocalTemp) {
FunctionAlias alias = new FunctionAlias(schema, id, name);
alias.source = source;
alias.bufferResultSetToLocalTemp = bufferResultSetToLocalTemp;
alias.init(force);
return alias;
}
private void init(boolean force) {
try {
// at least try to compile the class, otherwise the data type is not
// initialized if it could be
load();
} catch (DbException e) {
if (!force) {
throw e;
}
}
}
private synchronized void load() {
if (javaMethods != null) {
return;
}
if (source != null) {
loadFromSource();
} else {
loadClass();
}
}
private void loadFromSource() {
SourceCompiler compiler = database.getCompiler();
synchronized (compiler) {
String fullClassName = Constants.USER_PACKAGE + "." + getName();
compiler.setSource(fullClassName, source);
try {
Method m = compiler.getMethod(fullClassName);
JavaMethod method = new JavaMethod(m, 0);
javaMethods = new JavaMethod[] {
method
};
} catch (DbException e) {
throw e;
} catch (Exception e) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, e, source);
}
}
}
private void loadClass() {
Class<?> javaClass = JdbcUtils.loadUserClass(className);
Method[] methods = javaClass.getMethods();
ArrayList<JavaMethod> list = New.arrayList();
for (int i = 0, len = methods.length; i < len; i++) {
Method m = methods[i];
if (!Modifier.isStatic(m.getModifiers())) {
continue;
}
if (m.getName().equals(methodName) ||
getMethodSignature(m).equals(methodName)) {
JavaMethod javaMethod = new JavaMethod(m, i);
for (JavaMethod old : list) {
if (old.getParameterCount() == javaMethod.getParameterCount()) {
throw DbException.get(ErrorCode.
METHODS_MUST_HAVE_DIFFERENT_PARAMETER_COUNTS_2,
old.toString(), javaMethod.toString());
}
}
list.add(javaMethod);
}
}
if (list.isEmpty()) {
throw DbException.get(
ErrorCode.PUBLIC_STATIC_JAVA_METHOD_NOT_FOUND_1,
methodName + " (" + className + ")");
}
javaMethods = list.toArray(new JavaMethod[0]);
// Sort elements. Methods with a variable number of arguments must be at
// the end. Reason: there could be one method without parameters and one
// with a variable number. The one without parameters needs to be used
// if no parameters are given.
Arrays.sort(javaMethods);
}
private static String getMethodSignature(Method m) {
StatementBuilder buff = new StatementBuilder(m.getName());
buff.append('(');
for (Class<?> p : m.getParameterTypes()) {
// do not use a space here, because spaces are removed
// in CreateFunctionAlias.setJavaClassMethod()
buff.appendExceptFirst(",");
if (p.isArray()) {
buff.append(p.getComponentType().getName()).append("[]");
} else {
buff.append(p.getName());
}
}
return buff.append(')').toString();
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getDropSQL() {
return "DROP ALIAS IF EXISTS " + getSQL();
}
@Override
public String getSQL() {
// TODO can remove this method once FUNCTIONS_IN_SCHEMA is enabled
if (database.getSettings().functionsInSchema ||
!getSchema().getName().equals(Constants.SCHEMA_MAIN)) {
return super.getSQL();
}
return Parser.quoteIdentifier(getName());
}
@Override
public String getCreateSQL() {
StringBuilder buff = new StringBuilder("CREATE FORCE ALIAS ");
buff.append(getSQL());
if (deterministic) {
buff.append(" DETERMINISTIC");
}
if (!bufferResultSetToLocalTemp) {
buff.append(" NOBUFFER");
}
if (source != null) {
buff.append(" AS ").append(StringUtils.quoteStringSQL(source));
} else {
buff.append(" FOR ").append(Parser.quoteIdentifier(
className + "." + methodName));
}
return buff.toString();
}
@Override
public int getType() {
return DbObject.FUNCTION_ALIAS;
}
@Override
public synchronized void removeChildrenAndResources(Session session) {
database.removeMeta(session, getId());
className = null;
methodName = null;
javaMethods = null;
invalidate();
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("RENAME");
}
/**
* Find the Java method that matches the arguments.
*
* @param args the argument list
* @return the Java method
* @throws DbException if no matching method could be found
*/
public JavaMethod findJavaMethod(Expression[] args) {
load();
int parameterCount = args.length;
for (JavaMethod m : javaMethods) {
int count = m.getParameterCount();
if (count == parameterCount || (m.isVarArgs() &&
count <= parameterCount + 1)) {
return m;
}
}
throw DbException.get(ErrorCode.METHOD_NOT_FOUND_1, getName() + " (" +
className + ", parameter count: " + parameterCount + ")");
}
public String getJavaClassName() {
return this.className;
}
public String getJavaMethodName() {
return this.methodName;
}
/**
* Get the Java methods mapped by this function.
*
* @return the Java methods.
*/
public JavaMethod[] getJavaMethods() {
load();
return javaMethods;
}
public void setDeterministic(boolean deterministic) {
this.deterministic = deterministic;
}
public boolean isDeterministic() {
return deterministic;
}
public String getSource() {
return source;
}
/**
* Should the return value ResultSet be buffered in a local temporary file?
*
* @return true if yes
*/
public boolean isBufferResultSetToLocalTemp() {
return bufferResultSetToLocalTemp;
}
/**
* There may be multiple Java methods that match a function name.
* Each method must have a different number of parameters however.
* This helper class represents one such method.
*/
public static class JavaMethod implements Comparable<JavaMethod> {
private final int id;
private final Method method;
private final int dataType;
private boolean hasConnectionParam;
private boolean varArgs;
private Class<?> varArgClass;
private int paramCount;
JavaMethod(Method method, int id) {
this.method = method;
this.id = id;
Class<?>[] paramClasses = method.getParameterTypes();
paramCount = paramClasses.length;
if (paramCount > 0) {
Class<?> paramClass = paramClasses[0];
if (Connection.class.isAssignableFrom(paramClass)) {
hasConnectionParam = true;
paramCount--;
}
}
if (paramCount > 0) {
Class<?> lastArg = paramClasses[paramClasses.length - 1];
if (lastArg.isArray() && method.isVarArgs()) {
varArgs = true;
varArgClass = lastArg.getComponentType();
}
}
Class<?> returnClass = method.getReturnType();
dataType = DataType.getTypeFromClass(returnClass);
}
@Override
public String toString() {
return method.toString();
}
/**
* Check if this function requires a database connection.
*
* @return if the function requires a connection
*/
public boolean hasConnectionParam() {
return this.hasConnectionParam;
}
/**
* Call the user-defined function and return the value.
*
* @param session the session
* @param args the argument list
* @param columnList true if the function should only return the column
* list
* @return the value
*/
public Value getValue(Session session, Expression[] args,
boolean columnList) {
Class<?>[] paramClasses = method.getParameterTypes();
Object[] params = new Object[paramClasses.length];
int p = 0;
if (hasConnectionParam && params.length > 0) {
params[p++] = session.createConnection(columnList);
}
// allocate array for varArgs parameters
Object varArg = null;
if (varArgs) {
int len = args.length - params.length + 1 +
(hasConnectionParam ? 1 : 0);
varArg = Array.newInstance(varArgClass, len);
params[params.length - 1] = varArg;
}
for (int a = 0, len = args.length; a < len; a++, p++) {
boolean currentIsVarArg = varArgs &&
p >= paramClasses.length - 1;
Class<?> paramClass;
if (currentIsVarArg) {
paramClass = varArgClass;
} else {
paramClass = paramClasses[p];
}
int type = DataType.getTypeFromClass(paramClass);
Value v = args[a].getValue(session);
Object o;
if (Value.class.isAssignableFrom(paramClass)) {
o = v;
} else if (v.getType() == Value.ARRAY &&
paramClass.isArray() &&
paramClass.getComponentType() != Object.class) {
Value[] array = ((ValueArray) v).getList();
Object[] objArray = (Object[]) Array.newInstance(
paramClass.getComponentType(), array.length);
int componentType = DataType.getTypeFromClass(
paramClass.getComponentType());
for (int i = 0; i < objArray.length; i++) {
objArray[i] = array[i].convertTo(componentType).getObject();
}
o = objArray;
} else {
v = v.convertTo(type, -1, session.getDatabase().getMode());
o = v.getObject();
}
if (o == null) {
if (paramClass.isPrimitive()) {
if (columnList) {
// If the column list is requested, the parameters
// may be null. Need to set to default value,
// otherwise the function can't be called at all.
o = DataType.getDefaultForPrimitiveType(paramClass);
} else {
// NULL for a java primitive: return NULL
return ValueNull.INSTANCE;
}
}
} else {
if (!paramClass.isAssignableFrom(o.getClass()) && !paramClass.isPrimitive()) {
o = DataType.convertTo(session.createConnection(false), v, paramClass);
}
}
if (currentIsVarArg) {
Array.set(varArg, p - params.length + 1, o);
} else {
params[p] = o;
}
}
boolean old = session.getAutoCommit();
Value identity = session.getLastScopeIdentity();
boolean defaultConnection = session.getDatabase().
getSettings().defaultConnection;
try {
session.setAutoCommit(false);
Object returnValue;
try {
if (defaultConnection) {
Driver.setDefaultConnection(
session.createConnection(columnList));
}
returnValue = method.invoke(null, params);
if (returnValue == null) {
return ValueNull.INSTANCE;
}
} catch (InvocationTargetException e) {
StatementBuilder buff = new StatementBuilder(method.getName());
buff.append('(');
for (Object o : params) {
buff.appendExceptFirst(", ");
buff.append(o == null ? "null" : o.toString());
}
buff.append(')');
throw DbException.convertInvocation(e, buff.toString());
} catch (Exception e) {
throw DbException.convert(e);
}
if (Value.class.isAssignableFrom(method.getReturnType())) {
return (Value) returnValue;
}
Value ret = DataType.convertToValue(session, returnValue, dataType);
return ret.convertTo(dataType);
} finally {
session.setLastScopeIdentity(identity);
session.setAutoCommit(old);
if (defaultConnection) {
Driver.setDefaultConnection(null);
}
}
}
public Class<?>[] getColumnClasses() {
return method.getParameterTypes();
}
public int getDataType() {
return dataType;
}
public int getParameterCount() {
return paramCount;
}
public boolean isVarArgs() {
return varArgs;
}
@Override
public int compareTo(JavaMethod m) {
if (varArgs != m.varArgs) {
return varArgs ? 1 : -1;
}
if (paramCount != m.paramCount) {
return paramCount - m.paramCount;
}
if (hasConnectionParam != m.hasConnectionParam) {
return hasConnectionParam ? 1 : -1;
}
return id - m.id;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/GeneratedKeys.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.result.LocalResult;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.util.New;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* Class for gathering and processing of generated keys.
*/
public final class GeneratedKeys {
/**
* Data for result set with generated keys.
*/
private final ArrayList<Map<Column, Value>> data = New.arrayList();
/**
* Columns with generated keys in the current row.
*/
private final ArrayList<Column> row = New.arrayList();
/**
* All columns with generated keys.
*/
private final ArrayList<Column> allColumns = New.arrayList();
/**
* Request for keys gathering. {@code false} if generated keys are not needed,
* {@code true} if generated keys should be configured automatically,
* {@code int[]} to specify column indices to return generated keys from, or
* {@code String[]} to specify column names to return generated keys from.
*/
private Object generatedKeysRequest;
/**
* Processed table.
*/
private Table table;
/**
* Remembers columns with generated keys.
*
* @param column
* table column
*/
public void add(Column column) {
if (Boolean.FALSE.equals(generatedKeysRequest)) {
return;
}
row.add(column);
}
/**
* Clears all information from previous runs and sets a new request for
* gathering of generated keys.
*
* @param generatedKeysRequest
* {@code false} if generated keys are not needed, {@code true} if
* generated keys should be configured automatically, {@code int[]}
* to specify column indices to return generated keys from, or
* {@code String[]} to specify column names to return generated keys
* from
*/
public void clear(Object generatedKeysRequest) {
this.generatedKeysRequest = generatedKeysRequest;
data.clear();
row.clear();
allColumns.clear();
table = null;
}
/**
* Saves row with generated keys if any.
*
* @param tableRow
* table row that was inserted
*/
public void confirmRow(Row tableRow) {
if (Boolean.FALSE.equals(generatedKeysRequest)) {
return;
}
int size = row.size();
if (size > 0) {
if (size == 1) {
Column column = row.get(0);
data.add(Collections.singletonMap(column, tableRow.getValue(column.getColumnId())));
if (!allColumns.contains(column)) {
allColumns.add(column);
}
} else {
HashMap<Column, Value> map = new HashMap<>();
for (Column column : row) {
map.put(column, tableRow.getValue(column.getColumnId()));
if (!allColumns.contains(column)) {
allColumns.add(column);
}
}
data.add(map);
}
row.clear();
}
}
/**
* Returns generated keys.
*
* @param session
* session
* @return local result with generated keys
*/
public LocalResult getKeys(Session session) {
Database db = session == null ? null : session.getDatabase();
if (Boolean.FALSE.equals(generatedKeysRequest)) {
clear(null);
return new LocalResult();
}
ArrayList<ExpressionColumn> expressionColumns;
if (Boolean.TRUE.equals(generatedKeysRequest)) {
expressionColumns = new ArrayList<>(allColumns.size());
for (Column column : allColumns) {
expressionColumns.add(new ExpressionColumn(db, column));
}
} else if (generatedKeysRequest instanceof int[]) {
if (table != null) {
int[] indices = (int[]) generatedKeysRequest;
Column[] columns = table.getColumns();
int cnt = columns.length;
allColumns.clear();
expressionColumns = new ArrayList<>(indices.length);
for (int idx : indices) {
if (idx >= 1 && idx <= cnt) {
Column column = columns[idx - 1];
expressionColumns.add(new ExpressionColumn(db, column));
allColumns.add(column);
}
}
} else {
clear(null);
return new LocalResult();
}
} else if (generatedKeysRequest instanceof String[]) {
if (table != null) {
String[] names = (String[]) generatedKeysRequest;
allColumns.clear();
expressionColumns = new ArrayList<>(names.length);
for (String name : names) {
Column column;
search: if (table.doesColumnExist(name)) {
column = table.getColumn(name);
} else {
name = StringUtils.toUpperEnglish(name);
if (table.doesColumnExist(name)) {
column = table.getColumn(name);
} else {
for (Column c : table.getColumns()) {
if (c.getName().equalsIgnoreCase(name)) {
column = c;
break search;
}
}
continue;
}
}
expressionColumns.add(new ExpressionColumn(db, column));
allColumns.add(column);
}
} else {
clear(null);
return new LocalResult();
}
} else {
clear(null);
return new LocalResult();
}
int columnCount = expressionColumns.size();
if (columnCount == 0) {
clear(null);
return new LocalResult();
}
LocalResult result = new LocalResult(session, expressionColumns.toArray(new Expression[0]), columnCount);
for (Map<Column, Value> map : data) {
Value[] row = new Value[columnCount];
for (Map.Entry<Column, Value> entry : map.entrySet()) {
int idx = allColumns.indexOf(entry.getKey());
if (idx >= 0) {
row[idx] = entry.getValue();
}
}
for (int i = 0; i < columnCount; i++) {
if (row[i] == null) {
row[i] = ValueNull.INSTANCE;
}
}
result.addRow(row);
}
clear(null);
return result;
}
/**
* Initializes processing of the specified table. Should be called after
* {@code clear()}, but before other methods.
*
* @param table
* table
*/
public void initialize(Table table) {
this.table = table;
}
/**
* Clears unsaved information about previous row, if any. Should be called
* before processing of a new row if previous row was not confirmed or simply
* always before each row.
*/
public void nextRow() {
row.clear();
}
@Override
public String toString() {
return allColumns + ": " + data.size();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/GeneratedKeysMode.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* Modes of generated keys' gathering.
*/
public final class GeneratedKeysMode {
/**
* Generated keys are not needed.
*/
public static final int NONE = 0;
/**
* Generated keys should be configured automatically.
*/
public static final int AUTO = 1;
/**
* Use specified column indices to return generated keys from.
*/
public static final int COLUMN_NUMBERS = 2;
/**
* Use specified column names to return generated keys from.
*/
public static final int COLUMN_NAMES = 3;
/**
* Determines mode of generated keys' gathering.
*
* @param generatedKeysRequest
* {@code false} if generated keys are not needed, {@code true} if
* generated keys should be configured automatically, {@code int[]}
* to specify column indices to return generated keys from, or
* {@code String[]} to specify column names to return generated keys
* from
* @return mode for the specified generated keys request
*/
public static int valueOf(Object generatedKeysRequest) {
if (Boolean.FALSE.equals(generatedKeysRequest)) {
return NONE;
}
if (Boolean.TRUE.equals(generatedKeysRequest)) {
return AUTO;
}
if (generatedKeysRequest instanceof int[]) {
return COLUMN_NUMBERS;
}
if (generatedKeysRequest instanceof String[]) {
return COLUMN_NAMES;
}
throw DbException.get(ErrorCode.INVALID_VALUE_2,
generatedKeysRequest == null ? "null" : generatedKeysRequest.toString());
}
private GeneratedKeysMode() {
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/MetaRecord.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.sql.SQLException;
import org.h2.api.DatabaseEventListener;
import org.h2.command.Prepared;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.SearchRow;
import org.h2.value.ValueInt;
import org.h2.value.ValueString;
/**
* A record in the system table of the database.
* It contains the SQL statement to create the database object.
*/
public class MetaRecord implements Comparable<MetaRecord> {
private final int id;
private final int objectType;
private final String sql;
public MetaRecord(SearchRow r) {
id = r.getValue(0).getInt();
objectType = r.getValue(2).getInt();
sql = r.getValue(3).getString();
}
MetaRecord(DbObject obj) {
id = obj.getId();
objectType = obj.getType();
sql = obj.getCreateSQL();
}
void setRecord(SearchRow r) {
r.setValue(0, ValueInt.get(id));
r.setValue(1, ValueInt.get(0));
r.setValue(2, ValueInt.get(objectType));
r.setValue(3, ValueString.get(sql));
}
/**
* Execute the meta data statement.
*
* @param db the database
* @param systemSession the system session
* @param listener the database event listener
*/
void execute(Database db, Session systemSession,
DatabaseEventListener listener) {
try {
Prepared command = systemSession.prepare(sql);
command.setObjectId(id);
command.update();
} catch (DbException e) {
e = e.addSQL(sql);
SQLException s = e.getSQLException();
db.getTrace(Trace.DATABASE).error(s, sql);
if (listener != null) {
listener.exceptionThrown(s, sql);
// continue startup in this case
} else {
throw e;
}
}
}
public int getId() {
return id;
}
public int getObjectType() {
return objectType;
}
public String getSQL() {
return sql;
}
/**
* Sort the list of meta records by 'create order'.
*
* @param other the other record
* @return -1, 0, or 1
*/
@Override
public int compareTo(MetaRecord other) {
int c1 = getCreateOrder();
int c2 = other.getCreateOrder();
if (c1 != c2) {
return c1 - c2;
}
return getId() - other.getId();
}
/**
* Get the sort order id for this object type. Objects are created in this
* order when opening a database.
*
* @return the sort index
*/
private int getCreateOrder() {
switch (objectType) {
case DbObject.SETTING:
return 0;
case DbObject.USER:
return 1;
case DbObject.SCHEMA:
return 2;
case DbObject.FUNCTION_ALIAS:
return 3;
case DbObject.USER_DATATYPE:
return 4;
case DbObject.SEQUENCE:
return 5;
case DbObject.CONSTANT:
return 6;
case DbObject.TABLE_OR_VIEW:
return 7;
case DbObject.INDEX:
return 8;
case DbObject.CONSTRAINT:
return 9;
case DbObject.TRIGGER:
return 10;
case DbObject.SYNONYM:
return 11;
case DbObject.ROLE:
return 12;
case DbObject.RIGHT:
return 13;
case DbObject.AGGREGATE:
return 14;
case DbObject.COMMENT:
return 15;
default:
throw DbException.throwInternalError("type="+objectType);
}
}
@Override
public String toString() {
return "MetaRecord [id=" + id + ", objectType=" + objectType +
", sql=" + sql + "]";
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Mode.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Pattern;
import org.h2.util.StringUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* The compatibility modes. There is a fixed set of modes (for example
* PostgreSQL, MySQL). Each mode has different settings.
*/
public class Mode {
public enum ModeEnum {
REGULAR, DB2, Derby, MSSQLServer, HSQLDB, MySQL, Oracle, PostgreSQL, Ignite,
}
/**
* Determines how rows with {@code NULL} values in indexed columns are handled
* in unique indexes.
*/
public enum UniqueIndexNullsHandling {
/**
* Multiple rows with identical values in indexed columns with at least one
* indexed {@code NULL} value are allowed in unique index.
*/
ALLOW_DUPLICATES_WITH_ANY_NULL,
/**
* Multiple rows with identical values in indexed columns with all indexed
* {@code NULL} values are allowed in unique index.
*/
ALLOW_DUPLICATES_WITH_ALL_NULLS,
/**
* Multiple rows with identical values in indexed columns are not allowed in
* unique index.
*/
FORBID_ANY_DUPLICATES
}
private static final HashMap<String, Mode> MODES = new HashMap<>();
// Modes are also documented in the features section
/**
* When enabled, aliased columns (as in SELECT ID AS I FROM TEST) return the
* alias (I in this case) in ResultSetMetaData.getColumnName() and 'null' in
* getTableName(). If disabled, the real column name (ID in this case) and
* table name is returned.
*/
public boolean aliasColumnName;
/**
* When inserting data, if a column is defined to be NOT NULL and NULL is
* inserted, then a 0 (or empty string, or the current timestamp for
* timestamp columns) value is used. Usually, this operation is not allowed
* and an exception is thrown.
*/
public boolean convertInsertNullToZero;
/**
* When converting the scale of decimal data, the number is only converted
* if the new scale is smaller than the current scale. Usually, the scale is
* converted and 0s are added if required.
*/
public boolean convertOnlyToSmallerScale;
/**
* Creating indexes in the CREATE TABLE statement is allowed using
* <code>INDEX(..)</code> or <code>KEY(..)</code>.
* Example: <code>create table test(id int primary key, name varchar(255),
* key idx_name(name));</code>
*/
public boolean indexDefinitionInCreateTable;
/**
* Meta data calls return identifiers in lower case.
*/
public boolean lowerCaseIdentifiers;
/**
* Concatenation with NULL results in NULL. Usually, NULL is treated as an
* empty string if only one of the operands is NULL, and NULL is only
* returned if both operands are NULL.
*/
public boolean nullConcatIsNull;
/**
* Identifiers may be quoted using square brackets as in [Test].
*/
public boolean squareBracketQuotedNames;
/**
* The system columns 'CTID' and 'OID' are supported.
*/
public boolean systemColumns;
/**
* Determines how rows with {@code NULL} values in indexed columns are handled
* in unique indexes.
*/
public UniqueIndexNullsHandling uniqueIndexNullsHandling = UniqueIndexNullsHandling.ALLOW_DUPLICATES_WITH_ANY_NULL;
/**
* Empty strings are treated like NULL values. Useful for Oracle emulation.
*/
public boolean treatEmptyStringsAsNull;
/**
* Support the pseudo-table SYSIBM.SYSDUMMY1.
*/
public boolean sysDummy1;
/**
* Text can be concatenated using '+'.
*/
public boolean allowPlusForStringConcat;
/**
* The function LOG() uses base 10 instead of E.
*/
public boolean logIsLogBase10;
/**
* The function REGEXP_REPLACE() uses \ for back-references.
*/
public boolean regexpReplaceBackslashReferences;
/**
* SERIAL and BIGSERIAL columns are not automatically primary keys.
*/
public boolean serialColumnIsNotPK;
/**
* Swap the parameters of the CONVERT function.
*/
public boolean swapConvertFunctionParameters;
/**
* can set the isolation level using WITH {RR|RS|CS|UR}
*/
public boolean isolationLevelInSelectOrInsertStatement;
/**
* MySQL style INSERT ... ON DUPLICATE KEY UPDATE ... and INSERT IGNORE
*/
public boolean onDuplicateKeyUpdate;
/**
* Pattern describing the keys the java.sql.Connection.setClientInfo()
* method accepts.
*/
public Pattern supportedClientInfoPropertiesRegEx;
/**
* Support the # for column names
*/
public boolean supportPoundSymbolForColumnNames;
/**
* Whether an empty list as in "NAME IN()" results in a syntax error.
*/
public boolean prohibitEmptyInPredicate;
/**
* Whether AFFINITY KEY keywords are supported.
*/
public boolean allowAffinityKey;
/**
* Whether to right-pad fixed strings with spaces.
*/
public boolean padFixedLengthStrings;
/**
* Whether DB2 TIMESTAMP formats are allowed.
*/
public boolean allowDB2TimestampFormat;
/**
* An optional Set of hidden/disallowed column types.
* Certain DBMSs don't support all column types provided by H2, such as
* "NUMBER" when using PostgreSQL mode.
*/
public Set<String> disallowedTypes = Collections.emptySet();
/**
* Custom mappings from type names to data types.
*/
public HashMap<String, DataType> typeByNameMap = new HashMap<>();
private final String name;
private ModeEnum modeEnum;
static {
Mode mode = new Mode(ModeEnum.REGULAR.name());
mode.nullConcatIsNull = true;
add(mode);
mode = new Mode(ModeEnum.DB2.name());
mode.aliasColumnName = true;
mode.sysDummy1 = true;
mode.isolationLevelInSelectOrInsertStatement = true;
// See
// https://www.ibm.com/support/knowledgecenter/SSEPEK_11.0.0/
// com.ibm.db2z11.doc.java/src/tpc/imjcc_r0052001.dita
mode.supportedClientInfoPropertiesRegEx =
Pattern.compile("ApplicationName|ClientAccountingInformation|" +
"ClientUser|ClientCorrelationToken");
mode.prohibitEmptyInPredicate = true;
mode.allowDB2TimestampFormat = true;
add(mode);
mode = new Mode(ModeEnum.Derby.name());
mode.aliasColumnName = true;
mode.uniqueIndexNullsHandling = UniqueIndexNullsHandling.FORBID_ANY_DUPLICATES;
mode.sysDummy1 = true;
mode.isolationLevelInSelectOrInsertStatement = true;
// Derby does not support client info properties as of version 10.12.1.1
mode.supportedClientInfoPropertiesRegEx = null;
add(mode);
mode = new Mode(ModeEnum.HSQLDB.name());
mode.aliasColumnName = true;
mode.convertOnlyToSmallerScale = true;
mode.nullConcatIsNull = true;
mode.uniqueIndexNullsHandling = UniqueIndexNullsHandling.FORBID_ANY_DUPLICATES;
mode.allowPlusForStringConcat = true;
// HSQLDB does not support client info properties. See
// http://hsqldb.org/doc/apidocs/
// org/hsqldb/jdbc/JDBCConnection.html#
// setClientInfo%28java.lang.String,%20java.lang.String%29
mode.supportedClientInfoPropertiesRegEx = null;
add(mode);
mode = new Mode(ModeEnum.MSSQLServer.name());
mode.aliasColumnName = true;
mode.squareBracketQuotedNames = true;
mode.uniqueIndexNullsHandling = UniqueIndexNullsHandling.FORBID_ANY_DUPLICATES;
mode.allowPlusForStringConcat = true;
mode.swapConvertFunctionParameters = true;
mode.supportPoundSymbolForColumnNames = true;
// MS SQL Server does not support client info properties. See
// https://msdn.microsoft.com/en-Us/library/dd571296%28v=sql.110%29.aspx
mode.supportedClientInfoPropertiesRegEx = null;
add(mode);
mode = new Mode(ModeEnum.MySQL.name());
mode.convertInsertNullToZero = true;
mode.indexDefinitionInCreateTable = true;
mode.lowerCaseIdentifiers = true;
// Next one is for MariaDB
mode.regexpReplaceBackslashReferences = true;
mode.onDuplicateKeyUpdate = true;
// MySQL allows to use any key for client info entries. See
// http://grepcode.com/file/repo1.maven.org/maven2/mysql/
// mysql-connector-java/5.1.24/com/mysql/jdbc/
// JDBC4CommentClientInfoProvider.java
mode.supportedClientInfoPropertiesRegEx =
Pattern.compile(".*");
mode.prohibitEmptyInPredicate = true;
add(mode);
mode = new Mode(ModeEnum.Oracle.name());
mode.aliasColumnName = true;
mode.convertOnlyToSmallerScale = true;
mode.uniqueIndexNullsHandling = UniqueIndexNullsHandling.ALLOW_DUPLICATES_WITH_ALL_NULLS;
mode.treatEmptyStringsAsNull = true;
mode.regexpReplaceBackslashReferences = true;
mode.supportPoundSymbolForColumnNames = true;
// Oracle accepts keys of the form <namespace>.*. See
// https://docs.oracle.com/database/121/JJDBC/jdbcvers.htm#JJDBC29006
mode.supportedClientInfoPropertiesRegEx =
Pattern.compile(".*\\..*");
mode.prohibitEmptyInPredicate = true;
mode.typeByNameMap.put("DATE", DataType.getDataType(Value.TIMESTAMP));
add(mode);
mode = new Mode(ModeEnum.PostgreSQL.name());
mode.aliasColumnName = true;
mode.nullConcatIsNull = true;
mode.systemColumns = true;
mode.logIsLogBase10 = true;
mode.regexpReplaceBackslashReferences = true;
mode.serialColumnIsNotPK = true;
// PostgreSQL only supports the ApplicationName property. See
// https://github.com/hhru/postgres-jdbc/blob/master/postgresql-jdbc-9.2-1002.src/
// org/postgresql/jdbc4/AbstractJdbc4Connection.java
mode.supportedClientInfoPropertiesRegEx =
Pattern.compile("ApplicationName");
mode.prohibitEmptyInPredicate = true;
mode.padFixedLengthStrings = true;
// Enumerate all H2 types NOT supported by PostgreSQL:
Set<String> disallowedTypes = new java.util.HashSet<>();
disallowedTypes.add("NUMBER");
disallowedTypes.add("IDENTITY");
disallowedTypes.add("TINYINT");
disallowedTypes.add("BLOB");
mode.disallowedTypes = disallowedTypes;
add(mode);
mode = new Mode(ModeEnum.Ignite.name());
mode.nullConcatIsNull = true;
mode.allowAffinityKey = true;
mode.indexDefinitionInCreateTable = true;
add(mode);
}
private Mode(String name) {
this.name = name;
this.modeEnum = ModeEnum.valueOf(name);
}
private static void add(Mode mode) {
MODES.put(StringUtils.toUpperEnglish(mode.name), mode);
}
/**
* Get the mode with the given name.
*
* @param name the name of the mode
* @return the mode object
*/
public static Mode getInstance(String name) {
return MODES.get(StringUtils.toUpperEnglish(name));
}
public static Mode getRegular() {
return getInstance(ModeEnum.REGULAR.name());
}
public String getName() {
return name;
}
public ModeEnum getEnum() {
return this.modeEnum;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Procedure.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.command.Prepared;
/**
* Represents a procedure. Procedures are implemented for PostgreSQL
* compatibility.
*/
public class Procedure {
private final String name;
private final Prepared prepared;
public Procedure(String name, Prepared prepared) {
this.name = name;
this.prepared = prepared;
}
public String getName() {
return name;
}
public Prepared getPrepared() {
return prepared;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/QueryStatisticsData.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
/**
* Maintains query statistics.
*/
public class QueryStatisticsData {
private static final Comparator<QueryEntry> QUERY_ENTRY_COMPARATOR =
new Comparator<QueryEntry>() {
@Override
public int compare(QueryEntry o1, QueryEntry o2) {
return (int) Math.signum(o1.lastUpdateTime - o2.lastUpdateTime);
}
};
private final HashMap<String, QueryEntry> map =
new HashMap<>();
private int maxQueryEntries;
public QueryStatisticsData(int maxQueryEntries) {
this.maxQueryEntries = maxQueryEntries;
}
public synchronized void setMaxQueryEntries(int maxQueryEntries) {
this.maxQueryEntries = maxQueryEntries;
}
public synchronized List<QueryEntry> getQueries() {
// return a copy of the map so we don't have to
// worry about external synchronization
ArrayList<QueryEntry> list = new ArrayList<>(map.values());
// only return the newest 100 entries
Collections.sort(list, QUERY_ENTRY_COMPARATOR);
return list.subList(0, Math.min(list.size(), maxQueryEntries));
}
/**
* Update query statistics.
*
* @param sqlStatement the statement being executed
* @param executionTimeNanos the time in nanoseconds the query/update took
* to execute
* @param rowCount the query or update row count
*/
public synchronized void update(String sqlStatement, long executionTimeNanos,
int rowCount) {
QueryEntry entry = map.get(sqlStatement);
if (entry == null) {
entry = new QueryEntry(sqlStatement);
map.put(sqlStatement, entry);
}
entry.update(executionTimeNanos, rowCount);
// Age-out the oldest entries if the map gets too big.
// Test against 1.5 x max-size so we don't do this too often
if (map.size() > maxQueryEntries * 1.5f) {
// Sort the entries by age
ArrayList<QueryEntry> list = new ArrayList<>(map.values());
Collections.sort(list, QUERY_ENTRY_COMPARATOR);
// Create a set of the oldest 1/3 of the entries
HashSet<QueryEntry> oldestSet =
new HashSet<>(list.subList(0, list.size() / 3));
// Loop over the map using the set and remove
// the oldest 1/3 of the entries.
for (Iterator<Entry<String, QueryEntry>> it =
map.entrySet().iterator(); it.hasNext();) {
Entry<String, QueryEntry> mapEntry = it.next();
if (oldestSet.contains(mapEntry.getValue())) {
it.remove();
}
}
}
}
/**
* The collected statistics for one query.
*/
public static final class QueryEntry {
/**
* The SQL statement.
*/
public final String sqlStatement;
/**
* The number of times the statement was executed.
*/
public int count;
/**
* The last time the statistics for this entry were updated,
* in milliseconds since 1970.
*/
public long lastUpdateTime;
/**
* The minimum execution time, in nanoseconds.
*/
public long executionTimeMinNanos;
/**
* The maximum execution time, in nanoseconds.
*/
public long executionTimeMaxNanos;
/**
* The total execution time.
*/
public long executionTimeCumulativeNanos;
/**
* The minimum number of rows.
*/
public int rowCountMin;
/**
* The maximum number of rows.
*/
public int rowCountMax;
/**
* The total number of rows.
*/
public long rowCountCumulative;
/**
* The mean execution time.
*/
public double executionTimeMeanNanos;
/**
* The mean number of rows.
*/
public double rowCountMean;
// Using Welford's method, see also
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
// http://www.johndcook.com/standard_deviation.html
private double executionTimeM2Nanos;
private double rowCountM2;
public QueryEntry(String sql) {
this.sqlStatement = sql;
}
/**
* Update the statistics entry.
*
* @param timeNanos the execution time in nanos
* @param rows the number of rows
*/
void update(long timeNanos, int rows) {
count++;
executionTimeMinNanos = Math.min(timeNanos, executionTimeMinNanos);
executionTimeMaxNanos = Math.max(timeNanos, executionTimeMaxNanos);
rowCountMin = Math.min(rows, rowCountMin);
rowCountMax = Math.max(rows, rowCountMax);
double rowDelta = rows - rowCountMean;
rowCountMean += rowDelta / count;
rowCountM2 += rowDelta * (rows - rowCountMean);
double timeDelta = timeNanos - executionTimeMeanNanos;
executionTimeMeanNanos += timeDelta / count;
executionTimeM2Nanos += timeDelta * (timeNanos - executionTimeMeanNanos);
executionTimeCumulativeNanos += timeNanos;
rowCountCumulative += rows;
lastUpdateTime = System.currentTimeMillis();
}
public double getExecutionTimeStandardDeviation() {
// population standard deviation
return Math.sqrt(executionTimeM2Nanos / count);
}
public double getRowCountStandardDeviation() {
// population standard deviation
return Math.sqrt(rowCountM2 / count);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Right.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.schema.Schema;
import org.h2.table.Table;
/**
* An access right. Rights are regular database objects, but have generated
* names.
*/
public class Right extends DbObjectBase {
/**
* The right bit mask that means: selecting from a table is allowed.
*/
public static final int SELECT = 1;
/**
* The right bit mask that means: deleting rows from a table is allowed.
*/
public static final int DELETE = 2;
/**
* The right bit mask that means: inserting rows into a table is allowed.
*/
public static final int INSERT = 4;
/**
* The right bit mask that means: updating data is allowed.
*/
public static final int UPDATE = 8;
/**
* The right bit mask that means: create/alter/drop schema is allowed.
*/
public static final int ALTER_ANY_SCHEMA = 16;
/**
* The right bit mask that means: select, insert, update, delete, and update
* for this object is allowed.
*/
public static final int ALL = SELECT | DELETE | INSERT | UPDATE;
/**
* To whom the right is granted.
*/
private RightOwner grantee;
/**
* The granted role, or null if a right was granted.
*/
private Role grantedRole;
/**
* The granted right.
*/
private int grantedRight;
/**
* The object. If the right is global, this is null.
*/
private DbObject grantedObject;
public Right(Database db, int id, RightOwner grantee, Role grantedRole) {
initDbObjectBase(db, id, "RIGHT_" + id, Trace.USER);
this.grantee = grantee;
this.grantedRole = grantedRole;
}
public Right(Database db, int id, RightOwner grantee, int grantedRight,
DbObject grantedObject) {
initDbObjectBase(db, id, "" + id, Trace.USER);
this.grantee = grantee;
this.grantedRight = grantedRight;
this.grantedObject = grantedObject;
}
private static boolean appendRight(StringBuilder buff, int right, int mask,
String name, boolean comma) {
if ((right & mask) != 0) {
if (comma) {
buff.append(", ");
}
buff.append(name);
return true;
}
return comma;
}
public String getRights() {
StringBuilder buff = new StringBuilder();
if (grantedRight == ALL) {
buff.append("ALL");
} else {
boolean comma = false;
comma = appendRight(buff, grantedRight, SELECT, "SELECT", comma);
comma = appendRight(buff, grantedRight, DELETE, "DELETE", comma);
comma = appendRight(buff, grantedRight, INSERT, "INSERT", comma);
comma = appendRight(buff, grantedRight, ALTER_ANY_SCHEMA,
"ALTER ANY SCHEMA", comma);
appendRight(buff, grantedRight, UPDATE, "UPDATE", comma);
}
return buff.toString();
}
public Role getGrantedRole() {
return grantedRole;
}
public DbObject getGrantedObject() {
return grantedObject;
}
public DbObject getGrantee() {
return grantee;
}
@Override
public String getDropSQL() {
return null;
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
return getCreateSQLForCopy(table);
}
private String getCreateSQLForCopy(DbObject object) {
StringBuilder buff = new StringBuilder();
buff.append("GRANT ");
if (grantedRole != null) {
buff.append(grantedRole.getSQL());
} else {
buff.append(getRights());
if (object != null) {
if (object instanceof Schema) {
buff.append(" ON SCHEMA ").append(object.getSQL());
} else if (object instanceof Table) {
buff.append(" ON ").append(object.getSQL());
}
}
}
buff.append(" TO ").append(grantee.getSQL());
return buff.toString();
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(grantedObject);
}
@Override
public int getType() {
return DbObject.RIGHT;
}
@Override
public void removeChildrenAndResources(Session session) {
if (grantedRole != null) {
grantee.revokeRole(grantedRole);
} else {
grantee.revokeRight(grantedObject);
}
database.removeMeta(session, getId());
grantedRole = null;
grantedObject = null;
grantee = null;
invalidate();
}
@Override
public void checkRename() {
DbException.throwInternalError();
}
public void setRightMask(int rightMask) {
grantedRight = rightMask;
}
public int getRightMask() {
return grantedRight;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/RightOwner.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.HashMap;
import org.h2.table.Table;
/**
* A right owner (sometimes called principal).
*/
public abstract class RightOwner extends DbObjectBase {
/**
* The map of granted roles.
*/
private HashMap<Role, Right> grantedRoles;
/**
* The map of granted rights.
*/
private HashMap<DbObject, Right> grantedRights;
protected RightOwner(Database database, int id, String name,
int traceModuleId) {
initDbObjectBase(database, id, name, traceModuleId);
}
/**
* Check if a role has been granted for this right owner.
*
* @param grantedRole the role
* @return true if the role has been granted
*/
public boolean isRoleGranted(Role grantedRole) {
if (grantedRole == this) {
return true;
}
if (grantedRoles != null) {
for (Role role : grantedRoles.keySet()) {
if (role == grantedRole) {
return true;
}
if (role.isRoleGranted(grantedRole)) {
return true;
}
}
}
return false;
}
/**
* Check if a right is already granted to this object or to objects that
* were granted to this object. The rights for schemas takes
* precedence over rights of tables, in other words, the rights of schemas
* will be valid for every each table in the related schema.
*
* @param table the table to check
* @param rightMask the right mask to check
* @return true if the right was already granted
*/
boolean isRightGrantedRecursive(Table table, int rightMask) {
Right right;
if (grantedRights != null) {
if (table != null) {
right = grantedRights.get(table.getSchema());
if (right != null) {
if ((right.getRightMask() & rightMask) == rightMask) {
return true;
}
}
}
right = grantedRights.get(table);
if (right != null) {
if ((right.getRightMask() & rightMask) == rightMask) {
return true;
}
}
}
if (grantedRoles != null) {
for (RightOwner role : grantedRoles.keySet()) {
if (role.isRightGrantedRecursive(table, rightMask)) {
return true;
}
}
}
return false;
}
/**
* Grant a right for the given table. Only one right object per table is
* supported.
*
* @param object the object (table or schema)
* @param right the right
*/
public void grantRight(DbObject object, Right right) {
if (grantedRights == null) {
grantedRights = new HashMap<>();
}
grantedRights.put(object, right);
}
/**
* Revoke the right for the given object (table or schema).
*
* @param object the object
*/
void revokeRight(DbObject object) {
if (grantedRights == null) {
return;
}
grantedRights.remove(object);
if (grantedRights.size() == 0) {
grantedRights = null;
}
}
/**
* Grant a role to this object.
*
* @param role the role
* @param right the right to grant
*/
public void grantRole(Role role, Right right) {
if (grantedRoles == null) {
grantedRoles = new HashMap<>();
}
grantedRoles.put(role, right);
}
/**
* Remove the right for the given role.
*
* @param role the role to revoke
*/
void revokeRole(Role role) {
if (grantedRoles == null) {
return;
}
Right right = grantedRoles.get(role);
if (right == null) {
return;
}
grantedRoles.remove(role);
if (grantedRoles.size() == 0) {
grantedRoles = null;
}
}
/**
* Get the 'grant schema' right of this object.
*
* @param object the granted object (table or schema)
* @return the right or null if the right has not been granted
*/
public Right getRightForObject(DbObject object) {
if (grantedRights == null) {
return null;
}
return grantedRights.get(object);
}
/**
* Get the 'grant role' right of this object.
*
* @param role the granted role
* @return the right or null if the right has not been granted
*/
public Right getRightForRole(Role role) {
if (grantedRoles == null) {
return null;
}
return grantedRoles.get(role);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Role.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.table.Table;
/**
* Represents a role. Roles can be granted to users, and to other roles.
*/
public class Role extends RightOwner {
private final boolean system;
public Role(Database database, int id, String roleName, boolean system) {
super(database, id, roleName, Trace.USER);
this.system = system;
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getDropSQL() {
return null;
}
/**
* Get the CREATE SQL statement for this object.
*
* @param ifNotExists true if IF NOT EXISTS should be used
* @return the SQL statement
*/
public String getCreateSQL(boolean ifNotExists) {
if (system) {
return null;
}
StringBuilder buff = new StringBuilder("CREATE ROLE ");
if (ifNotExists) {
buff.append("IF NOT EXISTS ");
}
buff.append(getSQL());
return buff.toString();
}
@Override
public String getCreateSQL() {
return getCreateSQL(false);
}
@Override
public int getType() {
return DbObject.ROLE;
}
@Override
public void removeChildrenAndResources(Session session) {
for (User user : database.getAllUsers()) {
Right right = user.getRightForRole(this);
if (right != null) {
database.removeDatabaseObject(session, right);
}
}
for (Role r2 : database.getAllRoles()) {
Right right = r2.getRightForRole(this);
if (right != null) {
database.removeDatabaseObject(session, right);
}
}
for (Right right : database.getAllRights()) {
if (right.getGrantee() == this) {
database.removeDatabaseObject(session, right);
}
}
database.removeMeta(session, getId());
invalidate();
}
@Override
public void checkRename() {
// ok
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Session.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.h2.api.ErrorCode;
import org.h2.command.Command;
import org.h2.command.CommandInterface;
import org.h2.command.Parser;
import org.h2.command.Prepared;
import org.h2.command.ddl.Analyze;
import org.h2.command.dml.Query;
import org.h2.command.dml.SetTypes;
import org.h2.constraint.Constraint;
import org.h2.ext.pulsar.PulsarExtension;
import org.h2.index.Index;
import org.h2.index.ViewIndex;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.message.TraceSystem;
import org.h2.mvstore.db.MVTable;
import org.h2.mvstore.db.TransactionStore.Change;
import org.h2.mvstore.db.TransactionStore.Transaction;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.SortOrder;
import org.h2.schema.Schema;
import org.h2.store.DataHandler;
import org.h2.store.InDoubtTransaction;
import org.h2.store.LobStorageFrontend;
import org.h2.table.SubQueryInfo;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.table.TableType;
import org.h2.util.ColumnNamerConfiguration;
import org.h2.util.New;
import org.h2.util.SmallLRUCache;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* A session represents an embedded database connection. When using the server
* mode, this object resides on the server side and communicates with a
* SessionRemote object on the client side.
*/
public class Session extends SessionWithState {
/**
* This special log position means that the log entry has been written.
*/
public static final int LOG_WRITTEN = -1;
/**
* The prefix of generated identifiers. It may not have letters, because
* they are case sensitive.
*/
private static final String SYSTEM_IDENTIFIER_PREFIX = "_";
private static int nextSerialId;
private final int serialId = nextSerialId++;
private int commandSequence = 0;
private final Database database;
private ConnectionInfo connectionInfo;
private final User user;
private final int id;
private final ArrayList<Table> locks = New.arrayList();
private final UndoLog undoLog;
private boolean autoCommit = true;
private Random random;
private int lockTimeout;
private Value lastIdentity = ValueLong.get(0);
private Value lastScopeIdentity = ValueLong.get(0);
private Value lastTriggerIdentity;
private GeneratedKeys generatedKeys;
private int firstUncommittedLog = Session.LOG_WRITTEN;
private int firstUncommittedPos = Session.LOG_WRITTEN;
private HashMap<String, Savepoint> savepoints;
private HashMap<String, Table> localTempTables;
private HashMap<String, Index> localTempTableIndexes;
private HashMap<String, Constraint> localTempTableConstraints;
private long throttleNs;
private long lastThrottle;
private Command currentCommand;
private boolean allowLiterals;
private String currentSchemaName;
private String[] schemaSearchPath;
private Trace trace;
private HashMap<String, Value> removeLobMap;
private int systemIdentifier;
private HashMap<String, Procedure> procedures;
private boolean undoLogEnabled = true;
private boolean redoLogBinary = true;
private boolean autoCommitAtTransactionEnd;
private String currentTransactionName;
private volatile long cancelAtNs;
private boolean closed;
private final long sessionStart = System.currentTimeMillis();
private long transactionStart;
private long currentCommandStart;
private HashMap<String, Value> variables;
private HashSet<ResultInterface> temporaryResults;
private int queryTimeout;
private boolean commitOrRollbackDisabled;
private Table waitForLock;
private Thread waitForLockThread;
private int modificationId;
private int objectId;
private final int queryCacheSize;
private SmallLRUCache<String, Command> queryCache;
private long modificationMetaID = -1;
private SubQueryInfo subQueryInfo;
private int parsingView;
private final Deque<String> viewNameStack = new ArrayDeque<>();
private int preparingQueryExpression;
private volatile SmallLRUCache<Object, ViewIndex> viewIndexCache;
private HashMap<Object, ViewIndex> subQueryIndexCache;
private boolean joinBatchEnabled;
private boolean forceJoinOrder;
private boolean lazyQueryExecution;
private ColumnNamerConfiguration columnNamerConfiguration;
/**
* Tables marked for ANALYZE after the current transaction is committed.
* Prevents us calling ANALYZE repeatedly in large transactions.
*/
private HashSet<Table> tablesToAnalyze;
/**
* Temporary LOBs from result sets. Those are kept for some time. The
* problem is that transactions are committed before the result is returned,
* and in some cases the next transaction is already started before the
* result is read (for example when using the server mode, when accessing
* metadata methods). We can't simply free those values up when starting the
* next transaction, because they would be removed too early.
*/
private LinkedList<TimeoutValue> temporaryResultLobs;
/**
* The temporary LOBs that need to be removed on commit.
*/
private ArrayList<Value> temporaryLobs;
private Transaction transaction;
private long startStatement = -1;
public Session(Database database, User user, int id) {
this.database = database;
this.queryTimeout = database.getSettings().maxQueryTimeout;
this.queryCacheSize = database.getSettings().queryCacheSize;
this.undoLog = new UndoLog(this);
this.user = user;
this.id = id;
Setting setting = database.findSetting(
SetTypes.getTypeName(SetTypes.DEFAULT_LOCK_TIMEOUT));
this.lockTimeout = setting == null ?
Constants.INITIAL_LOCK_TIMEOUT : setting.getIntValue();
this.currentSchemaName = Constants.SCHEMA_MAIN;
this.columnNamerConfiguration = ColumnNamerConfiguration.getDefault();
}
/**
* @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
* */
public int getSerialId() {
return serialId;
}
public int getCommandSequence() {
return commandSequence;
}
public void setLazyQueryExecution(boolean lazyQueryExecution) {
this.lazyQueryExecution = lazyQueryExecution;
}
public boolean isLazyQueryExecution() {
return lazyQueryExecution;
}
public void setForceJoinOrder(boolean forceJoinOrder) {
this.forceJoinOrder = forceJoinOrder;
}
public boolean isForceJoinOrder() {
return forceJoinOrder;
}
public void setJoinBatchEnabled(boolean joinBatchEnabled) {
this.joinBatchEnabled = joinBatchEnabled;
}
public boolean isJoinBatchEnabled() {
return joinBatchEnabled;
}
/**
* Create a new row for a table.
*
* @param data the values
* @param memory whether the row is in memory
* @return the created row
*/
public Row createRow(Value[] data, int memory) {
return database.createRow(data, memory);
}
/**
* Add a subquery info on top of the subquery info stack.
*
* @param masks the mask
* @param filters the filters
* @param filter the filter index
* @param sortOrder the sort order
*/
public void pushSubQueryInfo(int[] masks, TableFilter[] filters, int filter,
SortOrder sortOrder) {
subQueryInfo = new SubQueryInfo(subQueryInfo, masks, filters, filter, sortOrder);
}
/**
* Remove the current subquery info from the stack.
*/
public void popSubQueryInfo() {
subQueryInfo = subQueryInfo.getUpper();
}
public SubQueryInfo getSubQueryInfo() {
return subQueryInfo;
}
/**
* Stores name of currently parsed view in a stack so it can be determined
* during {@code prepare()}.
*
* @param parsingView
* {@code true} to store one more name, {@code false} to remove it
* from stack
* @param viewName
* name of the view
*/
public void setParsingCreateView(boolean parsingView, String viewName) {
// It can be recursive, thus implemented as counter.
this.parsingView += parsingView ? 1 : -1;
assert this.parsingView >= 0;
if (parsingView) {
viewNameStack.push(viewName);
} else {
assert viewName.equals(viewNameStack.peek());
viewNameStack.pop();
}
}
public String getParsingCreateViewName() {
if (viewNameStack.isEmpty()) {
return null;
}
return viewNameStack.peek();
}
public boolean isParsingCreateView() {
assert parsingView >= 0;
return parsingView != 0;
}
/**
* Optimize a query. This will remember the subquery info, clear it, prepare
* the query, and reset the subquery info.
*
* @param query the query to prepare
*/
public void optimizeQueryExpression(Query query) {
// we have to hide current subQueryInfo if we are going to optimize
// query expression
SubQueryInfo tmp = subQueryInfo;
subQueryInfo = null;
preparingQueryExpression++;
try {
query.prepare();
} finally {
subQueryInfo = tmp;
preparingQueryExpression--;
}
}
public boolean isPreparingQueryExpression() {
assert preparingQueryExpression >= 0;
return preparingQueryExpression != 0;
}
@Override
public ArrayList<String> getClusterServers() {
return new ArrayList<>();
}
public boolean setCommitOrRollbackDisabled(boolean x) {
boolean old = commitOrRollbackDisabled;
commitOrRollbackDisabled = x;
return old;
}
private void initVariables() {
if (variables == null) {
variables = database.newStringMap();
}
}
/**
* Set the value of the given variable for this session.
*
* @param name the name of the variable (may not be null)
* @param value the new value (may not be null)
*/
public void setVariable(String name, Value value) {
initVariables();
modificationId++;
Value old;
if (value == ValueNull.INSTANCE) {
old = variables.remove(name);
} else {
// link LOB values, to make sure we have our own object
value = value.copy(database,
LobStorageFrontend.TABLE_ID_SESSION_VARIABLE);
old = variables.put(name, value);
}
if (old != null) {
// remove the old value (in case it is a lob)
old.remove();
}
}
/**
* Get the value of the specified user defined variable. This method always
* returns a value; it returns ValueNull.INSTANCE if the variable doesn't
* exist.
*
* @param name the variable name
* @return the value, or NULL
*/
public Value getVariable(String name) {
initVariables();
Value v = variables.get(name);
return v == null ? ValueNull.INSTANCE : v;
}
/**
* Get the list of variable names that are set for this session.
*
* @return the list of names
*/
public String[] getVariableNames() {
if (variables == null) {
return new String[0];
}
return variables.keySet().toArray(new String[variables.size()]);
}
/**
* Get the local temporary table if one exists with that name, or null if
* not.
*
* @param name the table name
* @return the table, or null
*/
public Table findLocalTempTable(String name) {
if (localTempTables == null) {
return null;
}
return localTempTables.get(name);
}
public ArrayList<Table> getLocalTempTables() {
if (localTempTables == null) {
return New.arrayList();
}
return new ArrayList<>(localTempTables.values());
}
/**
* Add a local temporary table to this session.
*
* @param table the table to add
* @throws DbException if a table with this name already exists
*/
public void addLocalTempTable(Table table) {
if (localTempTables == null) {
localTempTables = database.newStringMap();
}
if (localTempTables.get(table.getName()) != null) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1,
table.getSQL()+" AS "+table.getName());
}
modificationId++;
localTempTables.put(table.getName(), table);
}
/**
* Drop and remove the given local temporary table from this session.
*
* @param table the table
*/
public void removeLocalTempTable(Table table) {
// Exception thrown in org.h2.engine.Database.removeMeta if line below
// is missing with TestGeneralCommonTableQueries
database.lockMeta(this);
modificationId++;
localTempTables.remove(table.getName());
synchronized (database) {
table.removeChildrenAndResources(this);
}
}
/**
* Get the local temporary index if one exists with that name, or null if
* not.
*
* @param name the table name
* @return the table, or null
*/
public Index findLocalTempTableIndex(String name) {
if (localTempTableIndexes == null) {
return null;
}
return localTempTableIndexes.get(name);
}
public HashMap<String, Index> getLocalTempTableIndexes() {
if (localTempTableIndexes == null) {
return new HashMap<>();
}
return localTempTableIndexes;
}
/**
* Add a local temporary index to this session.
*
* @param index the index to add
* @throws DbException if a index with this name already exists
*/
public void addLocalTempTableIndex(Index index) {
if (localTempTableIndexes == null) {
localTempTableIndexes = database.newStringMap();
}
if (localTempTableIndexes.get(index.getName()) != null) {
throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1,
index.getSQL());
}
localTempTableIndexes.put(index.getName(), index);
}
/**
* Drop and remove the given local temporary index from this session.
*
* @param index the index
*/
public void removeLocalTempTableIndex(Index index) {
if (localTempTableIndexes != null) {
localTempTableIndexes.remove(index.getName());
synchronized (database) {
index.removeChildrenAndResources(this);
}
}
}
/**
* Get the local temporary constraint if one exists with that name, or
* null if not.
*
* @param name the constraint name
* @return the constraint, or null
*/
public Constraint findLocalTempTableConstraint(String name) {
if (localTempTableConstraints == null) {
return null;
}
return localTempTableConstraints.get(name);
}
/**
* Get the map of constraints for all constraints on local, temporary
* tables, if any. The map's keys are the constraints' names.
*
* @return the map of constraints, or null
*/
public HashMap<String, Constraint> getLocalTempTableConstraints() {
if (localTempTableConstraints == null) {
return new HashMap<>();
}
return localTempTableConstraints;
}
/**
* Add a local temporary constraint to this session.
*
* @param constraint the constraint to add
* @throws DbException if a constraint with the same name already exists
*/
public void addLocalTempTableConstraint(Constraint constraint) {
if (localTempTableConstraints == null) {
localTempTableConstraints = database.newStringMap();
}
String name = constraint.getName();
if (localTempTableConstraints.get(name) != null) {
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1,
constraint.getSQL());
}
localTempTableConstraints.put(name, constraint);
}
/**
* Drop and remove the given local temporary constraint from this session.
*
* @param constraint the constraint
*/
void removeLocalTempTableConstraint(Constraint constraint) {
if (localTempTableConstraints != null) {
localTempTableConstraints.remove(constraint.getName());
synchronized (database) {
constraint.removeChildrenAndResources(this);
}
}
}
@Override
public boolean getAutoCommit() {
return autoCommit;
}
public User getUser() {
return user;
}
@Override
public void setAutoCommit(boolean b) {
autoCommit = b;
}
public int getLockTimeout() {
return lockTimeout;
}
public void setLockTimeout(int lockTimeout) {
this.lockTimeout = lockTimeout;
}
@Override
public synchronized CommandInterface prepareCommand(String sql,
int fetchSize) {
++commandSequence;
return prepareLocal(sql);
}
/**
* Parse and prepare the given SQL statement. This method also checks the
* rights.
*
* @param sql the SQL statement
* @return the prepared statement
*/
public Prepared prepare(String sql) {
return prepare(sql, false, false);
}
/**
* Parse and prepare the given SQL statement.
*
* @param sql the SQL statement
* @param rightsChecked true if the rights have already been checked
* @param literalsChecked true if the sql string has already been checked
* for literals (only used if ALLOW_LITERALS NONE is set).
* @return the prepared statement
*/
public Prepared prepare(String sql, boolean rightsChecked, boolean literalsChecked) {
Parser parser = new Parser(this);
parser.setRightsChecked(rightsChecked);
parser.setLiteralsChecked(literalsChecked);
return parser.prepare(sql);
}
/**
* Parse and prepare the given SQL statement.
* This method also checks if the connection has been closed.
*
* @param sql the SQL statement
* @return the prepared statement
*/
public Command prepareLocal(String sql) {
if (closed) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1,
"session closed");
}
Command command;
if (queryCacheSize > 0) {
if (queryCache == null) {
queryCache = SmallLRUCache.newInstance(queryCacheSize);
modificationMetaID = database.getModificationMetaId();
} else {
long newModificationMetaID = database.getModificationMetaId();
if (newModificationMetaID != modificationMetaID) {
queryCache.clear();
modificationMetaID = newModificationMetaID;
}
command = queryCache.get(sql);
if (command != null && command.canReuse()) {
command.reuse();
return command;
}
}
}
Parser parser = new Parser(this);
try {
command = parser.prepareCommand(sql);
} finally {
// we can't reuse sub-query indexes, so just drop the whole cache
subQueryIndexCache = null;
}
command.prepareJoinBatch();
if (queryCache != null) {
if (command.isCacheable()) {
queryCache.put(sql, command);
}
}
return command;
}
public Database getDatabase() {
return database;
}
@Override
public int getPowerOffCount() {
return database.getPowerOffCount();
}
@Override
public void setPowerOffCount(int count) {
database.setPowerOffCount(count);
}
/**
* Commit the current transaction. If the statement was not a data
* definition statement, and if there are temporary tables that should be
* dropped or truncated at commit, this is done as well.
*
* @param ddl if the statement was a data definition statement
*/
public void commit(boolean ddl) {
checkCommitRollback();
currentTransactionName = null;
transactionStart = 0;
if (transaction != null) {
// increment the data mod count, so that other sessions
// see the changes
// TODO should not rely on locking
if (!locks.isEmpty()) {
for (Table t : locks) {
if (t instanceof MVTable) {
((MVTable) t).commit();
}
}
}
transaction.commit();
transaction = null;
}
if (containsUncommitted()) {
// need to commit even if rollback is not possible
// (create/drop table and so on)
database.commit(this);
}
removeTemporaryLobs(true);
if (undoLog.size() > 0) {
// commit the rows when using MVCC
if (database.isMultiVersion()) {
ArrayList<Row> rows = New.arrayList();
synchronized (database) {
while (undoLog.size() > 0) {
UndoLogRecord entry = undoLog.getLast();
entry.commit();
rows.add(entry.getRow());
undoLog.removeLast(false);
}
for (Row r : rows) {
r.commit();
}
}
}
undoLog.clear();
}
if (!ddl) {
// do not clean the temp tables if the last command was a
// create/drop
cleanTempTables(false);
if (autoCommitAtTransactionEnd) {
autoCommit = true;
autoCommitAtTransactionEnd = false;
}
}
int rows = getDatabase().getSettings().analyzeSample / 10;
if (tablesToAnalyze != null) {
for (Table table : tablesToAnalyze) {
Analyze.analyzeTable(this, table, rows, false);
}
// analyze can lock the meta
database.unlockMeta(this);
}
tablesToAnalyze = null;
endTransaction();
}
private void removeTemporaryLobs(boolean onTimeout) {
if (SysProperties.CHECK2) {
if (this == getDatabase().getLobSession()
&& !Thread.holdsLock(this) && !Thread.holdsLock(getDatabase())) {
throw DbException.throwInternalError();
}
}
if (temporaryLobs != null) {
for (Value v : temporaryLobs) {
if (!v.isLinkedToTable()) {
v.remove();
}
}
temporaryLobs.clear();
}
if (temporaryResultLobs != null && !temporaryResultLobs.isEmpty()) {
long keepYoungerThan = System.nanoTime() -
TimeUnit.MILLISECONDS.toNanos(database.getSettings().lobTimeout);
while (!temporaryResultLobs.isEmpty()) {
TimeoutValue tv = temporaryResultLobs.getFirst();
if (onTimeout && tv.created >= keepYoungerThan) {
break;
}
Value v = temporaryResultLobs.removeFirst().value;
if (!v.isLinkedToTable()) {
v.remove();
}
}
}
}
private void checkCommitRollback() {
if (commitOrRollbackDisabled && !locks.isEmpty()) {
throw DbException.get(ErrorCode.COMMIT_ROLLBACK_NOT_ALLOWED);
}
}
private void endTransaction() {
if (removeLobMap != null && removeLobMap.size() > 0) {
if (database.getMvStore() == null) {
// need to flush the transaction log, because we can't unlink
// lobs if the commit record is not written
database.flush();
}
for (Value v : removeLobMap.values()) {
v.remove();
}
removeLobMap = null;
}
unlockAll();
}
/**
* Fully roll back the current transaction.
*/
public void rollback() {
checkCommitRollback();
currentTransactionName = null;
transactionStart = 0;
boolean needCommit = false;
if (undoLog.size() > 0) {
rollbackTo(null, false);
needCommit = true;
}
if (transaction != null) {
rollbackTo(null, false);
needCommit = true;
// rollback stored the undo operations in the transaction
// committing will end the transaction
transaction.commit();
transaction = null;
}
if (!locks.isEmpty() || needCommit) {
database.commit(this);
}
cleanTempTables(false);
if (autoCommitAtTransactionEnd) {
autoCommit = true;
autoCommitAtTransactionEnd = false;
}
endTransaction();
}
/**
* Partially roll back the current transaction.
*
* @param savepoint the savepoint to which should be rolled back
* @param trimToSize if the list should be trimmed
*/
public void rollbackTo(Savepoint savepoint, boolean trimToSize) {
int index = savepoint == null ? 0 : savepoint.logIndex;
while (undoLog.size() > index) {
UndoLogRecord entry = undoLog.getLast();
entry.undo(this);
undoLog.removeLast(trimToSize);
}
if (transaction != null) {
long savepointId = savepoint == null ? 0 : savepoint.transactionSavepoint;
HashMap<String, MVTable> tableMap =
database.getMvStore().getTables();
Iterator<Change> it = transaction.getChanges(savepointId);
while (it.hasNext()) {
Change c = it.next();
MVTable t = tableMap.get(c.mapName);
if (t != null) {
long key = ((ValueLong) c.key).getLong();
ValueArray value = (ValueArray) c.value;
short op;
Row row;
if (value == null) {
op = UndoLogRecord.INSERT;
row = t.getRow(this, key);
} else {
op = UndoLogRecord.DELETE;
row = createRow(value.getList(), Row.MEMORY_CALCULATE);
}
row.setKey(key);
UndoLogRecord log = new UndoLogRecord(t, op, row);
log.undo(this);
}
}
}
if (savepoints != null) {
String[] names = savepoints.keySet().toArray(new String[savepoints.size()]);
for (String name : names) {
Savepoint sp = savepoints.get(name);
int savepointIndex = sp.logIndex;
if (savepointIndex > index) {
savepoints.remove(name);
}
}
}
}
@Override
public boolean hasPendingTransaction() {
return undoLog.size() > 0;
}
/**
* Create a savepoint to allow rolling back to this state.
*
* @return the savepoint
*/
public Savepoint setSavepoint() {
Savepoint sp = new Savepoint();
sp.logIndex = undoLog.size();
if (database.getMvStore() != null) {
sp.transactionSavepoint = getStatementSavepoint();
}
return sp;
}
public int getId() {
return id;
}
@Override
public void cancel() {
cancelAtNs = System.nanoTime();
}
@Override
public void close() {
if (!closed) {
// @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
try {
PulsarExtension.closeSession(this);
} catch (Exception e) {
getTrace().debug(e.getMessage());
}
try {
database.checkPowerOff();
// release any open table locks
rollback();
removeTemporaryLobs(false);
cleanTempTables(true);
undoLog.clear();
// Table#removeChildrenAndResources can take the meta lock,
// and we need to unlock before we call removeSession(), which might
// want to take the meta lock using the system session.
database.unlockMeta(this);
database.removeSession(this);
} finally {
closed = true;
}
}
}
/**
* Add a lock for the given table. The object is unlocked on commit or
* rollback.
*
* @param table the table that is locked
*/
public void addLock(Table table) {
if (SysProperties.CHECK) {
if (locks.contains(table)) {
DbException.throwInternalError(table.toString());
}
}
locks.add(table);
}
/**
* Add an undo log entry to this session.
*
* @param table the table
* @param operation the operation type (see {@link UndoLogRecord})
* @param row the row
*/
public void log(Table table, short operation, Row row) {
if (table.isMVStore()) {
return;
}
if (undoLogEnabled) {
UndoLogRecord log = new UndoLogRecord(table, operation, row);
// called _after_ the row was inserted successfully into the table,
// otherwise rollback will try to rollback a not-inserted row
if (SysProperties.CHECK) {
int lockMode = database.getLockMode();
if (lockMode != Constants.LOCK_MODE_OFF &&
!database.isMultiVersion()) {
TableType tableType = log.getTable().getTableType();
if (!locks.contains(log.getTable())
&& TableType.TABLE_LINK != tableType
&& TableType.EXTERNAL_TABLE_ENGINE != tableType) {
DbException.throwInternalError("" + tableType);
}
}
}
undoLog.add(log);
} else {
if (database.isMultiVersion()) {
// see also UndoLogRecord.commit
ArrayList<Index> indexes = table.getIndexes();
for (Index index : indexes) {
index.commit(operation, row);
}
row.commit();
}
}
}
/**
* Unlock all read locks. This is done if the transaction isolation mode is
* READ_COMMITTED.
*/
public void unlockReadLocks() {
if (database.isMultiVersion()) {
// MVCC: keep shared locks (insert / update / delete)
return;
}
// locks is modified in the loop
for (int i = 0; i < locks.size(); i++) {
Table t = locks.get(i);
if (!t.isLockedExclusively()) {
synchronized (database) {
t.unlock(this);
locks.remove(i);
}
i--;
}
}
}
/**
* Unlock just this table.
*
* @param t the table to unlock
*/
void unlock(Table t) {
locks.remove(t);
}
private void unlockAll() {
if (SysProperties.CHECK) {
if (undoLog.size() > 0) {
DbException.throwInternalError();
}
}
if (!locks.isEmpty()) {
// don't use the enhanced for loop to save memory
for (Table t : locks) {
t.unlock(this);
}
locks.clear();
}
database.unlockMetaDebug(this);
savepoints = null;
sessionStateChanged = true;
}
private void cleanTempTables(boolean closeSession) {
if (localTempTables != null && localTempTables.size() > 0) {
synchronized (database) {
Iterator<Table> it = localTempTables.values().iterator();
while (it.hasNext()) {
Table table = it.next();
if (closeSession || table.getOnCommitDrop()) {
modificationId++;
table.setModified();
it.remove();
// Exception thrown in org.h2.engine.Database.removeMeta
// if line below is missing with TestDeadlock
database.lockMeta(this);
table.removeChildrenAndResources(this);
if (closeSession) {
// need to commit, otherwise recovery might
// ignore the table removal
database.commit(this);
}
} else if (table.getOnCommitTruncate()) {
table.truncate(this);
}
}
}
}
}
public Random getRandom() {
if (random == null) {
random = new Random();
}
return random;
}
@Override
public Trace getTrace() {
if (trace != null && !closed) {
return trace;
}
String traceModuleName = "jdbc[" + id + "]";
if (closed) {
return new TraceSystem(null).getTrace(traceModuleName);
}
trace = database.getTraceSystem().getTrace(traceModuleName);
return trace;
}
public void setLastIdentity(Value last) {
this.lastIdentity = last;
this.lastScopeIdentity = last;
}
public Value getLastIdentity() {
return lastIdentity;
}
public void setLastScopeIdentity(Value last) {
this.lastScopeIdentity = last;
}
public Value getLastScopeIdentity() {
return lastScopeIdentity;
}
public void setLastTriggerIdentity(Value last) {
this.lastTriggerIdentity = last;
}
public Value getLastTriggerIdentity() {
return lastTriggerIdentity;
}
public GeneratedKeys getGeneratedKeys() {
if (generatedKeys == null) {
generatedKeys = new GeneratedKeys();
}
return generatedKeys;
}
/**
* Called when a log entry for this session is added. The session keeps
* track of the first entry in the transaction log that is not yet
* committed.
*
* @param logId the transaction log id
* @param pos the position of the log entry in the transaction log
*/
public void addLogPos(int logId, int pos) {
if (firstUncommittedLog == Session.LOG_WRITTEN) {
firstUncommittedLog = logId;
firstUncommittedPos = pos;
}
}
public int getFirstUncommittedLog() {
return firstUncommittedLog;
}
/**
* This method is called after the transaction log has written the commit
* entry for this session.
*/
void setAllCommitted() {
firstUncommittedLog = Session.LOG_WRITTEN;
firstUncommittedPos = Session.LOG_WRITTEN;
}
/**
* Whether the session contains any uncommitted changes.
*
* @return true if yes
*/
public boolean containsUncommitted() {
if (database.getMvStore() != null) {
return transaction != null;
}
return firstUncommittedLog != Session.LOG_WRITTEN;
}
/**
* Create a savepoint that is linked to the current log position.
*
* @param name the savepoint name
*/
public void addSavepoint(String name) {
if (savepoints == null) {
savepoints = database.newStringMap();
}
Savepoint sp = new Savepoint();
sp.logIndex = undoLog.size();
if (database.getMvStore() != null) {
sp.transactionSavepoint = getStatementSavepoint();
}
savepoints.put(name, sp);
}
/**
* Undo all operations back to the log position of the given savepoint.
*
* @param name the savepoint name
*/
public void rollbackToSavepoint(String name) {
checkCommitRollback();
currentTransactionName = null;
transactionStart = 0;
if (savepoints == null) {
throw DbException.get(ErrorCode.SAVEPOINT_IS_INVALID_1, name);
}
Savepoint savepoint = savepoints.get(name);
if (savepoint == null) {
throw DbException.get(ErrorCode.SAVEPOINT_IS_INVALID_1, name);
}
rollbackTo(savepoint, false);
}
/**
* Prepare the given transaction.
*
* @param transactionName the name of the transaction
*/
public void prepareCommit(String transactionName) {
if (containsUncommitted()) {
// need to commit even if rollback is not possible (create/drop
// table and so on)
database.prepareCommit(this, transactionName);
}
currentTransactionName = transactionName;
}
/**
* Commit or roll back the given transaction.
*
* @param transactionName the name of the transaction
* @param commit true for commit, false for rollback
*/
public void setPreparedTransaction(String transactionName, boolean commit) {
if (currentTransactionName != null &&
currentTransactionName.equals(transactionName)) {
if (commit) {
commit(false);
} else {
rollback();
}
} else {
ArrayList<InDoubtTransaction> list = database
.getInDoubtTransactions();
int state = commit ? InDoubtTransaction.COMMIT
: InDoubtTransaction.ROLLBACK;
boolean found = false;
if (list != null) {
for (InDoubtTransaction p: list) {
if (p.getTransactionName().equals(transactionName)) {
p.setState(state);
found = true;
break;
}
}
}
if (!found) {
throw DbException.get(ErrorCode.TRANSACTION_NOT_FOUND_1,
transactionName);
}
}
}
@Override
public boolean isClosed() {
return closed;
}
public void setThrottle(int throttle) {
this.throttleNs = TimeUnit.MILLISECONDS.toNanos(throttle);
}
/**
* Wait for some time if this session is throttled (slowed down).
*/
public void throttle() {
if (currentCommandStart == 0) {
currentCommandStart = System.currentTimeMillis();
}
if (throttleNs == 0) {
return;
}
long time = System.nanoTime();
if (lastThrottle + TimeUnit.MILLISECONDS.toNanos(Constants.THROTTLE_DELAY) > time) {
return;
}
lastThrottle = time + throttleNs;
try {
Thread.sleep(TimeUnit.NANOSECONDS.toMillis(throttleNs));
} catch (Exception e) {
// ignore InterruptedException
}
}
/**
* Set the current command of this session. This is done just before
* executing the statement.
*
* @param command the command
* @param generatedKeysRequest
* {@code false} if generated keys are not needed, {@code true} if
* generated keys should be configured automatically, {@code int[]}
* to specify column indices to return generated keys from, or
* {@code String[]} to specify column names to return generated keys
* from
*/
public void setCurrentCommand(Command command, Object generatedKeysRequest) {
this.currentCommand = command;
// Preserve generated keys in case of a new query due to possible nested
// queries in update
if (command != null && !command.isQuery()) {
getGeneratedKeys().clear(generatedKeysRequest);
}
if (queryTimeout > 0 && command != null) {
currentCommandStart = System.currentTimeMillis();
long now = System.nanoTime();
cancelAtNs = now + TimeUnit.MILLISECONDS.toNanos(queryTimeout);
}
}
/**
* Check if the current transaction is canceled by calling
* Statement.cancel() or because a session timeout was set and expired.
*
* @throws DbException if the transaction is canceled
*/
public void checkCanceled() {
throttle();
if (cancelAtNs == 0) {
return;
}
long time = System.nanoTime();
if (time >= cancelAtNs) {
cancelAtNs = 0;
throw DbException.get(ErrorCode.STATEMENT_WAS_CANCELED);
}
}
/**
* Get the cancel time.
*
* @return the time or 0 if not set
*/
public long getCancel() {
return cancelAtNs;
}
public Command getCurrentCommand() {
return currentCommand;
}
public long getCurrentCommandStart() {
return currentCommandStart;
}
public boolean getAllowLiterals() {
return allowLiterals;
}
public void setAllowLiterals(boolean b) {
this.allowLiterals = b;
}
public void setCurrentSchema(Schema schema) {
modificationId++;
this.currentSchemaName = schema.getName();
}
@Override
public String getCurrentSchemaName() {
return currentSchemaName;
}
@Override
public void setCurrentSchemaName(String schemaName) {
Schema schema = database.getSchema(schemaName);
setCurrentSchema(schema);
}
/**
* Create an internal connection. This connection is used when initializing
* triggers, and when calling user defined functions.
*
* @param columnList if the url should be 'jdbc:columnlist:connection'
* @return the internal connection
*/
public JdbcConnection createConnection(boolean columnList) {
String url;
if (columnList) {
url = Constants.CONN_URL_COLUMNLIST;
} else {
url = Constants.CONN_URL_INTERNAL;
}
return new JdbcConnection(this, getUser().getName(), url);
}
@Override
public DataHandler getDataHandler() {
return database;
}
/**
* Remember that the given LOB value must be removed at commit.
*
* @param v the value
*/
public void removeAtCommit(Value v) {
if (SysProperties.CHECK && !v.isLinkedToTable()) {
DbException.throwInternalError(v.toString());
}
if (removeLobMap == null) {
removeLobMap = new HashMap<>();
}
removeLobMap.put(v.toString(), v);
}
/**
* Do not remove this LOB value at commit any longer.
*
* @param v the value
*/
public void removeAtCommitStop(Value v) {
if (removeLobMap != null) {
removeLobMap.remove(v.toString());
}
}
/**
* Get the next system generated identifiers. The identifier returned does
* not occur within the given SQL statement.
*
* @param sql the SQL statement
* @return the new identifier
*/
public String getNextSystemIdentifier(String sql) {
String identifier;
do {
identifier = SYSTEM_IDENTIFIER_PREFIX + systemIdentifier++;
} while (sql.contains(identifier));
return identifier;
}
/**
* Add a procedure to this session.
*
* @param procedure the procedure to add
*/
public void addProcedure(Procedure procedure) {
if (procedures == null) {
procedures = database.newStringMap();
}
procedures.put(procedure.getName(), procedure);
}
/**
* Remove a procedure from this session.
*
* @param name the name of the procedure to remove
*/
public void removeProcedure(String name) {
if (procedures != null) {
procedures.remove(name);
}
}
/**
* Get the procedure with the given name, or null
* if none exists.
*
* @param name the procedure name
* @return the procedure or null
*/
public Procedure getProcedure(String name) {
if (procedures == null) {
return null;
}
return procedures.get(name);
}
public void setSchemaSearchPath(String[] schemas) {
modificationId++;
this.schemaSearchPath = schemas;
}
public String[] getSchemaSearchPath() {
return schemaSearchPath;
}
@Override
public int hashCode() {
return serialId;
}
@Override
public String toString() {
return "#" + serialId + " (user: " + user.getName() + ")";
}
public void setUndoLogEnabled(boolean b) {
this.undoLogEnabled = b;
}
public void setRedoLogBinary(boolean b) {
this.redoLogBinary = b;
}
public boolean isUndoLogEnabled() {
return undoLogEnabled;
}
/**
* Begin a transaction.
*/
public void begin() {
autoCommitAtTransactionEnd = true;
autoCommit = false;
}
public long getSessionStart() {
return sessionStart;
}
public long getTransactionStart() {
if (transactionStart == 0) {
transactionStart = System.currentTimeMillis();
}
return transactionStart;
}
public Table[] getLocks() {
// copy the data without synchronizing
ArrayList<Table> copy = New.arrayList();
for (Table lock : locks) {
try {
copy.add(lock);
} catch (Exception e) {
// ignore
break;
}
}
return copy.toArray(new Table[0]);
}
/**
* Wait if the exclusive mode has been enabled for another session. This
* method returns as soon as the exclusive mode has been disabled.
*/
public void waitIfExclusiveModeEnabled() {
// Even in exclusive mode, we have to let the LOB session proceed, or we
// will get deadlocks.
if (database.getLobSession() == this) {
return;
}
while (true) {
Session exclusive = database.getExclusiveSession();
if (exclusive == null || exclusive == this) {
break;
}
if (Thread.holdsLock(exclusive)) {
// if another connection is used within the connection
break;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// ignore
}
}
}
/**
* Get the view cache for this session. There are two caches: the subquery
* cache (which is only use for a single query, has no bounds, and is
* cleared after use), and the cache for regular views.
*
* @param subQuery true to get the subquery cache
* @return the view cache
*/
public Map<Object, ViewIndex> getViewIndexCache(boolean subQuery) {
if (subQuery) {
// for sub-queries we don't need to use LRU because the cache should
// not grow too large for a single query (we drop the whole cache in
// the end of prepareLocal)
if (subQueryIndexCache == null) {
subQueryIndexCache = new HashMap<>();
}
return subQueryIndexCache;
}
SmallLRUCache<Object, ViewIndex> cache = viewIndexCache;
if (cache == null) {
viewIndexCache = cache = SmallLRUCache.newInstance(Constants.VIEW_INDEX_CACHE_SIZE);
}
return cache;
}
/**
* Remember the result set and close it as soon as the transaction is
* committed (if it needs to be closed). This is done to delete temporary
* files as soon as possible, and free object ids of temporary tables.
*
* @param result the temporary result set
*/
public void addTemporaryResult(ResultInterface result) {
if (!result.needToClose()) {
return;
}
if (temporaryResults == null) {
temporaryResults = new HashSet<>();
}
if (temporaryResults.size() < 100) {
// reference at most 100 result sets to avoid memory problems
temporaryResults.add(result);
}
}
private void closeTemporaryResults() {
if (temporaryResults != null) {
for (ResultInterface result : temporaryResults) {
result.close();
}
temporaryResults = null;
}
}
public void setQueryTimeout(int queryTimeout) {
int max = database.getSettings().maxQueryTimeout;
if (max != 0 && (max < queryTimeout || queryTimeout == 0)) {
// the value must be at most max
queryTimeout = max;
}
this.queryTimeout = queryTimeout;
// must reset the cancel at here,
// otherwise it is still used
this.cancelAtNs = 0;
}
public int getQueryTimeout() {
return queryTimeout;
}
/**
* Set the table this session is waiting for, and the thread that is
* waiting.
*
* @param waitForLock the table
* @param waitForLockThread the current thread (the one that is waiting)
*/
public void setWaitForLock(Table waitForLock, Thread waitForLockThread) {
this.waitForLock = waitForLock;
this.waitForLockThread = waitForLockThread;
}
public Table getWaitForLock() {
return waitForLock;
}
public Thread getWaitForLockThread() {
return waitForLockThread;
}
public int getModificationId() {
return modificationId;
}
@Override
public boolean isReconnectNeeded(boolean write) {
while (true) {
boolean reconnect = database.isReconnectNeeded();
if (reconnect) {
return true;
}
if (write) {
if (database.beforeWriting()) {
return false;
}
} else {
return false;
}
}
}
@Override
public void afterWriting() {
database.afterWriting();
}
@Override
public SessionInterface reconnect(boolean write) {
readSessionState();
close();
// Session newSession = Engine.getInstance().createSession(connectionInfo);
// @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
Session newSession = null;
try {
newSession = (Session) PulsarExtension.createSession(connectionInfo);
} catch (Exception e) {
e.printStackTrace();
}
newSession.sessionState = sessionState;
newSession.recreateSessionState();
if (write) {
while (!newSession.database.beforeWriting()) {
// wait until we are allowed to write
}
}
return newSession;
}
public void setConnectionInfo(ConnectionInfo ci) {
connectionInfo = ci;
}
public Value getTransactionId() {
if (database.getMvStore() != null) {
if (transaction == null) {
return ValueNull.INSTANCE;
}
return ValueString.get(Long.toString(getTransaction().getId()));
}
if (!database.isPersistent()) {
return ValueNull.INSTANCE;
}
if (undoLog.size() == 0) {
return ValueNull.INSTANCE;
}
return ValueString.get(firstUncommittedLog + "-" + firstUncommittedPos +
"-" + id);
}
/**
* Get the next object id.
*
* @return the next object id
*/
public int nextObjectId() {
return objectId++;
}
public boolean isRedoLogBinaryEnabled() {
return redoLogBinary;
}
/**
* Get the transaction to use for this session.
*
* @return the transaction
*/
public Transaction getTransaction() {
if (transaction == null) {
if (database.getMvStore().getStore().isClosed()) {
database.shutdownImmediately();
throw DbException.get(ErrorCode.DATABASE_IS_CLOSED);
}
transaction = database.getMvStore().getTransactionStore().begin();
startStatement = -1;
}
return transaction;
}
public long getStatementSavepoint() {
if (startStatement == -1) {
startStatement = getTransaction().setSavepoint();
}
return startStatement;
}
/**
* Start a new statement within a transaction.
*/
public void startStatementWithinTransaction() {
startStatement = -1;
}
/**
* Mark the statement as completed. This also close all temporary result
* set, and deletes all temporary files held by the result sets.
*/
public void endStatement() {
startStatement = -1;
closeTemporaryResults();
}
/**
* Clear the view cache for this session.
*/
public void clearViewIndexCache() {
viewIndexCache = null;
}
@Override
public void addTemporaryLob(Value v) {
if (v.getType() != Value.CLOB && v.getType() != Value.BLOB) {
return;
}
if (v.getTableId() == LobStorageFrontend.TABLE_RESULT ||
v.getTableId() == LobStorageFrontend.TABLE_TEMP) {
if (temporaryResultLobs == null) {
temporaryResultLobs = new LinkedList<>();
}
temporaryResultLobs.add(new TimeoutValue(v));
} else {
if (temporaryLobs == null) {
temporaryLobs = new ArrayList<>();
}
temporaryLobs.add(v);
}
}
@Override
public boolean isRemote() {
return false;
}
/**
* Mark that the given table needs to be analyzed on commit.
*
* @param table the table
*/
public void markTableForAnalyze(Table table) {
if (tablesToAnalyze == null) {
tablesToAnalyze = new HashSet<>();
}
tablesToAnalyze.add(table);
}
/**
* Represents a savepoint (a position in a transaction to where one can roll
* back to).
*/
public static class Savepoint {
/**
* The undo log index.
*/
int logIndex;
/**
* The transaction savepoint id.
*/
long transactionSavepoint;
}
/**
* An object with a timeout.
*/
public static class TimeoutValue {
/**
* The time when this object was created.
*/
final long created = System.nanoTime();
/**
* The value.
*/
final Value value;
TimeoutValue(Value v) {
this.value = v;
}
}
public ColumnNamerConfiguration getColumnNamerConfiguration() {
return columnNamerConfiguration;
}
public void setColumnNamerConfiguration(ColumnNamerConfiguration columnNamerConfiguration) {
this.columnNamerConfiguration = columnNamerConfiguration;
}
@Override
public boolean isSupportsGeneratedKeys() {
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SessionFactory.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.sql.SQLException;
/**
* A class that implements this interface can create new database sessions. This
* exists so that the JDBC layer (the client) can be compiled without dependency
* to the core database engine.
*/
public interface SessionFactory {
/**
* Create a new session.
*
* @param ci the connection parameters
* @return the new session
*/
SessionInterface createSession(ConnectionInfo ci) throws SQLException;
/**
* Close a session and release resources
* @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
*
* @param sessionId The session id
* */
void closeSession(int sessionId) throws SQLException;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SessionInterface.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.io.Closeable;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.message.Trace;
import org.h2.store.DataHandler;
import org.h2.value.Value;
/**
* A local or remote session. A session represents a database connection.
*/
public interface SessionInterface extends Closeable {
/**
* Get the list of the cluster servers for this session.
*
* @return A list of "ip:port" strings for the cluster servers in this
* session.
*/
ArrayList<String> getClusterServers();
/**
* Parse a command and prepare it for execution.
*
* @param sql the SQL statement
* @param fetchSize the number of rows to fetch in one step
* @return the prepared command
*/
CommandInterface prepareCommand(String sql, int fetchSize);
/**
* Roll back pending transactions and close the session.
*/
@Override
void close();
/**
* Get the trace object
*
* @return the trace object
*/
Trace getTrace();
/**
* Check if close was called.
*
* @return if the session has been closed
*/
boolean isClosed();
/**
* Get the number of disk operations before power failure is simulated.
* This is used for testing. If not set, 0 is returned
*
* @return the number of operations, or 0
*/
int getPowerOffCount();
/**
* Set the number of disk operations before power failure is simulated.
* To disable the countdown, use 0.
*
* @param i the number of operations
*/
void setPowerOffCount(int i);
/**
* Get the data handler object.
*
* @return the data handler
*/
DataHandler getDataHandler();
/**
* Check whether this session has a pending transaction.
*
* @return true if it has
*/
boolean hasPendingTransaction();
/**
* Cancel the current or next command (called when closing a connection).
*/
void cancel();
/**
* Check if the database changed and therefore reconnecting is required.
*
* @param write if the next operation may be writing
* @return true if reconnecting is required
*/
boolean isReconnectNeeded(boolean write);
/**
* Close the connection and open a new connection.
*
* @param write if the next operation may be writing
* @return the new connection
*/
SessionInterface reconnect(boolean write);
/**
* Called after writing has ended. It needs to be called after
* isReconnectNeeded(true) returned false.
*/
void afterWriting();
/**
* Check if this session is in auto-commit mode.
*
* @return true if the session is in auto-commit mode
*/
boolean getAutoCommit();
/**
* Set the auto-commit mode. This call doesn't commit the current
* transaction.
*
* @param autoCommit the new value
*/
void setAutoCommit(boolean autoCommit);
/**
* Add a temporary LOB, which is closed when the session commits.
*
* @param v the value
*/
void addTemporaryLob(Value v);
/**
* Check if this session is remote or embedded.
*
* @return true if this session is remote
*/
boolean isRemote();
/**
* Set current schema.
*
* @param schema the schema name
*/
void setCurrentSchemaName(String schema);
/**
* Get current schema.
*
* @return the current schema name
*/
String getCurrentSchemaName();
/**
* Returns is this session supports generated keys.
*
* @return {@code true} if generated keys are supported, {@code false} if only
* {@code SCOPE_IDENTITY()} is supported
*/
boolean isSupportsGeneratedKeys();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SessionRemote.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.api.DatabaseEventListener;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.command.CommandInterface;
import org.h2.command.CommandRemote;
import org.h2.command.dml.SetTypes;
import org.h2.ext.pulsar.PulsarExtension;
import org.h2.jdbc.JdbcSQLException;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.message.TraceSystem;
import org.h2.result.ResultInterface;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.store.LobStorageFrontend;
import org.h2.store.LobStorageInterface;
import org.h2.store.fs.FileUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.NetUtils;
import org.h2.util.New;
import org.h2.util.SmallLRUCache;
import org.h2.util.StringUtils;
import org.h2.util.TempFileDeleter;
import org.h2.value.CompareMode;
import org.h2.value.Transfer;
import org.h2.value.Value;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
/**
* The client side part of a session when using the server mode. This object
* communicates with a Session on the server side.
*/
public class SessionRemote extends SessionWithState implements DataHandler {
public static final int SESSION_PREPARE = 0;
public static final int SESSION_CLOSE = 1;
public static final int COMMAND_EXECUTE_QUERY = 2;
public static final int COMMAND_EXECUTE_UPDATE = 3;
public static final int COMMAND_CLOSE = 4;
public static final int RESULT_FETCH_ROWS = 5;
public static final int RESULT_RESET = 6;
public static final int RESULT_CLOSE = 7;
public static final int COMMAND_COMMIT = 8;
public static final int CHANGE_ID = 9;
public static final int COMMAND_GET_META_DATA = 10;
public static final int SESSION_PREPARE_READ_PARAMS = 11;
public static final int SESSION_SET_ID = 12;
public static final int SESSION_CANCEL_STATEMENT = 13;
public static final int SESSION_CHECK_KEY = 14;
public static final int SESSION_SET_AUTOCOMMIT = 15;
public static final int SESSION_HAS_PENDING_TRANSACTION = 16;
public static final int LOB_READ = 17;
public static final int SESSION_PREPARE_READ_PARAMS2 = 18;
public static final int STATUS_ERROR = 0;
public static final int STATUS_OK = 1;
public static final int STATUS_CLOSED = 2;
public static final int STATUS_OK_STATE_CHANGED = 3;
private static SessionFactory sessionFactory;
private TraceSystem traceSystem;
private Trace trace;
private ArrayList<Transfer> transferList = New.arrayList();
private int nextId;
private boolean autoCommit = true;
private CommandInterface autoCommitFalse, autoCommitTrue;
private ConnectionInfo connectionInfo;
private String databaseName;
private String cipher;
private byte[] fileEncryptionKey;
private final Object lobSyncObject = new Object();
private String sessionId;
private int clientVersion;
private boolean autoReconnect;
private int lastReconnect;
private SessionInterface embedded;
private DatabaseEventListener eventListener;
private LobStorageFrontend lobStorage;
private boolean cluster;
private TempFileDeleter tempFileDeleter;
private JavaObjectSerializer javaObjectSerializer;
private volatile boolean javaObjectSerializerInitialized;
private final CompareMode compareMode = CompareMode.getInstance(null, 0);
public SessionRemote(ConnectionInfo ci) {
this.connectionInfo = ci;
}
@Override
public ArrayList<String> getClusterServers() {
ArrayList<String> serverList = new ArrayList<>();
for (Transfer transfer : transferList) {
serverList.add(transfer.getSocket().getInetAddress().
getHostAddress() + ":" +
transfer.getSocket().getPort());
}
return serverList;
}
private Transfer initTransfer(ConnectionInfo ci, String db, String server)
throws IOException {
Socket socket = NetUtils.createSocket(server,
Constants.DEFAULT_TCP_PORT, ci.isSSL());
Transfer trans = new Transfer(this, socket);
trans.setSSL(ci.isSSL());
trans.init();
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_MIN_SUPPORTED);
trans.writeInt(Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED);
trans.writeString(db);
trans.writeString(ci.getOriginalURL());
trans.writeString(ci.getUserName());
trans.writeBytes(ci.getUserPasswordHash());
trans.writeBytes(ci.getFilePasswordHash());
String[] keys = ci.getKeys();
trans.writeInt(keys.length);
for (String key : keys) {
trans.writeString(key).writeString(ci.getProperty(key));
}
try {
done(trans);
clientVersion = trans.readInt();
trans.setVersion(clientVersion);
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_14) {
if (ci.getFileEncryptionKey() != null) {
trans.writeBytes(ci.getFileEncryptionKey());
}
}
trans.writeInt(SessionRemote.SESSION_SET_ID);
trans.writeString(sessionId);
done(trans);
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_15) {
autoCommit = trans.readBoolean();
} else {
autoCommit = true;
}
return trans;
} catch (DbException e) {
trans.close();
throw e;
}
}
@Override
public boolean hasPendingTransaction() {
if (clientVersion < Constants.TCP_PROTOCOL_VERSION_10) {
return true;
}
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("SESSION_HAS_PENDING_TRANSACTION", 0);
transfer.writeInt(
SessionRemote.SESSION_HAS_PENDING_TRANSACTION);
done(transfer);
return transfer.readInt() != 0;
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
return true;
}
@Override
public void cancel() {
// this method is called when closing the connection
// the statement that is currently running is not canceled in this case
// however Statement.cancel is supported
}
/**
* Cancel the statement with the given id.
*
* @param id the statement id
*/
public void cancelStatement(int id) {
for (Transfer transfer : transferList) {
try {
Transfer trans = transfer.openNewConnection();
trans.init();
trans.writeInt(clientVersion);
trans.writeInt(clientVersion);
trans.writeString(null);
trans.writeString(null);
trans.writeString(sessionId);
trans.writeInt(SessionRemote.SESSION_CANCEL_STATEMENT);
trans.writeInt(id);
trans.close();
} catch (IOException e) {
trace.debug(e, "could not cancel statement");
}
}
}
private void checkClusterDisableAutoCommit(String serverList) {
if (autoCommit && transferList.size() > 1) {
setAutoCommitSend(false);
CommandInterface c = prepareCommand(
"SET CLUSTER " + serverList, Integer.MAX_VALUE);
// this will set autoCommit to false
c.executeUpdate(false);
// so we need to switch it on
autoCommit = true;
cluster = true;
}
}
public int getClientVersion() {
return clientVersion;
}
@Override
public boolean getAutoCommit() {
return autoCommit;
}
@Override
public void setAutoCommit(boolean autoCommit) {
if (!cluster) {
setAutoCommitSend(autoCommit);
}
this.autoCommit = autoCommit;
}
public void setAutoCommitFromServer(boolean autoCommit) {
if (cluster) {
if (autoCommit) {
// the user executed SET AUTOCOMMIT TRUE
setAutoCommitSend(false);
this.autoCommit = true;
}
} else {
this.autoCommit = autoCommit;
}
}
private synchronized void setAutoCommitSend(boolean autoCommit) {
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_8) {
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("SESSION_SET_AUTOCOMMIT", autoCommit ? 1 : 0);
transfer.writeInt(SessionRemote.SESSION_SET_AUTOCOMMIT).
writeBoolean(autoCommit);
done(transfer);
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
} else {
if (autoCommit) {
if (autoCommitTrue == null) {
autoCommitTrue = prepareCommand(
"SET AUTOCOMMIT TRUE", Integer.MAX_VALUE);
}
autoCommitTrue.executeUpdate(false);
} else {
if (autoCommitFalse == null) {
autoCommitFalse = prepareCommand(
"SET AUTOCOMMIT FALSE", Integer.MAX_VALUE);
}
autoCommitFalse.executeUpdate(false);
}
}
}
/**
* Calls COMMIT if the session is in cluster mode.
*/
public void autoCommitIfCluster() {
if (autoCommit && cluster) {
// server side auto commit is off because of race conditions
// (update set id=1 where id=0, but update set id=2 where id=0 is
// faster)
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("COMMAND_COMMIT", 0);
transfer.writeInt(SessionRemote.COMMAND_COMMIT);
done(transfer);
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
}
}
private String getFilePrefix(String dir) {
StringBuilder buff = new StringBuilder(dir);
buff.append('/');
for (int i = 0; i < databaseName.length(); i++) {
char ch = databaseName.charAt(i);
if (Character.isLetterOrDigit(ch)) {
buff.append(ch);
} else {
buff.append('_');
}
}
return buff.toString();
}
@Override
public int getPowerOffCount() {
return 0;
}
@Override
public void setPowerOffCount(int count) {
throw DbException.getUnsupportedException("remote");
}
/**
* Open a new (remote or embedded) session.
*
* @param openNew whether to open a new session in any case
* @return the session
*/
public SessionInterface connectEmbeddedOrServer(boolean openNew) {
ConnectionInfo ci = connectionInfo;
if (ci.isRemote()) {
connectServer(ci);
return this;
}
// create the session using reflection,
// so that the JDBC layer can be compiled without it
boolean autoServerMode = ci.getProperty("AUTO_SERVER", false);
ConnectionInfo backup = null;
try {
if (autoServerMode) {
backup = ci.clone();
connectionInfo = ci.clone();
}
if (openNew) {
ci.setProperty("OPEN_NEW", "true");
}
// @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
// return sessionFactory.createSession(ci);
return PulsarExtension.createSession(ci);
} catch (Exception re) {
DbException e = DbException.convert(re);
if (e.getErrorCode() == ErrorCode.DATABASE_ALREADY_OPEN_1) {
if (autoServerMode) {
String serverKey = ((JdbcSQLException) e.getSQLException()).
getSQL();
if (serverKey != null) {
backup.setServerKey(serverKey);
// OPEN_NEW must be removed now, otherwise
// opening a session with AUTO_SERVER fails
// if another connection is already open
backup.removeProperty("OPEN_NEW", null);
connectServer(backup);
return this;
}
}
}
throw e;
}
}
private void connectServer(ConnectionInfo ci) {
String name = ci.getName();
if (name.startsWith("//")) {
name = name.substring("//".length());
}
int idx = name.indexOf('/');
if (idx < 0) {
throw ci.getFormatException();
}
databaseName = name.substring(idx + 1);
String server = name.substring(0, idx);
traceSystem = new TraceSystem(null);
String traceLevelFile = ci.getProperty(
SetTypes.TRACE_LEVEL_FILE, null);
if (traceLevelFile != null) {
int level = Integer.parseInt(traceLevelFile);
String prefix = getFilePrefix(
SysProperties.CLIENT_TRACE_DIRECTORY);
try {
traceSystem.setLevelFile(level);
if (level > 0 && level < 4) {
String file = FileUtils.createTempFile(prefix,
Constants.SUFFIX_TRACE_FILE, false, false);
traceSystem.setFileName(file);
}
} catch (IOException e) {
throw DbException.convertIOException(e, prefix);
}
}
String traceLevelSystemOut = ci.getProperty(
SetTypes.TRACE_LEVEL_SYSTEM_OUT, null);
if (traceLevelSystemOut != null) {
int level = Integer.parseInt(traceLevelSystemOut);
traceSystem.setLevelSystemOut(level);
}
trace = traceSystem.getTrace(Trace.JDBC);
String serverList = null;
if (server.indexOf(',') >= 0) {
serverList = StringUtils.quoteStringSQL(server);
ci.setProperty("CLUSTER", Constants.CLUSTERING_ENABLED);
}
autoReconnect = ci.getProperty("AUTO_RECONNECT", false);
// AUTO_SERVER implies AUTO_RECONNECT
boolean autoServer = ci.getProperty("AUTO_SERVER", false);
if (autoServer && serverList != null) {
throw DbException
.getUnsupportedException("autoServer && serverList != null");
}
autoReconnect |= autoServer;
if (autoReconnect) {
String className = ci.getProperty("DATABASE_EVENT_LISTENER");
if (className != null) {
className = StringUtils.trim(className, true, true, "'");
try {
eventListener = (DatabaseEventListener) JdbcUtils
.loadUserClass(className).newInstance();
} catch (Throwable e) {
throw DbException.convert(e);
}
}
}
cipher = ci.getProperty("CIPHER");
if (cipher != null) {
fileEncryptionKey = MathUtils.secureRandomBytes(32);
}
String[] servers = StringUtils.arraySplit(server, ',', true);
int len = servers.length;
transferList.clear();
sessionId = StringUtils.convertBytesToHex(MathUtils.secureRandomBytes(32));
// TODO cluster: support more than 2 connections
boolean switchOffCluster = false;
try {
for (String s : servers) {
try {
Transfer trans = initTransfer(ci, databaseName, s);
transferList.add(trans);
} catch (IOException e) {
if (len == 1) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, e, e + ": " + s);
}
switchOffCluster = true;
}
}
checkClosed();
if (switchOffCluster) {
switchOffCluster();
}
checkClusterDisableAutoCommit(serverList);
} catch (DbException e) {
traceSystem.close();
throw e;
}
}
private void switchOffCluster() {
CommandInterface ci = prepareCommand("SET CLUSTER ''", Integer.MAX_VALUE);
ci.executeUpdate(false);
}
/**
* Remove a server from the list of cluster nodes and disables the cluster
* mode.
*
* @param e the exception (used for debugging)
* @param i the index of the server to remove
* @param count the retry count index
*/
public void removeServer(IOException e, int i, int count) {
trace.debug(e, "removing server because of exception");
transferList.remove(i);
if (transferList.isEmpty() && autoReconnect(count)) {
return;
}
checkClosed();
switchOffCluster();
}
@Override
public synchronized CommandInterface prepareCommand(String sql, int fetchSize) {
checkClosed();
return new CommandRemote(this, transferList, sql, fetchSize);
}
/**
* Automatically re-connect if necessary and if configured to do so.
*
* @param count the retry count index
* @return true if reconnected
*/
private boolean autoReconnect(int count) {
if (!isClosed()) {
return false;
}
if (!autoReconnect) {
return false;
}
if (!cluster && !autoCommit) {
return false;
}
if (count > SysProperties.MAX_RECONNECT) {
return false;
}
lastReconnect++;
while (true) {
try {
embedded = connectEmbeddedOrServer(false);
break;
} catch (DbException e) {
if (e.getErrorCode() != ErrorCode.DATABASE_IS_IN_EXCLUSIVE_MODE) {
throw e;
}
// exclusive mode: re-try endlessly
try {
Thread.sleep(500);
} catch (Exception e2) {
// ignore
}
}
}
if (embedded == this) {
// connected to a server somewhere else
embedded = null;
} else {
// opened an embedded connection now -
// must connect to this database in server mode
// unfortunately
connectEmbeddedOrServer(true);
}
recreateSessionState();
if (eventListener != null) {
eventListener.setProgress(DatabaseEventListener.STATE_RECONNECTED,
databaseName, count, SysProperties.MAX_RECONNECT);
}
return true;
}
/**
* Check if this session is closed and throws an exception if so.
*
* @throws DbException if the session is closed
*/
public void checkClosed() {
if (isClosed()) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "session closed");
}
}
@Override
public void close() {
RuntimeException closeError = null;
if (transferList != null) {
synchronized (this) {
for (Transfer transfer : transferList) {
try {
traceOperation("SESSION_CLOSE", 0);
transfer.writeInt(SessionRemote.SESSION_CLOSE);
done(transfer);
transfer.close();
} catch (RuntimeException e) {
trace.error(e, "close");
closeError = e;
} catch (Exception e) {
trace.error(e, "close");
}
}
}
transferList = null;
}
traceSystem.close();
if (embedded != null) {
embedded.close();
embedded = null;
}
if (closeError != null) {
throw closeError;
}
}
@Override
public Trace getTrace() {
return traceSystem.getTrace(Trace.JDBC);
}
public int getNextId() {
return nextId++;
}
public int getCurrentId() {
return nextId;
}
/**
* Called to flush the output after data has been sent to the server and
* just before receiving data. This method also reads the status code from
* the server and throws any exception the server sent.
*
* @param transfer the transfer object
* @throws DbException if the server sent an exception
* @throws IOException if there is a communication problem between client
* and server
*/
public void done(Transfer transfer) throws IOException {
transfer.flush();
int status = transfer.readInt();
if (status == STATUS_ERROR) {
String sqlstate = transfer.readString();
String message = transfer.readString();
String sql = transfer.readString();
int errorCode = transfer.readInt();
String stackTrace = transfer.readString();
JdbcSQLException s = new JdbcSQLException(message, sql, sqlstate,
errorCode, null, stackTrace);
if (errorCode == ErrorCode.CONNECTION_BROKEN_1) {
// allow re-connect
throw new IOException(s.toString(), s);
}
throw DbException.convert(s);
} else if (status == STATUS_CLOSED) {
transferList = null;
} else if (status == STATUS_OK_STATE_CHANGED) {
sessionStateChanged = true;
} else if (status == STATUS_OK) {
// ok
} else {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1,
"unexpected status " + status);
}
}
/**
* Returns true if the connection was opened in cluster mode.
*
* @return true if it is
*/
public boolean isClustered() {
return cluster;
}
@Override
public boolean isClosed() {
return transferList == null || transferList.isEmpty();
}
/**
* Write the operation to the trace system if debug trace is enabled.
*
* @param operation the operation performed
* @param id the id of the operation
*/
public void traceOperation(String operation, int id) {
if (trace.isDebugEnabled()) {
trace.debug("{0} {1}", operation, id);
}
}
@Override
public void checkPowerOff() {
// ok
}
@Override
public void checkWritingAllowed() {
// ok
}
@Override
public String getDatabasePath() {
return "";
}
@Override
public String getLobCompressionAlgorithm(int type) {
return null;
}
@Override
public int getMaxLengthInplaceLob() {
return SysProperties.LOB_CLIENT_MAX_SIZE_MEMORY;
}
@Override
public FileStore openFile(String name, String mode, boolean mustExist) {
if (mustExist && !FileUtils.exists(name)) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, name);
}
FileStore store;
if (cipher == null) {
store = FileStore.open(this, name, mode);
} else {
store = FileStore.open(this, name, mode, cipher, fileEncryptionKey, 0);
}
store.setCheckedWriting(false);
try {
store.init();
} catch (DbException e) {
store.closeSilently();
throw e;
}
return store;
}
@Override
public DataHandler getDataHandler() {
return this;
}
@Override
public Object getLobSyncObject() {
return lobSyncObject;
}
@Override
public SmallLRUCache<String, String[]> getLobFileListCache() {
return null;
}
public int getLastReconnect() {
return lastReconnect;
}
@Override
public TempFileDeleter getTempFileDeleter() {
if (tempFileDeleter == null) {
tempFileDeleter = TempFileDeleter.getInstance();
}
return tempFileDeleter;
}
@Override
public boolean isReconnectNeeded(boolean write) {
return false;
}
@Override
public SessionInterface reconnect(boolean write) {
return this;
}
@Override
public void afterWriting() {
// nothing to do
}
@Override
public LobStorageInterface getLobStorage() {
if (lobStorage == null) {
lobStorage = new LobStorageFrontend(this);
}
return lobStorage;
}
@Override
public synchronized int readLob(long lobId, byte[] hmac, long offset,
byte[] buff, int off, int length) {
checkClosed();
for (int i = 0, count = 0; i < transferList.size(); i++) {
Transfer transfer = transferList.get(i);
try {
traceOperation("LOB_READ", (int) lobId);
transfer.writeInt(SessionRemote.LOB_READ);
transfer.writeLong(lobId);
if (clientVersion >= Constants.TCP_PROTOCOL_VERSION_12) {
transfer.writeBytes(hmac);
}
transfer.writeLong(offset);
transfer.writeInt(length);
done(transfer);
length = transfer.readInt();
if (length <= 0) {
return length;
}
transfer.readBytes(buff, off, length);
return length;
} catch (IOException e) {
removeServer(e, i--, ++count);
}
}
return 1;
}
@Override
public JavaObjectSerializer getJavaObjectSerializer() {
initJavaObjectSerializer();
return javaObjectSerializer;
}
private void initJavaObjectSerializer() {
if (javaObjectSerializerInitialized) {
return;
}
synchronized (this) {
if (javaObjectSerializerInitialized) {
return;
}
String serializerFQN = readSerializationSettings();
if (serializerFQN != null) {
serializerFQN = serializerFQN.trim();
if (!serializerFQN.isEmpty() && !serializerFQN.equals("null")) {
try {
javaObjectSerializer = (JavaObjectSerializer) JdbcUtils
.loadUserClass(serializerFQN).newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
}
}
javaObjectSerializerInitialized = true;
}
}
/**
* Read the serializer name from the persistent database settings.
*
* @return the serializer
*/
private String readSerializationSettings() {
String javaObjectSerializerFQN = null;
CommandInterface ci = prepareCommand(
"SELECT VALUE FROM INFORMATION_SCHEMA.SETTINGS "+
" WHERE NAME='JAVA_OBJECT_SERIALIZER'", Integer.MAX_VALUE);
try {
ResultInterface result = ci.executeQuery(0, false);
if (result.next()) {
Value[] row = result.currentRow();
javaObjectSerializerFQN = row[0].getString();
}
} finally {
ci.close();
}
return javaObjectSerializerFQN;
}
@Override
public void addTemporaryLob(Value v) {
// do nothing
}
@Override
public CompareMode getCompareMode() {
return compareMode;
}
@Override
public boolean isRemote() {
return true;
}
@Override
public String getCurrentSchemaName() {
throw DbException.getUnsupportedException("getSchema && remote session");
}
@Override
public void setCurrentSchemaName(String schema) {
throw DbException.getUnsupportedException("setSchema && remote session");
}
@Override
public boolean isSupportsGeneratedKeys() {
return getClientVersion() >= Constants.TCP_PROTOCOL_VERSION_17;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SessionWithState.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.result.ResultInterface;
import org.h2.util.New;
import org.h2.value.Value;
/**
* The base class for both remote and embedded sessions.
*/
abstract class SessionWithState implements SessionInterface {
protected ArrayList<String> sessionState;
protected boolean sessionStateChanged;
private boolean sessionStateUpdating;
/**
* Re-create the session state using the stored sessionState list.
*/
protected void recreateSessionState() {
if (sessionState != null && !sessionState.isEmpty()) {
sessionStateUpdating = true;
try {
for (String sql : sessionState) {
CommandInterface ci = prepareCommand(sql, Integer.MAX_VALUE);
ci.executeUpdate(false);
}
} finally {
sessionStateUpdating = false;
sessionStateChanged = false;
}
}
}
/**
* Read the session state if necessary.
*/
public void readSessionState() {
if (!sessionStateChanged || sessionStateUpdating) {
return;
}
sessionStateChanged = false;
sessionState = New.arrayList();
CommandInterface ci = prepareCommand(
"SELECT * FROM INFORMATION_SCHEMA.SESSION_STATE",
Integer.MAX_VALUE);
ResultInterface result = ci.executeQuery(0, false);
while (result.next()) {
Value[] row = result.currentRow();
sessionState.add(row[1].getString());
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/Setting.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.table.Table;
/**
* A persistent database setting.
*/
public class Setting extends DbObjectBase {
private int intValue;
private String stringValue;
public Setting(Database database, int id, String settingName) {
initDbObjectBase(database, id, settingName, Trace.SETTING);
}
public void setIntValue(int value) {
intValue = value;
}
public int getIntValue() {
return intValue;
}
public void setStringValue(String value) {
stringValue = value;
}
public String getStringValue() {
return stringValue;
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getDropSQL() {
return null;
}
@Override
public String getCreateSQL() {
StringBuilder buff = new StringBuilder("SET ");
buff.append(getSQL()).append(' ');
if (stringValue != null) {
buff.append(stringValue);
} else {
buff.append(intValue);
}
return buff.toString();
}
@Override
public int getType() {
return DbObject.SETTING;
}
@Override
public void removeChildrenAndResources(Session session) {
database.removeMeta(session, getId());
invalidate();
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("RENAME");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SettingsBase.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.HashMap;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.util.Utils;
/**
* The base class for settings.
*/
public class SettingsBase {
private final HashMap<String, String> settings;
protected SettingsBase(HashMap<String, String> s) {
this.settings = s;
}
/**
* Get the setting for the given key.
*
* @param key the key
* @param defaultValue the default value
* @return the setting
*/
protected boolean get(String key, boolean defaultValue) {
String s = get(key, Boolean.toString(defaultValue));
try {
return Utils.parseBoolean(s, defaultValue, true);
} catch (IllegalArgumentException e) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1,
e, "key:" + key + " value:" + s);
}
}
/**
* Get the setting for the given key.
*
* @param key the key
* @param defaultValue the default value
* @return the setting
*/
protected int get(String key, int defaultValue) {
String s = get(key, "" + defaultValue);
try {
return Integer.decode(s);
} catch (NumberFormatException e) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1,
e, "key:" + key + " value:" + s);
}
}
/**
* Get the setting for the given key.
*
* @param key the key
* @param defaultValue the default value
* @return the setting
*/
protected String get(String key, String defaultValue) {
String v = settings.get(key);
if (v != null) {
return v;
}
StringBuilder buff = new StringBuilder("h2.");
boolean nextUpper = false;
for (char c : key.toCharArray()) {
if (c == '_') {
nextUpper = true;
} else {
// Character.toUpperCase / toLowerCase ignores the locale
buff.append(nextUpper ? Character.toUpperCase(c) : Character.toLowerCase(c));
nextUpper = false;
}
}
String sysProperty = buff.toString();
v = Utils.getProperty(sysProperty, defaultValue);
settings.put(key, v);
return v;
}
/**
* Check if the settings contains the given key.
*
* @param k the key
* @return true if they do
*/
protected boolean containsKey(String k) {
return settings.containsKey(k);
}
/**
* Get all settings.
*
* @return the settings
*/
public HashMap<String, String> getSettings() {
return settings;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/SysProperties.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.util.MathUtils;
import org.h2.util.Utils;
/**
* The constants defined in this class are initialized from system properties.
* Some system properties are per machine settings, and others are as a last
* resort and temporary solution to work around a problem in the application or
* database engine. Also, there are system properties to enable features that
* are not yet fully tested or that are not backward compatible.
* <p>
* System properties can be set when starting the virtual machine:
* </p>
*
* <pre>
* java -Dh2.baseDir=/temp
* </pre>
*
* They can be set within the application, but this must be done before loading
* any classes of this database (before loading the JDBC driver):
*
* <pre>
* System.setProperty("h2.baseDir", "/temp");
* </pre>
*/
public class SysProperties {
/**
* INTERNAL
*/
public static final String H2_SCRIPT_DIRECTORY = "h2.scriptDirectory";
/**
* INTERNAL
*/
public static final String H2_BROWSER = "h2.browser";
/**
* System property <code>file.encoding</code> (default: Cp1252).<br />
* It is usually set by the system and is the default encoding used for the
* RunScript and CSV tool.
*/
public static final String FILE_ENCODING =
Utils.getProperty("file.encoding", "Cp1252");
/**
* System property <code>file.separator</code> (default: /).<br />
* It is usually set by the system, and used to build absolute file names.
*/
public static final String FILE_SEPARATOR =
Utils.getProperty("file.separator", "/");
/**
* System property <code>line.separator</code> (default: \n).<br />
* It is usually set by the system, and used by the script and trace tools.
*/
public static final String LINE_SEPARATOR =
Utils.getProperty("line.separator", "\n");
/**
* System property <code>user.home</code> (empty string if not set).<br />
* It is usually set by the system, and used as a replacement for ~ in file
* names.
*/
public static final String USER_HOME =
Utils.getProperty("user.home", "");
/**
* System property <code>h2.allowedClasses</code> (default: *).<br />
* Comma separated list of class names or prefixes.
*/
public static final String ALLOWED_CLASSES =
Utils.getProperty("h2.allowedClasses", "*");
/**
* System property <code>h2.enableAnonymousTLS</code> (default: true).<br />
* When using TLS connection, the anonymous cipher suites should be enabled.
*/
public static final boolean ENABLE_ANONYMOUS_TLS =
Utils.getProperty("h2.enableAnonymousTLS", true);
/**
* System property <code>h2.bindAddress</code> (default: null).<br />
* The bind address to use.
*/
public static final String BIND_ADDRESS =
Utils.getProperty("h2.bindAddress", null);
/**
* System property <code>h2.check</code> (default: true).<br />
* Assertions in the database engine.
*/
//## CHECK ##
public static final boolean CHECK =
Utils.getProperty("h2.check", true);
/*/
public static final boolean CHECK = false;
//*/
/**
* System property <code>h2.check2</code> (default: false).<br />
* Additional assertions in the database engine.
*/
//## CHECK ##
public static final boolean CHECK2 =
Utils.getProperty("h2.check2", false);
/*/
public static final boolean CHECK2 = false;
//*/
/**
* System property <code>h2.clientTraceDirectory</code> (default:
* trace.db/).<br />
* Directory where the trace files of the JDBC client are stored (only for
* client / server).
*/
public static final String CLIENT_TRACE_DIRECTORY =
Utils.getProperty("h2.clientTraceDirectory", "trace.db/");
/**
* System property <code>h2.collatorCacheSize</code> (default: 32000).<br />
* The cache size for collation keys (in elements). Used when a collator has
* been set for the database.
*/
public static final int COLLATOR_CACHE_SIZE =
Utils.getProperty("h2.collatorCacheSize", 32_000);
/**
* System property <code>h2.consoleTableIndexes</code>
* (default: 100).<br />
* Up to this many tables, the column type and indexes are listed.
*/
public static final int CONSOLE_MAX_TABLES_LIST_INDEXES =
Utils.getProperty("h2.consoleTableIndexes", 100);
/**
* System property <code>h2.consoleTableColumns</code>
* (default: 500).<br />
* Up to this many tables, the column names are listed.
*/
public static final int CONSOLE_MAX_TABLES_LIST_COLUMNS =
Utils.getProperty("h2.consoleTableColumns", 500);
/**
* System property <code>h2.consoleProcedureColumns</code>
* (default: 500).<br />
* Up to this many procedures, the column names are listed.
*/
public static final int CONSOLE_MAX_PROCEDURES_LIST_COLUMNS =
Utils.getProperty("h2.consoleProcedureColumns", 300);
/**
* System property <code>h2.consoleStream</code> (default: true).<br />
* H2 Console: stream query results.
*/
public static final boolean CONSOLE_STREAM =
Utils.getProperty("h2.consoleStream", true);
/**
* System property <code>h2.consoleTimeout</code> (default: 1800000).<br />
* H2 Console: session timeout in milliseconds. The default is 30 minutes.
*/
public static final int CONSOLE_TIMEOUT =
Utils.getProperty("h2.consoleTimeout", 30 * 60 * 1000);
/**
* System property <code>h2.dataSourceTraceLevel</code> (default: 1).<br />
* The trace level of the data source implementation. Default is 1 for
* error.
*/
public static final int DATASOURCE_TRACE_LEVEL =
Utils.getProperty("h2.dataSourceTraceLevel", 1);
/**
* System property <code>h2.delayWrongPasswordMin</code>
* (default: 250).<br />
* The minimum delay in milliseconds before an exception is thrown for using
* the wrong user name or password. This slows down brute force attacks. The
* delay is reset to this value after a successful login. Unsuccessful
* logins will double the time until DELAY_WRONG_PASSWORD_MAX.
* To disable the delay, set this system property to 0.
*/
public static final int DELAY_WRONG_PASSWORD_MIN =
Utils.getProperty("h2.delayWrongPasswordMin", 250);
/**
* System property <code>h2.delayWrongPasswordMax</code>
* (default: 4000).<br />
* The maximum delay in milliseconds before an exception is thrown for using
* the wrong user name or password. This slows down brute force attacks. The
* delay is reset after a successful login. The value 0 means there is no
* maximum delay.
*/
public static final int DELAY_WRONG_PASSWORD_MAX =
Utils.getProperty("h2.delayWrongPasswordMax", 4000);
/**
* System property <code>h2.javaSystemCompiler</code> (default: true).<br />
* Whether to use the Java system compiler
* (ToolProvider.getSystemJavaCompiler()) if it is available to compile user
* defined functions. If disabled or if the system compiler is not
* available, the com.sun.tools.javac compiler is used if available, and
* "javac" (as an external process) is used if not.
*/
public static final boolean JAVA_SYSTEM_COMPILER =
Utils.getProperty("h2.javaSystemCompiler", true);
/**
* System property <code>h2.lobCloseBetweenReads</code>
* (default: false).<br />
* Close LOB files between read operations.
*/
public static boolean lobCloseBetweenReads =
Utils.getProperty("h2.lobCloseBetweenReads", false);
/**
* System property <code>h2.lobFilesPerDirectory</code>
* (default: 256).<br />
* Maximum number of LOB files per directory.
*/
public static final int LOB_FILES_PER_DIRECTORY =
Utils.getProperty("h2.lobFilesPerDirectory", 256);
/**
* System property <code>h2.lobClientMaxSizeMemory</code> (default:
* 1048576).<br />
* The maximum size of a LOB object to keep in memory on the client side
* when using the server mode.
*/
public static final int LOB_CLIENT_MAX_SIZE_MEMORY =
Utils.getProperty("h2.lobClientMaxSizeMemory", 1024 * 1024);
/**
* System property <code>h2.maxFileRetry</code> (default: 16).<br />
* Number of times to retry file delete and rename. in Windows, files can't
* be deleted if they are open. Waiting a bit can help (sometimes the
* Windows Explorer opens the files for a short time) may help. Sometimes,
* running garbage collection may close files if the user forgot to call
* Connection.close() or InputStream.close().
*/
public static final int MAX_FILE_RETRY =
Math.max(1, Utils.getProperty("h2.maxFileRetry", 16));
/**
* System property <code>h2.maxReconnect</code> (default: 3).<br />
* The maximum number of tries to reconnect in a row.
*/
public static final int MAX_RECONNECT =
Utils.getProperty("h2.maxReconnect", 3);
/**
* System property <code>h2.maxMemoryRows</code>
* (default: 40000 per GB of available RAM).<br />
* The default maximum number of rows to be kept in memory in a result set.
*/
public static final int MAX_MEMORY_ROWS =
getAutoScaledForMemoryProperty("h2.maxMemoryRows", 40_000);
/**
* System property <code>h2.maxTraceDataLength</code>
* (default: 65535).<br />
* The maximum size of a LOB value that is written as data to the trace
* system.
*/
public static final long MAX_TRACE_DATA_LENGTH =
Utils.getProperty("h2.maxTraceDataLength", 65535);
/**
* System property <code>h2.modifyOnWrite</code> (default: false).<br />
* Only modify the database file when recovery is necessary, or when writing
* to the database. If disabled, opening the database always writes to the
* file (except if the database is read-only). When enabled, the serialized
* file lock is faster.
*/
public static final boolean MODIFY_ON_WRITE =
Utils.getProperty("h2.modifyOnWrite", false);
/**
* System property <code>h2.nioLoadMapped</code> (default: false).<br />
* If the mapped buffer should be loaded when the file is opened.
* This can improve performance.
*/
public static final boolean NIO_LOAD_MAPPED =
Utils.getProperty("h2.nioLoadMapped", false);
/**
* System property <code>h2.nioCleanerHack</code> (default: false).<br />
* If enabled, use the reflection hack to un-map the mapped file if
* possible. If disabled, System.gc() is called in a loop until the object
* is garbage collected. See also
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4724038
*/
public static final boolean NIO_CLEANER_HACK =
Utils.getProperty("h2.nioCleanerHack", false);
/**
* System property <code>h2.objectCache</code> (default: true).<br />
* Cache commonly used values (numbers, strings). There is a shared cache
* for all values.
*/
public static final boolean OBJECT_CACHE =
Utils.getProperty("h2.objectCache", true);
/**
* System property <code>h2.objectCacheMaxPerElementSize</code> (default:
* 4096).<br />
* The maximum size (precision) of an object in the cache.
*/
public static final int OBJECT_CACHE_MAX_PER_ELEMENT_SIZE =
Utils.getProperty("h2.objectCacheMaxPerElementSize", 4096);
/**
* System property <code>h2.objectCacheSize</code> (default: 1024).<br />
* The maximum number of objects in the cache.
* This value must be a power of 2.
*/
public static final int OBJECT_CACHE_SIZE;
static {
try {
OBJECT_CACHE_SIZE = MathUtils.nextPowerOf2(
Utils.getProperty("h2.objectCacheSize", 1024));
} catch (IllegalArgumentException e) {
throw new IllegalStateException("Invalid h2.objectCacheSize", e);
}
}
/**
* System property <code>h2.oldStyleOuterJoin</code>
* (default: true for version 1.3, false for version 1.4).<br />
* Limited support for the old-style Oracle outer join with "(+)".
*/
public static final boolean OLD_STYLE_OUTER_JOIN =
Utils.getProperty("h2.oldStyleOuterJoin",
Constants.VERSION_MINOR < 4);
/**
* System property {@code h2.oldResultSetGetObject}, {@code true} by default.
* Return {@code Byte} and {@code Short} instead of {@code Integer} from
* {@code ResultSet#getObject(...)} for {@code TINYINT} and {@code SMALLINT}
* values.
*/
public static final boolean OLD_RESULT_SET_GET_OBJECT =
Utils.getProperty("h2.oldResultSetGetObject", true);
/**
* System property {@code h2.bigDecimalIsDecimal}, {@code true} by default. If
* {@code true} map {@code BigDecimal} to {@code DECIMAL} type, if {@code false}
* map it to {@code NUMERIC} as specified in JDBC specification (see Mapping
* from Java Object Types to JDBC Types).
*/
public static final boolean BIG_DECIMAL_IS_DECIMAL =
Utils.getProperty("h2.bigDecimalIsDecimal", true);
/**
* System property {@code h2.unlimitedTimeRange}, {@code false} by default.
*
* <p>
* Controls limits of TIME data type.
* </p>
*
* <table>
* <thead>
* <tr>
* <th>h2.unlimitedTimeRange</th>
* <th>Minimum TIME value</th>
* <th>Maximum TIME value</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td>false</td>
* <td>00:00:00.000000000</td>
* <td>23:59:59.999999999</td>
* </tr>
* <tr>
* <td>true</td>
* <td>-2562047:47:16.854775808</td>
* <td>2562047:47:16.854775807</td>
* </tr>
* </tbody>
* </table>
*/
public static final boolean UNLIMITED_TIME_RANGE =
Utils.getProperty("h2.unlimitedTimeRange", false);
/**
* System property <code>h2.pgClientEncoding</code> (default: UTF-8).<br />
* Default client encoding for PG server. It is used if the client does not
* sends his encoding.
*/
public static final String PG_DEFAULT_CLIENT_ENCODING =
Utils.getProperty("h2.pgClientEncoding", "UTF-8");
/**
* System property <code>h2.prefixTempFile</code> (default: h2.temp).<br />
* The prefix for temporary files in the temp directory.
*/
public static final String PREFIX_TEMP_FILE =
Utils.getProperty("h2.prefixTempFile", "h2.temp");
/**
* System property <code>h2.serverCachedObjects</code> (default: 64).<br />
* TCP Server: number of cached objects per session.
*/
public static final int SERVER_CACHED_OBJECTS =
Utils.getProperty("h2.serverCachedObjects", 64);
/**
* System property <code>h2.serverResultSetFetchSize</code>
* (default: 100).<br />
* The default result set fetch size when using the server mode.
*/
public static final int SERVER_RESULT_SET_FETCH_SIZE =
Utils.getProperty("h2.serverResultSetFetchSize", 100);
/**
* System property <code>h2.socketConnectRetry</code> (default: 16).<br />
* The number of times to retry opening a socket. Windows sometimes fails
* to open a socket, see bug
* http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213296
*/
public static final int SOCKET_CONNECT_RETRY =
Utils.getProperty("h2.socketConnectRetry", 16);
/**
* System property <code>h2.socketConnectTimeout</code>
* (default: 2000).<br />
* The timeout in milliseconds to connect to a server.
*/
public static final int SOCKET_CONNECT_TIMEOUT =
Utils.getProperty("h2.socketConnectTimeout", 2000);
/**
* System property <code>h2.sortBinaryUnsigned</code>
* (default: false with version 1.3, true with version 1.4).<br />
* Whether binary data should be sorted in unsigned mode
* (0xff is larger than 0x00).
*/
public static final boolean SORT_BINARY_UNSIGNED =
Utils.getProperty("h2.sortBinaryUnsigned",
Constants.VERSION_MINOR >= 4);
/**
* System property <code>h2.sortNullsHigh</code> (default: false).<br />
* Invert the default sorting behavior for NULL, such that NULL
* is at the end of a result set in an ascending sort and at
* the beginning of a result set in a descending sort.
*/
public static final boolean SORT_NULLS_HIGH =
Utils.getProperty("h2.sortNullsHigh", false);
/**
* System property <code>h2.splitFileSizeShift</code> (default: 30).<br />
* The maximum file size of a split file is 1L << x.
*/
public static final long SPLIT_FILE_SIZE_SHIFT =
Utils.getProperty("h2.splitFileSizeShift", 30);
/**
* System property <code>h2.syncMethod</code> (default: sync).<br />
* What method to call when closing the database, on checkpoint, and on
* CHECKPOINT SYNC. The following options are supported:
* "sync" (default): RandomAccessFile.getFD().sync();
* "force": RandomAccessFile.getChannel().force(true);
* "forceFalse": RandomAccessFile.getChannel().force(false);
* "": do not call a method (fast but there is a risk of data loss
* on power failure).
*/
public static final String SYNC_METHOD =
Utils.getProperty("h2.syncMethod", "sync");
/**
* System property <code>h2.traceIO</code> (default: false).<br />
* Trace all I/O operations.
*/
public static final boolean TRACE_IO =
Utils.getProperty("h2.traceIO", false);
/**
* System property <code>h2.threadDeadlockDetector</code>
* (default: false).<br />
* Detect thread deadlocks in a background thread.
*/
public static final boolean THREAD_DEADLOCK_DETECTOR =
Utils.getProperty("h2.threadDeadlockDetector", false);
/**
* System property <code>h2.implicitRelativePath</code>
* (default: true for version 1.3, false for version 1.4).<br />
* If disabled, relative paths in database URLs need to be written as
* jdbc:h2:./test instead of jdbc:h2:test.
*/
public static final boolean IMPLICIT_RELATIVE_PATH =
Utils.getProperty("h2.implicitRelativePath",
Constants.VERSION_MINOR < 4);
/**
* System property <code>h2.urlMap</code> (default: null).<br />
* A properties file that contains a mapping between database URLs. New
* connections are written into the file. An empty value in the map means no
* redirection is used for the given URL.
*/
public static final String URL_MAP =
Utils.getProperty("h2.urlMap", null);
/**
* System property <code>h2.useThreadContextClassLoader</code>
* (default: false).<br />
* Instead of using the default class loader when deserializing objects, the
* current thread-context class loader will be used.
*/
public static final boolean USE_THREAD_CONTEXT_CLASS_LOADER =
Utils.getProperty("h2.useThreadContextClassLoader", false);
/**
* System property <code>h2.serializeJavaObject</code>
* (default: true).<br />
* <b>If true</b>, values of type OTHER will be stored in serialized form
* and have the semantics of binary data for all operations (such as sorting
* and conversion to string).
* <br />
* <b>If false</b>, the objects will be serialized only for I/O operations
* and a few other special cases (for example when someone tries to get the
* value in binary form or when comparing objects that are not comparable
* otherwise).
* <br />
* If the object implements the Comparable interface, the method compareTo
* will be used for sorting (but only if objects being compared have a
* common comparable super type). Otherwise the objects will be compared by
* type, and if they are the same by hashCode, and if the hash codes are
* equal, but objects are not, the serialized forms (the byte arrays) are
* compared.
* <br />
* The string representation of the values use the toString method of
* object.
* <br />
* In client-server mode, the server must have all required classes in the
* class path. On the client side, this setting is required to be disabled
* as well, to have correct string representation and display size.
* <br />
* In embedded mode, no data copying occurs, so the user has to make
* defensive copy himself before storing, or ensure that the value object is
* immutable.
*/
public static boolean serializeJavaObject =
Utils.getProperty("h2.serializeJavaObject", true);
/**
* System property <code>h2.javaObjectSerializer</code>
* (default: null).<br />
* The JavaObjectSerializer class name for java objects being stored in
* column of type OTHER. It must be the same on client and server to work
* correctly.
*/
public static final String JAVA_OBJECT_SERIALIZER =
Utils.getProperty("h2.javaObjectSerializer", null);
/**
* System property <code>h2.customDataTypesHandler</code>
* (default: null).<br />
* The CustomDataTypesHandler class name that is used
* to provide support for user defined custom data types.
* It must be the same on client and server to work correctly.
*/
public static final String CUSTOM_DATA_TYPES_HANDLER =
Utils.getProperty("h2.customDataTypesHandler", null);
private static final String H2_BASE_DIR = "h2.baseDir";
private SysProperties() {
// utility class
}
/**
* INTERNAL
*/
public static void setBaseDir(String dir) {
if (!dir.endsWith("/")) {
dir += "/";
}
System.setProperty(H2_BASE_DIR, dir);
}
/**
* INTERNAL
*/
public static String getBaseDir() {
return Utils.getProperty(H2_BASE_DIR, null);
}
/**
* System property <code>h2.scriptDirectory</code> (default: empty
* string).<br />
* Relative or absolute directory where the script files are stored to or
* read from.
*
* @return the current value
*/
public static String getScriptDirectory() {
return Utils.getProperty(H2_SCRIPT_DIRECTORY, "");
}
/**
* This method attempts to auto-scale some of our properties to take
* advantage of more powerful machines out of the box. We assume that our
* default properties are set correctly for approx. 1G of memory, and scale
* them up if we have more.
*/
private static int getAutoScaledForMemoryProperty(String key, int defaultValue) {
String s = Utils.getProperty(key, null);
if (s != null) {
try {
return Integer.decode(s).intValue();
} catch (NumberFormatException e) {
// ignore
}
}
return Utils.scaleForAvailableMemory(defaultValue);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/UndoLog.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import java.util.HashMap;
import org.h2.message.DbException;
import org.h2.store.Data;
import org.h2.store.FileStore;
import org.h2.table.Table;
import org.h2.util.New;
/**
* Each session keeps a undo log if rollback is required.
*/
public class UndoLog {
private final Database database;
private final ArrayList<Long> storedEntriesPos = New.arrayList();
private final ArrayList<UndoLogRecord> records = New.arrayList();
private FileStore file;
private Data rowBuff;
private int memoryUndo;
private int storedEntries;
private HashMap<Integer, Table> tables;
private final boolean largeTransactions;
/**
* Create a new undo log for the given session.
*
* @param session the session
*/
UndoLog(Session session) {
this.database = session.getDatabase();
largeTransactions = database.getSettings().largeTransactions;
}
/**
* Get the number of active rows in this undo log.
*
* @return the number of rows
*/
int size() {
if (largeTransactions) {
return storedEntries + records.size();
}
if (SysProperties.CHECK && memoryUndo > records.size()) {
DbException.throwInternalError();
}
return records.size();
}
/**
* Clear the undo log. This method is called after the transaction is
* committed.
*/
void clear() {
records.clear();
storedEntries = 0;
storedEntriesPos.clear();
memoryUndo = 0;
if (file != null) {
file.closeAndDeleteSilently();
file = null;
rowBuff = null;
}
}
/**
* Get the last record and remove it from the list of operations.
*
* @return the last record
*/
public UndoLogRecord getLast() {
int i = records.size() - 1;
if (largeTransactions) {
if (i < 0 && storedEntries > 0) {
int last = storedEntriesPos.size() - 1;
long pos = storedEntriesPos.remove(last);
long end = file.length();
int bufferLength = (int) (end - pos);
Data buff = Data.create(database, bufferLength);
file.seek(pos);
file.readFully(buff.getBytes(), 0, bufferLength);
while (buff.length() < bufferLength) {
UndoLogRecord e = UndoLogRecord.loadFromBuffer(buff, this);
records.add(e);
memoryUndo++;
}
storedEntries -= records.size();
file.setLength(pos);
file.seek(pos);
}
i = records.size() - 1;
}
UndoLogRecord entry = records.get(i);
if (entry.isStored()) {
int start = Math.max(0, i - database.getMaxMemoryUndo() / 2);
UndoLogRecord first = null;
for (int j = start; j <= i; j++) {
UndoLogRecord e = records.get(j);
if (e.isStored()) {
e.load(rowBuff, file, this);
memoryUndo++;
if (first == null) {
first = e;
}
}
}
for (int k = 0; k < i; k++) {
UndoLogRecord e = records.get(k);
e.invalidatePos();
}
seek(first.getFilePos());
}
return entry;
}
/**
* Go to the right position in the file.
*
* @param filePos the position in the file
*/
void seek(long filePos) {
file.seek(filePos * Constants.FILE_BLOCK_SIZE);
}
/**
* Remove the last record from the list of operations.
*
* @param trimToSize if the undo array should shrink to conserve memory
*/
void removeLast(boolean trimToSize) {
int i = records.size() - 1;
UndoLogRecord r = records.remove(i);
if (!r.isStored()) {
memoryUndo--;
}
if (trimToSize && i > 1024 && (i & 1023) == 0) {
records.trimToSize();
}
}
/**
* Append an undo log entry to the log.
*
* @param entry the entry
*/
void add(UndoLogRecord entry) {
records.add(entry);
if (largeTransactions) {
memoryUndo++;
if (memoryUndo > database.getMaxMemoryUndo() &&
database.isPersistent() &&
!database.isMultiVersion()) {
if (file == null) {
String fileName = database.createTempFile();
file = database.openFile(fileName, "rw", false);
file.setCheckedWriting(false);
file.setLength(FileStore.HEADER_LENGTH);
}
Data buff = Data.create(database, Constants.DEFAULT_PAGE_SIZE);
for (int i = 0; i < records.size(); i++) {
UndoLogRecord r = records.get(i);
buff.checkCapacity(Constants.DEFAULT_PAGE_SIZE);
r.append(buff, this);
if (i == records.size() - 1 || buff.length() > Constants.UNDO_BLOCK_SIZE) {
storedEntriesPos.add(file.getFilePointer());
file.write(buff.getBytes(), 0, buff.length());
buff.reset();
}
}
storedEntries += records.size();
memoryUndo = 0;
records.clear();
file.autoDelete();
}
} else {
if (!entry.isStored()) {
memoryUndo++;
}
if (memoryUndo > database.getMaxMemoryUndo() &&
database.isPersistent() &&
!database.isMultiVersion()) {
if (file == null) {
String fileName = database.createTempFile();
file = database.openFile(fileName, "rw", false);
file.setCheckedWriting(false);
file.seek(FileStore.HEADER_LENGTH);
rowBuff = Data.create(database, Constants.DEFAULT_PAGE_SIZE);
Data buff = rowBuff;
for (UndoLogRecord r : records) {
saveIfPossible(r, buff);
}
} else {
saveIfPossible(entry, rowBuff);
}
file.autoDelete();
}
}
}
private void saveIfPossible(UndoLogRecord r, Data buff) {
if (!r.isStored() && r.canStore()) {
r.save(buff, file, this);
memoryUndo--;
}
}
/**
* Get the table id for this undo log. If the table is not registered yet,
* this is done as well.
*
* @param table the table
* @return the id
*/
int getTableId(Table table) {
int id = table.getId();
if (tables == null) {
tables = new HashMap<>();
}
// need to overwrite the old entry, because the old object
// might be deleted in the meantime
tables.put(id, table);
return id;
}
/**
* Get the table for this id. The table must be registered for this undo log
* first by calling getTableId.
*
* @param id the table id
* @return the table object
*/
Table getTable(int id) {
return tables.get(id);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/UndoLogRecord.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.store.Data;
import org.h2.store.FileStore;
import org.h2.table.Table;
import org.h2.value.Value;
/**
* An entry in a undo log.
*/
public class UndoLogRecord {
/**
* Operation type meaning the row was inserted.
*/
public static final short INSERT = 0;
/**
* Operation type meaning the row was deleted.
*/
public static final short DELETE = 1;
private static final int IN_MEMORY = 0, STORED = 1, IN_MEMORY_INVALID = 2;
private Table table;
private Row row;
private short operation;
private short state;
private int filePos;
/**
* Create a new undo log record
*
* @param table the table
* @param op the operation type
* @param row the row that was deleted or inserted
*/
UndoLogRecord(Table table, short op, Row row) {
this.table = table;
this.row = row;
this.operation = op;
this.state = IN_MEMORY;
}
/**
* Check if the log record is stored in the file.
*
* @return true if it is
*/
boolean isStored() {
return state == STORED;
}
/**
* Check if this undo log record can be store. Only record can be stored if
* the table has a unique index.
*
* @return if it can be stored
*/
boolean canStore() {
// if large transactions are enabled, this method is not called
return table.getUniqueIndex() != null;
}
/**
* Un-do the operation. If the row was inserted before, it is deleted now,
* and vice versa.
*
* @param session the session
*/
void undo(Session session) {
Database db = session.getDatabase();
switch (operation) {
case INSERT:
if (state == IN_MEMORY_INVALID) {
state = IN_MEMORY;
}
if (db.getLockMode() == Constants.LOCK_MODE_OFF) {
if (row.isDeleted()) {
// it might have been deleted by another thread
return;
}
}
try {
row.setDeleted(false);
table.removeRow(session, row);
table.fireAfterRow(session, row, null, true);
} catch (DbException e) {
if (session.getDatabase().getLockMode() == Constants.LOCK_MODE_OFF
&& e.getErrorCode() == ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1) {
// it might have been deleted by another thread
// ignore
} else {
throw e;
}
}
break;
case DELETE:
try {
table.addRow(session, row);
table.fireAfterRow(session, null, row, true);
// reset session id, otherwise other sessions think
// that this row was inserted by this session
row.commit();
} catch (DbException e) {
if (session.getDatabase().getLockMode() == Constants.LOCK_MODE_OFF
&& e.getSQLException().getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
// it might have been added by another thread
// ignore
} else {
throw e;
}
}
break;
default:
DbException.throwInternalError("op=" + operation);
}
}
/**
* Append the row to the buffer.
*
* @param buff the buffer
* @param log the undo log
*/
void append(Data buff, UndoLog log) {
int p = buff.length();
buff.writeInt(0);
buff.writeInt(operation);
buff.writeByte(row.isDeleted() ? (byte) 1 : (byte) 0);
buff.writeInt(log.getTableId(table));
buff.writeLong(row.getKey());
buff.writeInt(row.getSessionId());
int count = row.getColumnCount();
buff.writeInt(count);
for (int i = 0; i < count; i++) {
Value v = row.getValue(i);
buff.checkCapacity(buff.getValueLen(v));
buff.writeValue(v);
}
buff.fillAligned();
buff.setInt(p, (buff.length() - p) / Constants.FILE_BLOCK_SIZE);
}
/**
* Save the row in the file using a buffer.
*
* @param buff the buffer
* @param file the file
* @param log the undo log
*/
void save(Data buff, FileStore file, UndoLog log) {
buff.reset();
append(buff, log);
filePos = (int) (file.getFilePointer() / Constants.FILE_BLOCK_SIZE);
file.write(buff.getBytes(), 0, buff.length());
row = null;
state = STORED;
}
/**
* Load an undo log record row using a buffer.
*
* @param buff the buffer
* @param log the log
* @return the undo log record
*/
static UndoLogRecord loadFromBuffer(Data buff, UndoLog log) {
UndoLogRecord rec = new UndoLogRecord(null, (short) 0, null);
int pos = buff.length();
int len = buff.readInt() * Constants.FILE_BLOCK_SIZE;
rec.load(buff, log);
buff.setPos(pos + len);
return rec;
}
/**
* Load an undo log record row using a buffer.
*
* @param buff the buffer
* @param file the source file
* @param log the log
*/
void load(Data buff, FileStore file, UndoLog log) {
int min = Constants.FILE_BLOCK_SIZE;
log.seek(filePos);
buff.reset();
file.readFully(buff.getBytes(), 0, min);
int len = buff.readInt() * Constants.FILE_BLOCK_SIZE;
buff.checkCapacity(len);
if (len - min > 0) {
file.readFully(buff.getBytes(), min, len - min);
}
int oldOp = operation;
load(buff, log);
if (SysProperties.CHECK) {
if (operation != oldOp) {
DbException.throwInternalError("operation=" + operation + " op=" + oldOp);
}
}
}
private void load(Data buff, UndoLog log) {
operation = (short) buff.readInt();
boolean deleted = buff.readByte() == 1;
table = log.getTable(buff.readInt());
long key = buff.readLong();
int sessionId = buff.readInt();
int columnCount = buff.readInt();
Value[] values = new Value[columnCount];
for (int i = 0; i < columnCount; i++) {
values[i] = buff.readValue();
}
row = getTable().getDatabase().createRow(values, Row.MEMORY_CALCULATE);
row.setKey(key);
row.setDeleted(deleted);
row.setSessionId(sessionId);
state = IN_MEMORY_INVALID;
}
/**
* Get the table.
*
* @return the table
*/
public Table getTable() {
return table;
}
/**
* Get the position in the file.
*
* @return the file position
*/
public long getFilePos() {
return filePos;
}
/**
* This method is called after the operation was committed.
* It commits the change to the indexes.
*/
void commit() {
table.commit(operation, row);
}
/**
* Get the row that was deleted or inserted.
*
* @return the row
*/
public Row getRow() {
return row;
}
/**
* Change the state from IN_MEMORY to IN_MEMORY_INVALID. This method is
* called if a later record was read from the temporary file, and therefore
* the position could have changed.
*/
void invalidatePos() {
if (this.state == IN_MEMORY) {
state = IN_MEMORY_INVALID;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/User.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.util.ArrayList;
import java.util.Arrays;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.schema.Schema;
import org.h2.security.SHA256;
import org.h2.table.MetaTable;
import org.h2.table.RangeTable;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.table.TableView;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* Represents a user object.
*/
public class User extends RightOwner {
private final boolean systemUser;
private byte[] salt;
private byte[] passwordHash;
private boolean admin;
public User(Database database, int id, String userName, boolean systemUser) {
super(database, id, userName, Trace.USER);
this.systemUser = systemUser;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public boolean isAdmin() {
return admin;
}
/**
* Set the salt and hash of the password for this user.
*
* @param salt the salt
* @param hash the password hash
*/
public void setSaltAndHash(byte[] salt, byte[] hash) {
this.salt = salt;
this.passwordHash = hash;
}
/**
* Set the user name password hash. A random salt is generated as well.
* The parameter is filled with zeros after use.
*
* @param userPasswordHash the user name password hash
*/
public void setUserPasswordHash(byte[] userPasswordHash) {
if (userPasswordHash != null) {
if (userPasswordHash.length == 0) {
salt = passwordHash = userPasswordHash;
} else {
salt = new byte[Constants.SALT_LEN];
MathUtils.randomBytes(salt);
passwordHash = SHA256.getHashWithSalt(userPasswordHash, salt);
}
}
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getCreateSQL() {
return getCreateSQL(true);
}
@Override
public String getDropSQL() {
return null;
}
/**
* Checks that this user has the given rights for this database object.
*
* @param table the database object
* @param rightMask the rights required
* @throws DbException if this user does not have the required rights
*/
public void checkRight(Table table, int rightMask) {
if (!hasRight(table, rightMask)) {
throw DbException.get(ErrorCode.NOT_ENOUGH_RIGHTS_FOR_1, table.getSQL());
}
}
/**
* See if this user has the given rights for this database object.
*
* @param table the database object, or null for schema-only check
* @param rightMask the rights required
* @return true if the user has the rights
*/
public boolean hasRight(Table table, int rightMask) {
if (rightMask != Right.SELECT && !systemUser && table != null) {
table.checkWritingAllowed();
}
if (admin) {
return true;
}
Role publicRole = database.getPublicRole();
if (publicRole.isRightGrantedRecursive(table, rightMask)) {
return true;
}
if (table instanceof MetaTable || table instanceof RangeTable) {
// everybody has access to the metadata information
return true;
}
if (table != null) {
if (hasRight(null, Right.ALTER_ANY_SCHEMA)) {
return true;
}
TableType tableType = table.getTableType();
if (TableType.VIEW == tableType) {
TableView v = (TableView) table;
if (v.getOwner() == this) {
// the owner of a view has access:
// SELECT * FROM (SELECT * FROM ...)
return true;
}
} else if (tableType == null) {
// function table
return true;
}
if (table.isTemporary() && !table.isGlobalTemporary()) {
// the owner has all rights on local temporary tables
return true;
}
}
return isRightGrantedRecursive(table, rightMask);
}
/**
* Get the CREATE SQL statement for this object.
*
* @param password true if the password (actually the salt and hash) should
* be returned
* @return the SQL statement
*/
public String getCreateSQL(boolean password) {
StringBuilder buff = new StringBuilder("CREATE USER IF NOT EXISTS ");
buff.append(getSQL());
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
if (password) {
buff.append(" SALT '").
append(StringUtils.convertBytesToHex(salt)).
append("' HASH '").
append(StringUtils.convertBytesToHex(passwordHash)).
append('\'');
} else {
buff.append(" PASSWORD ''");
}
if (admin) {
buff.append(" ADMIN");
}
return buff.toString();
}
/**
* Check the password of this user.
*
* @param userPasswordHash the password data (the user password hash)
* @return true if the user password hash is correct
*/
boolean validateUserPasswordHash(byte[] userPasswordHash) {
if (userPasswordHash.length == 0 && passwordHash.length == 0) {
return true;
}
if (userPasswordHash.length == 0) {
userPasswordHash = SHA256.getKeyPasswordHash(getName(), new char[0]);
}
byte[] hash = SHA256.getHashWithSalt(userPasswordHash, salt);
return Utils.compareSecure(hash, passwordHash);
}
/**
* Check if this user has admin rights. An exception is thrown if he does
* not have them.
*
* @throws DbException if this user is not an admin
*/
public void checkAdmin() {
if (!admin) {
throw DbException.get(ErrorCode.ADMIN_RIGHTS_REQUIRED);
}
}
/**
* Check if this user has schema admin rights. An exception is thrown if he
* does not have them.
*
* @throws DbException if this user is not a schema admin
*/
public void checkSchemaAdmin() {
if (!hasRight(null, Right.ALTER_ANY_SCHEMA)) {
throw DbException.get(ErrorCode.ADMIN_RIGHTS_REQUIRED);
}
}
@Override
public int getType() {
return DbObject.USER;
}
@Override
public ArrayList<DbObject> getChildren() {
ArrayList<DbObject> children = New.arrayList();
for (Right right : database.getAllRights()) {
if (right.getGrantee() == this) {
children.add(right);
}
}
for (Schema schema : database.getAllSchemas()) {
if (schema.getOwner() == this) {
children.add(schema);
}
}
return children;
}
@Override
public void removeChildrenAndResources(Session session) {
for (Right right : database.getAllRights()) {
if (right.getGrantee() == this) {
database.removeDatabaseObject(session, right);
}
}
database.removeMeta(session, getId());
salt = null;
Arrays.fill(passwordHash, (byte) 0);
passwordHash = null;
invalidate();
}
@Override
public void checkRename() {
// ok
}
/**
* Check that this user does not own any schema. An exception is thrown if
* he owns one or more schemas.
*
* @throws DbException if this user owns a schema
*/
public void checkOwnsNoSchemas() {
for (Schema s : database.getAllSchemas()) {
if (this == s.getOwner()) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, getName(), s.getName());
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/UserAggregate.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import java.sql.Connection;
import java.sql.SQLException;
import org.h2.api.Aggregate;
import org.h2.api.AggregateFunction;
import org.h2.command.Parser;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.table.Table;
import org.h2.util.JdbcUtils;
import org.h2.value.DataType;
/**
* Represents a user-defined aggregate function.
*/
public class UserAggregate extends DbObjectBase {
private String className;
private Class<?> javaClass;
public UserAggregate(Database db, int id, String name, String className,
boolean force) {
initDbObjectBase(db, id, name, Trace.FUNCTION);
this.className = className;
if (!force) {
getInstance();
}
}
public Aggregate getInstance() {
if (javaClass == null) {
javaClass = JdbcUtils.loadUserClass(className);
}
Object obj;
try {
obj = javaClass.newInstance();
Aggregate agg;
if (obj instanceof Aggregate) {
agg = (Aggregate) obj;
} else {
agg = new AggregateWrapper((AggregateFunction) obj);
}
return agg;
} catch (Exception e) {
throw DbException.convert(e);
}
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getDropSQL() {
return "DROP AGGREGATE IF EXISTS " + getSQL();
}
@Override
public String getCreateSQL() {
return "CREATE FORCE AGGREGATE " + getSQL() +
" FOR " + Parser.quoteIdentifier(className);
}
@Override
public int getType() {
return DbObject.AGGREGATE;
}
@Override
public synchronized void removeChildrenAndResources(Session session) {
database.removeMeta(session, getId());
className = null;
javaClass = null;
invalidate();
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("AGGREGATE");
}
public String getJavaClassName() {
return this.className;
}
/**
* Wrap {@link AggregateFunction} in order to behave as
* {@link org.h2.api.Aggregate}
**/
private static class AggregateWrapper implements Aggregate {
private final AggregateFunction aggregateFunction;
AggregateWrapper(AggregateFunction aggregateFunction) {
this.aggregateFunction = aggregateFunction;
}
@Override
public void init(Connection conn) throws SQLException {
aggregateFunction.init(conn);
}
@Override
public int getInternalType(int[] inputTypes) throws SQLException {
int[] sqlTypes = new int[inputTypes.length];
for (int i = 0; i < inputTypes.length; i++) {
sqlTypes[i] = DataType.convertTypeToSQLType(inputTypes[i]);
}
return DataType.convertSQLTypeToValueType(aggregateFunction.getType(sqlTypes));
}
@Override
public void add(Object value) throws SQLException {
aggregateFunction.add(value);
}
@Override
public Object getResult() throws SQLException {
return aggregateFunction.getResult();
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/engine/UserDataType.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.engine;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.table.Column;
import org.h2.table.Table;
/**
* Represents a domain (user-defined data type).
*/
public class UserDataType extends DbObjectBase {
private Column column;
public UserDataType(Database database, int id, String name) {
initDbObjectBase(database, id, name, Trace.DATABASE);
}
@Override
public String getCreateSQLForCopy(Table table, String quotedName) {
throw DbException.throwInternalError(toString());
}
@Override
public String getDropSQL() {
return "DROP DOMAIN IF EXISTS " + getSQL();
}
@Override
public String getCreateSQL() {
return "CREATE DOMAIN " + getSQL() + " AS " + column.getCreateSQL();
}
public Column getColumn() {
return column;
}
@Override
public int getType() {
return DbObject.USER_DATATYPE;
}
@Override
public void removeChildrenAndResources(Session session) {
database.removeMeta(session, getId());
}
@Override
public void checkRename() {
// ok
}
public void setColumn(Column column) {
this.column = column;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Aggregate.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import org.h2.api.ErrorCode;
import org.h2.command.dml.Select;
import org.h2.command.dml.SelectOrderBy;
import org.h2.engine.Session;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueDouble;
import org.h2.value.ValueInt;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* Implements the integrated aggregate functions, such as COUNT, MAX, SUM.
*/
public class Aggregate extends Expression {
public enum AggregateType {
/**
* The aggregate type for COUNT(*).
*/
COUNT_ALL,
/**
* The aggregate type for COUNT(expression).
*/
COUNT,
/**
* The aggregate type for GROUP_CONCAT(...).
*/
GROUP_CONCAT,
/**
* The aggregate type for SUM(expression).
*/
SUM,
/**
* The aggregate type for MIN(expression).
*/
MIN,
/**
* The aggregate type for MAX(expression).
*/
MAX,
/**
* The aggregate type for AVG(expression).
*/
AVG,
/**
* The aggregate type for STDDEV_POP(expression).
*/
STDDEV_POP,
/**
* The aggregate type for STDDEV_SAMP(expression).
*/
STDDEV_SAMP,
/**
* The aggregate type for VAR_POP(expression).
*/
VAR_POP,
/**
* The aggregate type for VAR_SAMP(expression).
*/
VAR_SAMP,
/**
* The aggregate type for BOOL_OR(expression).
*/
BOOL_OR,
/**
* The aggregate type for BOOL_AND(expression).
*/
BOOL_AND,
/**
* The aggregate type for BOOL_OR(expression).
*/
BIT_OR,
/**
* The aggregate type for BOOL_AND(expression).
*/
BIT_AND,
/**
* The aggregate type for SELECTIVITY(expression).
*/
SELECTIVITY,
/**
* The aggregate type for HISTOGRAM(expression).
*/
HISTOGRAM,
/**
* The aggregate type for MEDIAN(expression).
*/
MEDIAN,
/**
* The aggregate type for ARRAY_AGG(expression).
*/
ARRAY_AGG
}
private static final HashMap<String, AggregateType> AGGREGATES = new HashMap<>(26);
private final AggregateType type;
private final Select select;
private final boolean distinct;
private Expression on;
private Expression groupConcatSeparator;
private ArrayList<SelectOrderBy> groupConcatOrderList;
private ArrayList<SelectOrderBy> arrayAggOrderList;
private SortOrder groupConcatSort;
private SortOrder arrayOrderSort;
private int dataType, scale;
private long precision;
private int displaySize;
private int lastGroupRowId;
private Expression filterCondition;
/**
* Create a new aggregate object.
*
* @param type the aggregate type
* @param on the aggregated expression
* @param select the select statement
* @param distinct if distinct is used
*/
public Aggregate(AggregateType type, Expression on, Select select, boolean distinct) {
this.type = type;
this.on = on;
this.select = select;
this.distinct = distinct;
}
static {
/*
* Update initial size of AGGREGATES after editing the following list.
*/
addAggregate("COUNT", AggregateType.COUNT);
addAggregate("SUM", AggregateType.SUM);
addAggregate("MIN", AggregateType.MIN);
addAggregate("MAX", AggregateType.MAX);
addAggregate("AVG", AggregateType.AVG);
addAggregate("GROUP_CONCAT", AggregateType.GROUP_CONCAT);
// PostgreSQL compatibility: string_agg(expression, delimiter)
addAggregate("STRING_AGG", AggregateType.GROUP_CONCAT);
addAggregate("STDDEV_SAMP", AggregateType.STDDEV_SAMP);
addAggregate("STDDEV", AggregateType.STDDEV_SAMP);
addAggregate("STDDEV_POP", AggregateType.STDDEV_POP);
addAggregate("STDDEVP", AggregateType.STDDEV_POP);
addAggregate("VAR_POP", AggregateType.VAR_POP);
addAggregate("VARP", AggregateType.VAR_POP);
addAggregate("VAR_SAMP", AggregateType.VAR_SAMP);
addAggregate("VAR", AggregateType.VAR_SAMP);
addAggregate("VARIANCE", AggregateType.VAR_SAMP);
addAggregate("BOOL_OR", AggregateType.BOOL_OR);
// HSQLDB compatibility, but conflicts with x > EVERY(...)
addAggregate("SOME", AggregateType.BOOL_OR);
addAggregate("BOOL_AND", AggregateType.BOOL_AND);
// HSQLDB compatibility, but conflicts with x > SOME(...)
addAggregate("EVERY", AggregateType.BOOL_AND);
addAggregate("SELECTIVITY", AggregateType.SELECTIVITY);
addAggregate("HISTOGRAM", AggregateType.HISTOGRAM);
addAggregate("BIT_OR", AggregateType.BIT_OR);
addAggregate("BIT_AND", AggregateType.BIT_AND);
addAggregate("MEDIAN", AggregateType.MEDIAN);
addAggregate("ARRAY_AGG", AggregateType.ARRAY_AGG);
}
private static void addAggregate(String name, AggregateType type) {
AGGREGATES.put(name, type);
}
/**
* Get the aggregate type for this name, or -1 if no aggregate has been
* found.
*
* @param name the aggregate function name
* @return null if no aggregate function has been found, or the aggregate type
*/
public static AggregateType getAggregateType(String name) {
return AGGREGATES.get(name);
}
/**
* Set the order for GROUP_CONCAT() aggregate.
*
* @param orderBy the order by list
*/
public void setGroupConcatOrder(ArrayList<SelectOrderBy> orderBy) {
this.groupConcatOrderList = orderBy;
}
/**
* Set the order for ARRAY_AGG() aggregate.
*
* @param orderBy the order by list
*/
public void setArrayAggOrder(ArrayList<SelectOrderBy> orderBy) {
this.arrayAggOrderList = orderBy;
}
/**
* Set the separator for the GROUP_CONCAT() aggregate.
*
* @param separator the separator expression
*/
public void setGroupConcatSeparator(Expression separator) {
this.groupConcatSeparator = separator;
}
/**
* Sets the FILTER condition.
*
* @param filterCondition condition
*/
public void setFilterCondition(Expression filterCondition) {
this.filterCondition = filterCondition;
}
private SortOrder initOrder(ArrayList<SelectOrderBy> orderList, Session session) {
int size = orderList.size();
int[] index = new int[size];
int[] sortType = new int[size];
for (int i = 0; i < size; i++) {
SelectOrderBy o = orderList.get(i);
index[i] = i + 1;
int order = o.descending ? SortOrder.DESCENDING : SortOrder.ASCENDING;
sortType[i] = order;
}
return new SortOrder(session.getDatabase(), index, sortType, null);
}
@Override
public void updateAggregate(Session session) {
// TODO aggregates: check nested MIN(MAX(ID)) and so on
// if (on != null) {
// on.updateAggregate();
// }
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
// this is a different level (the enclosing query)
return;
}
int groupRowId = select.getCurrentGroupRowId();
if (lastGroupRowId == groupRowId) {
// already visited
return;
}
lastGroupRowId = groupRowId;
AggregateData data = (AggregateData) group.get(this);
if (data == null) {
data = AggregateData.create(type);
group.put(this, data);
}
Value v = on == null ? null : on.getValue(session);
if (type == AggregateType.GROUP_CONCAT) {
if (v != ValueNull.INSTANCE) {
v = v.convertTo(Value.STRING);
if (groupConcatOrderList != null) {
int size = groupConcatOrderList.size();
Value[] array = new Value[1 + size];
array[0] = v;
for (int i = 0; i < size; i++) {
SelectOrderBy o = groupConcatOrderList.get(i);
array[i + 1] = o.expression.getValue(session);
}
v = ValueArray.get(array);
}
}
}
if (type == AggregateType.ARRAY_AGG) {
if (v != ValueNull.INSTANCE) {
if (arrayAggOrderList != null) {
int size = arrayAggOrderList.size();
Value[] array = new Value[1 + size];
array[0] = v;
for (int i = 0; i < size; i++) {
SelectOrderBy o = arrayAggOrderList.get(i);
array[i + 1] = o.expression.getValue(session);
}
v = ValueArray.get(array);
}
}
}
if (filterCondition != null) {
if (!filterCondition.getBooleanValue(session)) {
return;
}
}
data.add(session.getDatabase(), dataType, distinct, v);
}
@Override
public Value getValue(Session session) {
if (select.isQuickAggregateQuery()) {
switch (type) {
case COUNT:
case COUNT_ALL:
Table table = select.getTopTableFilter().getTable();
return ValueLong.get(table.getRowCount(session));
case MIN:
case MAX: {
boolean first = type == AggregateType.MIN;
Index index = getMinMaxColumnIndex();
int sortType = index.getIndexColumns()[0].sortType;
if ((sortType & SortOrder.DESCENDING) != 0) {
first = !first;
}
Cursor cursor = index.findFirstOrLast(session, first);
SearchRow row = cursor.getSearchRow();
Value v;
if (row == null) {
v = ValueNull.INSTANCE;
} else {
v = row.getValue(index.getColumns()[0].getColumnId());
}
return v;
}
case MEDIAN: {
return AggregateDataMedian.getResultFromIndex(session, on, dataType);
}
default:
DbException.throwInternalError("type=" + type);
}
}
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getSQL());
}
AggregateData data = (AggregateData) group.get(this);
if (data == null) {
data = AggregateData.create(type);
}
Value v = data.getValue(session.getDatabase(), dataType, distinct);
if (type == AggregateType.GROUP_CONCAT) {
ArrayList<Value> list = ((AggregateDataArrayCollecting) data).getList();
if (list == null || list.isEmpty()) {
return ValueNull.INSTANCE;
}
if (groupConcatOrderList != null) {
final SortOrder sortOrder = groupConcatSort;
Collections.sort(list, new Comparator<Value>() {
@Override
public int compare(Value v1, Value v2) {
Value[] a1 = ((ValueArray) v1).getList();
Value[] a2 = ((ValueArray) v2).getList();
return sortOrder.compare(a1, a2);
}
});
}
StatementBuilder buff = new StatementBuilder();
String sep = groupConcatSeparator == null ?
"," : groupConcatSeparator.getValue(session).getString();
for (Value val : list) {
String s;
if (val.getType() == Value.ARRAY) {
s = ((ValueArray) val).getList()[0].getString();
} else {
s = val.getString();
}
if (s == null) {
continue;
}
if (sep != null) {
buff.appendExceptFirst(sep);
}
buff.append(s);
}
v = ValueString.get(buff.toString());
} else if (type == AggregateType.ARRAY_AGG) {
ArrayList<Value> list = ((AggregateDataArrayCollecting) data).getList();
if (list == null || list.isEmpty()) {
return ValueNull.INSTANCE;
}
if (arrayAggOrderList != null) {
final SortOrder sortOrder = arrayOrderSort;
Collections.sort(list, new Comparator<Value>() {
@Override
public int compare(Value v1, Value v2) {
Value[] a1 = ((ValueArray) v1).getList();
Value[] a2 = ((ValueArray) v2).getList();
return sortOrder.compare(a1, a2);
}
});
}
v = ValueArray.get(list.toArray(new Value[list.size()]));
}
return v;
}
@Override
public int getType() {
return dataType;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
if (on != null) {
on.mapColumns(resolver, level);
}
if (groupConcatOrderList != null) {
for (SelectOrderBy o : groupConcatOrderList) {
o.expression.mapColumns(resolver, level);
}
}
if (arrayAggOrderList != null) {
for (SelectOrderBy o : arrayAggOrderList) {
o.expression.mapColumns(resolver, level);
}
}
if (groupConcatSeparator != null) {
groupConcatSeparator.mapColumns(resolver, level);
}
if (filterCondition != null) {
filterCondition.mapColumns(resolver, level);
}
}
@Override
public Expression optimize(Session session) {
if (on != null) {
on = on.optimize(session);
dataType = on.getType();
scale = on.getScale();
precision = on.getPrecision();
displaySize = on.getDisplaySize();
}
if (groupConcatOrderList != null) {
for (SelectOrderBy o : groupConcatOrderList) {
o.expression = o.expression.optimize(session);
}
groupConcatSort = initOrder(groupConcatOrderList, session);
}
if (arrayAggOrderList != null) {
for (SelectOrderBy o : arrayAggOrderList) {
o.expression = o.expression.optimize(session);
}
arrayOrderSort = initOrder(arrayAggOrderList, session);
}
if (groupConcatSeparator != null) {
groupConcatSeparator = groupConcatSeparator.optimize(session);
}
if (filterCondition != null) {
filterCondition = filterCondition.optimize(session);
}
switch (type) {
case GROUP_CONCAT:
dataType = Value.STRING;
scale = 0;
precision = displaySize = Integer.MAX_VALUE;
break;
case COUNT_ALL:
case COUNT:
dataType = Value.LONG;
scale = 0;
precision = ValueLong.PRECISION;
displaySize = ValueLong.DISPLAY_SIZE;
break;
case SELECTIVITY:
dataType = Value.INT;
scale = 0;
precision = ValueInt.PRECISION;
displaySize = ValueInt.DISPLAY_SIZE;
break;
case HISTOGRAM:
dataType = Value.ARRAY;
scale = 0;
precision = displaySize = Integer.MAX_VALUE;
break;
case SUM:
if (dataType == Value.BOOLEAN) {
// example: sum(id > 3) (count the rows)
dataType = Value.LONG;
} else if (!DataType.supportsAdd(dataType)) {
throw DbException.get(ErrorCode.SUM_OR_AVG_ON_WRONG_DATATYPE_1, getSQL());
} else {
dataType = DataType.getAddProofType(dataType);
}
break;
case AVG:
if (!DataType.supportsAdd(dataType)) {
throw DbException.get(ErrorCode.SUM_OR_AVG_ON_WRONG_DATATYPE_1, getSQL());
}
break;
case MIN:
case MAX:
case MEDIAN:
break;
case STDDEV_POP:
case STDDEV_SAMP:
case VAR_POP:
case VAR_SAMP:
dataType = Value.DOUBLE;
precision = ValueDouble.PRECISION;
displaySize = ValueDouble.DISPLAY_SIZE;
scale = 0;
break;
case BOOL_AND:
case BOOL_OR:
dataType = Value.BOOLEAN;
precision = ValueBoolean.PRECISION;
displaySize = ValueBoolean.DISPLAY_SIZE;
scale = 0;
break;
case BIT_AND:
case BIT_OR:
if (!DataType.supportsAdd(dataType)) {
throw DbException.get(ErrorCode.SUM_OR_AVG_ON_WRONG_DATATYPE_1, getSQL());
}
break;
case ARRAY_AGG:
dataType = Value.ARRAY;
scale = 0;
precision = displaySize = Integer.MAX_VALUE;
break;
default:
DbException.throwInternalError("type=" + type);
}
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
if (on != null) {
on.setEvaluatable(tableFilter, b);
}
if (groupConcatOrderList != null) {
for (SelectOrderBy o : groupConcatOrderList) {
o.expression.setEvaluatable(tableFilter, b);
}
}
if (arrayAggOrderList != null) {
for (SelectOrderBy o : arrayAggOrderList) {
o.expression.setEvaluatable(tableFilter, b);
}
}
if (groupConcatSeparator != null) {
groupConcatSeparator.setEvaluatable(tableFilter, b);
}
if (filterCondition != null) {
filterCondition.setEvaluatable(tableFilter, b);
}
}
@Override
public int getScale() {
return scale;
}
@Override
public long getPrecision() {
return precision;
}
@Override
public int getDisplaySize() {
return displaySize;
}
private String getSQLGroupConcat() {
StatementBuilder buff = new StatementBuilder("GROUP_CONCAT(");
if (distinct) {
buff.append("DISTINCT ");
}
buff.append(on.getSQL());
if (groupConcatOrderList != null) {
buff.append(" ORDER BY ");
for (SelectOrderBy o : groupConcatOrderList) {
buff.appendExceptFirst(", ");
buff.append(o.expression.getSQL());
if (o.descending) {
buff.append(" DESC");
}
}
}
if (groupConcatSeparator != null) {
buff.append(" SEPARATOR ").append(groupConcatSeparator.getSQL());
}
buff.append(')');
if (filterCondition != null) {
buff.append(" FILTER (WHERE ").append(filterCondition.getSQL()).append(')');
}
return buff.toString();
}
private String getSQLArrayAggregate() {
StatementBuilder buff = new StatementBuilder("ARRAY_AGG(");
if (distinct) {
buff.append("DISTINCT ");
}
buff.append(on.getSQL());
if (arrayAggOrderList != null) {
buff.append(" ORDER BY ");
for (SelectOrderBy o : arrayAggOrderList) {
buff.appendExceptFirst(", ");
buff.append(o.expression.getSQL());
if (o.descending) {
buff.append(" DESC");
}
}
}
buff.append(')');
if (filterCondition != null) {
buff.append(" FILTER (WHERE ").append(filterCondition.getSQL()).append(')');
}
return buff.toString();
}
@Override
public String getSQL() {
String text;
switch (type) {
case GROUP_CONCAT:
return getSQLGroupConcat();
case COUNT_ALL:
return "COUNT(*)";
case COUNT:
text = "COUNT";
break;
case SELECTIVITY:
text = "SELECTIVITY";
break;
case HISTOGRAM:
text = "HISTOGRAM";
break;
case SUM:
text = "SUM";
break;
case MIN:
text = "MIN";
break;
case MAX:
text = "MAX";
break;
case AVG:
text = "AVG";
break;
case STDDEV_POP:
text = "STDDEV_POP";
break;
case STDDEV_SAMP:
text = "STDDEV_SAMP";
break;
case VAR_POP:
text = "VAR_POP";
break;
case VAR_SAMP:
text = "VAR_SAMP";
break;
case BOOL_AND:
text = "BOOL_AND";
break;
case BOOL_OR:
text = "BOOL_OR";
break;
case BIT_AND:
text = "BIT_AND";
break;
case BIT_OR:
text = "BIT_OR";
break;
case MEDIAN:
text = "MEDIAN";
break;
case ARRAY_AGG:
return getSQLArrayAggregate();
default:
throw DbException.throwInternalError("type=" + type);
}
if (distinct) {
text += "(DISTINCT " + on.getSQL() + ')';
} else {
text += StringUtils.enclose(on.getSQL());
}
if (filterCondition != null) {
text += " FILTER (WHERE " + filterCondition.getSQL() + ')';
}
return text;
}
private Index getMinMaxColumnIndex() {
if (on instanceof ExpressionColumn) {
ExpressionColumn col = (ExpressionColumn) on;
Column column = col.getColumn();
TableFilter filter = col.getTableFilter();
if (filter != null) {
Table table = filter.getTable();
return table.getIndexForColumn(column, true, false);
}
}
return null;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
if (filterCondition != null && !filterCondition.isEverything(visitor)) {
return false;
}
if (visitor.getType() == ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL) {
switch (type) {
case COUNT:
if (!distinct && on.getNullable() == Column.NOT_NULLABLE) {
return visitor.getTable().canGetRowCount();
}
return false;
case COUNT_ALL:
return visitor.getTable().canGetRowCount();
case MIN:
case MAX:
Index index = getMinMaxColumnIndex();
return index != null;
case MEDIAN:
if (distinct) {
return false;
}
return AggregateDataMedian.getMedianColumnIndex(on) != null;
default:
return false;
}
}
if (on != null && !on.isEverything(visitor)) {
return false;
}
if (groupConcatSeparator != null &&
!groupConcatSeparator.isEverything(visitor)) {
return false;
}
if (groupConcatOrderList != null) {
for (SelectOrderBy o : groupConcatOrderList) {
if (!o.expression.isEverything(visitor)) {
return false;
}
}
}
if (arrayAggOrderList != null) {
for (SelectOrderBy o : arrayAggOrderList) {
if (!o.expression.isEverything(visitor)) {
return false;
}
}
}
return true;
}
@Override
public int getCost() {
int cost = 1;
if (on != null) {
cost += on.getCost();
}
if (filterCondition != null) {
cost += filterCondition.getCost();
}
return cost;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateData.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Database;
import org.h2.expression.Aggregate.AggregateType;
import org.h2.value.Value;
/**
* Abstract class for the computation of an aggregate.
*/
abstract class AggregateData {
/**
* Create an AggregateData object of the correct sub-type.
*
* @param aggregateType the type of the aggregate operation
* @return the aggregate data object of the specified type
*/
static AggregateData create(AggregateType aggregateType) {
if (aggregateType == AggregateType.SELECTIVITY) {
return new AggregateDataSelectivity();
} else if (aggregateType == AggregateType.GROUP_CONCAT) {
return new AggregateDataArrayCollecting();
} else if (aggregateType == AggregateType.ARRAY_AGG) {
return new AggregateDataArrayCollecting();
} else if (aggregateType == AggregateType.COUNT_ALL) {
return new AggregateDataCountAll();
} else if (aggregateType == AggregateType.COUNT) {
return new AggregateDataCount();
} else if (aggregateType == AggregateType.HISTOGRAM) {
return new AggregateDataHistogram();
} else if (aggregateType == AggregateType.MEDIAN) {
return new AggregateDataMedian();
} else {
return new AggregateDataDefault(aggregateType);
}
}
/**
* Add a value to this aggregate.
*
* @param database the database
* @param dataType the datatype of the computed result
* @param distinct if the calculation should be distinct
* @param v the value
*/
abstract void add(Database database, int dataType, boolean distinct, Value v);
/**
* Get the aggregate result.
*
* @param database the database
* @param dataType the datatype of the computed result
* @param distinct if distinct is used
* @return the value
*/
abstract Value getValue(Database database, int dataType, boolean distinct);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataArrayCollecting.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import org.h2.engine.Database;
import org.h2.util.New;
import org.h2.util.ValueHashMap;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* Data stored while calculating a GROUP_CONCAT/ARRAY_AGG aggregate.
*/
class AggregateDataArrayCollecting extends AggregateData {
private ArrayList<Value> list;
private ValueHashMap<AggregateDataArrayCollecting> distinctValues;
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (v == ValueNull.INSTANCE) {
return;
}
if (distinct) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
return;
}
if (list == null) {
list = New.arrayList();
}
list.add(v);
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
distinct(database, dataType);
}
return null;
}
ArrayList<Value> getList() {
return list;
}
private void distinct(Database database, int dataType) {
if (distinctValues == null) {
return;
}
for (Value v : distinctValues.keys()) {
add(database, dataType, false, v);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataCount.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Database;
import org.h2.util.ValueHashMap;
import org.h2.value.Value;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
/**
* Data stored while calculating an aggregate.
*/
class AggregateDataCount extends AggregateData {
private long count;
private ValueHashMap<AggregateDataCount> distinctValues;
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (v == ValueNull.INSTANCE) {
return;
}
count++;
if (distinct) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
}
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
if (distinctValues != null) {
count = distinctValues.size();
} else {
count = 0;
}
}
Value v = ValueLong.get(count);
return v.convertTo(dataType);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataCountAll.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Database;
import org.h2.message.DbException;
import org.h2.value.Value;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
/**
* Data stored while calculating a COUNT(*) aggregate.
*/
class AggregateDataCountAll extends AggregateData {
private long count;
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (distinct) {
throw DbException.throwInternalError();
}
count++;
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
throw DbException.throwInternalError();
}
Value v = ValueLong.get(count);
return v == null ? ValueNull.INSTANCE : v.convertTo(dataType);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataDefault.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Database;
import org.h2.expression.Aggregate.AggregateType;
import org.h2.message.DbException;
import org.h2.util.ValueHashMap;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueDouble;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
/**
* Data stored while calculating an aggregate.
*/
class AggregateDataDefault extends AggregateData {
private final AggregateType aggregateType;
private long count;
private ValueHashMap<AggregateDataDefault> distinctValues;
private Value value;
private double m2, mean;
/**
* @param aggregateType the type of the aggregate operation
*/
AggregateDataDefault(AggregateType aggregateType) {
this.aggregateType = aggregateType;
}
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (v == ValueNull.INSTANCE) {
return;
}
count++;
if (distinct) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
distinctValues.put(v, this);
return;
}
switch (aggregateType) {
case SUM:
if (value == null) {
value = v.convertTo(dataType);
} else {
v = v.convertTo(value.getType());
value = value.add(v);
}
break;
case AVG:
if (value == null) {
value = v.convertTo(DataType.getAddProofType(dataType));
} else {
v = v.convertTo(value.getType());
value = value.add(v);
}
break;
case MIN:
if (value == null || database.compare(v, value) < 0) {
value = v;
}
break;
case MAX:
if (value == null || database.compare(v, value) > 0) {
value = v;
}
break;
case STDDEV_POP:
case STDDEV_SAMP:
case VAR_POP:
case VAR_SAMP: {
// Using Welford's method, see also
// http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
// http://www.johndcook.com/standard_deviation.html
double x = v.getDouble();
if (count == 1) {
mean = x;
m2 = 0;
} else {
double delta = x - mean;
mean += delta / count;
m2 += delta * (x - mean);
}
break;
}
case BOOL_AND:
v = v.convertTo(Value.BOOLEAN);
if (value == null) {
value = v;
} else {
value = ValueBoolean.get(value.getBoolean() && v.getBoolean());
}
break;
case BOOL_OR:
v = v.convertTo(Value.BOOLEAN);
if (value == null) {
value = v;
} else {
value = ValueBoolean.get(value.getBoolean() || v.getBoolean());
}
break;
case BIT_AND:
if (value == null) {
value = v.convertTo(dataType);
} else {
value = ValueLong.get(value.getLong() & v.getLong()).convertTo(dataType);
}
break;
case BIT_OR:
if (value == null) {
value = v.convertTo(dataType);
} else {
value = ValueLong.get(value.getLong() | v.getLong()).convertTo(dataType);
}
break;
default:
DbException.throwInternalError("type=" + aggregateType);
}
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
count = 0;
groupDistinct(database, dataType);
}
Value v = null;
switch (aggregateType) {
case SUM:
case MIN:
case MAX:
case BIT_OR:
case BIT_AND:
case BOOL_OR:
case BOOL_AND:
v = value;
break;
case AVG:
if (value != null) {
v = divide(value, count);
}
break;
case STDDEV_POP: {
if (count < 1) {
return ValueNull.INSTANCE;
}
v = ValueDouble.get(Math.sqrt(m2 / count));
break;
}
case STDDEV_SAMP: {
if (count < 2) {
return ValueNull.INSTANCE;
}
v = ValueDouble.get(Math.sqrt(m2 / (count - 1)));
break;
}
case VAR_POP: {
if (count < 1) {
return ValueNull.INSTANCE;
}
v = ValueDouble.get(m2 / count);
break;
}
case VAR_SAMP: {
if (count < 2) {
return ValueNull.INSTANCE;
}
v = ValueDouble.get(m2 / (count - 1));
break;
}
default:
DbException.throwInternalError("type=" + aggregateType);
}
return v == null ? ValueNull.INSTANCE : v.convertTo(dataType);
}
private static Value divide(Value a, long by) {
if (by == 0) {
return ValueNull.INSTANCE;
}
int type = Value.getHigherOrder(a.getType(), Value.LONG);
Value b = ValueLong.get(by).convertTo(type);
a = a.convertTo(type).divide(b);
return a;
}
private void groupDistinct(Database database, int dataType) {
if (distinctValues == null) {
return;
}
count = 0;
for (Value v : distinctValues.keys()) {
add(database, dataType, false, v);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataHistogram.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.Arrays;
import java.util.Comparator;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.util.ValueHashMap;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueLong;
/**
* Data stored while calculating a HISTOGRAM aggregate.
*/
class AggregateDataHistogram extends AggregateData {
private long count;
private ValueHashMap<AggregateDataHistogram> distinctValues;
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (distinctValues == null) {
distinctValues = ValueHashMap.newInstance();
}
AggregateDataHistogram a = distinctValues.get(v);
if (a == null) {
if (distinctValues.size() < Constants.SELECTIVITY_DISTINCT_COUNT) {
a = new AggregateDataHistogram();
distinctValues.put(v, a);
}
}
if (a != null) {
a.count++;
}
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
count = 0;
groupDistinct(database, dataType);
}
ValueArray[] values = new ValueArray[distinctValues.size()];
int i = 0;
for (Value dv : distinctValues.keys()) {
AggregateDataHistogram d = distinctValues.get(dv);
values[i] = ValueArray.get(new Value[] { dv, ValueLong.get(d.count) });
i++;
}
final CompareMode compareMode = database.getCompareMode();
Arrays.sort(values, new Comparator<ValueArray>() {
@Override
public int compare(ValueArray v1, ValueArray v2) {
Value a1 = v1.getList()[0];
Value a2 = v2.getList()[0];
return a1.compareTo(a2, compareMode);
}
});
Value v = ValueArray.get(values);
return v.convertTo(dataType);
}
private void groupDistinct(Database database, int dataType) {
if (distinctValues == null) {
return;
}
count = 0;
for (Value v : distinctValues.keys()) {
add(database, dataType, false, v);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataMedian.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashSet;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.DateTimeUtils;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueDate;
import org.h2.value.ValueDecimal;
import org.h2.value.ValueDouble;
import org.h2.value.ValueFloat;
import org.h2.value.ValueInt;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* Data stored while calculating a MEDIAN aggregate.
*/
class AggregateDataMedian extends AggregateData {
private Collection<Value> values;
private static boolean isNullsLast(Index index) {
IndexColumn ic = index.getIndexColumns()[0];
int sortType = ic.sortType;
return (sortType & SortOrder.NULLS_LAST) != 0
|| (sortType & SortOrder.DESCENDING) != 0 && (sortType & SortOrder.NULLS_FIRST) == 0;
}
/**
* Get the index (if any) for the column specified in the median aggregate.
*
* @param on the expression (usually a column expression)
* @return the index, or null
*/
static Index getMedianColumnIndex(Expression on) {
if (on instanceof ExpressionColumn) {
ExpressionColumn col = (ExpressionColumn) on;
Column column = col.getColumn();
TableFilter filter = col.getTableFilter();
if (filter != null) {
Table table = filter.getTable();
ArrayList<Index> indexes = table.getIndexes();
Index result = null;
if (indexes != null) {
boolean nullable = column.isNullable();
for (int i = 1, size = indexes.size(); i < size; i++) {
Index index = indexes.get(i);
if (!index.canFindNext()) {
continue;
}
if (!index.isFirstColumn(column)) {
continue;
}
// Prefer index without nulls last for nullable columns
if (result == null || result.getColumns().length > index.getColumns().length
|| nullable && isNullsLast(result) && !isNullsLast(index)) {
result = index;
}
}
}
return result;
}
}
return null;
}
/**
* Get the result from the index.
*
* @param session the session
* @param on the expression
* @param dataType the data type
* @return the result
*/
static Value getResultFromIndex(Session session, Expression on, int dataType) {
Index index = getMedianColumnIndex(on);
long count = index.getRowCount(session);
if (count == 0) {
return ValueNull.INSTANCE;
}
Cursor cursor = index.find(session, null, null);
cursor.next();
int columnId = index.getColumns()[0].getColumnId();
ExpressionColumn expr = (ExpressionColumn) on;
if (expr.getColumn().isNullable()) {
boolean hasNulls = false;
SearchRow row;
// Try to skip nulls from the start first with the same cursor that
// will be used to read values.
while (count > 0) {
row = cursor.getSearchRow();
if (row == null) {
return ValueNull.INSTANCE;
}
if (row.getValue(columnId) == ValueNull.INSTANCE) {
count--;
cursor.next();
hasNulls = true;
} else {
break;
}
}
if (count == 0) {
return ValueNull.INSTANCE;
}
// If no nulls found and if index orders nulls last create a second
// cursor to count nulls at the end.
if (!hasNulls && isNullsLast(index)) {
TableFilter tableFilter = expr.getTableFilter();
SearchRow check = tableFilter.getTable().getTemplateSimpleRow(true);
check.setValue(columnId, ValueNull.INSTANCE);
Cursor nullsCursor = index.find(session, check, check);
while (nullsCursor.next()) {
count--;
}
if (count <= 0) {
return ValueNull.INSTANCE;
}
}
}
long skip = (count - 1) / 2;
for (int i = 0; i < skip; i++) {
cursor.next();
}
SearchRow row = cursor.getSearchRow();
if (row == null) {
return ValueNull.INSTANCE;
}
Value v = row.getValue(columnId);
if (v == ValueNull.INSTANCE) {
return v;
}
if ((count & 1) == 0) {
cursor.next();
row = cursor.getSearchRow();
if (row == null) {
return v;
}
Value v2 = row.getValue(columnId);
if (v2 == ValueNull.INSTANCE) {
return v;
}
return getMedian(v, v2, dataType, session.getDatabase().getCompareMode());
}
return v;
}
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
if (v == ValueNull.INSTANCE) {
return;
}
Collection<Value> c = values;
if (c == null) {
values = c = distinct ? new HashSet<Value>() : new ArrayList<Value>();
}
c.add(v);
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
Collection<Value> c = values;
// Non-null collection cannot be empty here
if (c == null) {
return ValueNull.INSTANCE;
}
if (distinct && c instanceof ArrayList) {
c = new HashSet<>(c);
}
Value[] a = c.toArray(new Value[0]);
final CompareMode mode = database.getCompareMode();
Arrays.sort(a, new Comparator<Value>() {
@Override
public int compare(Value o1, Value o2) {
return o1.compareTo(o2, mode);
}
});
int len = a.length;
int idx = len / 2;
Value v1 = a[idx];
if ((len & 1) == 1) {
return v1.convertTo(dataType);
}
return getMedian(a[idx - 1], v1, dataType, mode);
}
private static Value getMedian(Value v0, Value v1, int dataType, CompareMode mode) {
if (v0.compareTo(v1, mode) == 0) {
return v0.convertTo(dataType);
}
switch (dataType) {
case Value.BYTE:
case Value.SHORT:
case Value.INT:
return ValueInt.get((v0.getInt() + v1.getInt()) / 2).convertTo(dataType);
case Value.LONG:
return ValueLong.get((v0.getLong() + v1.getLong()) / 2);
case Value.DECIMAL:
return ValueDecimal.get(v0.getBigDecimal().add(v1.getBigDecimal()).divide(BigDecimal.valueOf(2)));
case Value.FLOAT:
return ValueFloat.get((v0.getFloat() + v1.getFloat()) / 2);
case Value.DOUBLE:
return ValueDouble.get((v0.getFloat() + v1.getDouble()) / 2);
case Value.TIME: {
ValueTime t0 = (ValueTime) v0.convertTo(Value.TIME), t1 = (ValueTime) v1.convertTo(Value.TIME);
return ValueTime.fromNanos((t0.getNanos() + t1.getNanos()) / 2);
}
case Value.DATE: {
ValueDate d0 = (ValueDate) v0.convertTo(Value.DATE), d1 = (ValueDate) v1.convertTo(Value.DATE);
return ValueDate.fromDateValue(
DateTimeUtils.dateValueFromAbsoluteDay((DateTimeUtils.absoluteDayFromDateValue(d0.getDateValue())
+ DateTimeUtils.absoluteDayFromDateValue(d1.getDateValue())) / 2));
}
case Value.TIMESTAMP: {
ValueTimestamp ts0 = (ValueTimestamp) v0.convertTo(Value.TIMESTAMP),
ts1 = (ValueTimestamp) v1.convertTo(Value.TIMESTAMP);
long dateSum = DateTimeUtils.absoluteDayFromDateValue(ts0.getDateValue())
+ DateTimeUtils.absoluteDayFromDateValue(ts1.getDateValue());
long nanos = (ts0.getTimeNanos() + ts1.getTimeNanos()) / 2;
if ((dateSum & 1) != 0) {
nanos += DateTimeUtils.NANOS_PER_DAY / 2;
if (nanos >= DateTimeUtils.NANOS_PER_DAY) {
nanos -= DateTimeUtils.NANOS_PER_DAY;
dateSum++;
}
}
return ValueTimestamp.fromDateValueAndNanos(DateTimeUtils.dateValueFromAbsoluteDay(dateSum / 2), nanos);
}
case Value.TIMESTAMP_TZ: {
ValueTimestampTimeZone ts0 = (ValueTimestampTimeZone) v0.convertTo(Value.TIMESTAMP_TZ),
ts1 = (ValueTimestampTimeZone) v1.convertTo(Value.TIMESTAMP_TZ);
long dateSum = DateTimeUtils.absoluteDayFromDateValue(ts0.getDateValue())
+ DateTimeUtils.absoluteDayFromDateValue(ts1.getDateValue());
long nanos = (ts0.getTimeNanos() + ts1.getTimeNanos()) / 2;
int offset = ts0.getTimeZoneOffsetMins() + ts1.getTimeZoneOffsetMins();
if ((dateSum & 1) != 0) {
nanos += DateTimeUtils.NANOS_PER_DAY / 2;
}
if ((offset & 1) != 0) {
nanos += 30_000_000_000L;
}
if (nanos >= DateTimeUtils.NANOS_PER_DAY) {
nanos -= DateTimeUtils.NANOS_PER_DAY;
dateSum++;
}
return ValueTimestampTimeZone.fromDateValueAndNanos(DateTimeUtils.dateValueFromAbsoluteDay(dateSum / 2),
nanos, (short) (offset / 2));
}
default:
// Just return first
return v0.convertTo(dataType);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/AggregateDataSelectivity.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.util.IntIntHashMap;
import org.h2.value.Value;
import org.h2.value.ValueInt;
/**
* Data stored while calculating a SELECTIVITY aggregate.
*/
class AggregateDataSelectivity extends AggregateData {
private long count;
private IntIntHashMap distinctHashes;
private double m2;
@Override
void add(Database database, int dataType, boolean distinct, Value v) {
count++;
if (distinctHashes == null) {
distinctHashes = new IntIntHashMap();
}
int size = distinctHashes.size();
if (size > Constants.SELECTIVITY_DISTINCT_COUNT) {
distinctHashes = new IntIntHashMap();
m2 += size;
}
int hash = v.hashCode();
// the value -1 is not supported
distinctHashes.put(hash, 1);
}
@Override
Value getValue(Database database, int dataType, boolean distinct) {
if (distinct) {
count = 0;
}
Value v = null;
int s = 0;
if (count == 0) {
s = 0;
} else {
m2 += distinctHashes.size();
m2 = 100 * m2 / count;
s = (int) m2;
s = s <= 0 ? 1 : s > 100 ? 100 : s;
}
v = ValueInt.get(s);
return v.convertTo(dataType);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Alias.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.command.Parser;
import org.h2.engine.Session;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
/**
* A column alias as in SELECT 'Hello' AS NAME ...
*/
public class Alias extends Expression {
private final String alias;
private Expression expr;
private final boolean aliasColumnName;
public Alias(Expression expression, String alias, boolean aliasColumnName) {
this.expr = expression;
this.alias = alias;
this.aliasColumnName = aliasColumnName;
}
@Override
public Expression getNonAliasExpression() {
return expr;
}
@Override
public Value getValue(Session session) {
return expr.getValue(session);
}
@Override
public int getType() {
return expr.getType();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
expr.mapColumns(resolver, level);
}
@Override
public Expression optimize(Session session) {
expr = expr.optimize(session);
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
expr.setEvaluatable(tableFilter, b);
}
@Override
public int getScale() {
return expr.getScale();
}
@Override
public long getPrecision() {
return expr.getPrecision();
}
@Override
public int getDisplaySize() {
return expr.getDisplaySize();
}
@Override
public boolean isAutoIncrement() {
return expr.isAutoIncrement();
}
@Override
public String getSQL() {
return expr.getSQL() + " AS " + Parser.quoteIdentifier(alias);
}
@Override
public void updateAggregate(Session session) {
expr.updateAggregate(session);
}
@Override
public String getAlias() {
return alias;
}
@Override
public int getNullable() {
return expr.getNullable();
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return expr.isEverything(visitor);
}
@Override
public int getCost() {
return expr.getCost();
}
@Override
public String getTableName() {
if (aliasColumnName) {
return super.getTableName();
}
return expr.getTableName();
}
@Override
public String getColumnName() {
if (!(expr instanceof ExpressionColumn) || aliasColumnName) {
return super.getColumnName();
}
return expr.getColumnName();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/CompareLike.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.h2.api.ErrorCode;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.CompareMode;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* Pattern matching comparison expression: WHERE NAME LIKE ?
*/
public class CompareLike extends Condition {
private static final int MATCH = 0, ONE = 1, ANY = 2;
private final CompareMode compareMode;
private final String defaultEscape;
private Expression left;
private Expression right;
private Expression escape;
private boolean isInit;
private char[] patternChars;
private String patternString;
/** one of MATCH / ONE / ANY */
private int[] patternTypes;
private int patternLength;
private final boolean regexp;
private Pattern patternRegexp;
private boolean ignoreCase;
private boolean fastCompare;
private boolean invalidPattern;
/** indicates that we can shortcut the comparison and use startsWith */
private boolean shortcutToStartsWith;
/** indicates that we can shortcut the comparison and use endsWith */
private boolean shortcutToEndsWith;
/** indicates that we can shortcut the comparison and use contains */
private boolean shortcutToContains;
public CompareLike(Database db, Expression left, Expression right,
Expression escape, boolean regexp) {
this(db.getCompareMode(), db.getSettings().defaultEscape, left, right,
escape, regexp);
}
public CompareLike(CompareMode compareMode, String defaultEscape,
Expression left, Expression right, Expression escape, boolean regexp) {
this.compareMode = compareMode;
this.defaultEscape = defaultEscape;
this.regexp = regexp;
this.left = left;
this.right = right;
this.escape = escape;
}
private static Character getEscapeChar(String s) {
return s == null || s.length() == 0 ? null : s.charAt(0);
}
@Override
public String getSQL() {
String sql;
if (regexp) {
sql = left.getSQL() + " REGEXP " + right.getSQL();
} else {
sql = left.getSQL() + " LIKE " + right.getSQL();
if (escape != null) {
sql += " ESCAPE " + escape.getSQL();
}
}
return "(" + sql + ")";
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
right = right.optimize(session);
if (left.getType() == Value.STRING_IGNORECASE) {
ignoreCase = true;
}
if (left.isValueSet()) {
Value l = left.getValue(session);
if (l == ValueNull.INSTANCE) {
// NULL LIKE something > NULL
return ValueExpression.getNull();
}
}
if (escape != null) {
escape = escape.optimize(session);
}
if (right.isValueSet() && (escape == null || escape.isValueSet())) {
if (left.isValueSet()) {
return ValueExpression.get(getValue(session));
}
Value r = right.getValue(session);
if (r == ValueNull.INSTANCE) {
// something LIKE NULL > NULL
return ValueExpression.getNull();
}
Value e = escape == null ? null : escape.getValue(session);
if (e == ValueNull.INSTANCE) {
return ValueExpression.getNull();
}
String p = r.getString();
initPattern(p, getEscapeChar(e));
if (invalidPattern) {
return ValueExpression.getNull();
}
if ("%".equals(p)) {
// optimization for X LIKE '%': convert to X IS NOT NULL
return new Comparison(session,
Comparison.IS_NOT_NULL, left, null).optimize(session);
}
if (isFullMatch()) {
// optimization for X LIKE 'Hello': convert to X = 'Hello'
Value value = ValueString.get(patternString);
Expression expr = ValueExpression.get(value);
return new Comparison(session,
Comparison.EQUAL, left, expr).optimize(session);
}
isInit = true;
}
return this;
}
private Character getEscapeChar(Value e) {
if (e == null) {
return getEscapeChar(defaultEscape);
}
String es = e.getString();
Character esc;
if (es == null) {
esc = getEscapeChar(defaultEscape);
} else if (es.length() == 0) {
esc = null;
} else if (es.length() > 1) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, es);
} else {
esc = es.charAt(0);
}
return esc;
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (regexp) {
return;
}
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
// parameters are always evaluatable, but
// we need to check if the value is set
// (at prepare time)
// otherwise we would need to prepare at execute time,
// which may be slower (possibly not in this case)
if (!right.isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) {
return;
}
if (escape != null &&
!escape.isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) {
return;
}
String p = right.getValue(session).getString();
if (!isInit) {
Value e = escape == null ? null : escape.getValue(session);
if (e == ValueNull.INSTANCE) {
// should already be optimized
DbException.throwInternalError();
}
initPattern(p, getEscapeChar(e));
}
if (invalidPattern) {
return;
}
if (patternLength <= 0 || patternTypes[0] != MATCH) {
// can't use an index
return;
}
int dataType = l.getColumn().getType();
if (dataType != Value.STRING && dataType != Value.STRING_IGNORECASE &&
dataType != Value.STRING_FIXED) {
// column is not a varchar - can't use the index
return;
}
// Get the MATCH prefix and see if we can create an index condition from
// that.
int maxMatch = 0;
StringBuilder buff = new StringBuilder();
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
buff.append(patternChars[maxMatch++]);
}
String begin = buff.toString();
if (maxMatch == patternLength) {
filter.addIndexCondition(IndexCondition.get(Comparison.EQUAL, l,
ValueExpression.get(ValueString.get(begin))));
} else {
// TODO check if this is correct according to Unicode rules
// (code points)
String end;
if (begin.length() > 0) {
filter.addIndexCondition(IndexCondition.get(
Comparison.BIGGER_EQUAL, l,
ValueExpression.get(ValueString.get(begin))));
char next = begin.charAt(begin.length() - 1);
// search the 'next' unicode character (or at least a character
// that is higher)
for (int i = 1; i < 2000; i++) {
end = begin.substring(0, begin.length() - 1) + (char) (next + i);
if (compareMode.compareString(begin, end, ignoreCase) == -1) {
filter.addIndexCondition(IndexCondition.get(
Comparison.SMALLER, l,
ValueExpression.get(ValueString.get(end))));
break;
}
}
}
}
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session);
if (l == ValueNull.INSTANCE) {
return l;
}
if (!isInit) {
Value r = right.getValue(session);
if (r == ValueNull.INSTANCE) {
return r;
}
String p = r.getString();
Value e = escape == null ? null : escape.getValue(session);
if (e == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
initPattern(p, getEscapeChar(e));
}
if (invalidPattern) {
return ValueNull.INSTANCE;
}
String value = l.getString();
boolean result;
if (regexp) {
result = patternRegexp.matcher(value).find();
} else if (shortcutToStartsWith) {
result = value.regionMatches(ignoreCase, 0, patternString, 0, patternLength - 1);
} else if (shortcutToEndsWith) {
result = value.regionMatches(ignoreCase, value.length() -
patternLength + 1, patternString, 1, patternLength - 1);
} else if (shortcutToContains) {
String p = patternString.substring(1, patternString.length() - 1);
if (ignoreCase) {
result = containsIgnoreCase(value, p);
} else {
result = value.contains(p);
}
} else {
result = compareAt(value, 0, 0, value.length(), patternChars, patternTypes);
}
return ValueBoolean.get(result);
}
private static boolean containsIgnoreCase(String src, String what) {
final int length = what.length();
if (length == 0) {
// Empty string is contained
return true;
}
final char firstLo = Character.toLowerCase(what.charAt(0));
final char firstUp = Character.toUpperCase(what.charAt(0));
for (int i = src.length() - length; i >= 0; i--) {
// Quick check before calling the more expensive regionMatches()
final char ch = src.charAt(i);
if (ch != firstLo && ch != firstUp) {
continue;
}
if (src.regionMatches(true, i, what, 0, length)) {
return true;
}
}
return false;
}
private boolean compareAt(String s, int pi, int si, int sLen,
char[] pattern, int[] types) {
for (; pi < patternLength; pi++) {
switch (types[pi]) {
case MATCH:
if ((si >= sLen) || !compare(pattern, s, pi, si++)) {
return false;
}
break;
case ONE:
if (si++ >= sLen) {
return false;
}
break;
case ANY:
if (++pi >= patternLength) {
return true;
}
while (si < sLen) {
if (compare(pattern, s, pi, si) &&
compareAt(s, pi, si, sLen, pattern, types)) {
return true;
}
si++;
}
return false;
default:
DbException.throwInternalError("" + types[pi]);
}
}
return si == sLen;
}
private boolean compare(char[] pattern, String s, int pi, int si) {
return pattern[pi] == s.charAt(si) ||
(!fastCompare && compareMode.equalsChars(patternString, pi, s,
si, ignoreCase));
}
/**
* Test if the value matches the pattern.
*
* @param testPattern the pattern
* @param value the value
* @param escapeChar the escape character
* @return true if the value matches
*/
public boolean test(String testPattern, String value, char escapeChar) {
initPattern(testPattern, escapeChar);
if (invalidPattern) {
return false;
}
return compareAt(value, 0, 0, value.length(), patternChars, patternTypes);
}
private void initPattern(String p, Character escapeChar) {
if (compareMode.getName().equals(CompareMode.OFF) && !ignoreCase) {
fastCompare = true;
}
if (regexp) {
patternString = p;
try {
if (ignoreCase) {
patternRegexp = Pattern.compile(p, Pattern.CASE_INSENSITIVE);
} else {
patternRegexp = Pattern.compile(p);
}
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, p);
}
return;
}
patternLength = 0;
if (p == null) {
patternTypes = null;
patternChars = null;
return;
}
int len = p.length();
patternChars = new char[len];
patternTypes = new int[len];
boolean lastAny = false;
for (int i = 0; i < len; i++) {
char c = p.charAt(i);
int type;
if (escapeChar != null && escapeChar == c) {
if (i >= len - 1) {
invalidPattern = true;
return;
}
c = p.charAt(++i);
type = MATCH;
lastAny = false;
} else if (c == '%') {
if (lastAny) {
continue;
}
type = ANY;
lastAny = true;
} else if (c == '_') {
type = ONE;
} else {
type = MATCH;
lastAny = false;
}
patternTypes[patternLength] = type;
patternChars[patternLength++] = c;
}
for (int i = 0; i < patternLength - 1; i++) {
if ((patternTypes[i] == ANY) && (patternTypes[i + 1] == ONE)) {
patternTypes[i] = ONE;
patternTypes[i + 1] = ANY;
}
}
patternString = new String(patternChars, 0, patternLength);
// Clear optimizations
shortcutToStartsWith = false;
shortcutToEndsWith = false;
shortcutToContains = false;
// optimizes the common case of LIKE 'foo%'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
int maxMatch = 0;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
shortcutToStartsWith = true;
return;
}
}
// optimizes the common case of LIKE '%foo'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 1) {
if (patternTypes[0] == ANY) {
int maxMatch = 1;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength) {
shortcutToEndsWith = true;
return;
}
}
}
// optimizes the common case of LIKE '%foo%'
if (compareMode.getName().equals(CompareMode.OFF) && patternLength > 2) {
if (patternTypes[0] == ANY) {
int maxMatch = 1;
while (maxMatch < patternLength && patternTypes[maxMatch] == MATCH) {
maxMatch++;
}
if (maxMatch == patternLength - 1 && patternTypes[patternLength - 1] == ANY) {
shortcutToContains = true;
}
}
}
}
private boolean isFullMatch() {
if (patternTypes == null) {
return false;
}
for (int type : patternTypes) {
if (type != MATCH) {
return false;
}
}
return true;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
right.mapColumns(resolver, level);
if (escape != null) {
escape.mapColumns(resolver, level);
}
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
right.setEvaluatable(tableFilter, b);
if (escape != null) {
escape.setEvaluatable(tableFilter, b);
}
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
right.updateAggregate(session);
if (escape != null) {
escape.updateAggregate(session);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) && right.isEverything(visitor)
&& (escape == null || escape.isEverything(visitor));
}
@Override
public int getCost() {
return left.getCost() + right.getCost() + 3;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Comparison.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import java.util.Arrays;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.MathUtils;
import org.h2.value.*;
/**
* Example comparison expressions are ID=1, NAME=NAME, NAME IS NULL.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class Comparison extends Condition {
/**
* This is a flag meaning the comparison is null safe (meaning never returns
* NULL even if one operand is NULL). Only EQUAL and NOT_EQUAL are supported
* currently.
*/
public static final int NULL_SAFE = 16;
/**
* The comparison type meaning = as in ID=1.
*/
public static final int EQUAL = 0;
/**
* The comparison type meaning ID IS 1 (ID IS NOT DISTINCT FROM 1).
*/
public static final int EQUAL_NULL_SAFE = EQUAL | NULL_SAFE;
/**
* The comparison type meaning >= as in ID>=1.
*/
public static final int BIGGER_EQUAL = 1;
/**
* The comparison type meaning > as in ID>1.
*/
public static final int BIGGER = 2;
/**
* The comparison type meaning <= as in ID<=1.
*/
public static final int SMALLER_EQUAL = 3;
/**
* The comparison type meaning < as in ID<1.
*/
public static final int SMALLER = 4;
/**
* The comparison type meaning <> as in ID<>1.
*/
public static final int NOT_EQUAL = 5;
/**
* The comparison type meaning ID IS NOT 1 (ID IS DISTINCT FROM 1).
*/
public static final int NOT_EQUAL_NULL_SAFE = NOT_EQUAL | NULL_SAFE;
/**
* The comparison type meaning IS NULL as in NAME IS NULL.
*/
public static final int IS_NULL = 6;
/**
* The comparison type meaning IS NOT NULL as in NAME IS NOT NULL.
*/
public static final int IS_NOT_NULL = 7;
/**
* This is a pseudo comparison type that is only used for index conditions.
* It means the comparison will always yield FALSE. Example: 1=0.
*/
public static final int FALSE = 8;
/**
* This is a pseudo comparison type that is only used for index conditions.
* It means equals any value of a list. Example: IN(1, 2, 3).
*/
public static final int IN_LIST = 9;
/**
* This is a pseudo comparison type that is only used for index conditions.
* It means equals any value of a list. Example: IN(SELECT ...).
*/
public static final int IN_QUERY = 10;
/**
* This is a comparison type that is only used for spatial index
* conditions (operator "&&").
*/
public static final int SPATIAL_INTERSECTS = 11;
private final Database database;
private int compareType;
private Expression left;
private Expression right;
public Comparison(Session session, int compareType, Expression left,
Expression right) {
this.database = session.getDatabase();
this.left = left;
this.right = right;
this.compareType = compareType;
}
@Override
public String getSQL() {
String sql;
switch (compareType) {
case IS_NULL:
sql = left.getSQL() + " IS NULL";
break;
case IS_NOT_NULL:
sql = left.getSQL() + " IS NOT NULL";
break;
case SPATIAL_INTERSECTS:
sql = "INTERSECTS(" + left.getSQL() + ", " + right.getSQL() + ")";
break;
default:
sql = left.getSQL() + " " + getCompareOperator(compareType) +
" " + right.getSQL();
}
return "(" + sql + ")";
}
/**
* Get the comparison operator string ("=", ">",...).
*
* @param compareType the compare type
* @return the string
*/
static String getCompareOperator(int compareType) {
switch (compareType) {
case EQUAL:
return "=";
case EQUAL_NULL_SAFE:
return "IS";
case BIGGER_EQUAL:
return ">=";
case BIGGER:
return ">";
case SMALLER_EQUAL:
return "<=";
case SMALLER:
return "<";
case NOT_EQUAL:
return "<>";
case NOT_EQUAL_NULL_SAFE:
return "IS NOT";
case SPATIAL_INTERSECTS:
return "&&";
default:
throw DbException.throwInternalError("compareType=" + compareType);
}
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
if (right != null) {
right = right.optimize(session);
if (right instanceof ExpressionColumn) {
if (left.isConstant() || left instanceof Parameter) {
Expression temp = left;
left = right;
right = temp;
compareType = getReversedCompareType(compareType);
}
}
if (left instanceof ExpressionColumn) {
if (right.isConstant()) {
Value r = right.getValue(session);
if (r == ValueNull.INSTANCE) {
if ((compareType & NULL_SAFE) == 0) {
return ValueExpression.getNull();
}
}
int colType = left.getType();
int constType = r.getType();
int resType = Value.getHigherOrder(colType, constType);
// If not, the column values will need to be promoted
// to constant type, but vise versa, then let's do this here
// once.
if (constType != resType) {
Column column = ((ExpressionColumn) left).getColumn();
right = ValueExpression.get(r.convertTo(resType,
MathUtils.convertLongToInt(left.getPrecision()),
session.getDatabase().getMode(), column, column.getEnumerators()));
}
} else if (right instanceof Parameter) {
((Parameter) right).setColumn(
((ExpressionColumn) left).getColumn());
}
}
}
if (compareType == IS_NULL || compareType == IS_NOT_NULL) {
if (left.isConstant()) {
return ValueExpression.get(getValue(session));
}
} else {
if (SysProperties.CHECK && (left == null || right == null)) {
DbException.throwInternalError(left + " " + right);
}
if (left == ValueExpression.getNull() ||
right == ValueExpression.getNull()) {
// TODO NULL handling: maybe issue a warning when comparing with
// a NULL constants
if ((compareType & NULL_SAFE) == 0) {
return ValueExpression.getNull();
}
}
if (left.isConstant() && right.isConstant()) {
return ValueExpression.get(getValue(session));
}
}
return this;
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session);
if (right == null) {
boolean result;
switch (compareType) {
case IS_NULL:
result = l == ValueNull.INSTANCE;
break;
case IS_NOT_NULL:
result = !(l == ValueNull.INSTANCE);
break;
default:
throw DbException.throwInternalError("type=" + compareType);
}
return ValueBoolean.get(result);
}
if (l == ValueNull.INSTANCE) {
if ((compareType & NULL_SAFE) == 0) {
return ValueNull.INSTANCE;
}
}
Value r = right.getValue(session);
if (r == ValueNull.INSTANCE) {
if ((compareType & NULL_SAFE) == 0) {
return ValueNull.INSTANCE;
}
}
int dataType = Value.getHigherOrder(left.getType(), right.getType());
if (dataType == Value.ENUM) {
String[] enumerators = getEnumerators(l, r);
l = l.convertToEnum(enumerators);
r = r.convertToEnum(enumerators);
} else {
l = l.convertTo(dataType);
r = r.convertTo(dataType);
}
boolean result = compareNotNull(database, l, r, compareType);
return ValueBoolean.get(result);
}
private String[] getEnumerators(Value left, Value right) {
if (left.getType() == Value.ENUM) {
return ((ValueEnum) left).getEnumerators();
} else if (right.getType() == Value.ENUM) {
return ((ValueEnum) right).getEnumerators();
} else {
return new String[0];
}
}
/**
* Compare two values, given the values are not NULL.
*
* @param database the database
* @param l the first value
* @param r the second value
* @param compareType the compare type
* @return true if the comparison indicated by the comparison type evaluates
* to true
*/
static boolean compareNotNull(Database database, Value l, Value r,
int compareType) {
boolean result;
switch (compareType) {
case EQUAL:
case EQUAL_NULL_SAFE:
result = database.areEqual(l, r);
break;
case NOT_EQUAL:
case NOT_EQUAL_NULL_SAFE:
result = !database.areEqual(l, r);
break;
case BIGGER_EQUAL:
result = database.compare(l, r) >= 0;
break;
case BIGGER:
result = database.compare(l, r) > 0;
break;
case SMALLER_EQUAL:
result = database.compare(l, r) <= 0;
break;
case SMALLER:
result = database.compare(l, r) < 0;
break;
case SPATIAL_INTERSECTS: {
ValueGeometry lg = (ValueGeometry) l.convertTo(Value.GEOMETRY);
ValueGeometry rg = (ValueGeometry) r.convertTo(Value.GEOMETRY);
result = lg.intersectsBoundingBox(rg);
break;
}
default:
throw DbException.throwInternalError("type=" + compareType);
}
return result;
}
private int getReversedCompareType(int type) {
switch (compareType) {
case EQUAL:
case EQUAL_NULL_SAFE:
case NOT_EQUAL:
case NOT_EQUAL_NULL_SAFE:
case SPATIAL_INTERSECTS:
return type;
case BIGGER_EQUAL:
return SMALLER_EQUAL;
case BIGGER:
return SMALLER;
case SMALLER_EQUAL:
return BIGGER_EQUAL;
case SMALLER:
return BIGGER;
default:
throw DbException.throwInternalError("type=" + compareType);
}
}
@Override
public Expression getNotIfPossible(Session session) {
if (compareType == SPATIAL_INTERSECTS) {
return null;
}
int type = getNotCompareType();
return new Comparison(session, type, left, right);
}
private int getNotCompareType() {
switch (compareType) {
case EQUAL:
return NOT_EQUAL;
case EQUAL_NULL_SAFE:
return NOT_EQUAL_NULL_SAFE;
case NOT_EQUAL:
return EQUAL;
case NOT_EQUAL_NULL_SAFE:
return EQUAL_NULL_SAFE;
case BIGGER_EQUAL:
return SMALLER;
case BIGGER:
return SMALLER_EQUAL;
case SMALLER_EQUAL:
return BIGGER;
case SMALLER:
return BIGGER_EQUAL;
case IS_NULL:
return IS_NOT_NULL;
case IS_NOT_NULL:
return IS_NULL;
default:
throw DbException.throwInternalError("type=" + compareType);
}
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (!filter.getTable().isQueryComparable()) {
return;
}
ExpressionColumn l = null;
if (left instanceof ExpressionColumn) {
l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
l = null;
}
}
if (right == null) {
if (l != null) {
switch (compareType) {
case IS_NULL:
if (session.getDatabase().getSettings().optimizeIsNull) {
filter.addIndexCondition(
IndexCondition.get(
Comparison.EQUAL_NULL_SAFE, l,
ValueExpression.getNull()));
}
}
}
return;
}
ExpressionColumn r = null;
if (right instanceof ExpressionColumn) {
r = (ExpressionColumn) right;
if (filter != r.getTableFilter()) {
r = null;
}
}
// one side must be from the current filter
if (l == null && r == null) {
return;
}
if (l != null && r != null) {
return;
}
if (l == null) {
ExpressionVisitor visitor =
ExpressionVisitor.getNotFromResolverVisitor(filter);
if (!left.isEverything(visitor)) {
return;
}
} else if (r == null) {
ExpressionVisitor visitor =
ExpressionVisitor.getNotFromResolverVisitor(filter);
if (!right.isEverything(visitor)) {
return;
}
} else {
// if both sides are part of the same filter, it can't be used for
// index lookup
return;
}
boolean addIndex;
switch (compareType) {
case NOT_EQUAL:
case NOT_EQUAL_NULL_SAFE:
addIndex = false;
break;
case EQUAL:
case EQUAL_NULL_SAFE:
case BIGGER:
case BIGGER_EQUAL:
case SMALLER_EQUAL:
case SMALLER:
case SPATIAL_INTERSECTS:
addIndex = true;
break;
default:
throw DbException.throwInternalError("type=" + compareType);
}
if (addIndex) {
if (l != null) {
filter.addIndexCondition(
IndexCondition.get(compareType, l, right));
} else if (r != null) {
int compareRev = getReversedCompareType(compareType);
filter.addIndexCondition(
IndexCondition.get(compareRev, r, left));
}
}
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
if (right != null) {
right.setEvaluatable(tableFilter, b);
}
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
if (right != null) {
right.updateAggregate(session);
}
}
@Override
public void addFilterConditions(TableFilter filter, boolean outerJoin) {
if (compareType == IS_NULL && outerJoin) {
// can not optimize:
// select * from test t1 left join test t2 on t1.id = t2.id
// where t2.id is null
// to
// select * from test t1 left join test t2
// on t1.id = t2.id and t2.id is null
return;
}
super.addFilterConditions(filter, outerJoin);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
if (right != null) {
right.mapColumns(resolver, level);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) &&
(right == null || right.isEverything(visitor));
}
@Override
public int getCost() {
return left.getCost() + (right == null ? 0 : right.getCost()) + 1;
}
/**
* Get the other expression if this is an equals comparison and the other
* expression matches.
*
* @param match the expression that should match
* @return null if no match, the other expression if there is a match
*/
Expression getIfEquals(Expression match) {
if (compareType == EQUAL) {
String sql = match.getSQL();
if (left.getSQL().equals(sql)) {
return right;
} else if (right.getSQL().equals(sql)) {
return left;
}
}
return null;
}
/**
* Get an additional condition if possible. Example: given two conditions
* A=B AND B=C, the new condition A=C is returned. Given the two conditions
* A=1 OR A=2, the new condition A IN(1, 2) is returned.
*
* @param session the session
* @param other the second condition
* @param and true for AND, false for OR
* @return null or the third condition
*/
Expression getAdditional(Session session, Comparison other, boolean and) {
if (compareType == other.compareType && compareType == EQUAL) {
boolean lc = left.isConstant();
boolean rc = right.isConstant();
boolean l2c = other.left.isConstant();
boolean r2c = other.right.isConstant();
String l = left.getSQL();
String l2 = other.left.getSQL();
String r = right.getSQL();
String r2 = other.right.getSQL();
if (and) {
// a=b AND a=c
// must not compare constants. example: NOT(B=2 AND B=3)
if (!(rc && r2c) && l.equals(l2)) {
return new Comparison(session, EQUAL, right, other.right);
} else if (!(rc && l2c) && l.equals(r2)) {
return new Comparison(session, EQUAL, right, other.left);
} else if (!(lc && r2c) && r.equals(l2)) {
return new Comparison(session, EQUAL, left, other.right);
} else if (!(lc && l2c) && r.equals(r2)) {
return new Comparison(session, EQUAL, left, other.left);
}
} else {
// a=b OR a=c
Database db = session.getDatabase();
if (rc && r2c && l.equals(l2)) {
return new ConditionIn(db, left,
new ArrayList<>(Arrays.asList(right, other.right)));
} else if (rc && l2c && l.equals(r2)) {
return new ConditionIn(db, left,
new ArrayList<>(Arrays.asList(right, other.left)));
} else if (lc && r2c && r.equals(l2)) {
return new ConditionIn(db, right,
new ArrayList<>(Arrays.asList(left, other.right)));
} else if (lc && l2c && r.equals(r2)) {
return new ConditionIn(db, right,
new ArrayList<>(Arrays.asList(left, other.left)));
}
}
}
return null;
}
/**
* Get the left or the right sub-expression of this condition.
*
* @param getLeft true to get the left sub-expression, false to get the
* right sub-expression.
* @return the sub-expression
*/
public Expression getExpression(boolean getLeft) {
return getLeft ? this.left : right;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Condition.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
/**
* Represents a condition returning a boolean value, or NULL.
*/
abstract class Condition extends Expression {
@Override
public int getType() {
return Value.BOOLEAN;
}
@Override
public int getScale() {
return 0;
}
@Override
public long getPrecision() {
return ValueBoolean.PRECISION;
}
@Override
public int getDisplaySize() {
return ValueBoolean.DISPLAY_SIZE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionAndOr.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* An 'and' or 'or' condition as in WHERE ID=1 AND NAME=?
*/
public class ConditionAndOr extends Condition {
/**
* The AND condition type as in ID=1 AND NAME='Hello'.
*/
public static final int AND = 0;
/**
* The OR condition type as in ID=1 OR NAME='Hello'.
*/
public static final int OR = 1;
private final int andOrType;
private Expression left, right;
public ConditionAndOr(int andOrType, Expression left, Expression right) {
this.andOrType = andOrType;
this.left = left;
this.right = right;
if (SysProperties.CHECK && (left == null || right == null)) {
DbException.throwInternalError(left + " " + right);
}
}
@Override
public String getSQL() {
String sql;
switch (andOrType) {
case AND:
sql = left.getSQL() + "\n AND " + right.getSQL();
break;
case OR:
sql = left.getSQL() + "\n OR " + right.getSQL();
break;
default:
throw DbException.throwInternalError("andOrType=" + andOrType);
}
return "(" + sql + ")";
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (andOrType == AND) {
left.createIndexConditions(session, filter);
right.createIndexConditions(session, filter);
}
}
@Override
public Expression getNotIfPossible(Session session) {
// (NOT (A OR B)): (NOT(A) AND NOT(B))
// (NOT (A AND B)): (NOT(A) OR NOT(B))
Expression l = left.getNotIfPossible(session);
if (l == null) {
l = new ConditionNot(left);
}
Expression r = right.getNotIfPossible(session);
if (r == null) {
r = new ConditionNot(right);
}
int reversed = andOrType == AND ? OR : AND;
return new ConditionAndOr(reversed, l, r);
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session);
Value r;
switch (andOrType) {
case AND: {
if (l != ValueNull.INSTANCE && !l.getBoolean()) {
return l;
}
r = right.getValue(session);
if (r != ValueNull.INSTANCE && !r.getBoolean()) {
return r;
}
if (l == ValueNull.INSTANCE) {
return l;
}
if (r == ValueNull.INSTANCE) {
return r;
}
return ValueBoolean.TRUE;
}
case OR: {
if (l.getBoolean()) {
return l;
}
r = right.getValue(session);
if (r.getBoolean()) {
return r;
}
if (l == ValueNull.INSTANCE) {
return l;
}
if (r == ValueNull.INSTANCE) {
return r;
}
return ValueBoolean.FALSE;
}
default:
throw DbException.throwInternalError("type=" + andOrType);
}
}
@Override
public Expression optimize(Session session) {
// NULL handling: see wikipedia,
// http://www-cs-students.stanford.edu/~wlam/compsci/sqlnulls
left = left.optimize(session);
right = right.optimize(session);
int lc = left.getCost(), rc = right.getCost();
if (rc < lc) {
Expression t = left;
left = right;
right = t;
}
// this optimization does not work in the following case,
// but NOT is optimized before:
// CREATE TABLE TEST(A INT, B INT);
// INSERT INTO TEST VALUES(1, NULL);
// SELECT * FROM TEST WHERE NOT (B=A AND B=0); // no rows
// SELECT * FROM TEST WHERE NOT (B=A AND B=0 AND A=0); // 1, NULL
if (session.getDatabase().getSettings().optimizeTwoEquals &&
andOrType == AND) {
// try to add conditions (A=B AND B=1: add A=1)
if (left instanceof Comparison && right instanceof Comparison) {
Comparison compLeft = (Comparison) left;
Comparison compRight = (Comparison) right;
Expression added = compLeft.getAdditional(
session, compRight, true);
if (added != null) {
added = added.optimize(session);
return new ConditionAndOr(AND, this, added);
}
}
}
// TODO optimization: convert ((A=1 AND B=2) OR (A=1 AND B=3)) to
// (A=1 AND (B=2 OR B=3))
if (andOrType == OR &&
session.getDatabase().getSettings().optimizeOr) {
// try to add conditions (A=B AND B=1: add A=1)
if (left instanceof Comparison &&
right instanceof Comparison) {
Comparison compLeft = (Comparison) left;
Comparison compRight = (Comparison) right;
Expression added = compLeft.getAdditional(
session, compRight, false);
if (added != null) {
return added.optimize(session);
}
} else if (left instanceof ConditionIn &&
right instanceof Comparison) {
Expression added = ((ConditionIn) left).
getAdditional((Comparison) right);
if (added != null) {
return added.optimize(session);
}
} else if (right instanceof ConditionIn &&
left instanceof Comparison) {
Expression added = ((ConditionIn) right).
getAdditional((Comparison) left);
if (added != null) {
return added.optimize(session);
}
} else if (left instanceof ConditionInConstantSet &&
right instanceof Comparison) {
Expression added = ((ConditionInConstantSet) left).
getAdditional(session, (Comparison) right);
if (added != null) {
return added.optimize(session);
}
} else if (right instanceof ConditionInConstantSet &&
left instanceof Comparison) {
Expression added = ((ConditionInConstantSet) right).
getAdditional(session, (Comparison) left);
if (added != null) {
return added.optimize(session);
}
}
}
// TODO optimization: convert .. OR .. to UNION if the cost is lower
Value l = left.isConstant() ? left.getValue(session) : null;
Value r = right.isConstant() ? right.getValue(session) : null;
if (l == null && r == null) {
return this;
}
if (l != null && r != null) {
return ValueExpression.get(getValue(session));
}
switch (andOrType) {
case AND:
if (l != null) {
if (l != ValueNull.INSTANCE && !l.getBoolean()) {
return ValueExpression.get(l);
} else if (l.getBoolean()) {
return right;
}
} else if (r != null) {
if (r != ValueNull.INSTANCE && !r.getBoolean()) {
return ValueExpression.get(r);
} else if (r.getBoolean()) {
return left;
}
}
break;
case OR:
if (l != null) {
if (l.getBoolean()) {
return ValueExpression.get(l);
} else if (l != ValueNull.INSTANCE) {
return right;
}
} else if (r != null) {
if (r.getBoolean()) {
return ValueExpression.get(r);
} else if (r != ValueNull.INSTANCE) {
return left;
}
}
break;
default:
DbException.throwInternalError("type=" + andOrType);
}
return this;
}
@Override
public void addFilterConditions(TableFilter filter, boolean outerJoin) {
if (andOrType == AND) {
left.addFilterConditions(filter, outerJoin);
right.addFilterConditions(filter, outerJoin);
} else {
super.addFilterConditions(filter, outerJoin);
}
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
right.mapColumns(resolver, level);
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
right.setEvaluatable(tableFilter, b);
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
right.updateAggregate(session);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) && right.isEverything(visitor);
}
@Override
public int getCost() {
return left.getCost() + right.getCost();
}
/**
* Get the left or the right sub-expression of this condition.
*
* @param getLeft true to get the left sub-expression, false to get the
* right sub-expression.
* @return the sub-expression
*/
public Expression getExpression(boolean getLeft) {
return getLeft ? this.left : right;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionExists.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.command.dml.Query;
import org.h2.engine.Session;
import org.h2.result.ResultInterface;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
/**
* An 'exists' condition as in WHERE EXISTS(SELECT ...)
*/
public class ConditionExists extends Condition {
private final Query query;
public ConditionExists(Query query) {
this.query = query;
}
@Override
public Value getValue(Session session) {
query.setSession(session);
ResultInterface result = query.query(1);
session.addTemporaryResult(result);
boolean r = result.hasNext();
return ValueBoolean.get(r);
}
@Override
public Expression optimize(Session session) {
session.optimizeQueryExpression(query);
return this;
}
@Override
public String getSQL() {
return "EXISTS(\n" + StringUtils.indent(query.getPlanSQL(), 4, false) + ")";
}
@Override
public void updateAggregate(Session session) {
// TODO exists: is it allowed that the subquery contains aggregates?
// probably not
// select id from test group by id having exists (select * from test2
// where id=count(test.id))
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
query.mapColumns(resolver, level + 1);
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
query.setEvaluatable(tableFilter, b);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return query.isEverything(visitor);
}
@Override
public int getCost() {
return query.getCostAsExpression();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionIn.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* An 'in' condition with a list of values, as in WHERE NAME IN(...)
*/
public class ConditionIn extends Condition {
private final Database database;
private Expression left;
private final ArrayList<Expression> valueList;
private int queryLevel;
/**
* Create a new IN(..) condition.
*
* @param database the database
* @param left the expression before IN
* @param values the value list (at least one element)
*/
public ConditionIn(Database database, Expression left,
ArrayList<Expression> values) {
this.database = database;
this.left = left;
this.valueList = values;
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session);
if (l == ValueNull.INSTANCE) {
return l;
}
boolean result = false;
boolean hasNull = false;
for (Expression e : valueList) {
Value r = e.getValue(session);
if (r == ValueNull.INSTANCE) {
hasNull = true;
} else {
r = r.convertTo(l.getType());
result = Comparison.compareNotNull(database, l, r, Comparison.EQUAL);
if (result) {
break;
}
}
}
if (!result && hasNull) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(result);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
for (Expression e : valueList) {
e.mapColumns(resolver, level);
}
this.queryLevel = Math.max(level, this.queryLevel);
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
boolean constant = left.isConstant();
if (constant && left == ValueExpression.getNull()) {
return left;
}
boolean allValuesConstant = true;
boolean allValuesNull = true;
int size = valueList.size();
for (int i = 0; i < size; i++) {
Expression e = valueList.get(i);
e = e.optimize(session);
if (e.isConstant() && e.getValue(session) != ValueNull.INSTANCE) {
allValuesNull = false;
}
if (allValuesConstant && !e.isConstant()) {
allValuesConstant = false;
}
if (left instanceof ExpressionColumn && e instanceof Parameter) {
((Parameter) e)
.setColumn(((ExpressionColumn) left).getColumn());
}
valueList.set(i, e);
}
if (constant && allValuesConstant) {
return ValueExpression.get(getValue(session));
}
if (size == 1) {
Expression right = valueList.get(0);
Expression expr = new Comparison(session, Comparison.EQUAL, left, right);
expr = expr.optimize(session);
return expr;
}
if (allValuesConstant && !allValuesNull) {
int leftType = left.getType();
if (leftType == Value.UNKNOWN) {
return this;
}
Expression expr = new ConditionInConstantSet(session, left, valueList);
expr = expr.optimize(session);
return expr;
}
return this;
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
if (session.getDatabase().getSettings().optimizeInList) {
ExpressionVisitor visitor = ExpressionVisitor.getNotFromResolverVisitor(filter);
for (Expression e : valueList) {
if (!e.isEverything(visitor)) {
return;
}
}
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
}
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
for (Expression e : valueList) {
e.setEvaluatable(tableFilter, b);
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
buff.append(left.getSQL()).append(" IN(");
for (Expression e : valueList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append("))").toString();
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
for (Expression e : valueList) {
e.updateAggregate(session);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
if (!left.isEverything(visitor)) {
return false;
}
return areAllValues(visitor);
}
private boolean areAllValues(ExpressionVisitor visitor) {
for (Expression e : valueList) {
if (!e.isEverything(visitor)) {
return false;
}
}
return true;
}
@Override
public int getCost() {
int cost = left.getCost();
for (Expression e : valueList) {
cost += e.getCost();
}
return cost;
}
/**
* Add an additional element if possible. Example: given two conditions
* A IN(1, 2) OR A=3, the constant 3 is added: A IN(1, 2, 3).
*
* @param other the second condition
* @return null if the condition was not added, or the new condition
*/
Expression getAdditional(Comparison other) {
Expression add = other.getIfEquals(left);
if (add != null) {
valueList.add(add);
return this;
}
return null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionInConstantSet.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.TreeSet;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* Used for optimised IN(...) queries where the contents of the IN list are all
* constant and of the same type.
* <p>
* Checking using a HashSet is has time complexity O(1), instead of O(n) for
* checking using an array.
*/
public class ConditionInConstantSet extends Condition {
private Expression left;
private int queryLevel;
private final ArrayList<Expression> valueList;
private final TreeSet<Value> valueSet;
/**
* Create a new IN(..) condition.
*
* @param session the session
* @param left the expression before IN
* @param valueList the value list (at least two elements)
*/
public ConditionInConstantSet(final Session session, Expression left,
ArrayList<Expression> valueList) {
this.left = left;
this.valueList = valueList;
this.valueSet = new TreeSet<>(new Comparator<Value>() {
@Override
public int compare(Value o1, Value o2) {
return session.getDatabase().compare(o1, o2);
}
});
int type = left.getType();
for (Expression expression : valueList) {
valueSet.add(expression.getValue(session).convertTo(type));
}
}
@Override
public Value getValue(Session session) {
Value x = left.getValue(session);
if (x == ValueNull.INSTANCE) {
return x;
}
boolean result = valueSet.contains(x);
if (!result) {
boolean setHasNull = valueSet.contains(ValueNull.INSTANCE);
if (setHasNull) {
return ValueNull.INSTANCE;
}
}
return ValueBoolean.get(result);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
this.queryLevel = Math.max(level, this.queryLevel);
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
return this;
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
if (session.getDatabase().getSettings().optimizeInList) {
filter.addIndexCondition(IndexCondition.getInList(l, valueList));
}
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
buff.append(left.getSQL()).append(" IN(");
for (Expression e : valueList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append("))").toString();
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
if (!left.isEverything(visitor)) {
return false;
}
switch (visitor.getType()) {
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.INDEPENDENT:
case ExpressionVisitor.EVALUATABLE:
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.GET_COLUMNS:
return true;
default:
throw DbException.throwInternalError("type=" + visitor.getType());
}
}
@Override
public int getCost() {
return left.getCost();
}
/**
* Add an additional element if possible. Example: given two conditions
* A IN(1, 2) OR A=3, the constant 3 is added: A IN(1, 2, 3).
*
* @param session the session
* @param other the second condition
* @return null if the condition was not added, or the new condition
*/
Expression getAdditional(Session session, Comparison other) {
Expression add = other.getIfEquals(left);
if (add != null) {
if (add.isConstant()) {
valueList.add(add);
valueSet.add(add.getValue(session).convertTo(left.getType()));
return this;
}
}
return null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionInParameter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.AbstractList;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* A condition with parameter as {@code = ANY(?)}.
*/
public class ConditionInParameter extends Condition {
private static final class ParameterList extends AbstractList<Expression> {
private final Parameter parameter;
ParameterList(Parameter parameter) {
this.parameter = parameter;
}
@Override
public Expression get(int index) {
Value value = parameter.getParamValue();
if (value instanceof ValueArray) {
return ValueExpression.get(((ValueArray) value).getList()[index]);
}
if (index != 0) {
throw new IndexOutOfBoundsException();
}
return ValueExpression.get(value);
}
@Override
public int size() {
if (!parameter.isValueSet()) {
return 0;
}
Value value = parameter.getParamValue();
if (value instanceof ValueArray) {
return ((ValueArray) value).getList().length;
}
return 1;
}
}
private final Database database;
private Expression left;
private final Parameter parameter;
/**
* Create a new {@code = ANY(?)} condition.
*
* @param database
* the database
* @param left
* the expression before {@code = ANY(?)}
* @param parameter
* parameter
*/
public ConditionInParameter(Database database, Expression left, Parameter parameter) {
this.database = database;
this.left = left;
this.parameter = parameter;
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session);
if (l == ValueNull.INSTANCE) {
return l;
}
boolean result = false;
boolean hasNull = false;
Value value = parameter.getValue(session);
if (value instanceof ValueArray) {
for (Value r : ((ValueArray) value).getList()) {
if (r == ValueNull.INSTANCE) {
hasNull = true;
} else {
r = r.convertTo(l.getType());
result = Comparison.compareNotNull(database, l, r, Comparison.EQUAL);
if (result) {
break;
}
}
}
} else {
if (value == ValueNull.INSTANCE) {
hasNull = true;
} else {
value = value.convertTo(l.getType());
result = Comparison.compareNotNull(database, l, value, Comparison.EQUAL);
}
}
if (!result && hasNull) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(result);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
if (left.isConstant() && left == ValueExpression.getNull()) {
return left;
}
return this;
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
filter.addIndexCondition(IndexCondition.getInList(l, new ParameterList(parameter)));
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
}
@Override
public String getSQL() {
return '(' + left.getSQL() + " = ANY(" + parameter.getSQL() + "))";
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) && parameter.isEverything(visitor);
}
@Override
public int getCost() {
return left.getCost();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionInSelect.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.api.ErrorCode;
import org.h2.command.dml.Query;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* An 'in' condition with a subquery, as in WHERE ID IN(SELECT ...)
*/
public class ConditionInSelect extends Condition {
private final Database database;
private Expression left;
private final Query query;
private final boolean all;
private final int compareType;
private int queryLevel;
public ConditionInSelect(Database database, Expression left, Query query,
boolean all, int compareType) {
this.database = database;
this.left = left;
this.query = query;
this.all = all;
this.compareType = compareType;
}
@Override
public Value getValue(Session session) {
query.setSession(session);
if (!query.hasOrder()) {
query.setDistinct(true);
}
ResultInterface rows = query.query(0);
Value l = left.getValue(session);
if (!rows.hasNext()) {
return ValueBoolean.get(all);
} else if (l == ValueNull.INSTANCE) {
return l;
}
if (!session.getDatabase().getSettings().optimizeInSelect) {
return getValueSlow(rows, l);
}
if (all || (compareType != Comparison.EQUAL &&
compareType != Comparison.EQUAL_NULL_SAFE)) {
return getValueSlow(rows, l);
}
int dataType = rows.getColumnType(0);
if (dataType == Value.NULL) {
return ValueBoolean.FALSE;
}
l = l.convertTo(dataType);
if (rows.containsDistinct(new Value[] { l })) {
return ValueBoolean.TRUE;
}
if (rows.containsDistinct(new Value[] { ValueNull.INSTANCE })) {
return ValueNull.INSTANCE;
}
return ValueBoolean.FALSE;
}
private Value getValueSlow(ResultInterface rows, Value l) {
// this only returns the correct result if the result has at least one
// row, and if l is not null
boolean hasNull = false;
boolean result = all;
while (rows.next()) {
boolean value;
Value r = rows.currentRow()[0];
if (r == ValueNull.INSTANCE) {
value = false;
hasNull = true;
} else {
value = Comparison.compareNotNull(database, l, r, compareType);
}
if (!value && all) {
result = false;
break;
} else if (value && !all) {
result = true;
break;
}
}
if (!result && hasNull) {
return ValueNull.INSTANCE;
}
return ValueBoolean.get(result);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
query.mapColumns(resolver, level + 1);
this.queryLevel = Math.max(level, this.queryLevel);
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
query.setRandomAccessResult(true);
session.optimizeQueryExpression(query);
if (query.getColumnCount() != 1) {
throw DbException.get(ErrorCode.SUBQUERY_IS_NOT_SINGLE_COLUMN);
}
// Can not optimize: the data may change
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
query.setEvaluatable(tableFilter, b);
}
@Override
public String getSQL() {
StringBuilder buff = new StringBuilder();
buff.append('(').append(left.getSQL()).append(' ');
if (all) {
buff.append(Comparison.getCompareOperator(compareType)).
append(" ALL");
} else {
if (compareType == Comparison.EQUAL) {
buff.append("IN");
} else {
buff.append(Comparison.getCompareOperator(compareType)).
append(" ANY");
}
}
buff.append("(\n").append(StringUtils.indent(query.getPlanSQL(), 4, false)).
append("))");
return buff.toString();
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
query.updateAggregate(session);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) && query.isEverything(visitor);
}
@Override
public int getCost() {
return left.getCost() + query.getCostAsExpression();
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (!session.getDatabase().getSettings().optimizeInList) {
return;
}
if (!(left instanceof ExpressionColumn)) {
return;
}
ExpressionColumn l = (ExpressionColumn) left;
if (filter != l.getTableFilter()) {
return;
}
ExpressionVisitor visitor = ExpressionVisitor.getNotFromResolverVisitor(filter);
if (!query.isEverything(visitor)) {
return;
}
filter.addIndexCondition(IndexCondition.getInQuery(l, query));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ConditionNot.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* A NOT condition.
*/
public class ConditionNot extends Condition {
private Expression condition;
public ConditionNot(Expression condition) {
this.condition = condition;
}
@Override
public Expression getNotIfPossible(Session session) {
return condition;
}
@Override
public Value getValue(Session session) {
Value v = condition.getValue(session);
if (v == ValueNull.INSTANCE) {
return v;
}
return v.convertTo(Value.BOOLEAN).negate();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
condition.mapColumns(resolver, level);
}
@Override
public Expression optimize(Session session) {
Expression e2 = condition.getNotIfPossible(session);
if (e2 != null) {
return e2.optimize(session);
}
Expression expr = condition.optimize(session);
if (expr.isConstant()) {
Value v = expr.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueExpression.getNull();
}
return ValueExpression.get(v.convertTo(Value.BOOLEAN).negate());
}
condition = expr;
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
condition.setEvaluatable(tableFilter, b);
}
@Override
public String getSQL() {
return "(NOT " + condition.getSQL() + ")";
}
@Override
public void updateAggregate(Session session) {
condition.updateAggregate(session);
}
@Override
public void addFilterConditions(TableFilter filter, boolean outerJoin) {
if (outerJoin) {
// can not optimize:
// select * from test t1 left join test t2 on t1.id = t2.id where
// not t2.id is not null
// to
// select * from test t1 left join test t2 on t1.id = t2.id and
// t2.id is not null
return;
}
super.addFilterConditions(filter, outerJoin);
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return condition.isEverything(visitor);
}
@Override
public int getCost() {
return condition.getCost();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Expression.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StringUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
/**
* An expression is a operation, a value, or a function in a query.
*/
public abstract class Expression {
private boolean addedToFilter;
/**
* Return the resulting value for the current row.
*
* @param session the session
* @return the result
*/
public abstract Value getValue(Session session);
/**
* Return the data type. The data type may not be known before the
* optimization phase.
*
* @return the type
*/
public abstract int getType();
/**
* Map the columns of the resolver to expression columns.
*
* @param resolver the column resolver
* @param level the subquery nesting level
*/
public abstract void mapColumns(ColumnResolver resolver, int level);
/**
* Try to optimize the expression.
*
* @param session the session
* @return the optimized expression
*/
public abstract Expression optimize(Session session);
/**
* Tell the expression columns whether the table filter can return values
* now. This is used when optimizing the query.
*
* @param tableFilter the table filter
* @param value true if the table filter can return value
*/
public abstract void setEvaluatable(TableFilter tableFilter, boolean value);
/**
* Get the scale of this expression.
*
* @return the scale
*/
public abstract int getScale();
/**
* Get the precision of this expression.
*
* @return the precision
*/
public abstract long getPrecision();
/**
* Get the display size of this expression.
*
* @return the display size
*/
public abstract int getDisplaySize();
/**
* Get the SQL statement of this expression.
* This may not always be the original SQL statement,
* specially after optimization.
*
* @return the SQL statement
*/
public abstract String getSQL();
/**
* Update an aggregate value. This method is called at statement execution
* time. It is usually called once for each row, but if the expression is
* used multiple times (for example in the column list, and as part of the
* HAVING expression) it is called multiple times - the row counter needs to
* be used to make sure the internal state is only updated once.
*
* @param session the session
*/
public abstract void updateAggregate(Session session);
/**
* Check if this expression and all sub-expressions can fulfill a criteria.
* If any part returns false, the result is false.
*
* @param visitor the visitor
* @return if the criteria can be fulfilled
*/
public abstract boolean isEverything(ExpressionVisitor visitor);
/**
* Estimate the cost to process the expression.
* Used when optimizing the query, to calculate the query plan
* with the lowest estimated cost.
*
* @return the estimated cost
*/
public abstract int getCost();
/**
* If it is possible, return the negated expression. This is used
* to optimize NOT expressions: NOT ID>10 can be converted to
* ID<=10. Returns null if negating is not possible.
*
* @param session the session
* @return the negated expression, or null
*/
public Expression getNotIfPossible(@SuppressWarnings("unused") Session session) {
// by default it is not possible
return null;
}
/**
* Check if this expression will always return the same value.
*
* @return if the expression is constant
*/
public boolean isConstant() {
return false;
}
/**
* Is the value of a parameter set.
*
* @return true if set
*/
public boolean isValueSet() {
return false;
}
/**
* Check if this is an auto-increment column.
*
* @return true if it is an auto-increment column
*/
public boolean isAutoIncrement() {
return false;
}
/**
* Get the value in form of a boolean expression.
* Returns true or false.
* In this database, everything can be a condition.
*
* @param session the session
* @return the result
*/
public boolean getBooleanValue(Session session) {
return getValue(session).getBoolean();
}
/**
* Create index conditions if possible and attach them to the table filter.
*
* @param session the session
* @param filter the table filter
*/
@SuppressWarnings("unused")
public void createIndexConditions(Session session, TableFilter filter) {
// default is do nothing
}
/**
* Get the column name or alias name of this expression.
*
* @return the column name
*/
public String getColumnName() {
return getAlias();
}
/**
* Get the schema name, or null
*
* @return the schema name
*/
public String getSchemaName() {
return null;
}
/**
* Get the table name, or null
*
* @return the table name
*/
public String getTableName() {
return null;
}
/**
* Check whether this expression is a column and can store NULL.
*
* @return whether NULL is allowed
*/
public int getNullable() {
return Column.NULLABLE_UNKNOWN;
}
/**
* Get the table alias name or null
* if this expression does not represent a column.
*
* @return the table alias name
*/
public String getTableAlias() {
return null;
}
/**
* Get the alias name of a column or SQL expression
* if it is not an aliased expression.
*
* @return the alias name
*/
public String getAlias() {
return StringUtils.unEnclose(getSQL());
}
/**
* Only returns true if the expression is a wildcard.
*
* @return if this expression is a wildcard
*/
public boolean isWildcard() {
return false;
}
/**
* Returns the main expression, skipping aliases.
*
* @return the expression
*/
public Expression getNonAliasExpression() {
return this;
}
/**
* Add conditions to a table filter if they can be evaluated.
*
* @param filter the table filter
* @param outerJoin if the expression is part of an outer join
*/
public void addFilterConditions(TableFilter filter, boolean outerJoin) {
if (!addedToFilter && !outerJoin &&
isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
filter.addFilterCondition(this, false);
addedToFilter = true;
}
}
/**
* Convert this expression to a String.
*
* @return the string representation
*/
@Override
public String toString() {
return getSQL();
}
/**
* If this expression consists of column expressions it should return them.
*
* @param session the session
* @return array of expression columns if applicable, null otherwise
*/
@SuppressWarnings("unused")
public Expression[] getExpressionColumns(Session session) {
return null;
}
/**
* Extracts expression columns from ValueArray
*
* @param session the current session
* @param value the value to extract columns from
* @return array of expression columns
*/
static Expression[] getExpressionColumns(Session session, ValueArray value) {
Value[] list = value.getList();
ExpressionColumn[] expr = new ExpressionColumn[list.length];
for (int i = 0, len = list.length; i < len; i++) {
Value v = list[i];
Column col = new Column("C" + (i + 1), v.getType(),
v.getPrecision(), v.getScale(),
v.getDisplaySize());
expr[i] = new ExpressionColumn(session.getDatabase(), col);
}
return expr;
}
/**
* Extracts expression columns from the given result set.
*
* @param session the session
* @param rs the result set
* @return an array of expression columns
*/
public static Expression[] getExpressionColumns(Session session, ResultSet rs) {
try {
ResultSetMetaData meta = rs.getMetaData();
int columnCount = meta.getColumnCount();
Expression[] expressions = new Expression[columnCount];
Database db = session == null ? null : session.getDatabase();
for (int i = 0; i < columnCount; i++) {
String name = meta.getColumnLabel(i + 1);
int type = DataType.getValueTypeFromResultSet(meta, i + 1);
int precision = meta.getPrecision(i + 1);
int scale = meta.getScale(i + 1);
int displaySize = meta.getColumnDisplaySize(i + 1);
Column col = new Column(name, type, precision, scale, displaySize);
Expression expr = new ExpressionColumn(db, col);
expressions[i] = expr;
}
return expressions;
} catch (SQLException e) {
throw DbException.convert(e);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ExpressionColumn.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.HashMap;
import org.h2.api.ErrorCode;
import org.h2.command.Parser;
import org.h2.command.dml.Select;
import org.h2.command.dml.SelectListColumnResolver;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.schema.Constant;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueEnum;
import org.h2.value.ValueNull;
/**
* A expression that represents a column of a table or view.
*/
public class ExpressionColumn extends Expression {
private final Database database;
private final String schemaName;
private final String tableAlias;
private String columnName;
private ColumnResolver columnResolver;
private int queryLevel;
private Column column;
public ExpressionColumn(Database database, Column column) {
this.database = database;
this.column = column;
this.schemaName = null;
this.tableAlias = null;
this.columnName = null;
}
public ExpressionColumn(Database database, String schemaName,
String tableAlias, String columnName) {
this.database = database;
this.schemaName = schemaName;
this.tableAlias = tableAlias;
this.columnName = columnName;
}
@Override
public String getSQL() {
String sql;
boolean quote = database.getSettings().databaseToUpper;
if (column != null) {
sql = column.getSQL();
} else {
sql = quote ? Parser.quoteIdentifier(columnName) : columnName;
}
if (tableAlias != null) {
String a = quote ? Parser.quoteIdentifier(tableAlias) : tableAlias;
sql = a + "." + sql;
}
if (schemaName != null) {
String s = quote ? Parser.quoteIdentifier(schemaName) : schemaName;
sql = s + "." + sql;
}
return sql;
}
public TableFilter getTableFilter() {
return columnResolver == null ? null : columnResolver.getTableFilter();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
if (tableAlias != null && !database.equalsIdentifiers(
tableAlias, resolver.getTableAlias())) {
return;
}
if (schemaName != null && !database.equalsIdentifiers(
schemaName, resolver.getSchemaName())) {
return;
}
for (Column col : resolver.getColumns()) {
String n = resolver.getDerivedColumnName(col);
if (n == null) {
n = col.getName();
}
if (database.equalsIdentifiers(columnName, n)) {
mapColumn(resolver, col, level);
return;
}
}
if (database.equalsIdentifiers(Column.ROWID, columnName)) {
Column col = resolver.getRowIdColumn();
if (col != null) {
mapColumn(resolver, col, level);
return;
}
}
Column[] columns = resolver.getSystemColumns();
for (int i = 0; columns != null && i < columns.length; i++) {
Column col = columns[i];
if (database.equalsIdentifiers(columnName, col.getName())) {
mapColumn(resolver, col, level);
return;
}
}
}
private void mapColumn(ColumnResolver resolver, Column col, int level) {
if (this.columnResolver == null) {
queryLevel = level;
column = col;
this.columnResolver = resolver;
} else if (queryLevel == level && this.columnResolver != resolver) {
if (resolver instanceof SelectListColumnResolver) {
// ignore - already mapped, that's ok
} else {
throw DbException.get(ErrorCode.AMBIGUOUS_COLUMN_NAME_1, columnName);
}
}
}
@Override
public Expression optimize(Session session) {
if (columnResolver == null) {
Schema schema = session.getDatabase().findSchema(
tableAlias == null ? session.getCurrentSchemaName() : tableAlias);
if (schema != null) {
Constant constant = schema.findConstant(columnName);
if (constant != null) {
return constant.getValue();
}
}
String name = columnName;
if (tableAlias != null) {
name = tableAlias + "." + name;
if (schemaName != null) {
name = schemaName + "." + name;
}
}
throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1, name);
}
return columnResolver.optimize(this, column);
}
@Override
public void updateAggregate(Session session) {
Value now = columnResolver.getValue(column);
Select select = columnResolver.getSelect();
if (select == null) {
throw DbException.get(ErrorCode.MUST_GROUP_BY_COLUMN_1, getSQL());
}
HashMap<Expression, Object> values = select.getCurrentGroup();
if (values == null) {
// this is a different level (the enclosing query)
return;
}
Value v = (Value) values.get(this);
if (v == null) {
values.put(this, now);
} else {
if (!database.areEqual(now, v)) {
throw DbException.get(ErrorCode.MUST_GROUP_BY_COLUMN_1, getSQL());
}
}
}
@Override
public Value getValue(Session session) {
Select select = columnResolver.getSelect();
if (select != null) {
HashMap<Expression, Object> values = select.getCurrentGroup();
if (values != null) {
Value v = (Value) values.get(this);
if (v != null) {
return v;
}
}
}
Value value = columnResolver.getValue(column);
if (value == null) {
if (select == null) {
throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, getSQL());
} else {
throw DbException.get(ErrorCode.MUST_GROUP_BY_COLUMN_1, getSQL());
}
}
if (column.getEnumerators() != null && value != ValueNull.INSTANCE) {
return ValueEnum.get(column.getEnumerators(), value.getInt());
}
return value;
}
@Override
public int getType() {
return column.getType();
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
}
public Column getColumn() {
return column;
}
@Override
public int getScale() {
return column.getScale();
}
@Override
public long getPrecision() {
return column.getPrecision();
}
@Override
public int getDisplaySize() {
return column.getDisplaySize();
}
public String getOriginalColumnName() {
return columnName;
}
public String getOriginalTableAliasName() {
return tableAlias;
}
@Override
public String getColumnName() {
return columnName != null ? columnName : column.getName();
}
@Override
public String getSchemaName() {
Table table = column.getTable();
return table == null ? null : table.getSchema().getName();
}
@Override
public String getTableName() {
Table table = column.getTable();
return table == null ? null : table.getName();
}
@Override
public String getAlias() {
if (column != null) {
if (columnResolver != null) {
String name = columnResolver.getDerivedColumnName(column);
if (name != null) {
return name;
}
}
return column.getName();
}
if (tableAlias != null) {
return tableAlias + "." + columnName;
}
return columnName;
}
@Override
public boolean isAutoIncrement() {
return column.getSequence() != null;
}
@Override
public int getNullable() {
return column.isNullable() ? Column.NULLABLE : Column.NOT_NULLABLE;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
return false;
case ExpressionVisitor.READONLY:
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.QUERY_COMPARABLE:
return true;
case ExpressionVisitor.INDEPENDENT:
return this.queryLevel < visitor.getQueryLevel();
case ExpressionVisitor.EVALUATABLE:
// if this column belongs to a 'higher level' query and is
// therefore just a parameter
if (visitor.getQueryLevel() < this.queryLevel) {
return true;
}
if (getTableFilter() == null) {
return false;
}
return getTableFilter().isEvaluatable();
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
visitor.addDataModificationId(column.getTable().getMaxDataModificationId());
return true;
case ExpressionVisitor.NOT_FROM_RESOLVER:
return columnResolver != visitor.getResolver();
case ExpressionVisitor.GET_DEPENDENCIES:
if (column != null) {
visitor.addDependency(column.getTable());
}
return true;
case ExpressionVisitor.GET_COLUMNS:
visitor.addColumn(column);
return true;
default:
throw DbException.throwInternalError("type=" + visitor.getType());
}
}
@Override
public int getCost() {
return 2;
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
TableFilter tf = getTableFilter();
if (filter == tf && column.getType() == Value.BOOLEAN) {
IndexCondition cond = IndexCondition.get(
Comparison.EQUAL, this, ValueExpression.get(
ValueBoolean.TRUE));
filter.addIndexCondition(cond);
}
}
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.FALSE));
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ExpressionList.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueArray;
/**
* A list of expressions, as in (ID, NAME).
* The result of this expression is an array.
*/
public class ExpressionList extends Expression {
private final Expression[] list;
public ExpressionList(Expression[] list) {
this.list = list;
}
@Override
public Value getValue(Session session) {
Value[] v = new Value[list.length];
for (int i = 0; i < list.length; i++) {
v[i] = list[i].getValue(session);
}
return ValueArray.get(v);
}
@Override
public int getType() {
return Value.ARRAY;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
for (Expression e : list) {
e.mapColumns(resolver, level);
}
}
@Override
public Expression optimize(Session session) {
boolean allConst = true;
for (int i = 0; i < list.length; i++) {
Expression e = list[i].optimize(session);
if (!e.isConstant()) {
allConst = false;
}
list[i] = e;
}
if (allConst) {
return ValueExpression.get(getValue(session));
}
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
for (Expression e : list) {
e.setEvaluatable(tableFilter, b);
}
}
@Override
public int getScale() {
return 0;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
return Integer.MAX_VALUE;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder("(");
for (Expression e: list) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
if (list.length == 1) {
buff.append(',');
}
return buff.append(')').toString();
}
@Override
public void updateAggregate(Session session) {
for (Expression e : list) {
e.updateAggregate(session);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
for (Expression e : list) {
if (!e.isEverything(visitor)) {
return false;
}
}
return true;
}
@Override
public int getCost() {
int cost = 1;
for (Expression e : list) {
cost += e.getCost();
}
return cost;
}
@Override
public Expression[] getExpressionColumns(Session session) {
ExpressionColumn[] expr = new ExpressionColumn[list.length];
for (int i = 0; i < list.length; i++) {
Expression e = list[i];
Column col = new Column("C" + (i + 1),
e.getType(), e.getPrecision(), e.getScale(),
e.getDisplaySize());
expr[i] = new ExpressionColumn(session.getDatabase(), col);
}
return expr;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ExpressionVisitor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.HashSet;
import org.h2.engine.DbObject;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.Table;
import org.h2.table.TableFilter;
/**
* The visitor pattern is used to iterate through all expressions of a query
* to optimize a statement.
*/
public class ExpressionVisitor {
/**
* Is the value independent on unset parameters or on columns of a higher
* level query, or sequence values (that means can it be evaluated right
* now)?
*/
public static final int INDEPENDENT = 0;
/**
* The visitor singleton for the type INDEPENDENT.
*/
public static final ExpressionVisitor INDEPENDENT_VISITOR =
new ExpressionVisitor(INDEPENDENT);
/**
* Are all aggregates MIN(column), MAX(column), or COUNT(*) for the given
* table (getTable)?
*/
public static final int OPTIMIZABLE_MIN_MAX_COUNT_ALL = 1;
/**
* Does the expression return the same results for the same parameters?
*/
public static final int DETERMINISTIC = 2;
/**
* The visitor singleton for the type DETERMINISTIC.
*/
public static final ExpressionVisitor DETERMINISTIC_VISITOR =
new ExpressionVisitor(DETERMINISTIC);
/**
* Can the expression be evaluated, that means are all columns set to
* 'evaluatable'?
*/
public static final int EVALUATABLE = 3;
/**
* The visitor singleton for the type EVALUATABLE.
*/
public static final ExpressionVisitor EVALUATABLE_VISITOR =
new ExpressionVisitor(EVALUATABLE);
/**
* Request to set the latest modification id (addDataModificationId).
*/
public static final int SET_MAX_DATA_MODIFICATION_ID = 4;
/**
* Does the expression have no side effects (change the data)?
*/
public static final int READONLY = 5;
/**
* The visitor singleton for the type EVALUATABLE.
*/
public static final ExpressionVisitor READONLY_VISITOR =
new ExpressionVisitor(READONLY);
/**
* Does an expression have no relation to the given table filter
* (getResolver)?
*/
public static final int NOT_FROM_RESOLVER = 6;
/**
* Request to get the set of dependencies (addDependency).
*/
public static final int GET_DEPENDENCIES = 7;
/**
* Can the expression be added to a condition of an outer query. Example:
* ROWNUM() can't be added as a condition to the inner query of select id
* from (select t.*, rownum as r from test t) where r between 2 and 3; Also
* a sequence expression must not be used.
*/
public static final int QUERY_COMPARABLE = 8;
/**
* Get all referenced columns.
*/
public static final int GET_COLUMNS = 9;
/**
* The visitor singleton for the type QUERY_COMPARABLE.
*/
public static final ExpressionVisitor QUERY_COMPARABLE_VISITOR =
new ExpressionVisitor(QUERY_COMPARABLE);
private final int type;
private final int queryLevel;
private final HashSet<DbObject> dependencies;
private final HashSet<Column> columns;
private final Table table;
private final long[] maxDataModificationId;
private final ColumnResolver resolver;
private ExpressionVisitor(int type,
int queryLevel,
HashSet<DbObject> dependencies,
HashSet<Column> columns, Table table, ColumnResolver resolver,
long[] maxDataModificationId) {
this.type = type;
this.queryLevel = queryLevel;
this.dependencies = dependencies;
this.columns = columns;
this.table = table;
this.resolver = resolver;
this.maxDataModificationId = maxDataModificationId;
}
private ExpressionVisitor(int type) {
this.type = type;
this.queryLevel = 0;
this.dependencies = null;
this.columns = null;
this.table = null;
this.resolver = null;
this.maxDataModificationId = null;
}
/**
* Create a new visitor object to collect dependencies.
*
* @param dependencies the dependencies set
* @return the new visitor
*/
public static ExpressionVisitor getDependenciesVisitor(
HashSet<DbObject> dependencies) {
return new ExpressionVisitor(GET_DEPENDENCIES, 0, dependencies, null,
null, null, null);
}
/**
* Create a new visitor to check if all aggregates are for the given table.
*
* @param table the table
* @return the new visitor
*/
public static ExpressionVisitor getOptimizableVisitor(Table table) {
return new ExpressionVisitor(OPTIMIZABLE_MIN_MAX_COUNT_ALL, 0, null,
null, table, null, null);
}
/**
* Create a new visitor to check if no expression depends on the given
* resolver.
*
* @param resolver the resolver
* @return the new visitor
*/
static ExpressionVisitor getNotFromResolverVisitor(ColumnResolver resolver) {
return new ExpressionVisitor(NOT_FROM_RESOLVER, 0, null, null, null,
resolver, null);
}
/**
* Create a new visitor to get all referenced columns.
*
* @param columns the columns map
* @return the new visitor
*/
public static ExpressionVisitor getColumnsVisitor(HashSet<Column> columns) {
return new ExpressionVisitor(GET_COLUMNS, 0, null, columns, null, null, null);
}
public static ExpressionVisitor getMaxModificationIdVisitor() {
return new ExpressionVisitor(SET_MAX_DATA_MODIFICATION_ID, 0, null,
null, null, null, new long[1]);
}
/**
* Add a new dependency to the set of dependencies.
* This is used for GET_DEPENDENCIES visitors.
*
* @param obj the additional dependency.
*/
public void addDependency(DbObject obj) {
dependencies.add(obj);
}
/**
* Add a new column to the set of columns.
* This is used for GET_COLUMNS visitors.
*
* @param column the additional column.
*/
void addColumn(Column column) {
columns.add(column);
}
/**
* Get the dependency set.
* This is used for GET_DEPENDENCIES visitors.
*
* @return the set
*/
public HashSet<DbObject> getDependencies() {
return dependencies;
}
/**
* Increment or decrement the query level.
*
* @param offset 1 to increment, -1 to decrement
* @return a clone of this expression visitor, with the changed query level
*/
public ExpressionVisitor incrementQueryLevel(int offset) {
return new ExpressionVisitor(type, queryLevel + offset, dependencies,
columns, table, resolver, maxDataModificationId);
}
/**
* Get the column resolver.
* This is used for NOT_FROM_RESOLVER visitors.
*
* @return the column resolver
*/
public ColumnResolver getResolver() {
return resolver;
}
/**
* Update the field maxDataModificationId if this value is higher
* than the current value.
* This is used for SET_MAX_DATA_MODIFICATION_ID visitors.
*
* @param value the data modification id
*/
public void addDataModificationId(long value) {
long m = maxDataModificationId[0];
if (value > m) {
maxDataModificationId[0] = value;
}
}
/**
* Get the last data modification.
* This is used for SET_MAX_DATA_MODIFICATION_ID visitors.
*
* @return the maximum modification id
*/
public long getMaxDataModificationId() {
return maxDataModificationId[0];
}
int getQueryLevel() {
return queryLevel;
}
/**
* Get the table.
* This is used for OPTIMIZABLE_MIN_MAX_COUNT_ALL visitors.
*
* @return the table
*/
public Table getTable() {
return table;
}
/**
* Get the visitor type.
*
* @return the type
*/
public int getType() {
return type;
}
/**
* Get the set of columns of all tables.
*
* @param filters the filters
* @return the set of columns
*/
public static HashSet<Column> allColumnsForTableFilters(TableFilter[] filters) {
HashSet<Column> allColumnsSet = new HashSet<>();
for (TableFilter filter : filters) {
if (filter.getSelect() != null) {
filter.getSelect().isEverything(ExpressionVisitor.getColumnsVisitor(allColumnsSet));
}
}
return allColumnsSet;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Function.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.h2.api.ErrorCode;
import org.h2.command.Command;
import org.h2.command.Parser;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Mode;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
import org.h2.security.BlockCipher;
import org.h2.security.CipherFactory;
import org.h2.security.SHA256;
import org.h2.store.fs.FileUtils;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.LinkSchema;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.tools.CompressTool;
import org.h2.tools.Csv;
import org.h2.util.DateTimeFunctions;
import org.h2.util.DateTimeUtils;
import org.h2.util.IOUtils;
import org.h2.util.JdbcUtils;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.util.ToChar;
import org.h2.util.ToDateParser;
import org.h2.util.Utils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueBytes;
import org.h2.value.ValueDate;
import org.h2.value.ValueDouble;
import org.h2.value.ValueInt;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueResultSet;
import org.h2.value.ValueString;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
import org.h2.value.ValueUuid;
/**
* This class implements most built-in functions of this database.
*/
public class Function extends Expression implements FunctionCall {
public static final int ABS = 0, ACOS = 1, ASIN = 2, ATAN = 3, ATAN2 = 4,
BITAND = 5, BITOR = 6, BITXOR = 7, CEILING = 8, COS = 9, COT = 10,
DEGREES = 11, EXP = 12, FLOOR = 13, LOG = 14, LOG10 = 15, MOD = 16,
PI = 17, POWER = 18, RADIANS = 19, RAND = 20, ROUND = 21,
ROUNDMAGIC = 22, SIGN = 23, SIN = 24, SQRT = 25, TAN = 26,
TRUNCATE = 27, SECURE_RAND = 28, HASH = 29, ENCRYPT = 30,
DECRYPT = 31, COMPRESS = 32, EXPAND = 33, ZERO = 34,
RANDOM_UUID = 35, COSH = 36, SINH = 37, TANH = 38, LN = 39,
BITGET = 40;
public static final int ASCII = 50, BIT_LENGTH = 51, CHAR = 52,
CHAR_LENGTH = 53, CONCAT = 54, DIFFERENCE = 55, HEXTORAW = 56,
INSERT = 57, INSTR = 58, LCASE = 59, LEFT = 60, LENGTH = 61,
LOCATE = 62, LTRIM = 63, OCTET_LENGTH = 64, RAWTOHEX = 65,
REPEAT = 66, REPLACE = 67, RIGHT = 68, RTRIM = 69, SOUNDEX = 70,
SPACE = 71, SUBSTR = 72, SUBSTRING = 73, UCASE = 74, LOWER = 75,
UPPER = 76, POSITION = 77, TRIM = 78, STRINGENCODE = 79,
STRINGDECODE = 80, STRINGTOUTF8 = 81, UTF8TOSTRING = 82,
XMLATTR = 83, XMLNODE = 84, XMLCOMMENT = 85, XMLCDATA = 86,
XMLSTARTDOC = 87, XMLTEXT = 88, REGEXP_REPLACE = 89, RPAD = 90,
LPAD = 91, CONCAT_WS = 92, TO_CHAR = 93, TRANSLATE = 94, ORA_HASH = 95,
TO_DATE = 96, TO_TIMESTAMP = 97, ADD_MONTHS = 98, TO_TIMESTAMP_TZ = 99;
public static final int CURDATE = 100, CURTIME = 101, DATE_ADD = 102,
DATE_DIFF = 103, DAY_NAME = 104, DAY_OF_MONTH = 105,
DAY_OF_WEEK = 106, DAY_OF_YEAR = 107, HOUR = 108, MINUTE = 109,
MONTH = 110, MONTH_NAME = 111, NOW = 112, QUARTER = 113,
SECOND = 114, WEEK = 115, YEAR = 116, CURRENT_DATE = 117,
CURRENT_TIME = 118, CURRENT_TIMESTAMP = 119, EXTRACT = 120,
FORMATDATETIME = 121, PARSEDATETIME = 122, ISO_YEAR = 123,
ISO_WEEK = 124, ISO_DAY_OF_WEEK = 125, DATE_TRUNC = 132;
/**
* Pseudo functions for DATEADD, DATEDIFF, and EXTRACT.
*/
public static final int MILLISECOND = 126, EPOCH = 127, MICROSECOND = 128, NANOSECOND = 129,
TIMEZONE_HOUR = 130, TIMEZONE_MINUTE = 131, DECADE = 132, CENTURY = 133,
MILLENNIUM = 134;
public static final int DATABASE = 150, USER = 151, CURRENT_USER = 152,
IDENTITY = 153, SCOPE_IDENTITY = 154, AUTOCOMMIT = 155,
READONLY = 156, DATABASE_PATH = 157, LOCK_TIMEOUT = 158,
DISK_SPACE_USED = 159, SIGNAL = 160;
private static final Pattern SIGNAL_PATTERN = Pattern.compile("[0-9A-Z]{5}");
public static final int IFNULL = 200, CASEWHEN = 201, CONVERT = 202,
CAST = 203, COALESCE = 204, NULLIF = 205, CASE = 206,
NEXTVAL = 207, CURRVAL = 208, ARRAY_GET = 209, CSVREAD = 210,
CSVWRITE = 211, MEMORY_FREE = 212, MEMORY_USED = 213,
LOCK_MODE = 214, SCHEMA = 215, SESSION_ID = 216,
ARRAY_LENGTH = 217, LINK_SCHEMA = 218, GREATEST = 219, LEAST = 220,
CANCEL_SESSION = 221, SET = 222, TABLE = 223, TABLE_DISTINCT = 224,
FILE_READ = 225, TRANSACTION_ID = 226, TRUNCATE_VALUE = 227,
NVL2 = 228, DECODE = 229, ARRAY_CONTAINS = 230, FILE_WRITE = 232;
public static final int REGEXP_LIKE = 240;
/**
* Used in MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ... VALUES
*/
public static final int VALUES = 250;
/**
* This is called H2VERSION() and not VERSION(), because we return a fake
* value for VERSION() when running under the PostgreSQL ODBC driver.
*/
public static final int H2VERSION = 231;
public static final int ROW_NUMBER = 300;
private static final int VAR_ARGS = -1;
private static final long PRECISION_UNKNOWN = -1;
private static final HashMap<String, FunctionInfo> FUNCTIONS = new HashMap<>();
private static final char[] SOUNDEX_INDEX = new char[128];
protected Expression[] args;
private final FunctionInfo info;
private ArrayList<Expression> varArgs;
private int dataType, scale;
private long precision = PRECISION_UNKNOWN;
private int displaySize;
private final Database database;
static {
// SOUNDEX_INDEX
String index = "7AEIOUY8HW1BFPV2CGJKQSXZ3DT4L5MN6R";
char number = 0;
for (int i = 0, length = index.length(); i < length; i++) {
char c = index.charAt(i);
if (c < '9') {
number = c;
} else {
SOUNDEX_INDEX[c] = number;
SOUNDEX_INDEX[Character.toLowerCase(c)] = number;
}
}
// FUNCTIONS
addFunction("ABS", ABS, 1, Value.NULL);
addFunction("ACOS", ACOS, 1, Value.DOUBLE);
addFunction("ASIN", ASIN, 1, Value.DOUBLE);
addFunction("ATAN", ATAN, 1, Value.DOUBLE);
addFunction("ATAN2", ATAN2, 2, Value.DOUBLE);
addFunction("BITAND", BITAND, 2, Value.LONG);
addFunction("BITGET", BITGET, 2, Value.BOOLEAN);
addFunction("BITOR", BITOR, 2, Value.LONG);
addFunction("BITXOR", BITXOR, 2, Value.LONG);
addFunction("CEILING", CEILING, 1, Value.DOUBLE);
addFunction("CEIL", CEILING, 1, Value.DOUBLE);
addFunction("COS", COS, 1, Value.DOUBLE);
addFunction("COSH", COSH, 1, Value.DOUBLE);
addFunction("COT", COT, 1, Value.DOUBLE);
addFunction("DEGREES", DEGREES, 1, Value.DOUBLE);
addFunction("EXP", EXP, 1, Value.DOUBLE);
addFunction("FLOOR", FLOOR, 1, Value.DOUBLE);
addFunction("LOG", LOG, 1, Value.DOUBLE);
addFunction("LN", LN, 1, Value.DOUBLE);
addFunction("LOG10", LOG10, 1, Value.DOUBLE);
addFunction("MOD", MOD, 2, Value.LONG);
addFunction("PI", PI, 0, Value.DOUBLE);
addFunction("POWER", POWER, 2, Value.DOUBLE);
addFunction("RADIANS", RADIANS, 1, Value.DOUBLE);
// RAND without argument: get the next value
// RAND with one argument: seed the random generator
addFunctionNotDeterministic("RAND", RAND, VAR_ARGS, Value.DOUBLE);
addFunctionNotDeterministic("RANDOM", RAND, VAR_ARGS, Value.DOUBLE);
addFunction("ROUND", ROUND, VAR_ARGS, Value.DOUBLE);
addFunction("ROUNDMAGIC", ROUNDMAGIC, 1, Value.DOUBLE);
addFunction("SIGN", SIGN, 1, Value.INT);
addFunction("SIN", SIN, 1, Value.DOUBLE);
addFunction("SINH", SINH, 1, Value.DOUBLE);
addFunction("SQRT", SQRT, 1, Value.DOUBLE);
addFunction("TAN", TAN, 1, Value.DOUBLE);
addFunction("TANH", TANH, 1, Value.DOUBLE);
addFunction("TRUNCATE", TRUNCATE, VAR_ARGS, Value.NULL);
// same as TRUNCATE
addFunction("TRUNC", TRUNCATE, VAR_ARGS, Value.NULL);
addFunction("HASH", HASH, 3, Value.BYTES);
addFunction("ENCRYPT", ENCRYPT, 3, Value.BYTES);
addFunction("DECRYPT", DECRYPT, 3, Value.BYTES);
addFunctionNotDeterministic("SECURE_RAND", SECURE_RAND, 1, Value.BYTES);
addFunction("COMPRESS", COMPRESS, VAR_ARGS, Value.BYTES);
addFunction("EXPAND", EXPAND, 1, Value.BYTES);
addFunction("ZERO", ZERO, 0, Value.INT);
addFunctionNotDeterministic("RANDOM_UUID", RANDOM_UUID, 0, Value.UUID);
addFunctionNotDeterministic("SYS_GUID", RANDOM_UUID, 0, Value.UUID);
addFunctionNotDeterministic("UUID", RANDOM_UUID, 0, Value.UUID);
// string
addFunction("ASCII", ASCII, 1, Value.INT);
addFunction("BIT_LENGTH", BIT_LENGTH, 1, Value.LONG);
addFunction("CHAR", CHAR, 1, Value.STRING);
addFunction("CHR", CHAR, 1, Value.STRING);
addFunction("CHAR_LENGTH", CHAR_LENGTH, 1, Value.INT);
// same as CHAR_LENGTH
addFunction("CHARACTER_LENGTH", CHAR_LENGTH, 1, Value.INT);
addFunctionWithNull("CONCAT", CONCAT, VAR_ARGS, Value.STRING);
addFunctionWithNull("CONCAT_WS", CONCAT_WS, VAR_ARGS, Value.STRING);
addFunction("DIFFERENCE", DIFFERENCE, 2, Value.INT);
addFunction("HEXTORAW", HEXTORAW, 1, Value.STRING);
addFunctionWithNull("INSERT", INSERT, 4, Value.STRING);
addFunction("LCASE", LCASE, 1, Value.STRING);
addFunction("LEFT", LEFT, 2, Value.STRING);
addFunction("LENGTH", LENGTH, 1, Value.LONG);
// 2 or 3 arguments
addFunction("LOCATE", LOCATE, VAR_ARGS, Value.INT);
// alias for MSSQLServer
addFunction("CHARINDEX", LOCATE, VAR_ARGS, Value.INT);
// same as LOCATE with 2 arguments
addFunction("POSITION", LOCATE, 2, Value.INT);
addFunction("INSTR", INSTR, VAR_ARGS, Value.INT);
addFunction("LTRIM", LTRIM, VAR_ARGS, Value.STRING);
addFunction("OCTET_LENGTH", OCTET_LENGTH, 1, Value.LONG);
addFunction("RAWTOHEX", RAWTOHEX, 1, Value.STRING);
addFunction("REPEAT", REPEAT, 2, Value.STRING);
addFunction("REPLACE", REPLACE, VAR_ARGS, Value.STRING, false, true,true);
addFunction("RIGHT", RIGHT, 2, Value.STRING);
addFunction("RTRIM", RTRIM, VAR_ARGS, Value.STRING);
addFunction("SOUNDEX", SOUNDEX, 1, Value.STRING);
addFunction("SPACE", SPACE, 1, Value.STRING);
addFunction("SUBSTR", SUBSTR, VAR_ARGS, Value.STRING);
addFunction("SUBSTRING", SUBSTRING, VAR_ARGS, Value.STRING);
addFunction("UCASE", UCASE, 1, Value.STRING);
addFunction("LOWER", LOWER, 1, Value.STRING);
addFunction("UPPER", UPPER, 1, Value.STRING);
addFunction("POSITION", POSITION, 2, Value.INT);
addFunction("TRIM", TRIM, VAR_ARGS, Value.STRING);
addFunction("STRINGENCODE", STRINGENCODE, 1, Value.STRING);
addFunction("STRINGDECODE", STRINGDECODE, 1, Value.STRING);
addFunction("STRINGTOUTF8", STRINGTOUTF8, 1, Value.BYTES);
addFunction("UTF8TOSTRING", UTF8TOSTRING, 1, Value.STRING);
addFunction("XMLATTR", XMLATTR, 2, Value.STRING);
addFunctionWithNull("XMLNODE", XMLNODE, VAR_ARGS, Value.STRING);
addFunction("XMLCOMMENT", XMLCOMMENT, 1, Value.STRING);
addFunction("XMLCDATA", XMLCDATA, 1, Value.STRING);
addFunction("XMLSTARTDOC", XMLSTARTDOC, 0, Value.STRING);
addFunction("XMLTEXT", XMLTEXT, VAR_ARGS, Value.STRING);
addFunction("REGEXP_REPLACE", REGEXP_REPLACE, VAR_ARGS, Value.STRING);
addFunction("RPAD", RPAD, VAR_ARGS, Value.STRING);
addFunction("LPAD", LPAD, VAR_ARGS, Value.STRING);
addFunction("TO_CHAR", TO_CHAR, VAR_ARGS, Value.STRING);
addFunction("ORA_HASH", ORA_HASH, VAR_ARGS, Value.INT);
addFunction("TRANSLATE", TRANSLATE, 3, Value.STRING);
addFunction("REGEXP_LIKE", REGEXP_LIKE, VAR_ARGS, Value.BOOLEAN);
// date
addFunctionNotDeterministic("CURRENT_DATE", CURRENT_DATE,
0, Value.DATE);
addFunctionNotDeterministic("CURDATE", CURDATE,
0, Value.DATE);
addFunctionNotDeterministic("TODAY", CURRENT_DATE,
0, Value.DATE);
addFunction("TO_DATE", TO_DATE, VAR_ARGS, Value.TIMESTAMP);
addFunction("TO_TIMESTAMP", TO_TIMESTAMP, VAR_ARGS, Value.TIMESTAMP);
addFunction("ADD_MONTHS", ADD_MONTHS, 2, Value.TIMESTAMP);
addFunction("TO_TIMESTAMP_TZ", TO_TIMESTAMP_TZ, VAR_ARGS, Value.TIMESTAMP_TZ);
// alias for MSSQLServer
addFunctionNotDeterministic("GETDATE", CURDATE,
0, Value.DATE);
addFunctionNotDeterministic("CURRENT_TIME", CURRENT_TIME,
0, Value.TIME);
addFunctionNotDeterministic("SYSTIME", CURRENT_TIME,
0, Value.TIME);
addFunctionNotDeterministic("CURTIME", CURTIME,
0, Value.TIME);
addFunctionNotDeterministic("CURRENT_TIMESTAMP", CURRENT_TIMESTAMP,
VAR_ARGS, Value.TIMESTAMP);
addFunctionNotDeterministic("SYSDATE", CURRENT_TIMESTAMP,
VAR_ARGS, Value.TIMESTAMP);
addFunctionNotDeterministic("SYSTIMESTAMP", CURRENT_TIMESTAMP,
VAR_ARGS, Value.TIMESTAMP);
addFunctionNotDeterministic("NOW", NOW,
VAR_ARGS, Value.TIMESTAMP);
addFunction("DATEADD", DATE_ADD,
3, Value.TIMESTAMP);
addFunction("TIMESTAMPADD", DATE_ADD,
3, Value.TIMESTAMP);
addFunction("DATEDIFF", DATE_DIFF,
3, Value.LONG);
addFunction("TIMESTAMPDIFF", DATE_DIFF,
3, Value.LONG);
addFunction("DAYNAME", DAY_NAME,
1, Value.STRING);
addFunction("DAYNAME", DAY_NAME,
1, Value.STRING);
addFunction("DAY", DAY_OF_MONTH,
1, Value.INT);
addFunction("DAY_OF_MONTH", DAY_OF_MONTH,
1, Value.INT);
addFunction("DAY_OF_WEEK", DAY_OF_WEEK,
1, Value.INT);
addFunction("DAY_OF_YEAR", DAY_OF_YEAR,
1, Value.INT);
addFunction("DAYOFMONTH", DAY_OF_MONTH,
1, Value.INT);
addFunction("DAYOFWEEK", DAY_OF_WEEK,
1, Value.INT);
addFunction("DAYOFYEAR", DAY_OF_YEAR,
1, Value.INT);
addFunction("HOUR", HOUR,
1, Value.INT);
addFunction("MINUTE", MINUTE,
1, Value.INT);
addFunction("MONTH", MONTH,
1, Value.INT);
addFunction("MONTHNAME", MONTH_NAME,
1, Value.STRING);
addFunction("QUARTER", QUARTER,
1, Value.INT);
addFunction("SECOND", SECOND,
1, Value.INT);
addFunction("WEEK", WEEK,
1, Value.INT);
addFunction("YEAR", YEAR,
1, Value.INT);
addFunction("EXTRACT", EXTRACT,
2, Value.INT);
addFunctionWithNull("FORMATDATETIME", FORMATDATETIME,
VAR_ARGS, Value.STRING);
addFunctionWithNull("PARSEDATETIME", PARSEDATETIME,
VAR_ARGS, Value.TIMESTAMP);
addFunction("ISO_YEAR", ISO_YEAR,
1, Value.INT);
addFunction("ISO_WEEK", ISO_WEEK,
1, Value.INT);
addFunction("ISO_DAY_OF_WEEK", ISO_DAY_OF_WEEK,
1, Value.INT);
addFunction("DATE_TRUNC", DATE_TRUNC, 2, Value.NULL);
// system
addFunctionNotDeterministic("DATABASE", DATABASE,
0, Value.STRING);
addFunctionNotDeterministic("USER", USER,
0, Value.STRING);
addFunctionNotDeterministic("CURRENT_USER", CURRENT_USER,
0, Value.STRING);
addFunctionNotDeterministic("IDENTITY", IDENTITY,
0, Value.LONG);
addFunctionNotDeterministic("SCOPE_IDENTITY", SCOPE_IDENTITY,
0, Value.LONG);
addFunctionNotDeterministic("IDENTITY_VAL_LOCAL", IDENTITY,
0, Value.LONG);
addFunctionNotDeterministic("LAST_INSERT_ID", IDENTITY,
0, Value.LONG);
addFunctionNotDeterministic("LASTVAL", IDENTITY,
0, Value.LONG);
addFunctionNotDeterministic("AUTOCOMMIT", AUTOCOMMIT,
0, Value.BOOLEAN);
addFunctionNotDeterministic("READONLY", READONLY,
0, Value.BOOLEAN);
addFunction("DATABASE_PATH", DATABASE_PATH,
0, Value.STRING);
addFunctionNotDeterministic("LOCK_TIMEOUT", LOCK_TIMEOUT,
0, Value.INT);
addFunctionWithNull("IFNULL", IFNULL,
2, Value.NULL);
addFunctionWithNull("ISNULL", IFNULL,
2, Value.NULL);
addFunctionWithNull("CASEWHEN", CASEWHEN,
3, Value.NULL);
addFunctionWithNull("CONVERT", CONVERT,
1, Value.NULL);
addFunctionWithNull("CAST", CAST,
1, Value.NULL);
addFunctionWithNull("TRUNCATE_VALUE", TRUNCATE_VALUE,
3, Value.NULL);
addFunctionWithNull("COALESCE", COALESCE,
VAR_ARGS, Value.NULL);
addFunctionWithNull("NVL", COALESCE,
VAR_ARGS, Value.NULL);
addFunctionWithNull("NVL2", NVL2,
3, Value.NULL);
addFunctionWithNull("NULLIF", NULLIF,
2, Value.NULL);
addFunctionWithNull("CASE", CASE,
VAR_ARGS, Value.NULL);
addFunctionNotDeterministic("NEXTVAL", NEXTVAL,
VAR_ARGS, Value.LONG);
addFunctionNotDeterministic("CURRVAL", CURRVAL,
VAR_ARGS, Value.LONG);
addFunction("ARRAY_GET", ARRAY_GET,
2, Value.STRING);
addFunction("ARRAY_CONTAINS", ARRAY_CONTAINS,
2, Value.BOOLEAN, false, true, true);
addFunction("CSVREAD", CSVREAD,
VAR_ARGS, Value.RESULT_SET, false, false, false);
addFunction("CSVWRITE", CSVWRITE,
VAR_ARGS, Value.INT, false, false, true);
addFunctionNotDeterministic("MEMORY_FREE", MEMORY_FREE,
0, Value.INT);
addFunctionNotDeterministic("MEMORY_USED", MEMORY_USED,
0, Value.INT);
addFunctionNotDeterministic("LOCK_MODE", LOCK_MODE,
0, Value.INT);
addFunctionNotDeterministic("SCHEMA", SCHEMA,
0, Value.STRING);
addFunctionNotDeterministic("SESSION_ID", SESSION_ID,
0, Value.INT);
addFunction("ARRAY_LENGTH", ARRAY_LENGTH,
1, Value.INT);
addFunctionNotDeterministic("LINK_SCHEMA", LINK_SCHEMA,
6, Value.RESULT_SET);
addFunctionWithNull("LEAST", LEAST,
VAR_ARGS, Value.NULL);
addFunctionWithNull("GREATEST", GREATEST,
VAR_ARGS, Value.NULL);
addFunctionNotDeterministic("CANCEL_SESSION", CANCEL_SESSION,
1, Value.BOOLEAN);
addFunction("SET", SET,
2, Value.NULL, false, false, true);
addFunction("FILE_READ", FILE_READ,
VAR_ARGS, Value.NULL, false, false, true);
addFunction("FILE_WRITE", FILE_WRITE,
2, Value.LONG, false, false, true);
addFunctionNotDeterministic("TRANSACTION_ID", TRANSACTION_ID,
0, Value.STRING);
addFunctionWithNull("DECODE", DECODE,
VAR_ARGS, Value.NULL);
addFunctionNotDeterministic("DISK_SPACE_USED", DISK_SPACE_USED,
1, Value.LONG);
addFunctionWithNull("SIGNAL", SIGNAL, 2, Value.NULL);
addFunction("H2VERSION", H2VERSION, 0, Value.STRING);
// TableFunction
addFunctionWithNull("TABLE", TABLE,
VAR_ARGS, Value.RESULT_SET);
addFunctionWithNull("TABLE_DISTINCT", TABLE_DISTINCT,
VAR_ARGS, Value.RESULT_SET);
// pseudo function
addFunctionWithNull("ROW_NUMBER", ROW_NUMBER, 0, Value.LONG);
// ON DUPLICATE KEY VALUES function
addFunction("VALUES", VALUES, 1, Value.NULL, false, true, false);
}
protected Function(Database database, FunctionInfo info) {
this.database = database;
this.info = info;
if (info.parameterCount == VAR_ARGS) {
varArgs = New.arrayList();
} else {
args = new Expression[info.parameterCount];
}
}
private static void addFunction(String name, int type, int parameterCount,
int returnDataType, boolean nullIfParameterIsNull, boolean deterministic,
boolean bufferResultSetToLocalTemp) {
FunctionInfo info = new FunctionInfo();
info.name = name;
info.type = type;
info.parameterCount = parameterCount;
info.returnDataType = returnDataType;
info.nullIfParameterIsNull = nullIfParameterIsNull;
info.deterministic = deterministic;
info.bufferResultSetToLocalTemp = bufferResultSetToLocalTemp;
FUNCTIONS.put(name, info);
}
private static void addFunctionNotDeterministic(String name, int type,
int parameterCount, int returnDataType) {
addFunction(name, type, parameterCount, returnDataType, true, false, true);
}
private static void addFunction(String name, int type, int parameterCount,
int returnDataType) {
addFunction(name, type, parameterCount, returnDataType, true, true, true);
}
private static void addFunctionWithNull(String name, int type,
int parameterCount, int returnDataType) {
addFunction(name, type, parameterCount, returnDataType, false, true, true);
}
/**
* Get the function info object for this function, or null if there is no
* such function.
*
* @param name the function name
* @return the function info
*/
private static FunctionInfo getFunctionInfo(String name) {
return FUNCTIONS.get(name);
}
/**
* Get an instance of the given function for this database.
* If no function with this name is found, null is returned.
*
* @param database the database
* @param name the function name
* @return the function object or null
*/
public static Function getFunction(Database database, String name) {
if (!database.getSettings().databaseToUpper) {
// if not yet converted to uppercase, do it now
name = StringUtils.toUpperEnglish(name);
}
FunctionInfo info = getFunctionInfo(name);
if (info == null) {
return null;
}
switch (info.type) {
case TABLE:
case TABLE_DISTINCT:
return new TableFunction(database, info, Long.MAX_VALUE);
default:
return new Function(database, info);
}
}
/**
* Set the parameter expression at the given index.
*
* @param index the index (0, 1,...)
* @param param the expression
*/
public void setParameter(int index, Expression param) {
if (varArgs != null) {
varArgs.add(param);
} else {
if (index >= args.length) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2,
info.name, "" + args.length);
}
args[index] = param;
}
}
@Override
public Value getValue(Session session) {
return getValueWithArgs(session, args);
}
private Value getSimpleValue(Session session, Value v0, Expression[] args,
Value[] values) {
Value result;
switch (info.type) {
case ABS:
result = v0.getSignum() >= 0 ? v0 : v0.negate();
break;
case ACOS:
result = ValueDouble.get(Math.acos(v0.getDouble()));
break;
case ASIN:
result = ValueDouble.get(Math.asin(v0.getDouble()));
break;
case ATAN:
result = ValueDouble.get(Math.atan(v0.getDouble()));
break;
case CEILING:
result = ValueDouble.get(Math.ceil(v0.getDouble()));
break;
case COS:
result = ValueDouble.get(Math.cos(v0.getDouble()));
break;
case COSH:
result = ValueDouble.get(Math.cosh(v0.getDouble()));
break;
case COT: {
double d = Math.tan(v0.getDouble());
if (d == 0.0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
result = ValueDouble.get(1. / d);
break;
}
case DEGREES:
result = ValueDouble.get(Math.toDegrees(v0.getDouble()));
break;
case EXP:
result = ValueDouble.get(Math.exp(v0.getDouble()));
break;
case FLOOR:
result = ValueDouble.get(Math.floor(v0.getDouble()));
break;
case LN:
result = ValueDouble.get(Math.log(v0.getDouble()));
break;
case LOG:
if (database.getMode().logIsLogBase10) {
result = ValueDouble.get(Math.log10(v0.getDouble()));
} else {
result = ValueDouble.get(Math.log(v0.getDouble()));
}
break;
case LOG10:
result = ValueDouble.get(Math.log10(v0.getDouble()));
break;
case PI:
result = ValueDouble.get(Math.PI);
break;
case RADIANS:
result = ValueDouble.get(Math.toRadians(v0.getDouble()));
break;
case RAND: {
if (v0 != null) {
session.getRandom().setSeed(v0.getInt());
}
result = ValueDouble.get(session.getRandom().nextDouble());
break;
}
case ROUNDMAGIC:
result = ValueDouble.get(roundMagic(v0.getDouble()));
break;
case SIGN:
result = ValueInt.get(v0.getSignum());
break;
case SIN:
result = ValueDouble.get(Math.sin(v0.getDouble()));
break;
case SINH:
result = ValueDouble.get(Math.sinh(v0.getDouble()));
break;
case SQRT:
result = ValueDouble.get(Math.sqrt(v0.getDouble()));
break;
case TAN:
result = ValueDouble.get(Math.tan(v0.getDouble()));
break;
case TANH:
result = ValueDouble.get(Math.tanh(v0.getDouble()));
break;
case SECURE_RAND:
result = ValueBytes.getNoCopy(
MathUtils.secureRandomBytes(v0.getInt()));
break;
case EXPAND:
result = ValueBytes.getNoCopy(
CompressTool.getInstance().expand(v0.getBytesNoCopy()));
break;
case ZERO:
result = ValueInt.get(0);
break;
case RANDOM_UUID:
result = ValueUuid.getNewRandom();
break;
// string
case ASCII: {
String s = v0.getString();
if (s.length() == 0) {
result = ValueNull.INSTANCE;
} else {
result = ValueInt.get(s.charAt(0));
}
break;
}
case BIT_LENGTH:
result = ValueLong.get(16 * length(v0));
break;
case CHAR:
result = ValueString.get(String.valueOf((char) v0.getInt()),
database.getMode().treatEmptyStringsAsNull);
break;
case CHAR_LENGTH:
case LENGTH:
result = ValueLong.get(length(v0));
break;
case OCTET_LENGTH:
result = ValueLong.get(2 * length(v0));
break;
case CONCAT_WS:
case CONCAT: {
result = ValueNull.INSTANCE;
int start = 0;
String separator = "";
if (info.type == CONCAT_WS) {
start = 1;
separator = getNullOrValue(session, args, values, 0).getString();
}
for (int i = start; i < args.length; i++) {
Value v = getNullOrValue(session, args, values, i);
if (v == ValueNull.INSTANCE) {
continue;
}
if (result == ValueNull.INSTANCE) {
result = v;
} else {
String tmp = v.getString();
if (!StringUtils.isNullOrEmpty(separator)
&& !StringUtils.isNullOrEmpty(tmp)) {
tmp = separator + tmp;
}
result = ValueString.get(result.getString() + tmp,
database.getMode().treatEmptyStringsAsNull);
}
}
if (info.type == CONCAT_WS) {
if (separator != null && result == ValueNull.INSTANCE) {
result = ValueString.get("",
database.getMode().treatEmptyStringsAsNull);
}
}
break;
}
case HEXTORAW:
result = ValueString.get(hexToRaw(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case LOWER:
case LCASE:
// TODO this is locale specific, need to document or provide a way
// to set the locale
result = ValueString.get(v0.getString().toLowerCase(),
database.getMode().treatEmptyStringsAsNull);
break;
case RAWTOHEX:
result = ValueString.get(rawToHex(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case SOUNDEX:
result = ValueString.get(getSoundex(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case SPACE: {
int len = Math.max(0, v0.getInt());
char[] chars = new char[len];
for (int i = len - 1; i >= 0; i--) {
chars[i] = ' ';
}
result = ValueString.get(new String(chars),
database.getMode().treatEmptyStringsAsNull);
break;
}
case UPPER:
case UCASE:
// TODO this is locale specific, need to document or provide a way
// to set the locale
result = ValueString.get(v0.getString().toUpperCase(),
database.getMode().treatEmptyStringsAsNull);
break;
case STRINGENCODE:
result = ValueString.get(StringUtils.javaEncode(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case STRINGDECODE:
result = ValueString.get(StringUtils.javaDecode(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case STRINGTOUTF8:
result = ValueBytes.getNoCopy(v0.getString().
getBytes(StandardCharsets.UTF_8));
break;
case UTF8TOSTRING:
result = ValueString.get(new String(v0.getBytesNoCopy(),
StandardCharsets.UTF_8),
database.getMode().treatEmptyStringsAsNull);
break;
case XMLCOMMENT:
result = ValueString.get(StringUtils.xmlComment(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case XMLCDATA:
result = ValueString.get(StringUtils.xmlCData(v0.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case XMLSTARTDOC:
result = ValueString.get(StringUtils.xmlStartDoc(),
database.getMode().treatEmptyStringsAsNull);
break;
case DAY_NAME: {
int dayOfWeek = DateTimeUtils.getSundayDayOfWeek(DateTimeUtils.dateAndTimeFromValue(v0)[0]);
result = ValueString.get(DateTimeFunctions.getMonthsAndWeeks(1)[dayOfWeek],
database.getMode().treatEmptyStringsAsNull);
break;
}
case DAY_OF_MONTH:
case DAY_OF_WEEK:
case DAY_OF_YEAR:
case HOUR:
case MINUTE:
case MONTH:
case QUARTER:
case ISO_YEAR:
case ISO_WEEK:
case ISO_DAY_OF_WEEK:
case SECOND:
case WEEK:
case YEAR:
result = ValueInt.get(DateTimeFunctions.getIntDatePart(v0, info.type));
break;
case MONTH_NAME: {
int month = DateTimeUtils.monthFromDateValue(DateTimeUtils.dateAndTimeFromValue(v0)[0]);
result = ValueString.get(DateTimeFunctions.getMonthsAndWeeks(0)[month - 1],
database.getMode().treatEmptyStringsAsNull);
break;
}
case CURDATE:
case CURRENT_DATE: {
long now = session.getTransactionStart();
// need to normalize
result = ValueDate.fromMillis(now);
break;
}
case CURTIME:
case CURRENT_TIME: {
long now = session.getTransactionStart();
// need to normalize
result = ValueTime.fromMillis(now);
break;
}
case NOW:
case CURRENT_TIMESTAMP: {
long now = session.getTransactionStart();
ValueTimestamp vt = ValueTimestamp.fromMillis(now);
if (v0 != null) {
Mode mode = database.getMode();
vt = (ValueTimestamp) vt.convertScale(
mode.convertOnlyToSmallerScale, v0.getInt());
}
result = vt;
break;
}
case DATABASE:
result = ValueString.get(database.getShortName(),
database.getMode().treatEmptyStringsAsNull);
break;
case USER:
case CURRENT_USER:
result = ValueString.get(session.getUser().getName(),
database.getMode().treatEmptyStringsAsNull);
break;
case IDENTITY:
result = session.getLastIdentity();
break;
case SCOPE_IDENTITY:
result = session.getLastScopeIdentity();
break;
case AUTOCOMMIT:
result = ValueBoolean.get(session.getAutoCommit());
break;
case READONLY:
result = ValueBoolean.get(database.isReadOnly());
break;
case DATABASE_PATH: {
String path = database.getDatabasePath();
result = path == null ?
(Value) ValueNull.INSTANCE : ValueString.get(path,
database.getMode().treatEmptyStringsAsNull);
break;
}
case LOCK_TIMEOUT:
result = ValueInt.get(session.getLockTimeout());
break;
case DISK_SPACE_USED:
result = ValueLong.get(getDiskSpaceUsed(session, v0));
break;
case CAST:
case CONVERT: {
v0 = v0.convertTo(dataType);
Mode mode = database.getMode();
v0 = v0.convertScale(mode.convertOnlyToSmallerScale, scale);
v0 = v0.convertPrecision(getPrecision(), false);
result = v0;
break;
}
case MEMORY_FREE:
session.getUser().checkAdmin();
result = ValueInt.get(Utils.getMemoryFree());
break;
case MEMORY_USED:
session.getUser().checkAdmin();
result = ValueInt.get(Utils.getMemoryUsed());
break;
case LOCK_MODE:
result = ValueInt.get(database.getLockMode());
break;
case SCHEMA:
result = ValueString.get(session.getCurrentSchemaName(),
database.getMode().treatEmptyStringsAsNull);
break;
case SESSION_ID:
result = ValueInt.get(session.getId());
break;
case IFNULL: {
result = v0;
if (v0 == ValueNull.INSTANCE) {
result = getNullOrValue(session, args, values, 1);
}
result = convertResult(result);
break;
}
case CASEWHEN: {
Value v;
if (!v0.getBoolean()) {
v = getNullOrValue(session, args, values, 2);
} else {
v = getNullOrValue(session, args, values, 1);
}
result = v.convertTo(dataType);
break;
}
case DECODE: {
int index = -1;
for (int i = 1, len = args.length - 1; i < len; i += 2) {
if (database.areEqual(v0,
getNullOrValue(session, args, values, i))) {
index = i + 1;
break;
}
}
if (index < 0 && args.length % 2 == 0) {
index = args.length - 1;
}
Value v = index < 0 ? ValueNull.INSTANCE :
getNullOrValue(session, args, values, index);
result = v.convertTo(dataType);
break;
}
case NVL2: {
Value v;
if (v0 == ValueNull.INSTANCE) {
v = getNullOrValue(session, args, values, 2);
} else {
v = getNullOrValue(session, args, values, 1);
}
result = v.convertTo(dataType);
break;
}
case COALESCE: {
result = v0;
for (int i = 0; i < args.length; i++) {
Value v = getNullOrValue(session, args, values, i);
if (!(v == ValueNull.INSTANCE)) {
result = v.convertTo(dataType);
break;
}
}
break;
}
case GREATEST:
case LEAST: {
result = ValueNull.INSTANCE;
for (int i = 0; i < args.length; i++) {
Value v = getNullOrValue(session, args, values, i);
if (!(v == ValueNull.INSTANCE)) {
v = v.convertTo(dataType);
if (result == ValueNull.INSTANCE) {
result = v;
} else {
int comp = database.compareTypeSafe(result, v);
if (info.type == GREATEST && comp < 0) {
result = v;
} else if (info.type == LEAST && comp > 0) {
result = v;
}
}
}
}
break;
}
case CASE: {
Expression then = null;
if (v0 == null) {
// Searched CASE expression
// (null, when, then)
// (null, when, then, else)
// (null, when, then, when, then)
// (null, when, then, when, then, else)
for (int i = 1, len = args.length - 1; i < len; i += 2) {
Value when = args[i].getValue(session);
if (when.getBoolean()) {
then = args[i + 1];
break;
}
}
} else {
// Simple CASE expression
// (expr, when, then)
// (expr, when, then, else)
// (expr, when, then, when, then)
// (expr, when, then, when, then, else)
if (!(v0 == ValueNull.INSTANCE)) {
for (int i = 1, len = args.length - 1; i < len; i += 2) {
Value when = args[i].getValue(session);
if (database.areEqual(v0, when)) {
then = args[i + 1];
break;
}
}
}
}
if (then == null && args.length % 2 == 0) {
// then = elsePart
then = args[args.length - 1];
}
Value v = then == null ? ValueNull.INSTANCE : then.getValue(session);
result = v.convertTo(dataType);
break;
}
case ARRAY_GET: {
if (v0.getType() == Value.ARRAY) {
Value v1 = getNullOrValue(session, args, values, 1);
int element = v1.getInt();
Value[] list = ((ValueArray) v0).getList();
if (element < 1 || element > list.length) {
result = ValueNull.INSTANCE;
} else {
result = list[element - 1];
}
} else {
result = ValueNull.INSTANCE;
}
break;
}
case ARRAY_LENGTH: {
if (v0.getType() == Value.ARRAY) {
Value[] list = ((ValueArray) v0).getList();
result = ValueInt.get(list.length);
} else {
result = ValueNull.INSTANCE;
}
break;
}
case ARRAY_CONTAINS: {
result = ValueBoolean.FALSE;
if (v0.getType() == Value.ARRAY) {
Value v1 = getNullOrValue(session, args, values, 1);
Value[] list = ((ValueArray) v0).getList();
for (Value v : list) {
if (v.equals(v1)) {
result = ValueBoolean.TRUE;
break;
}
}
}
break;
}
case CANCEL_SESSION: {
result = ValueBoolean.get(cancelStatement(session, v0.getInt()));
break;
}
case TRANSACTION_ID: {
result = session.getTransactionId();
break;
}
default:
result = null;
}
return result;
}
private Value convertResult(Value v) {
return v.convertTo(dataType);
}
private static boolean cancelStatement(Session session, int targetSessionId) {
session.getUser().checkAdmin();
Session[] sessions = session.getDatabase().getSessions(false);
for (Session s : sessions) {
if (s.getId() == targetSessionId) {
Command c = s.getCurrentCommand();
if (c == null) {
return false;
}
c.cancel();
return true;
}
}
return false;
}
private static long getDiskSpaceUsed(Session session, Value v0) {
Parser p = new Parser(session);
String sql = v0.getString();
Table table = p.parseTableName(sql);
return table.getDiskSpaceUsed();
}
private static Value getNullOrValue(Session session, Expression[] args,
Value[] values, int i) {
if (i >= args.length) {
return null;
}
Value v = values[i];
if (v == null) {
Expression e = args[i];
if (e == null) {
return null;
}
v = values[i] = e.getValue(session);
}
return v;
}
private Value getValueWithArgs(Session session, Expression[] args) {
Value[] values = new Value[args.length];
if (info.nullIfParameterIsNull) {
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
Value v = e.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
values[i] = v;
}
}
Value v0 = getNullOrValue(session, args, values, 0);
Value resultSimple = getSimpleValue(session, v0, args, values);
if (resultSimple != null) {
return resultSimple;
}
Value v1 = getNullOrValue(session, args, values, 1);
Value v2 = getNullOrValue(session, args, values, 2);
Value v3 = getNullOrValue(session, args, values, 3);
Value v4 = getNullOrValue(session, args, values, 4);
Value v5 = getNullOrValue(session, args, values, 5);
Value result;
switch (info.type) {
case ATAN2:
result = ValueDouble.get(
Math.atan2(v0.getDouble(), v1.getDouble()));
break;
case BITAND:
result = ValueLong.get(v0.getLong() & v1.getLong());
break;
case BITGET:
result = ValueBoolean.get((v0.getLong() & (1L << v1.getInt())) != 0);
break;
case BITOR:
result = ValueLong.get(v0.getLong() | v1.getLong());
break;
case BITXOR:
result = ValueLong.get(v0.getLong() ^ v1.getLong());
break;
case MOD: {
long x = v1.getLong();
if (x == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
result = ValueLong.get(v0.getLong() % x);
break;
}
case POWER:
result = ValueDouble.get(Math.pow(
v0.getDouble(), v1.getDouble()));
break;
case ROUND: {
double f = v1 == null ? 1. : Math.pow(10., v1.getDouble());
double middleResult = v0.getDouble() * f;
int oneWithSymbol = middleResult > 0 ? 1 : -1;
result = ValueDouble.get(Math.round(Math.abs(middleResult)) / f * oneWithSymbol);
break;
}
case TRUNCATE: {
if (v0.getType() == Value.TIMESTAMP) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueTimestamp) v0).getDateValue(), 0);
} else if (v0.getType() == Value.DATE) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueDate) v0).getDateValue(), 0);
} else if (v0.getType() == Value.TIMESTAMP_TZ) {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v0;
result = ValueTimestampTimeZone.fromDateValueAndNanos(ts.getDateValue(), 0,
ts.getTimeZoneOffsetMins());
} else if (v0.getType() == Value.STRING) {
ValueTimestamp ts = ValueTimestamp.parse(v0.getString(), session.getDatabase().getMode());
result = ValueTimestamp.fromDateValueAndNanos(ts.getDateValue(), 0);
} else {
double d = v0.getDouble();
int p = v1 == null ? 0 : v1.getInt();
double f = Math.pow(10., p);
double g = d * f;
result = ValueDouble.get(((d < 0) ? Math.ceil(g) : Math.floor(g)) / f);
}
break;
}
case HASH:
result = ValueBytes.getNoCopy(getHash(v0.getString(),
v1.getBytesNoCopy(), v2.getInt()));
break;
case ENCRYPT:
result = ValueBytes.getNoCopy(encrypt(v0.getString(),
v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case DECRYPT:
result = ValueBytes.getNoCopy(decrypt(v0.getString(),
v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case COMPRESS: {
String algorithm = null;
if (v1 != null) {
algorithm = v1.getString();
}
result = ValueBytes.getNoCopy(CompressTool.getInstance().
compress(v0.getBytesNoCopy(), algorithm));
break;
}
case DIFFERENCE:
result = ValueInt.get(getDifference(
v0.getString(), v1.getString()));
break;
case INSERT: {
if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE) {
result = v1;
} else {
result = ValueString.get(insert(v0.getString(),
v1.getInt(), v2.getInt(), v3.getString()),
database.getMode().treatEmptyStringsAsNull);
}
break;
}
case LEFT:
result = ValueString.get(left(v0.getString(), v1.getInt()),
database.getMode().treatEmptyStringsAsNull);
break;
case LOCATE: {
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v0.getString(), v1.getString(), start));
break;
}
case INSTR: {
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v1.getString(), v0.getString(), start));
break;
}
case REPEAT: {
int count = Math.max(0, v1.getInt());
result = ValueString.get(repeat(v0.getString(), count),
database.getMode().treatEmptyStringsAsNull);
break;
}
case REPLACE: {
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE
|| v2 == ValueNull.INSTANCE && database.getMode().getEnum() != Mode.ModeEnum.Oracle) {
result = ValueNull.INSTANCE;
} else {
String s0 = v0.getString();
String s1 = v1.getString();
String s2 = (v2 == null) ? "" : v2.getString();
if (s2 == null) {
s2 = "";
}
result = ValueString.get(StringUtils.replaceAll(s0, s1, s2),
database.getMode().treatEmptyStringsAsNull);
}
break;
}
case RIGHT:
result = ValueString.get(right(v0.getString(), v1.getInt()),
database.getMode().treatEmptyStringsAsNull);
break;
case LTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(),
true, false, v1 == null ? " " : v1.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case TRIM:
result = ValueString.get(StringUtils.trim(v0.getString(),
true, true, v1 == null ? " " : v1.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case RTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(),
false, true, v1 == null ? " " : v1.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case SUBSTR:
case SUBSTRING: {
String s = v0.getString();
int offset = v1.getInt();
if (offset < 0) {
offset = s.length() + offset + 1;
}
int length = v2 == null ? s.length() : v2.getInt();
result = ValueString.get(substring(s, offset, length),
database.getMode().treatEmptyStringsAsNull);
break;
}
case POSITION:
result = ValueInt.get(locate(v0.getString(), v1.getString(), 0));
break;
case XMLATTR:
result = ValueString.get(
StringUtils.xmlAttr(v0.getString(), v1.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case XMLNODE: {
String attr = v1 == null ?
null : v1 == ValueNull.INSTANCE ? null : v1.getString();
String content = v2 == null ?
null : v2 == ValueNull.INSTANCE ? null : v2.getString();
boolean indent = v3 == null ?
true : v3.getBoolean();
result = ValueString.get(StringUtils.xmlNode(
v0.getString(), attr, content, indent),
database.getMode().treatEmptyStringsAsNull);
break;
}
case REGEXP_REPLACE: {
String regexp = v1.getString();
String replacement = v2.getString();
if (database.getMode().regexpReplaceBackslashReferences) {
if ((replacement.indexOf('\\') >= 0) || (replacement.indexOf('$') >= 0)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);
if (c == '$') {
sb.append('\\');
} else if (c == '\\' && ++i < replacement.length()) {
c = replacement.charAt(i);
sb.append(c >= '0' && c <= '9' ? '$' : '\\');
}
sb.append(c);
}
replacement = sb.toString();
}
}
String regexpMode = v3 == null || v3.getString() == null ? "" :
v3.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueString.get(
Pattern.compile(regexp, flags).matcher(v0.getString())
.replaceAll(replacement),
database.getMode().treatEmptyStringsAsNull);
} catch (StringIndexOutOfBoundsException e) {
throw DbException.get(
ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
} catch (PatternSyntaxException e) {
throw DbException.get(
ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
} catch (IllegalArgumentException e) {
throw DbException.get(
ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
}
break;
}
case RPAD:
result = ValueString.get(StringUtils.pad(v0.getString(),
v1.getInt(), v2 == null ? null : v2.getString(), true),
database.getMode().treatEmptyStringsAsNull);
break;
case LPAD:
result = ValueString.get(StringUtils.pad(v0.getString(),
v1.getInt(), v2 == null ? null : v2.getString(), false),
database.getMode().treatEmptyStringsAsNull);
break;
case ORA_HASH:
result = ValueLong.get(oraHash(v0.getString(),
v1 == null ? null : v1.getInt(),
v2 == null ? null : v2.getInt()));
break;
case TO_CHAR:
switch (v0.getType()){
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
result = ValueString.get(ToChar.toCharDateTime(v0,
v1 == null ? null : v1.getString(),
v2 == null ? null : v2.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
case Value.SHORT:
case Value.INT:
case Value.LONG:
case Value.DECIMAL:
case Value.DOUBLE:
case Value.FLOAT:
result = ValueString.get(ToChar.toChar(v0.getBigDecimal(),
v1 == null ? null : v1.getString(),
v2 == null ? null : v2.getString()),
database.getMode().treatEmptyStringsAsNull);
break;
default:
result = ValueString.get(v0.getString(),
database.getMode().treatEmptyStringsAsNull);
}
break;
case TO_DATE:
result = ToDateParser.toDate(v0.getString(),
v1 == null ? null : v1.getString());
break;
case TO_TIMESTAMP:
result = ToDateParser.toTimestamp(v0.getString(),
v1 == null ? null : v1.getString());
break;
case ADD_MONTHS:
result = DateTimeFunctions.dateadd("MONTH", v1.getInt(), v0);
break;
case TO_TIMESTAMP_TZ:
result = ToDateParser.toTimestampTz(v0.getString(),
v1 == null ? null : v1.getString());
break;
case TRANSLATE: {
String matching = v1.getString();
String replacement = v2.getString();
result = ValueString.get(
translate(v0.getString(), matching, replacement),
database.getMode().treatEmptyStringsAsNull);
break;
}
case H2VERSION:
result = ValueString.get(Constants.getVersion(),
database.getMode().treatEmptyStringsAsNull);
break;
case DATE_ADD:
result = DateTimeFunctions.dateadd(v0.getString(), v1.getLong(), v2);
break;
case DATE_DIFF:
result = ValueLong.get(DateTimeFunctions.datediff(v0.getString(), v1, v2));
break;
case DATE_TRUNC:
result = DateTimeFunctions.truncateDate(v0.getString(), v1);
break;
case EXTRACT:
result = DateTimeFunctions.extract(v0.getString(), v1);
break;
case FORMATDATETIME: {
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ?
null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ?
null : v3 == ValueNull.INSTANCE ? null : v3.getString();
if (v0 instanceof ValueTimestampTimeZone) {
tz = DateTimeUtils.timeZoneNameFromOffsetMins(
((ValueTimestampTimeZone) v0).getTimeZoneOffsetMins());
}
result = ValueString.get(DateTimeFunctions.formatDateTime(
v0.getTimestamp(), v1.getString(), locale, tz),
database.getMode().treatEmptyStringsAsNull);
}
break;
}
case PARSEDATETIME: {
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ?
null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ?
null : v3 == ValueNull.INSTANCE ? null : v3.getString();
java.util.Date d = DateTimeFunctions.parseDateTime(
v0.getString(), v1.getString(), locale, tz);
result = ValueTimestamp.fromMillis(d.getTime());
}
break;
}
case NULLIF:
result = database.areEqual(v0, v1) ? ValueNull.INSTANCE : v0;
break;
// system
case NEXTVAL: {
Sequence sequence = getSequence(session, v0, v1);
SequenceValue value = new SequenceValue(sequence);
result = value.getValue(session);
break;
}
case CURRVAL: {
Sequence sequence = getSequence(session, v0, v1);
result = ValueLong.get(sequence.getCurrentValue());
break;
}
case CSVREAD: {
String fileName = v0.getString();
String columnList = v1 == null ? null : v1.getString();
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorRead = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
setCsvDelimiterEscape(csv, fieldSeparatorRead, fieldDelimiter,
escapeCharacter);
csv.setNullString(nullString);
}
char fieldSeparator = csv.getFieldSeparatorRead();
String[] columns = StringUtils.arraySplit(columnList,
fieldSeparator, true);
try {
result = ValueResultSet.get(csv.read(fileName,
columns, charset));
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case LINK_SCHEMA: {
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
ResultSet rs = LinkSchema.linkSchema(conn, v0.getString(),
v1.getString(), v2.getString(), v3.getString(),
v4.getString(), v5.getString());
result = ValueResultSet.get(rs);
break;
}
case CSVWRITE: {
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorWrite = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
Value v7 = getNullOrValue(session, args, values, 7);
String lineSeparator = v7 == null ? null : v7.getString();
setCsvDelimiterEscape(csv, fieldSeparatorWrite, fieldDelimiter,
escapeCharacter);
csv.setNullString(nullString);
if (lineSeparator != null) {
csv.setLineSeparator(lineSeparator);
}
}
try {
int rows = csv.write(conn, v0.getString(), v1.getString(),
charset);
result = ValueInt.get(rows);
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case SET: {
Variable var = (Variable) args[0];
session.setVariable(var.getName(), v1);
result = v1;
break;
}
case FILE_READ: {
session.getUser().checkAdmin();
String fileName = v0.getString();
boolean blob = args.length == 1;
try {
long fileLength = FileUtils.size(fileName);
final InputStream in = FileUtils.newInputStream(fileName);
try {
if (blob) {
result = database.getLobStorage().createBlob(in, fileLength);
} else {
Reader reader;
if (v1 == ValueNull.INSTANCE) {
reader = new InputStreamReader(in);
} else {
reader = new InputStreamReader(in, v1.getString());
}
result = database.getLobStorage().createClob(reader, fileLength);
}
} finally {
IOUtils.closeSilently(in);
}
session.addTemporaryLob(result);
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case FILE_WRITE: {
session.getUser().checkAdmin();
result = ValueNull.INSTANCE;
String fileName = v1.getString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
try (InputStream in = v0.getInputStream()) {
result = ValueLong.get(IOUtils.copyAndClose(in,
fileOutputStream));
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case TRUNCATE_VALUE: {
result = v0.convertPrecision(v1.getLong(), v2.getBoolean());
break;
}
case XMLTEXT:
if (v1 == null) {
result = ValueString.get(StringUtils.xmlText(
v0.getString()),
database.getMode().treatEmptyStringsAsNull);
} else {
result = ValueString.get(StringUtils.xmlText(
v0.getString(), v1.getBoolean()),
database.getMode().treatEmptyStringsAsNull);
}
break;
case REGEXP_LIKE: {
String regexp = v1.getString();
String regexpMode = v2 == null || v2.getString() == null ? "" :
v2.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueBoolean.get(Pattern.compile(regexp, flags)
.matcher(v0.getString()).find());
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
}
break;
}
case VALUES:
result = session.getVariable(args[0].getSchemaName() + "." +
args[0].getTableName() + "." + args[0].getColumnName());
break;
case SIGNAL: {
String sqlState = v0.getString();
if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches()) {
throw DbException.getInvalidValueException("SQLSTATE", sqlState);
}
String msgText = v1.getString();
throw DbException.fromUser(sqlState, msgText);
}
default:
throw DbException.throwInternalError("type=" + info.type);
}
return result;
}
private Sequence getSequence(Session session, Value v0, Value v1) {
String schemaName, sequenceName;
if (v1 == null) {
Parser p = new Parser(session);
String sql = v0.getString();
Expression expr = p.parseExpression(sql);
if (expr instanceof ExpressionColumn) {
ExpressionColumn seq = (ExpressionColumn) expr;
schemaName = seq.getOriginalTableAliasName();
if (schemaName == null) {
schemaName = session.getCurrentSchemaName();
sequenceName = sql;
} else {
sequenceName = seq.getColumnName();
}
} else {
throw DbException.getSyntaxError(sql, 1);
}
} else {
schemaName = v0.getString();
sequenceName = v1.getString();
}
Schema s = database.findSchema(schemaName);
if (s == null) {
schemaName = StringUtils.toUpperEnglish(schemaName);
s = database.getSchema(schemaName);
}
Sequence seq = s.findSequence(sequenceName);
if (seq == null) {
sequenceName = StringUtils.toUpperEnglish(sequenceName);
seq = s.getSequence(sequenceName);
}
return seq;
}
private static long length(Value v) {
switch (v.getType()) {
case Value.BLOB:
case Value.CLOB:
case Value.BYTES:
case Value.JAVA_OBJECT:
return v.getPrecision();
default:
return v.getString().length();
}
}
private static byte[] getPaddedArrayCopy(byte[] data, int blockSize) {
int size = MathUtils.roundUpInt(data.length, blockSize);
return Utils.copyBytes(data, size);
}
private static byte[] decrypt(String algorithm, byte[] key, byte[] data) {
BlockCipher cipher = CipherFactory.getBlockCipher(algorithm);
byte[] newKey = getPaddedArrayCopy(key, cipher.getKeyLength());
cipher.setKey(newKey);
byte[] newData = getPaddedArrayCopy(data, BlockCipher.ALIGN);
cipher.decrypt(newData, 0, newData.length);
return newData;
}
private static byte[] encrypt(String algorithm, byte[] key, byte[] data) {
BlockCipher cipher = CipherFactory.getBlockCipher(algorithm);
byte[] newKey = getPaddedArrayCopy(key, cipher.getKeyLength());
cipher.setKey(newKey);
byte[] newData = getPaddedArrayCopy(data, BlockCipher.ALIGN);
cipher.encrypt(newData, 0, newData.length);
return newData;
}
private static byte[] getHash(String algorithm, byte[] bytes, int iterations) {
if (!"SHA256".equalsIgnoreCase(algorithm)) {
throw DbException.getInvalidValueException("algorithm", algorithm);
}
for (int i = 0; i < iterations; i++) {
bytes = SHA256.getHash(bytes, false);
}
return bytes;
}
private static String substring(String s, int start, int length) {
int len = s.length();
start--;
if (start < 0) {
start = 0;
}
if (length < 0) {
length = 0;
}
start = (start > len) ? len : start;
if (start + length > len) {
length = len - start;
}
return s.substring(start, start + length);
}
private static String repeat(String s, int count) {
StringBuilder buff = new StringBuilder(s.length() * count);
while (count-- > 0) {
buff.append(s);
}
return buff.toString();
}
private static String rawToHex(String s) {
int length = s.length();
StringBuilder buff = new StringBuilder(4 * length);
for (int i = 0; i < length; i++) {
String hex = Integer.toHexString(s.charAt(i) & 0xffff);
for (int j = hex.length(); j < 4; j++) {
buff.append('0');
}
buff.append(hex);
}
return buff.toString();
}
private static int locate(String search, String s, int start) {
if (start < 0) {
int i = s.length() + start;
return s.lastIndexOf(search, i) + 1;
}
int i = (start == 0) ? 0 : start - 1;
return s.indexOf(search, i) + 1;
}
private static String right(String s, int count) {
if (count < 0) {
count = 0;
} else if (count > s.length()) {
count = s.length();
}
return s.substring(s.length() - count);
}
private static String left(String s, int count) {
if (count < 0) {
count = 0;
} else if (count > s.length()) {
count = s.length();
}
return s.substring(0, count);
}
private static String insert(String s1, int start, int length, String s2) {
if (s1 == null) {
return s2;
}
if (s2 == null) {
return s1;
}
int len1 = s1.length();
int len2 = s2.length();
start--;
if (start < 0 || length <= 0 || len2 == 0 || start > len1) {
return s1;
}
if (start + length > len1) {
length = len1 - start;
}
return s1.substring(0, start) + s2 + s1.substring(start + length);
}
private static String hexToRaw(String s) {
// TODO function hextoraw compatibility with oracle
int len = s.length();
if (len % 4 != 0) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, s);
}
StringBuilder buff = new StringBuilder(len / 4);
for (int i = 0; i < len; i += 4) {
try {
char raw = (char) Integer.parseInt(s.substring(i, i + 4), 16);
buff.append(raw);
} catch (NumberFormatException e) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, s);
}
}
return buff.toString();
}
private static int getDifference(String s1, String s2) {
// TODO function difference: compatibility with SQL Server and HSQLDB
s1 = getSoundex(s1);
s2 = getSoundex(s2);
int e = 0;
for (int i = 0; i < 4; i++) {
if (s1.charAt(i) == s2.charAt(i)) {
e++;
}
}
return e;
}
private static String translate(String original, String findChars,
String replaceChars) {
if (StringUtils.isNullOrEmpty(original) ||
StringUtils.isNullOrEmpty(findChars)) {
return original;
}
// if it stays null, then no replacements have been made
StringBuilder buff = null;
// if shorter than findChars, then characters are removed
// (if null, we don't access replaceChars at all)
int replaceSize = replaceChars == null ? 0 : replaceChars.length();
for (int i = 0, size = original.length(); i < size; i++) {
char ch = original.charAt(i);
int index = findChars.indexOf(ch);
if (index >= 0) {
if (buff == null) {
buff = new StringBuilder(size);
if (i > 0) {
buff.append(original, 0, i);
}
}
if (index < replaceSize) {
ch = replaceChars.charAt(index);
}
}
if (buff != null) {
buff.append(ch);
}
}
return buff == null ? original : buff.toString();
}
private static double roundMagic(double d) {
if ((d < 0.000_000_000_000_1) && (d > -0.000_000_000_000_1)) {
return 0.0;
}
if ((d > 1_000_000_000_000d) || (d < -1_000_000_000_000d)) {
return d;
}
StringBuilder s = new StringBuilder();
s.append(d);
if (s.toString().indexOf('E') >= 0) {
return d;
}
int len = s.length();
if (len < 16) {
return d;
}
if (s.toString().indexOf('.') > len - 3) {
return d;
}
s.delete(len - 2, len);
len -= 2;
char c1 = s.charAt(len - 2);
char c2 = s.charAt(len - 3);
char c3 = s.charAt(len - 4);
if ((c1 == '0') && (c2 == '0') && (c3 == '0')) {
s.setCharAt(len - 1, '0');
} else if ((c1 == '9') && (c2 == '9') && (c3 == '9')) {
s.setCharAt(len - 1, '9');
s.append('9');
s.append('9');
s.append('9');
}
return Double.parseDouble(s.toString());
}
private static String getSoundex(String s) {
int len = s.length();
char[] chars = { '0', '0', '0', '0' };
char lastDigit = '0';
for (int i = 0, j = 0; i < len && j < 4; i++) {
char c = s.charAt(i);
char newDigit = c > SOUNDEX_INDEX.length ?
0 : SOUNDEX_INDEX[c];
if (newDigit != 0) {
if (j == 0) {
chars[j++] = c;
lastDigit = newDigit;
} else if (newDigit <= '6') {
if (newDigit != lastDigit) {
chars[j++] = newDigit;
lastDigit = newDigit;
}
} else if (newDigit == '7') {
lastDigit = newDigit;
}
}
}
return new String(chars);
}
private static Integer oraHash(String s, Integer bucket, Integer seed) {
int hc = s.hashCode();
if (seed != null && seed.intValue() != 0) {
hc *= seed.intValue() * 17;
}
if (bucket == null || bucket.intValue() <= 0) {
// do nothing
} else {
hc %= bucket.intValue();
}
return hc;
}
private static int makeRegexpFlags(String stringFlags) {
int flags = Pattern.UNICODE_CASE;
if (stringFlags != null) {
for (int i = 0; i < stringFlags.length(); ++i) {
switch (stringFlags.charAt(i)) {
case 'i':
flags |= Pattern.CASE_INSENSITIVE;
break;
case 'c':
flags &= ~Pattern.CASE_INSENSITIVE;
break;
case 'n':
flags |= Pattern.DOTALL;
break;
case 'm':
flags |= Pattern.MULTILINE;
break;
default:
throw DbException.get(ErrorCode.INVALID_VALUE_2, stringFlags);
}
}
}
return flags;
}
@Override
public int getType() {
return dataType;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
for (Expression e : args) {
if (e != null) {
e.mapColumns(resolver, level);
}
}
}
/**
* Check if the parameter count is correct.
*
* @param len the number of parameters set
* @throws DbException if the parameter count is incorrect
*/
protected void checkParameterCount(int len) {
int min = 0, max = Integer.MAX_VALUE;
switch (info.type) {
case COALESCE:
case CSVREAD:
case LEAST:
case GREATEST:
min = 1;
break;
case NOW:
case CURRENT_TIMESTAMP:
case RAND:
max = 1;
break;
case COMPRESS:
case LTRIM:
case RTRIM:
case TRIM:
case FILE_READ:
case ROUND:
case XMLTEXT:
case TRUNCATE:
case TO_TIMESTAMP:
case TO_TIMESTAMP_TZ:
min = 1;
max = 2;
break;
case DATE_TRUNC:
min = 2;
max = 2;
break;
case TO_CHAR:
case TO_DATE:
min = 1;
max = 3;
break;
case ORA_HASH:
min = 1;
max = 3;
break;
case REPLACE:
case LOCATE:
case INSTR:
case SUBSTR:
case SUBSTRING:
case LPAD:
case RPAD:
min = 2;
max = 3;
break;
case CONCAT:
case CONCAT_WS:
case CSVWRITE:
min = 2;
break;
case XMLNODE:
min = 1;
max = 4;
break;
case FORMATDATETIME:
case PARSEDATETIME:
min = 2;
max = 4;
break;
case CURRVAL:
case NEXTVAL:
min = 1;
max = 2;
break;
case DECODE:
case CASE:
min = 3;
break;
case REGEXP_REPLACE:
min = 3;
max = 4;
break;
case REGEXP_LIKE:
min = 2;
max = 3;
break;
default:
DbException.throwInternalError("type=" + info.type);
}
boolean ok = (len >= min) && (len <= max);
if (!ok) {
throw DbException.get(
ErrorCode.INVALID_PARAMETER_COUNT_2,
info.name, min + ".." + max);
}
}
/**
* This method is called after all the parameters have been set.
* It checks if the parameter count is correct.
*
* @throws DbException if the parameter count is incorrect.
*/
public void doneWithParameters() {
if (info.parameterCount == VAR_ARGS) {
checkParameterCount(varArgs.size());
args = varArgs.toArray(new Expression[0]);
varArgs = null;
} else {
int len = args.length;
if (len > 0 && args[len - 1] == null) {
throw DbException.get(
ErrorCode.INVALID_PARAMETER_COUNT_2,
info.name, "" + len);
}
}
}
public void setDataType(Column col) {
dataType = col.getType();
precision = col.getPrecision();
displaySize = col.getDisplaySize();
scale = col.getScale();
}
@Override
public Expression optimize(Session session) {
boolean allConst = info.deterministic;
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
if (e == null) {
continue;
}
e = e.optimize(session);
args[i] = e;
if (!e.isConstant()) {
allConst = false;
}
}
int t, s, d;
long p;
Expression p0 = args.length < 1 ? null : args[0];
switch (info.type) {
case IFNULL:
case NULLIF:
case COALESCE:
case LEAST:
case GREATEST: {
t = Value.UNKNOWN;
s = 0;
p = 0;
d = 0;
for (Expression e : args) {
if (e != ValueExpression.getNull()) {
int type = e.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, e.getScale());
p = Math.max(p, e.getPrecision());
d = Math.max(d, e.getDisplaySize());
}
}
}
if (t == Value.UNKNOWN) {
t = Value.STRING;
s = 0;
p = Integer.MAX_VALUE;
d = Integer.MAX_VALUE;
}
break;
}
case CASE:
case DECODE: {
t = Value.UNKNOWN;
s = 0;
p = 0;
d = 0;
// (expr, when, then)
// (expr, when, then, else)
// (expr, when, then, when, then)
// (expr, when, then, when, then, else)
for (int i = 2, len = args.length; i < len; i += 2) {
Expression then = args[i];
if (then != ValueExpression.getNull()) {
int type = then.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, then.getScale());
p = Math.max(p, then.getPrecision());
d = Math.max(d, then.getDisplaySize());
}
}
}
if (args.length % 2 == 0) {
Expression elsePart = args[args.length - 1];
if (elsePart != ValueExpression.getNull()) {
int type = elsePart.getType();
if (type != Value.UNKNOWN && type != Value.NULL) {
t = Value.getHigherOrder(t, type);
s = Math.max(s, elsePart.getScale());
p = Math.max(p, elsePart.getPrecision());
d = Math.max(d, elsePart.getDisplaySize());
}
}
}
if (t == Value.UNKNOWN) {
t = Value.STRING;
s = 0;
p = Integer.MAX_VALUE;
d = Integer.MAX_VALUE;
}
break;
}
case CASEWHEN:
t = Value.getHigherOrder(args[1].getType(), args[2].getType());
p = Math.max(args[1].getPrecision(), args[2].getPrecision());
d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
s = Math.max(args[1].getScale(), args[2].getScale());
break;
case NVL2:
switch (args[1].getType()) {
case Value.STRING:
case Value.CLOB:
case Value.STRING_FIXED:
case Value.STRING_IGNORECASE:
t = args[1].getType();
break;
default:
t = Value.getHigherOrder(args[1].getType(), args[2].getType());
break;
}
p = Math.max(args[1].getPrecision(), args[2].getPrecision());
d = Math.max(args[1].getDisplaySize(), args[2].getDisplaySize());
s = Math.max(args[1].getScale(), args[2].getScale());
break;
case CAST:
case CONVERT:
case TRUNCATE_VALUE:
// data type, precision and scale is already set
t = dataType;
p = precision;
s = scale;
d = displaySize;
break;
case TRUNCATE:
t = p0.getType();
s = p0.getScale();
p = p0.getPrecision();
d = p0.getDisplaySize();
if (t == Value.NULL) {
t = Value.INT;
p = ValueInt.PRECISION;
d = ValueInt.DISPLAY_SIZE;
s = 0;
} else if (t == Value.TIMESTAMP) {
t = Value.DATE;
p = ValueDate.PRECISION;
s = 0;
d = ValueDate.PRECISION;
}
break;
case ABS:
case FLOOR:
case ROUND:
t = p0.getType();
s = p0.getScale();
p = p0.getPrecision();
d = p0.getDisplaySize();
if (t == Value.NULL) {
t = Value.INT;
p = ValueInt.PRECISION;
d = ValueInt.DISPLAY_SIZE;
s = 0;
}
break;
case SET: {
Expression p1 = args[1];
t = p1.getType();
p = p1.getPrecision();
s = p1.getScale();
d = p1.getDisplaySize();
if (!(p0 instanceof Variable)) {
throw DbException.get(
ErrorCode.CAN_ONLY_ASSIGN_TO_VARIABLE_1, p0.getSQL());
}
break;
}
case FILE_READ: {
if (args.length == 1) {
t = Value.BLOB;
} else {
t = Value.CLOB;
}
p = Integer.MAX_VALUE;
s = 0;
d = Integer.MAX_VALUE;
break;
}
case SUBSTRING:
case SUBSTR: {
t = info.returnDataType;
p = args[0].getPrecision();
s = 0;
if (args[1].isConstant()) {
// if only two arguments are used,
// subtract offset from first argument length
p -= args[1].getValue(session).getLong() - 1;
}
if (args.length == 3 && args[2].isConstant()) {
// if the third argument is constant it is at most this value
p = Math.min(p, args[2].getValue(session).getLong());
}
p = Math.max(0, p);
d = MathUtils.convertLongToInt(p);
break;
}
default:
t = info.returnDataType;
DataType type = DataType.getDataType(t);
p = PRECISION_UNKNOWN;
d = 0;
s = type.defaultScale;
}
dataType = t;
precision = p;
scale = s;
displaySize = d;
if (allConst) {
Value v = getValue(session);
if (v == ValueNull.INSTANCE) {
if (info.type == CAST || info.type == CONVERT) {
return this;
}
}
return ValueExpression.get(v);
}
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
for (Expression e : args) {
if (e != null) {
e.setEvaluatable(tableFilter, b);
}
}
}
@Override
public int getScale() {
return scale;
}
@Override
public long getPrecision() {
if (precision == PRECISION_UNKNOWN) {
calculatePrecisionAndDisplaySize();
}
return precision;
}
@Override
public int getDisplaySize() {
if (precision == PRECISION_UNKNOWN) {
calculatePrecisionAndDisplaySize();
}
return displaySize;
}
private void calculatePrecisionAndDisplaySize() {
switch (info.type) {
case ENCRYPT:
case DECRYPT:
precision = args[2].getPrecision();
displaySize = args[2].getDisplaySize();
break;
case COMPRESS:
precision = args[0].getPrecision();
displaySize = args[0].getDisplaySize();
break;
case CHAR:
precision = 1;
displaySize = 1;
break;
case CONCAT:
precision = 0;
displaySize = 0;
for (Expression e : args) {
precision += e.getPrecision();
displaySize = MathUtils.convertLongToInt(
(long) displaySize + e.getDisplaySize());
if (precision < 0) {
precision = Long.MAX_VALUE;
}
}
break;
case HEXTORAW:
precision = (args[0].getPrecision() + 3) / 4;
displaySize = MathUtils.convertLongToInt(precision);
break;
case LCASE:
case LTRIM:
case RIGHT:
case RTRIM:
case UCASE:
case LOWER:
case UPPER:
case TRIM:
case STRINGDECODE:
case UTF8TOSTRING:
case TRUNCATE:
precision = args[0].getPrecision();
displaySize = args[0].getDisplaySize();
break;
case RAWTOHEX:
precision = args[0].getPrecision() * 4;
displaySize = MathUtils.convertLongToInt(precision);
break;
case SOUNDEX:
precision = 4;
displaySize = (int) precision;
break;
case DAY_NAME:
case MONTH_NAME:
// day and month names may be long in some languages
precision = 20;
displaySize = (int) precision;
break;
default:
DataType type = DataType.getDataType(dataType);
precision = type.defaultPrecision;
displaySize = type.defaultDisplaySize;
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder(info.name);
if (info.type == CASE) {
if (args[0] != null) {
buff.append(" ").append(args[0].getSQL());
}
for (int i = 1, len = args.length - 1; i < len; i += 2) {
buff.append(" WHEN ").append(args[i].getSQL());
buff.append(" THEN ").append(args[i + 1].getSQL());
}
if (args.length % 2 == 0) {
buff.append(" ELSE ").append(args[args.length - 1].getSQL());
}
return buff.append(" END").toString();
}
buff.append('(');
switch (info.type) {
case CAST: {
buff.append(args[0].getSQL()).append(" AS ").
append(new Column(null, dataType, precision,
scale, displaySize).getCreateSQL());
break;
}
case CONVERT: {
if (database.getMode().swapConvertFunctionParameters) {
buff.append(new Column(null, dataType, precision,
scale, displaySize).getCreateSQL()).
append(',').append(args[0].getSQL());
} else {
buff.append(args[0].getSQL()).append(',').
append(new Column(null, dataType, precision,
scale, displaySize).getCreateSQL());
}
break;
}
case EXTRACT: {
ValueString v = (ValueString) ((ValueExpression) args[0]).getValue(null);
buff.append(v.getString()).append(" FROM ").append(args[1].getSQL());
break;
}
default: {
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
}
}
return buff.append(')').toString();
}
@Override
public void updateAggregate(Session session) {
for (Expression e : args) {
if (e != null) {
e.updateAggregate(session);
}
}
}
public int getFunctionType() {
return info.type;
}
@Override
public String getName() {
return info.name;
}
@Override
public ValueResultSet getValueForColumnList(Session session,
Expression[] argList) {
switch (info.type) {
case CSVREAD: {
String fileName = argList[0].getValue(session).getString();
if (fileName == null) {
throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "fileName");
}
String columnList = argList.length < 2 ?
null : argList[1].getValue(session).getString();
Csv csv = new Csv();
String options = argList.length < 3 ?
null : argList[2].getValue(session).getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorRead = argList.length < 4 ?
null : argList[3].getValue(session).getString();
String fieldDelimiter = argList.length < 5 ?
null : argList[4].getValue(session).getString();
String escapeCharacter = argList.length < 6 ?
null : argList[5].getValue(session).getString();
setCsvDelimiterEscape(csv, fieldSeparatorRead, fieldDelimiter,
escapeCharacter);
}
char fieldSeparator = csv.getFieldSeparatorRead();
String[] columns = StringUtils.arraySplit(columnList, fieldSeparator, true);
ResultSet rs = null;
ValueResultSet x;
try {
rs = csv.read(fileName, columns, charset);
x = ValueResultSet.getCopy(rs, 0);
} catch (SQLException e) {
throw DbException.convert(e);
} finally {
csv.close();
JdbcUtils.closeSilently(rs);
}
return x;
}
default:
break;
}
return (ValueResultSet) getValueWithArgs(session, argList);
}
private static void setCsvDelimiterEscape(Csv csv, String fieldSeparator,
String fieldDelimiter, String escapeCharacter) {
if (fieldSeparator != null) {
csv.setFieldSeparatorWrite(fieldSeparator);
if (fieldSeparator.length() > 0) {
char fs = fieldSeparator.charAt(0);
csv.setFieldSeparatorRead(fs);
}
}
if (fieldDelimiter != null) {
char fd = fieldDelimiter.length() == 0 ?
0 : fieldDelimiter.charAt(0);
csv.setFieldDelimiter(fd);
}
if (escapeCharacter != null) {
char ec = escapeCharacter.length() == 0 ?
0 : escapeCharacter.charAt(0);
csv.setEscapeCharacter(ec);
}
}
@Override
public Expression[] getArgs() {
return args;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
for (Expression e : args) {
if (e != null && !e.isEverything(visitor)) {
return false;
}
}
switch (visitor.getType()) {
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.READONLY:
return info.deterministic;
case ExpressionVisitor.EVALUATABLE:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.INDEPENDENT:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
case ExpressionVisitor.GET_COLUMNS:
return true;
default:
throw DbException.throwInternalError("type=" + visitor.getType());
}
}
@Override
public int getCost() {
int cost = 3;
for (Expression e : args) {
if (e != null) {
cost += e.getCost();
}
}
return cost;
}
@Override
public boolean isDeterministic() {
return info.deterministic;
}
@Override
public boolean isBufferResultSetToLocalTemp() {
return info.bufferResultSetToLocalTemp;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/FunctionCall.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.value.ValueResultSet;
/**
* This interface is used by the built-in functions,
* as well as the user-defined functions.
*/
public interface FunctionCall {
/**
* Get the name of the function.
*
* @return the name
*/
String getName();
/**
* Get an empty result set with the column names set.
*
* @param session the session
* @param nullArgs the argument list (some arguments may be null)
* @return the empty result set
*/
ValueResultSet getValueForColumnList(Session session, Expression[] nullArgs);
/**
* Get the data type.
*
* @return the data type
*/
int getType();
/**
* Optimize the function if possible.
*
* @param session the session
* @return the optimized expression
*/
Expression optimize(Session session);
/**
* Get the function arguments.
*
* @return argument list
*/
Expression[] getArgs();
/**
* Get the SQL snippet of the function (including arguments).
*
* @return the SQL snippet.
*/
String getSQL();
/**
* Whether the function always returns the same result for the same
* parameters.
*
* @return true if it does
*/
boolean isDeterministic();
/**
* Should the return value ResultSet be buffered in a local temporary file?
*
* @return true if it should be.
*/
boolean isBufferResultSetToLocalTemp();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/FunctionInfo.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
/**
* This class contains information about a built-in function.
*/
class FunctionInfo {
/**
* The name of the function.
*/
String name;
/**
* The function type.
*/
int type;
/**
* The data type of the return value.
*/
int returnDataType;
/**
* The number of parameters.
*/
int parameterCount;
/**
* If the result of the function is NULL if any of the parameters is NULL.
*/
boolean nullIfParameterIsNull;
/**
* If this function always returns the same value for the same parameters.
*/
boolean deterministic;
/**
* Should the return value ResultSet be buffered in a local temporary file?
*/
boolean bufferResultSetToLocalTemp = true;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/JavaAggregate.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import org.h2.api.Aggregate;
import org.h2.api.ErrorCode;
import org.h2.command.Parser;
import org.h2.command.dml.Select;
import org.h2.engine.Session;
import org.h2.engine.UserAggregate;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* This class wraps a user-defined aggregate.
*/
public class JavaAggregate extends Expression {
private final UserAggregate userAggregate;
private final Select select;
private final Expression[] args;
private int[] argTypes;
private Expression filterCondition;
private int dataType;
private Connection userConnection;
private int lastGroupRowId;
public JavaAggregate(UserAggregate userAggregate, Expression[] args,
Select select, Expression filterCondition) {
this.userAggregate = userAggregate;
this.args = args;
this.select = select;
this.filterCondition = filterCondition;
}
@Override
public int getCost() {
int cost = 5;
for (Expression e : args) {
cost += e.getCost();
}
if (filterCondition != null) {
cost += filterCondition.getCost();
}
return cost;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
return Integer.MAX_VALUE;
}
@Override
public int getScale() {
return DataType.getDataType(dataType).defaultScale;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder();
buff.append(Parser.quoteIdentifier(userAggregate.getName())).append('(');
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
buff.append(')');
if (filterCondition != null) {
buff.append(" FILTER (WHERE ").append(filterCondition.getSQL()).append(')');
}
return buff.toString();
}
@Override
public int getType() {
return dataType;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.DETERMINISTIC:
// TODO optimization: some functions are deterministic, but we don't
// know (no setting for that)
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
// user defined aggregate functions can not be optimized
return false;
case ExpressionVisitor.GET_DEPENDENCIES:
visitor.addDependency(userAggregate);
break;
default:
}
for (Expression e : args) {
if (e != null && !e.isEverything(visitor)) {
return false;
}
}
return filterCondition == null || filterCondition.isEverything(visitor);
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
for (Expression arg : args) {
arg.mapColumns(resolver, level);
}
if (filterCondition != null) {
filterCondition.mapColumns(resolver, level);
}
}
@Override
public Expression optimize(Session session) {
userConnection = session.createConnection(false);
int len = args.length;
argTypes = new int[len];
for (int i = 0; i < len; i++) {
Expression expr = args[i];
args[i] = expr.optimize(session);
int type = expr.getType();
argTypes[i] = type;
}
try {
Aggregate aggregate = getInstance();
dataType = aggregate.getInternalType(argTypes);
} catch (SQLException e) {
throw DbException.convert(e);
}
if (filterCondition != null) {
filterCondition = filterCondition.optimize(session);
}
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
for (Expression e : args) {
e.setEvaluatable(tableFilter, b);
}
if (filterCondition != null) {
filterCondition.setEvaluatable(tableFilter, b);
}
}
private Aggregate getInstance() throws SQLException {
Aggregate agg = userAggregate.getInstance();
agg.init(userConnection);
return agg;
}
@Override
public Value getValue(Session session) {
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
throw DbException.get(ErrorCode.INVALID_USE_OF_AGGREGATE_FUNCTION_1, getSQL());
}
try {
Aggregate agg = (Aggregate) group.get(this);
if (agg == null) {
agg = getInstance();
}
Object obj = agg.getResult();
if (obj == null) {
return ValueNull.INSTANCE;
}
return DataType.convertToValue(session, obj, dataType);
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
public void updateAggregate(Session session) {
HashMap<Expression, Object> group = select.getCurrentGroup();
if (group == null) {
// this is a different level (the enclosing query)
return;
}
int groupRowId = select.getCurrentGroupRowId();
if (lastGroupRowId == groupRowId) {
// already visited
return;
}
lastGroupRowId = groupRowId;
if (filterCondition != null) {
if (!filterCondition.getBooleanValue(session)) {
return;
}
}
Aggregate agg = (Aggregate) group.get(this);
try {
if (agg == null) {
agg = getInstance();
group.put(this, agg);
}
Object[] argValues = new Object[args.length];
Object arg = null;
for (int i = 0, len = args.length; i < len; i++) {
Value v = args[i].getValue(session);
v = v.convertTo(argTypes[i]);
arg = v.getObject();
argValues[i] = arg;
}
if (args.length == 1) {
agg.add(arg);
} else {
agg.add(argValues);
}
} catch (SQLException e) {
throw DbException.convert(e);
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/JavaFunction.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.command.Parser;
import org.h2.engine.Constants;
import org.h2.engine.FunctionAlias;
import org.h2.engine.Session;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueNull;
import org.h2.value.ValueResultSet;
/**
* This class wraps a user-defined function.
*/
public class JavaFunction extends Expression implements FunctionCall {
private final FunctionAlias functionAlias;
private final FunctionAlias.JavaMethod javaMethod;
private final Expression[] args;
public JavaFunction(FunctionAlias functionAlias, Expression[] args) {
this.functionAlias = functionAlias;
this.javaMethod = functionAlias.findJavaMethod(args);
this.args = args;
}
@Override
public Value getValue(Session session) {
return javaMethod.getValue(session, args, false);
}
@Override
public int getType() {
return javaMethod.getDataType();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
for (Expression e : args) {
e.mapColumns(resolver, level);
}
}
@Override
public Expression optimize(Session session) {
boolean allConst = isDeterministic();
for (int i = 0, len = args.length; i < len; i++) {
Expression e = args[i].optimize(session);
args[i] = e;
allConst &= e.isConstant();
}
if (allConst) {
return ValueExpression.get(getValue(session));
}
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
for (Expression e : args) {
if (e != null) {
e.setEvaluatable(tableFilter, b);
}
}
}
@Override
public int getScale() {
return DataType.getDataType(getType()).defaultScale;
}
@Override
public long getPrecision() {
return Integer.MAX_VALUE;
}
@Override
public int getDisplaySize() {
return Integer.MAX_VALUE;
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder();
// TODO always append the schema once FUNCTIONS_IN_SCHEMA is enabled
if (functionAlias.getDatabase().getSettings().functionsInSchema ||
!functionAlias.getSchema().getName().equals(Constants.SCHEMA_MAIN)) {
buff.append(
Parser.quoteIdentifier(functionAlias.getSchema().getName()))
.append('.');
}
buff.append(Parser.quoteIdentifier(functionAlias.getName())).append('(');
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
return buff.append(')').toString();
}
@Override
public void updateAggregate(Session session) {
for (Expression e : args) {
if (e != null) {
e.updateAggregate(session);
}
}
}
@Override
public String getName() {
return functionAlias.getName();
}
@Override
public ValueResultSet getValueForColumnList(Session session,
Expression[] argList) {
Value v = javaMethod.getValue(session, argList, true);
return v == ValueNull.INSTANCE ? null : (ValueResultSet) v;
}
@Override
public Expression[] getArgs() {
return args;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.DETERMINISTIC:
if (!isDeterministic()) {
return false;
}
// only if all parameters are deterministic as well
break;
case ExpressionVisitor.GET_DEPENDENCIES:
visitor.addDependency(functionAlias);
break;
default:
}
for (Expression e : args) {
if (e != null && !e.isEverything(visitor)) {
return false;
}
}
return true;
}
@Override
public int getCost() {
int cost = javaMethod.hasConnectionParam() ? 25 : 5;
for (Expression e : args) {
cost += e.getCost();
}
return cost;
}
@Override
public boolean isDeterministic() {
return functionAlias.isDeterministic();
}
@Override
public Expression[] getExpressionColumns(Session session) {
switch (getType()) {
case Value.RESULT_SET:
ValueResultSet rs = getValueForColumnList(session, getArgs());
return getExpressionColumns(session, rs.getResultSet());
case Value.ARRAY:
return getExpressionColumns(session, (ValueArray) getValue(session));
}
return super.getExpressionColumns(session);
}
@Override
public boolean isBufferResultSetToLocalTemp() {
return functionAlias.isBufferResultSetToLocalTemp();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Operation.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Mode;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.MathUtils;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* A mathematical expression, or string concatenation.
*/
public class Operation extends Expression {
public enum OpType {
/**
* This operation represents a string concatenation as in
* 'Hello' || 'World'.
*/
CONCAT,
/**
* This operation represents an addition as in 1 + 2.
*/
PLUS,
/**
* This operation represents a subtraction as in 2 - 1.
*/
MINUS,
/**
* This operation represents a multiplication as in 2 * 3.
*/
MULTIPLY,
/**
* This operation represents a division as in 4 * 2.
*/
DIVIDE,
/**
* This operation represents a negation as in - ID.
*/
NEGATE,
/**
* This operation represents a modulus as in 5 % 2.
*/
MODULUS
}
private OpType opType;
private Expression left, right;
private int dataType;
private boolean convertRight = true;
public Operation(OpType opType, Expression left, Expression right) {
this.opType = opType;
this.left = left;
this.right = right;
}
@Override
public String getSQL() {
String sql;
if (opType == OpType.NEGATE) {
// don't remove the space, otherwise it might end up some thing like
// --1 which is a line remark
sql = "- " + left.getSQL();
} else {
// don't remove the space, otherwise it might end up some thing like
// --1 which is a line remark
sql = left.getSQL() + " " + getOperationToken() + " " + right.getSQL();
}
return "(" + sql + ")";
}
private String getOperationToken() {
switch (opType) {
case NEGATE:
return "-";
case CONCAT:
return "||";
case PLUS:
return "+";
case MINUS:
return "-";
case MULTIPLY:
return "*";
case DIVIDE:
return "/";
case MODULUS:
return "%";
default:
throw DbException.throwInternalError("opType=" + opType);
}
}
@Override
public Value getValue(Session session) {
Value l = left.getValue(session).convertTo(dataType);
Value r;
if (right == null) {
r = null;
} else {
r = right.getValue(session);
if (convertRight) {
r = r.convertTo(dataType);
}
}
switch (opType) {
case NEGATE:
return l == ValueNull.INSTANCE ? l : l.negate();
case CONCAT: {
Mode mode = session.getDatabase().getMode();
if (l == ValueNull.INSTANCE) {
if (mode.nullConcatIsNull) {
return ValueNull.INSTANCE;
}
return r;
} else if (r == ValueNull.INSTANCE) {
if (mode.nullConcatIsNull) {
return ValueNull.INSTANCE;
}
return l;
}
String s1 = l.getString(), s2 = r.getString();
StringBuilder buff = new StringBuilder(s1.length() + s2.length());
buff.append(s1).append(s2);
return ValueString.get(buff.toString());
}
case PLUS:
if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
return l.add(r);
case MINUS:
if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
return l.subtract(r);
case MULTIPLY:
if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
return l.multiply(r);
case DIVIDE:
if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
return l.divide(r);
case MODULUS:
if (l == ValueNull.INSTANCE || r == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
return l.modulus(r);
default:
throw DbException.throwInternalError("type=" + opType);
}
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
left.mapColumns(resolver, level);
if (right != null) {
right.mapColumns(resolver, level);
}
}
@Override
public Expression optimize(Session session) {
left = left.optimize(session);
switch (opType) {
case NEGATE:
dataType = left.getType();
if (dataType == Value.UNKNOWN) {
dataType = Value.DECIMAL;
}
break;
case CONCAT:
right = right.optimize(session);
dataType = Value.STRING;
if (left.isConstant() && right.isConstant()) {
return ValueExpression.get(getValue(session));
}
break;
case PLUS:
case MINUS:
case MULTIPLY:
case DIVIDE:
case MODULUS:
right = right.optimize(session);
int l = left.getType();
int r = right.getType();
if ((l == Value.NULL && r == Value.NULL) ||
(l == Value.UNKNOWN && r == Value.UNKNOWN)) {
// (? + ?) - use decimal by default (the most safe data type) or
// string when text concatenation with + is enabled
if (opType == OpType.PLUS && session.getDatabase().
getMode().allowPlusForStringConcat) {
dataType = Value.STRING;
opType = OpType.CONCAT;
} else {
dataType = Value.DECIMAL;
}
} else if (l == Value.DATE || l == Value.TIMESTAMP ||
l == Value.TIME || r == Value.DATE ||
r == Value.TIMESTAMP || r == Value.TIME) {
if (opType == OpType.PLUS) {
if (r != Value.getHigherOrder(l, r)) {
// order left and right: INT < TIME < DATE < TIMESTAMP
swap();
int t = l;
l = r;
r = t;
}
if (l == Value.INT) {
// Oracle date add
Function f = Function.getFunction(session.getDatabase(), "DATEADD");
f.setParameter(0, ValueExpression.get(ValueString.get("DAY")));
f.setParameter(1, left);
f.setParameter(2, right);
f.doneWithParameters();
return f.optimize(session);
} else if (l == Value.DECIMAL || l == Value.FLOAT || l == Value.DOUBLE) {
// Oracle date add
Function f = Function.getFunction(session.getDatabase(), "DATEADD");
f.setParameter(0, ValueExpression.get(ValueString.get("SECOND")));
left = new Operation(OpType.MULTIPLY, ValueExpression.get(ValueInt
.get(60 * 60 * 24)), left);
f.setParameter(1, left);
f.setParameter(2, right);
f.doneWithParameters();
return f.optimize(session);
} else if (l == Value.TIME && r == Value.TIME) {
dataType = Value.TIME;
return this;
} else if (l == Value.TIME) {
dataType = Value.TIMESTAMP;
return this;
}
} else if (opType == OpType.MINUS) {
if ((l == Value.DATE || l == Value.TIMESTAMP) && r == Value.INT) {
// Oracle date subtract
Function f = Function.getFunction(session.getDatabase(), "DATEADD");
f.setParameter(0, ValueExpression.get(ValueString.get("DAY")));
right = new Operation(OpType.NEGATE, right, null);
right = right.optimize(session);
f.setParameter(1, right);
f.setParameter(2, left);
f.doneWithParameters();
return f.optimize(session);
} else if ((l == Value.DATE || l == Value.TIMESTAMP) &&
(r == Value.DECIMAL || r == Value.FLOAT || r == Value.DOUBLE)) {
// Oracle date subtract
Function f = Function.getFunction(session.getDatabase(), "DATEADD");
f.setParameter(0, ValueExpression.get(ValueString.get("SECOND")));
right = new Operation(OpType.MULTIPLY, ValueExpression.get(ValueInt
.get(60 * 60 * 24)), right);
right = new Operation(OpType.NEGATE, right, null);
right = right.optimize(session);
f.setParameter(1, right);
f.setParameter(2, left);
f.doneWithParameters();
return f.optimize(session);
} else if (l == Value.DATE || l == Value.TIMESTAMP) {
if (r == Value.TIME) {
dataType = Value.TIMESTAMP;
return this;
} else if (r == Value.DATE || r == Value.TIMESTAMP) {
// Oracle date subtract
Function f = Function.getFunction(session.getDatabase(), "DATEDIFF");
f.setParameter(0, ValueExpression.get(ValueString.get("DAY")));
f.setParameter(1, right);
f.setParameter(2, left);
f.doneWithParameters();
return f.optimize(session);
}
} else if (l == Value.TIME && r == Value.TIME) {
dataType = Value.TIME;
return this;
}
} else if (opType == OpType.MULTIPLY) {
if (l == Value.TIME) {
dataType = Value.TIME;
convertRight = false;
return this;
} else if (r == Value.TIME) {
swap();
dataType = Value.TIME;
convertRight = false;
return this;
}
} else if (opType == OpType.DIVIDE) {
if (l == Value.TIME) {
dataType = Value.TIME;
convertRight = false;
return this;
}
}
throw DbException.getUnsupportedException(
DataType.getDataType(l).name + " " +
getOperationToken() + " " +
DataType.getDataType(r).name);
} else {
dataType = Value.getHigherOrder(l, r);
if (DataType.isStringType(dataType) &&
session.getDatabase().getMode().allowPlusForStringConcat) {
opType = OpType.CONCAT;
}
}
break;
default:
DbException.throwInternalError("type=" + opType);
}
if (left.isConstant() && (right == null || right.isConstant())) {
return ValueExpression.get(getValue(session));
}
return this;
}
private void swap() {
Expression temp = left;
left = right;
right = temp;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
left.setEvaluatable(tableFilter, b);
if (right != null) {
right.setEvaluatable(tableFilter, b);
}
}
@Override
public int getType() {
return dataType;
}
@Override
public long getPrecision() {
if (right != null) {
switch (opType) {
case CONCAT:
return left.getPrecision() + right.getPrecision();
default:
return Math.max(left.getPrecision(), right.getPrecision());
}
}
return left.getPrecision();
}
@Override
public int getDisplaySize() {
if (right != null) {
switch (opType) {
case CONCAT:
return MathUtils.convertLongToInt((long) left.getDisplaySize() +
(long) right.getDisplaySize());
default:
return Math.max(left.getDisplaySize(), right.getDisplaySize());
}
}
return left.getDisplaySize();
}
@Override
public int getScale() {
if (right != null) {
return Math.max(left.getScale(), right.getScale());
}
return left.getScale();
}
@Override
public void updateAggregate(Session session) {
left.updateAggregate(session);
if (right != null) {
right.updateAggregate(session);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) &&
(right == null || right.isEverything(visitor));
}
@Override
public int getCost() {
return left.getCost() + 1 + (right == null ? 0 : right.getCost());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Parameter.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.api.ErrorCode;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
/**
* A parameter of a prepared statement.
*/
public class Parameter extends Expression implements ParameterInterface {
private Value value;
private Column column;
private final int index;
public Parameter(int index) {
this.index = index;
}
@Override
public String getSQL() {
return "?" + (index + 1);
}
@Override
public void setValue(Value v, boolean closeOld) {
// don't need to close the old value as temporary files are anyway
// removed
this.value = v;
}
public void setValue(Value v) {
this.value = v;
}
@Override
public Value getParamValue() {
if (value == null) {
// to allow parameters in function tables
return ValueNull.INSTANCE;
}
return value;
}
@Override
public Value getValue(Session session) {
return getParamValue();
}
@Override
public int getType() {
if (value != null) {
return value.getType();
}
if (column != null) {
return column.getType();
}
return Value.UNKNOWN;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
// can't map
}
@Override
public void checkSet() {
if (value == null) {
throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "#" + (index + 1));
}
}
@Override
public Expression optimize(Session session) {
if (session.getDatabase().getMode().treatEmptyStringsAsNull) {
if (value instanceof ValueString) {
value = ValueString.get(value.getString(), true);
}
}
return this;
}
@Override
public boolean isConstant() {
return false;
}
@Override
public boolean isValueSet() {
return value != null;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
// not bound
}
@Override
public int getScale() {
if (value != null) {
return value.getScale();
}
if (column != null) {
return column.getScale();
}
return 0;
}
@Override
public long getPrecision() {
if (value != null) {
return value.getPrecision();
}
if (column != null) {
return column.getPrecision();
}
return 0;
}
@Override
public int getDisplaySize() {
if (value != null) {
return value.getDisplaySize();
}
if (column != null) {
return column.getDisplaySize();
}
return 0;
}
@Override
public void updateAggregate(Session session) {
// nothing to do
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.EVALUATABLE:
// the parameter _will_be_ evaluatable at execute time
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
// it is checked independently if the value is the same as the last
// time
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.GET_COLUMNS:
return true;
case ExpressionVisitor.INDEPENDENT:
return value != null;
default:
throw DbException.throwInternalError("type="+visitor.getType());
}
}
@Override
public int getCost() {
return 0;
}
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.FALSE));
}
public void setColumn(Column column) {
this.column = column;
}
public int getIndex() {
return index;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ParameterInterface.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.message.DbException;
import org.h2.value.Value;
/**
* The interface for client side (remote) and server side parameters.
*/
public interface ParameterInterface {
/**
* Set the value of the parameter.
*
* @param value the new value
* @param closeOld if the old value (if one is set) should be closed
*/
void setValue(Value value, boolean closeOld);
/**
* Get the value of the parameter if set.
*
* @return the value or null
*/
Value getParamValue();
/**
* Check if the value is set.
*
* @throws DbException if not set.
*/
void checkSet() throws DbException;
/**
* Is the value of a parameter set.
*
* @return true if set
*/
boolean isValueSet();
/**
* Get the expected data type of the parameter if no value is set, or the
* data type of the value if one is set.
*
* @return the data type
*/
int getType();
/**
* Get the expected precision of this parameter.
*
* @return the expected precision
*/
long getPrecision();
/**
* Get the expected scale of this parameter.
*
* @return the expected scale
*/
int getScale();
/**
* Check if this column is nullable.
*
* @return Column.NULLABLE_*
*/
int getNullable();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ParameterRemote.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.io.IOException;
import java.sql.ResultSetMetaData;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
import org.h2.value.Transfer;
import org.h2.value.Value;
/**
* A client side (remote) parameter.
*/
public class ParameterRemote implements ParameterInterface {
private Value value;
private final int index;
private int dataType = Value.UNKNOWN;
private long precision;
private int scale;
private int nullable = ResultSetMetaData.columnNullableUnknown;
public ParameterRemote(int index) {
this.index = index;
}
@Override
public void setValue(Value newValue, boolean closeOld) {
if (closeOld && value != null) {
value.remove();
}
value = newValue;
}
@Override
public Value getParamValue() {
return value;
}
@Override
public void checkSet() {
if (value == null) {
throw DbException.get(ErrorCode.PARAMETER_NOT_SET_1, "#" + (index + 1));
}
}
@Override
public boolean isValueSet() {
return value != null;
}
@Override
public int getType() {
return value == null ? dataType : value.getType();
}
@Override
public long getPrecision() {
return value == null ? precision : value.getPrecision();
}
@Override
public int getScale() {
return value == null ? scale : value.getScale();
}
@Override
public int getNullable() {
return nullable;
}
/**
* Write the parameter meta data from the transfer object.
*
* @param transfer the transfer object
*/
public void readMetaData(Transfer transfer) throws IOException {
dataType = transfer.readInt();
precision = transfer.readLong();
scale = transfer.readInt();
nullable = transfer.readInt();
}
/**
* Write the parameter meta data to the transfer object.
*
* @param transfer the transfer object
* @param p the parameter
*/
public static void writeMetaData(Transfer transfer, ParameterInterface p)
throws IOException {
transfer.writeInt(p.getType());
transfer.writeLong(p.getPrecision());
transfer.writeInt(p.getScale());
transfer.writeInt(p.getNullable());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Rownum.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueInt;
/**
* Represents the ROWNUM function.
*/
public class Rownum extends Expression {
private final Prepared prepared;
public Rownum(Prepared prepared) {
if (prepared == null) {
throw DbException.throwInternalError();
}
this.prepared = prepared;
}
@Override
public Value getValue(Session session) {
return ValueInt.get(prepared.getCurrentRowNumber());
}
@Override
public int getType() {
return Value.INT;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
// nothing to do
}
@Override
public Expression optimize(Session session) {
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
// nothing to do
}
@Override
public int getScale() {
return 0;
}
@Override
public long getPrecision() {
return ValueInt.PRECISION;
}
@Override
public int getDisplaySize() {
return ValueInt.DISPLAY_SIZE;
}
@Override
public String getSQL() {
return "ROWNUM()";
}
@Override
public void updateAggregate(Session session) {
// nothing to do
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.INDEPENDENT:
return false;
case ExpressionVisitor.EVALUATABLE:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
case ExpressionVisitor.GET_COLUMNS:
// if everything else is the same, the rownum is the same
return true;
default:
throw DbException.throwInternalError("type="+visitor.getType());
}
}
@Override
public int getCost() {
return 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/SequenceValue.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Sequence;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueLong;
/**
* Wraps a sequence when used in a statement.
*/
public class SequenceValue extends Expression {
private final Sequence sequence;
public SequenceValue(Sequence sequence) {
this.sequence = sequence;
}
@Override
public Value getValue(Session session) {
long value = sequence.getNext(session);
session.setLastIdentity(ValueLong.get(value));
return ValueLong.get(value);
}
@Override
public int getType() {
return Value.LONG;
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
// nothing to do
}
@Override
public Expression optimize(Session session) {
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
// nothing to do
}
@Override
public int getScale() {
return 0;
}
@Override
public long getPrecision() {
return ValueInt.PRECISION;
}
@Override
public int getDisplaySize() {
return ValueInt.DISPLAY_SIZE;
}
@Override
public String getSQL() {
return "(NEXT VALUE FOR " + sequence.getSQL() +")";
}
@Override
public void updateAggregate(Session session) {
// nothing to do
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.EVALUATABLE:
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.GET_COLUMNS:
return true;
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.INDEPENDENT:
case ExpressionVisitor.QUERY_COMPARABLE:
return false;
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
visitor.addDataModificationId(sequence.getModificationId());
return true;
case ExpressionVisitor.GET_DEPENDENCIES:
visitor.addDependency(sequence);
return true;
default:
throw DbException.throwInternalError("type="+visitor.getType());
}
}
@Override
public int getCost() {
return 1;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Subquery.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.dml.Query;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueNull;
/**
* A query returning a single value.
* Subqueries are used inside other statements.
*/
public class Subquery extends Expression {
private final Query query;
private Expression expression;
public Subquery(Query query) {
this.query = query;
}
@Override
public Value getValue(Session session) {
query.setSession(session);
try (ResultInterface result = query.query(2)) {
Value v;
if (!result.next()) {
v = ValueNull.INSTANCE;
} else {
Value[] values = result.currentRow();
if (result.getVisibleColumnCount() == 1) {
v = values[0];
} else {
v = ValueArray.get(values);
}
if (result.hasNext()) {
throw DbException.get(ErrorCode.SCALAR_SUBQUERY_CONTAINS_MORE_THAN_ONE_ROW);
}
}
return v;
}
}
@Override
public int getType() {
return getExpression().getType();
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
query.mapColumns(resolver, level + 1);
}
@Override
public Expression optimize(Session session) {
session.optimizeQueryExpression(query);
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
query.setEvaluatable(tableFilter, b);
}
@Override
public int getScale() {
return getExpression().getScale();
}
@Override
public long getPrecision() {
return getExpression().getPrecision();
}
@Override
public int getDisplaySize() {
return getExpression().getDisplaySize();
}
@Override
public String getSQL() {
return "(" + query.getPlanSQL() + ")";
}
@Override
public void updateAggregate(Session session) {
query.updateAggregate(session);
}
private Expression getExpression() {
if (expression == null) {
ArrayList<Expression> expressions = query.getExpressions();
int columnCount = query.getColumnCount();
if (columnCount == 1) {
expression = expressions.get(0);
} else {
Expression[] list = new Expression[columnCount];
for (int i = 0; i < columnCount; i++) {
list[i] = expressions.get(i);
}
expression = new ExpressionList(list);
}
}
return expression;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return query.isEverything(visitor);
}
public Query getQuery() {
return query;
}
@Override
public int getCost() {
return query.getCostAsExpression();
}
@Override
public Expression[] getExpressionColumns(Session session) {
return getExpression().getExpressionColumns(session);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/TableFunction.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.LocalResult;
import org.h2.table.Column;
import org.h2.tools.SimpleResultSet;
import org.h2.util.MathUtils;
import org.h2.util.StatementBuilder;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueNull;
import org.h2.value.ValueResultSet;
/**
* Implementation of the functions TABLE(..) and TABLE_DISTINCT(..).
*/
public class TableFunction extends Function {
private final boolean distinct;
private final long rowCount;
private Column[] columnList;
TableFunction(Database database, FunctionInfo info, long rowCount) {
super(database, info);
distinct = info.type == Function.TABLE_DISTINCT;
this.rowCount = rowCount;
}
@Override
public Value getValue(Session session) {
return getTable(session, args, false, distinct);
}
@Override
protected void checkParameterCount(int len) {
if (len < 1) {
throw DbException.get(ErrorCode.INVALID_PARAMETER_COUNT_2, getName(), ">0");
}
}
@Override
public String getSQL() {
StatementBuilder buff = new StatementBuilder(getName());
buff.append('(');
int i = 0;
for (Expression e : args) {
buff.appendExceptFirst(", ");
buff.append(columnList[i++].getCreateSQL()).append('=').append(e.getSQL());
}
return buff.append(')').toString();
}
@Override
public String getName() {
return distinct ? "TABLE_DISTINCT" : "TABLE";
}
@Override
public ValueResultSet getValueForColumnList(Session session,
Expression[] nullArgs) {
return getTable(session, args, true, false);
}
public void setColumns(ArrayList<Column> columns) {
this.columnList = columns.toArray(new Column[0]);
}
private ValueResultSet getTable(Session session, Expression[] argList,
boolean onlyColumnList, boolean distinctRows) {
int len = columnList.length;
Expression[] header = new Expression[len];
Database db = session.getDatabase();
for (int i = 0; i < len; i++) {
Column c = columnList[i];
ExpressionColumn col = new ExpressionColumn(db, c);
header[i] = col;
}
LocalResult result = new LocalResult(session, header, len);
if (distinctRows) {
result.setDistinct();
}
if (!onlyColumnList) {
Value[][] list = new Value[len][];
int rows = 0;
for (int i = 0; i < len; i++) {
Value v = argList[i].getValue(session);
if (v == ValueNull.INSTANCE) {
list[i] = new Value[0];
} else {
ValueArray array = (ValueArray) v.convertTo(Value.ARRAY);
Value[] l = array.getList();
list[i] = l;
rows = Math.max(rows, l.length);
}
}
for (int row = 0; row < rows; row++) {
Value[] r = new Value[len];
for (int j = 0; j < len; j++) {
Value[] l = list[j];
Value v;
if (l.length <= row) {
v = ValueNull.INSTANCE;
} else {
Column c = columnList[j];
v = l[row];
v = c.convert(v);
v = v.convertPrecision(c.getPrecision(), false);
v = v.convertScale(true, c.getScale());
}
r[j] = v;
}
result.addRow(r);
}
}
result.done();
return ValueResultSet.get(getSimpleResultSet(result,
Integer.MAX_VALUE));
}
private static SimpleResultSet getSimpleResultSet(LocalResult rs,
int maxrows) {
int columnCount = rs.getVisibleColumnCount();
SimpleResultSet simple = new SimpleResultSet();
simple.setAutoClose(false);
for (int i = 0; i < columnCount; i++) {
String name = rs.getColumnName(i);
/*
* TODO Some types, such as Value.BYTES and Value.UUID are mapped to the same
* SQL type and we can lose real type here.
*/
int sqlType = DataType.convertTypeToSQLType(rs.getColumnType(i));
int precision = MathUtils.convertLongToInt(rs.getColumnPrecision(i));
int scale = rs.getColumnScale(i);
simple.addColumn(name, sqlType, precision, scale);
}
rs.reset();
for (int i = 0; i < maxrows && rs.next(); i++) {
Object[] list = new Object[columnCount];
for (int j = 0; j < columnCount; j++) {
list[j] = rs.currentRow()[j].getObject();
}
simple.addRow(list);
}
return simple;
}
public long getRowCount() {
return rowCount;
}
@Override
public Expression[] getExpressionColumns(Session session) {
return getExpressionColumns(session,
getTable(session, getArgs(), true, false).getResultSet());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/ValueExpression.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.engine.Session;
import org.h2.index.IndexCondition;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueNull;
/**
* An expression representing a constant value.
*/
public class ValueExpression extends Expression {
/**
* The expression represents ValueNull.INSTANCE.
*/
private static final Object NULL = new ValueExpression(ValueNull.INSTANCE);
/**
* This special expression represents the default value. It is used for
* UPDATE statements of the form SET COLUMN = DEFAULT. The value is
* ValueNull.INSTANCE, but should never be accessed.
*/
private static final Object DEFAULT = new ValueExpression(ValueNull.INSTANCE);
private final Value value;
private ValueExpression(Value value) {
this.value = value;
}
/**
* Get the NULL expression.
*
* @return the NULL expression
*/
public static ValueExpression getNull() {
return (ValueExpression) NULL;
}
/**
* Get the DEFAULT expression.
*
* @return the DEFAULT expression
*/
public static ValueExpression getDefault() {
return (ValueExpression) DEFAULT;
}
/**
* Create a new expression with the given value.
*
* @param value the value
* @return the expression
*/
public static ValueExpression get(Value value) {
if (value == ValueNull.INSTANCE) {
return getNull();
}
return new ValueExpression(value);
}
@Override
public Value getValue(Session session) {
return value;
}
@Override
public int getType() {
return value.getType();
}
@Override
public void createIndexConditions(Session session, TableFilter filter) {
if (value.getType() == Value.BOOLEAN) {
boolean v = ((ValueBoolean) value).getBoolean();
if (!v) {
filter.addIndexCondition(IndexCondition.get(Comparison.FALSE, null, this));
}
}
}
@Override
public Expression getNotIfPossible(Session session) {
return new Comparison(session, Comparison.EQUAL, this,
ValueExpression.get(ValueBoolean.FALSE));
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
// nothing to do
}
@Override
public Expression optimize(Session session) {
return this;
}
@Override
public boolean isConstant() {
return true;
}
@Override
public boolean isValueSet() {
return true;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
// nothing to do
}
@Override
public int getScale() {
return value.getScale();
}
@Override
public long getPrecision() {
return value.getPrecision();
}
@Override
public int getDisplaySize() {
return value.getDisplaySize();
}
@Override
public String getSQL() {
if (this == DEFAULT) {
return "DEFAULT";
}
return value.getSQL();
}
@Override
public void updateAggregate(Session session) {
// nothing to do
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.DETERMINISTIC:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.INDEPENDENT:
case ExpressionVisitor.EVALUATABLE:
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.GET_COLUMNS:
return true;
default:
throw DbException.throwInternalError("type=" + visitor.getType());
}
}
@Override
public int getCost() {
return 0;
}
@Override
public Expression[] getExpressionColumns(Session session) {
if (getType() == Value.ARRAY) {
return getExpressionColumns(session, (ValueArray) getValue(session));
}
return super.getExpressionColumns(session);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Variable.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.command.Parser;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.value.Value;
/**
* A user-defined variable, for example: @ID.
*/
public class Variable extends Expression {
private final String name;
private Value lastValue;
public Variable(Session session, String name) {
this.name = name;
lastValue = session.getVariable(name);
}
@Override
public int getCost() {
return 0;
}
@Override
public int getDisplaySize() {
return lastValue.getDisplaySize();
}
@Override
public long getPrecision() {
return lastValue.getPrecision();
}
@Override
public String getSQL() {
return "@" + Parser.quoteIdentifier(name);
}
@Override
public int getScale() {
return lastValue.getScale();
}
@Override
public int getType() {
return lastValue.getType();
}
@Override
public Value getValue(Session session) {
lastValue = session.getVariable(name);
return lastValue;
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.EVALUATABLE:
// the value will be evaluated at execute time
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID:
// it is checked independently if the value is the same as the last
// time
case ExpressionVisitor.OPTIMIZABLE_MIN_MAX_COUNT_ALL:
case ExpressionVisitor.READONLY:
case ExpressionVisitor.INDEPENDENT:
case ExpressionVisitor.NOT_FROM_RESOLVER:
case ExpressionVisitor.QUERY_COMPARABLE:
case ExpressionVisitor.GET_DEPENDENCIES:
case ExpressionVisitor.GET_COLUMNS:
return true;
case ExpressionVisitor.DETERMINISTIC:
return false;
default:
throw DbException.throwInternalError("type="+visitor.getType());
}
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
// nothing to do
}
@Override
public Expression optimize(Session session) {
return this;
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean value) {
// nothing to do
}
@Override
public void updateAggregate(Session session) {
// nothing to do
}
public String getName() {
return name;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/expression/Wildcard.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.expression;
import org.h2.api.ErrorCode;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.StringUtils;
import org.h2.value.Value;
/**
* A wildcard expression as in SELECT * FROM TEST.
* This object is only used temporarily during the parsing phase, and later
* replaced by column expressions.
*/
public class Wildcard extends Expression {
private final String schema;
private final String table;
public Wildcard(String schema, String table) {
this.schema = schema;
this.table = table;
}
@Override
public boolean isWildcard() {
return true;
}
@Override
public Value getValue(Session session) {
throw DbException.throwInternalError(toString());
}
@Override
public int getType() {
throw DbException.throwInternalError(toString());
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table);
}
@Override
public Expression optimize(Session session) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1, table);
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
DbException.throwInternalError(toString());
}
@Override
public int getScale() {
throw DbException.throwInternalError(toString());
}
@Override
public long getPrecision() {
throw DbException.throwInternalError(toString());
}
@Override
public int getDisplaySize() {
throw DbException.throwInternalError(toString());
}
@Override
public String getTableAlias() {
return table;
}
@Override
public String getSchemaName() {
return schema;
}
@Override
public String getSQL() {
if (table == null) {
return "*";
}
return StringUtils.quoteIdentifier(table) + ".*";
}
@Override
public void updateAggregate(Session session) {
DbException.throwInternalError(toString());
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
if (visitor.getType() == ExpressionVisitor.QUERY_COMPARABLE) {
return true;
}
throw DbException.throwInternalError("" + visitor.getType());
}
@Override
public int getCost() {
throw DbException.throwInternalError(toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/ext
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/ext/pulsar/PulsarExtension.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.ext.pulsar;
import org.h2.engine.ConnectionInfo;
import org.h2.engine.FunctionAlias;
import org.h2.engine.Session;
import org.h2.engine.SessionFactory;
import org.h2.engine.SessionInterface;
import org.h2.engine.UserAggregate;
import org.h2.util.JdbcUtils;
import org.h2.util.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
/**
* The extension to support platon pulsar
*
* @author Vincent Zhang ivincent.zhang@gmail.com 2020/08/04
* */
public class PulsarExtension {
public static SessionFactory sessionFactory;
/**
* The default constructor
* */
public PulsarExtension() {
}
/**
* Get the engine implementation
*
* @return The actual engine implementation
* */
public static Class<?> getEngineImplementation() {
String className = Utils.getProperty("h2.sessionFactory", "org.h2.engine.Engine");
return JdbcUtils.loadUserClass(className);
}
/**
* Create a session with the given connection information
*
* @param ci The connection information
* @return The session
* */
public static SessionInterface createSession(ConnectionInfo ci) throws Exception {
if (sessionFactory == null) {
Class<?> engine = getEngineImplementation();
System.err.println("H2 Engine implementation is: " + engine);
sessionFactory = (SessionFactory)engine.getMethod("getInstance").invoke((Object)null);
}
return sessionFactory.createSession(ci);
}
/**
* Close the given session
*
* @param session The session to close
* */
public static void closeSession(Session session) throws Exception {
sessionFactory.closeSession(session.getSerialId());
}
/**
* Shutdown the session factory
* */
public static void shutdownSessionFactory() {
Optional<Method> shutdownNow = Arrays.stream(sessionFactory.getClass().getMethods())
.filter((method) -> method.getName().equals("shutdownNow")).findFirst();
if (shutdownNow.isPresent()) {
try {
((Method)shutdownNow.get()).invoke(sessionFactory);
} catch (InvocationTargetException | IllegalAccessException var2) {
var2.printStackTrace();
}
}
}
/**
* Find a functions by alias
*
* @param functions The functions
* @param functionAlias The function alias to find
* @return The function matching the alias
* */
public static FunctionAlias findFunction(
ConcurrentHashMap<String, FunctionAlias> functions, String functionAlias) {
FunctionAlias f = functions.get(functionAlias);
if (f != null) {
return f;
}
// We support arbitrary "_" in a UDF name, for example, the following functions
// are the same: some_fun_(), _____some_fun_(), some______fun()
functionAlias = functionAlias.replaceAll("_", "");
return functions.get(functionAlias);
}
/**
* Find an aggregates by name
*
* @param aggregates The Aggregates
* @param name The name to find
* @return The UserAggregate matching the name
* */
public static UserAggregate findAggregate(
HashMap<String, UserAggregate> aggregates, String name) {
UserAggregate agg = aggregates.get(name);
if (agg != null) {
return agg;
}
// We support arbitrary "_" in a UDA name, for example, the following functions
// are the same: some_fun_(), _____some_fun_(), some______fun()
name = name.replaceAll("_", "");
return aggregates.get(name);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/fulltext/FullText.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.fulltext;
import java.io.IOException;
import java.io.Reader;
import java.io.StreamTokenizer;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import org.h2.api.Trigger;
import org.h2.command.Parser;
import org.h2.engine.Session;
import org.h2.expression.Comparison;
import org.h2.expression.ConditionAndOr;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ValueExpression;
import org.h2.jdbc.JdbcConnection;
import org.h2.message.DbException;
import org.h2.tools.SimpleResultSet;
import org.h2.util.IOUtils;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
/**
* This class implements the native full text search.
* Most methods can be called using SQL statements as well.
*/
public class FullText {
/**
* A column name of the result set returned by the searchData method.
*/
private static final String FIELD_SCHEMA = "SCHEMA";
/**
* A column name of the result set returned by the searchData method.
*/
private static final String FIELD_TABLE = "TABLE";
/**
* A column name of the result set returned by the searchData method.
*/
private static final String FIELD_COLUMNS = "COLUMNS";
/**
* A column name of the result set returned by the searchData method.
*/
private static final String FIELD_KEYS = "KEYS";
/**
* The hit score.
*/
private static final String FIELD_SCORE = "SCORE";
private static final String TRIGGER_PREFIX = "FT_";
private static final String SCHEMA = "FT";
private static final String SELECT_MAP_BY_WORD_ID =
"SELECT ROWID FROM " + SCHEMA + ".MAP WHERE WORDID=?";
private static final String SELECT_ROW_BY_ID =
"SELECT KEY, INDEXID FROM " + SCHEMA + ".ROWS WHERE ID=?";
/**
* The column name of the result set returned by the search method.
*/
private static final String FIELD_QUERY = "QUERY";
/**
* Initializes full text search functionality for this database. This adds
* the following Java functions to the database:
* <ul>
* <li>FT_CREATE_INDEX(schemaNameString, tableNameString,
* columnListString)</li>
* <li>FT_SEARCH(queryString, limitInt, offsetInt): result set</li>
* <li>FT_REINDEX()</li>
* <li>FT_DROP_ALL()</li>
* </ul>
* It also adds a schema FT to the database where bookkeeping information
* is stored. This function may be called from a Java application, or by
* using the SQL statements:
*
* <pre>
* CREATE ALIAS IF NOT EXISTS FT_INIT FOR
* "org.h2.fulltext.FullText.init";
* CALL FT_INIT();
* </pre>
*
* @param conn the connection
*/
public static void init(Connection conn) throws SQLException {
Statement stat = conn.createStatement();
stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA);
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".INDEXES(ID INT AUTO_INCREMENT PRIMARY KEY, " +
"SCHEMA VARCHAR, TABLE VARCHAR, COLUMNS VARCHAR, " +
"UNIQUE(SCHEMA, TABLE))");
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".WORDS(ID INT AUTO_INCREMENT PRIMARY KEY, " +
"NAME VARCHAR, UNIQUE(NAME))");
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".ROWS(ID IDENTITY, HASH INT, INDEXID INT, " +
"KEY VARCHAR, UNIQUE(HASH, INDEXID, KEY))");
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".MAP(ROWID INT, WORDID INT, PRIMARY KEY(WORDID, ROWID))");
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".IGNORELIST(LIST VARCHAR)");
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".SETTINGS(KEY VARCHAR PRIMARY KEY, VALUE VARCHAR)");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_CREATE_INDEX FOR \"" +
FullText.class.getName() + ".createIndex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_INDEX FOR \"" +
FullText.class.getName() + ".dropIndex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH FOR \"" +
FullText.class.getName() + ".search\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_SEARCH_DATA FOR \"" +
FullText.class.getName() + ".searchData\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_REINDEX FOR \"" +
FullText.class.getName() + ".reindex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FT_DROP_ALL FOR \"" +
FullText.class.getName() + ".dropAll\"");
FullTextSettings setting = FullTextSettings.getInstance(conn);
ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA +
".IGNORELIST");
while (rs.next()) {
String commaSeparatedList = rs.getString(1);
setIgnoreList(setting, commaSeparatedList);
}
rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".SETTINGS");
while (rs.next()) {
String key = rs.getString(1);
if ("whitespaceChars".equals(key)) {
String value = rs.getString(2);
setting.setWhitespaceChars(value);
}
}
rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".WORDS");
while (rs.next()) {
String word = rs.getString("NAME");
int id = rs.getInt("ID");
word = setting.convertWord(word);
if (word != null) {
setting.addWord(word, id);
}
}
setting.setInitialized(true);
}
/**
* Create a new full text index for a table and column list. Each table may
* only have one index at any time.
*
* @param conn the connection
* @param schema the schema name of the table (case sensitive)
* @param table the table name (case sensitive)
* @param columnList the column list (null for all columns)
*/
public static void createIndex(Connection conn, String schema,
String table, String columnList) throws SQLException {
init(conn);
PreparedStatement prep = conn.prepareStatement("INSERT INTO " + SCHEMA
+ ".INDEXES(SCHEMA, TABLE, COLUMNS) VALUES(?, ?, ?)");
prep.setString(1, schema);
prep.setString(2, table);
prep.setString(3, columnList);
prep.execute();
createTrigger(conn, schema, table);
indexExistingRows(conn, schema, table);
}
/**
* Re-creates the full text index for this database. Calling this method is
* usually not needed, as the index is kept up-to-date automatically.
*
* @param conn the connection
*/
public static void reindex(Connection conn) throws SQLException {
init(conn);
removeAllTriggers(conn, TRIGGER_PREFIX);
FullTextSettings setting = FullTextSettings.getInstance(conn);
setting.clearWordList();
Statement stat = conn.createStatement();
stat.execute("TRUNCATE TABLE " + SCHEMA + ".WORDS");
stat.execute("TRUNCATE TABLE " + SCHEMA + ".ROWS");
stat.execute("TRUNCATE TABLE " + SCHEMA + ".MAP");
ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".INDEXES");
while (rs.next()) {
String schema = rs.getString("SCHEMA");
String table = rs.getString("TABLE");
createTrigger(conn, schema, table);
indexExistingRows(conn, schema, table);
}
}
/**
* Drop an existing full text index for a table. This method returns
* silently if no index for this table exists.
*
* @param conn the connection
* @param schema the schema name of the table (case sensitive)
* @param table the table name (case sensitive)
*/
public static void dropIndex(Connection conn, String schema, String table)
throws SQLException {
init(conn);
PreparedStatement prep = conn.prepareStatement("SELECT ID FROM " + SCHEMA
+ ".INDEXES WHERE SCHEMA=? AND TABLE=?");
prep.setString(1, schema);
prep.setString(2, table);
ResultSet rs = prep.executeQuery();
if (!rs.next()) {
return;
}
int indexId = rs.getInt(1);
prep = conn.prepareStatement("DELETE FROM " + SCHEMA
+ ".INDEXES WHERE ID=?");
prep.setInt(1, indexId);
prep.execute();
createOrDropTrigger(conn, schema, table, false);
prep = conn.prepareStatement("DELETE FROM " + SCHEMA +
".ROWS WHERE INDEXID=? AND ROWNUM<10000");
while (true) {
prep.setInt(1, indexId);
int deleted = prep.executeUpdate();
if (deleted == 0) {
break;
}
}
prep = conn.prepareStatement("DELETE FROM " + SCHEMA + ".MAP " +
"WHERE NOT EXISTS (SELECT * FROM " + SCHEMA +
".ROWS R WHERE R.ID=ROWID) AND ROWID<10000");
while (true) {
int deleted = prep.executeUpdate();
if (deleted == 0) {
break;
}
}
}
/**
* Drops all full text indexes from the database.
*
* @param conn the connection
*/
public static void dropAll(Connection conn) throws SQLException {
init(conn);
Statement stat = conn.createStatement();
stat.execute("DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE");
removeAllTriggers(conn, TRIGGER_PREFIX);
FullTextSettings setting = FullTextSettings.getInstance(conn);
setting.removeAllIndexes();
setting.clearIgnored();
setting.clearWordList();
}
/**
* Searches from the full text index for this database.
* The returned result set has the following column:
* <ul><li>QUERY (varchar): the query to use to get the data.
* The query does not include 'SELECT * FROM '. Example:
* PUBLIC.TEST WHERE ID = 1
* </li><li>SCORE (float) the relevance score. This value is always 1.0
* for the native fulltext search.
* </li></ul>
*
* @param conn the connection
* @param text the search query
* @param limit the maximum number of rows or 0 for no limit
* @param offset the offset or 0 for no offset
* @return the result set
*/
public static ResultSet search(Connection conn, String text, int limit,
int offset) throws SQLException {
try {
return search(conn, text, limit, offset, false);
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
/**
* Searches from the full text index for this database. The result contains
* the primary key data as an array. The returned result set has the
* following columns:
* <ul>
* <li>SCHEMA (varchar): the schema name. Example: PUBLIC </li>
* <li>TABLE (varchar): the table name. Example: TEST </li>
* <li>COLUMNS (array of varchar): comma separated list of quoted column
* names. The column names are quoted if necessary. Example: (ID) </li>
* <li>KEYS (array of values): comma separated list of values. Example: (1)
* </li>
* <li>SCORE (float) the relevance score. This value is always 1.0
* for the native fulltext search.
* </li>
* </ul>
*
* @param conn the connection
* @param text the search query
* @param limit the maximum number of rows or 0 for no limit
* @param offset the offset or 0 for no offset
* @return the result set
*/
public static ResultSet searchData(Connection conn, String text, int limit,
int offset) throws SQLException {
try {
return search(conn, text, limit, offset, true);
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
/**
* Change the ignore list. The ignore list is a comma separated list of
* common words that must not be indexed. The default ignore list is empty.
* If indexes already exist at the time this list is changed, reindex must
* be called.
*
* @param conn the connection
* @param commaSeparatedList the list
*/
public static void setIgnoreList(Connection conn, String commaSeparatedList)
throws SQLException {
try {
init(conn);
FullTextSettings setting = FullTextSettings.getInstance(conn);
setIgnoreList(setting, commaSeparatedList);
Statement stat = conn.createStatement();
stat.execute("TRUNCATE TABLE " + SCHEMA + ".IGNORELIST");
PreparedStatement prep = conn.prepareStatement("INSERT INTO " +
SCHEMA + ".IGNORELIST VALUES(?)");
prep.setString(1, commaSeparatedList);
prep.execute();
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
/**
* Change the whitespace characters. The whitespace characters are used to
* separate words. If indexes already exist at the time this list is
* changed, reindex must be called.
*
* @param conn the connection
* @param whitespaceChars the list of characters
*/
public static void setWhitespaceChars(Connection conn,
String whitespaceChars) throws SQLException {
try {
init(conn);
FullTextSettings setting = FullTextSettings.getInstance(conn);
setting.setWhitespaceChars(whitespaceChars);
PreparedStatement prep = conn.prepareStatement("MERGE INTO " +
SCHEMA + ".SETTINGS VALUES(?, ?)");
prep.setString(1, "whitespaceChars");
prep.setString(2, whitespaceChars);
prep.execute();
} catch (DbException e) {
throw DbException.toSQLException(e);
}
}
/**
* INTERNAL.
* Convert the object to a string.
*
* @param data the object
* @param type the SQL type
* @return the string
*/
protected static String asString(Object data, int type) throws SQLException {
if (data == null) {
return "NULL";
}
switch (type) {
case Types.BIT:
case Types.BOOLEAN:
case Types.INTEGER:
case Types.BIGINT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.NUMERIC:
case Types.REAL:
case Types.SMALLINT:
case Types.TINYINT:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.LONGVARCHAR:
case Types.CHAR:
case Types.VARCHAR:
return data.toString();
case Types.CLOB:
try {
if (data instanceof Clob) {
data = ((Clob) data).getCharacterStream();
}
return IOUtils.readStringAndClose((Reader) data, -1);
} catch (IOException e) {
throw DbException.toSQLException(e);
}
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BINARY:
case Types.JAVA_OBJECT:
case Types.OTHER:
case Types.BLOB:
case Types.STRUCT:
case Types.REF:
case Types.NULL:
case Types.ARRAY:
case Types.DATALINK:
case Types.DISTINCT:
throw throwException("Unsupported column data type: " + type);
default:
return "";
}
}
/**
* Create an empty search result and initialize the columns.
*
* @param data true if the result set should contain the primary key data as
* an array.
* @return the empty result set
*/
protected static SimpleResultSet createResultSet(boolean data) {
SimpleResultSet result = new SimpleResultSet();
if (data) {
result.addColumn(FullText.FIELD_SCHEMA, Types.VARCHAR, 0, 0);
result.addColumn(FullText.FIELD_TABLE, Types.VARCHAR, 0, 0);
result.addColumn(FullText.FIELD_COLUMNS, Types.ARRAY, 0, 0);
result.addColumn(FullText.FIELD_KEYS, Types.ARRAY, 0, 0);
} else {
result.addColumn(FullText.FIELD_QUERY, Types.VARCHAR, 0, 0);
}
result.addColumn(FullText.FIELD_SCORE, Types.FLOAT, 0, 0);
return result;
}
/**
* Parse a primary key condition into the primary key columns.
*
* @param conn the database connection
* @param key the primary key condition as a string
* @return an array containing the column name list and the data list
*/
protected static Object[][] parseKey(Connection conn, String key) {
ArrayList<String> columns = New.arrayList();
ArrayList<String> data = New.arrayList();
JdbcConnection c = (JdbcConnection) conn;
Session session = (Session) c.getSession();
Parser p = new Parser(session);
Expression expr = p.parseExpression(key);
addColumnData(columns, data, expr);
Object[] col = columns.toArray();
Object[] dat = data.toArray();
Object[][] columnData = { col, dat };
return columnData;
}
/**
* INTERNAL.
* Convert an object to a String as used in a SQL statement.
*
* @param data the object
* @param type the SQL type
* @return the SQL String
*/
protected static String quoteSQL(Object data, int type) throws SQLException {
if (data == null) {
return "NULL";
}
switch (type) {
case Types.BIT:
case Types.BOOLEAN:
case Types.INTEGER:
case Types.BIGINT:
case Types.DECIMAL:
case Types.DOUBLE:
case Types.FLOAT:
case Types.NUMERIC:
case Types.REAL:
case Types.SMALLINT:
case Types.TINYINT:
return data.toString();
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
case Types.LONGVARCHAR:
case Types.CHAR:
case Types.VARCHAR:
return quoteString(data.toString());
case Types.VARBINARY:
case Types.LONGVARBINARY:
case Types.BINARY:
if (data instanceof UUID) {
return "'" + data.toString() + "'";
}
return "'" + StringUtils.convertBytesToHex((byte[]) data) + "'";
case Types.CLOB:
case Types.JAVA_OBJECT:
case Types.OTHER:
case Types.BLOB:
case Types.STRUCT:
case Types.REF:
case Types.NULL:
case Types.ARRAY:
case Types.DATALINK:
case Types.DISTINCT:
throw throwException("Unsupported key data type: " + type);
default:
return "";
}
}
/**
* Remove all triggers that start with the given prefix.
*
* @param conn the database connection
* @param prefix the prefix
*/
protected static void removeAllTriggers(Connection conn, String prefix)
throws SQLException {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM INFORMATION_SCHEMA.TRIGGERS");
Statement stat2 = conn.createStatement();
while (rs.next()) {
String schema = rs.getString("TRIGGER_SCHEMA");
String name = rs.getString("TRIGGER_NAME");
if (name.startsWith(prefix)) {
name = StringUtils.quoteIdentifier(schema) + "." +
StringUtils.quoteIdentifier(name);
stat2.execute("DROP TRIGGER " + name);
}
}
}
/**
* Set the column indices of a set of keys.
*
* @param index the column indices (will be modified)
* @param keys the key list
* @param columns the column list
*/
protected static void setColumns(int[] index, ArrayList<String> keys,
ArrayList<String> columns) throws SQLException {
for (int i = 0, keySize = keys.size(); i < keySize; i++) {
String key = keys.get(i);
int found = -1;
int columnsSize = columns.size();
for (int j = 0; found == -1 && j < columnsSize; j++) {
String column = columns.get(j);
if (column.equals(key)) {
found = j;
}
}
if (found < 0) {
throw throwException("Column not found: " + key);
}
index[i] = found;
}
}
/**
* Do the search.
*
* @param conn the database connection
* @param text the query
* @param limit the limit
* @param offset the offset
* @param data whether the raw data should be returned
* @return the result set
*/
protected static ResultSet search(Connection conn, String text, int limit,
int offset, boolean data) throws SQLException {
SimpleResultSet result = createResultSet(data);
if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
// this is just to query the result set columns
return result;
}
if (text == null || text.trim().length() == 0) {
return result;
}
FullTextSettings setting = FullTextSettings.getInstance(conn);
if (!setting.isInitialized()) {
init(conn);
}
Set<String> words = new HashSet<>();
addWords(setting, words, text);
Set<Integer> rIds = null, lastRowIds;
PreparedStatement prepSelectMapByWordId = setting.prepare(conn,
SELECT_MAP_BY_WORD_ID);
for (String word : words) {
lastRowIds = rIds;
rIds = new HashSet<>();
Integer wId = setting.getWordId(word);
if (wId == null) {
continue;
}
prepSelectMapByWordId.setInt(1, wId.intValue());
ResultSet rs = prepSelectMapByWordId.executeQuery();
while (rs.next()) {
Integer rId = rs.getInt(1);
if (lastRowIds == null || lastRowIds.contains(rId)) {
rIds.add(rId);
}
}
}
if (rIds == null || rIds.isEmpty()) {
return result;
}
PreparedStatement prepSelectRowById = setting.prepare(conn, SELECT_ROW_BY_ID);
int rowCount = 0;
for (int rowId : rIds) {
prepSelectRowById.setInt(1, rowId);
ResultSet rs = prepSelectRowById.executeQuery();
if (!rs.next()) {
continue;
}
if (offset > 0) {
offset--;
} else {
String key = rs.getString(1);
int indexId = rs.getInt(2);
IndexInfo index = setting.getIndexInfo(indexId);
if (data) {
Object[][] columnData = parseKey(conn, key);
result.addRow(
index.schema,
index.table,
columnData[0],
columnData[1],
1.0);
} else {
String query = StringUtils.quoteIdentifier(index.schema) +
"." + StringUtils.quoteIdentifier(index.table) +
" WHERE " + key;
result.addRow(query, 1.0);
}
rowCount++;
if (limit > 0 && rowCount >= limit) {
break;
}
}
}
return result;
}
private static void addColumnData(ArrayList<String> columns,
ArrayList<String> data, Expression expr) {
if (expr instanceof ConditionAndOr) {
ConditionAndOr and = (ConditionAndOr) expr;
Expression left = and.getExpression(true);
Expression right = and.getExpression(false);
addColumnData(columns, data, left);
addColumnData(columns, data, right);
} else {
Comparison comp = (Comparison) expr;
ExpressionColumn ec = (ExpressionColumn) comp.getExpression(true);
ValueExpression ev = (ValueExpression) comp.getExpression(false);
String columnName = ec.getColumnName();
columns.add(columnName);
if (ev == null) {
data.add(null);
} else {
data.add(ev.getValue(null).getString());
}
}
}
/**
* Add all words in the given text to the hash set.
*
* @param setting the fulltext settings
* @param set the hash set
* @param reader the reader
*/
protected static void addWords(FullTextSettings setting,
Set<String> set, Reader reader) {
StreamTokenizer tokenizer = new StreamTokenizer(reader);
tokenizer.resetSyntax();
tokenizer.wordChars(' ' + 1, 255);
char[] whitespaceChars = setting.getWhitespaceChars().toCharArray();
for (char ch : whitespaceChars) {
tokenizer.whitespaceChars(ch, ch);
}
try {
while (true) {
int token = tokenizer.nextToken();
if (token == StreamTokenizer.TT_EOF) {
break;
} else if (token == StreamTokenizer.TT_WORD) {
String word = tokenizer.sval;
word = setting.convertWord(word);
if (word != null) {
set.add(word);
}
}
}
} catch (IOException e) {
throw DbException.convertIOException(e, "Tokenizer error");
}
}
/**
* Add all words in the given text to the hash set.
*
* @param setting the fulltext settings
* @param set the hash set
* @param text the text
*/
protected static void addWords(FullTextSettings setting,
Set<String> set, String text) {
String whitespaceChars = setting.getWhitespaceChars();
StringTokenizer tokenizer = new StringTokenizer(text, whitespaceChars);
while (tokenizer.hasMoreTokens()) {
String word = tokenizer.nextToken();
word = setting.convertWord(word);
if (word != null) {
set.add(word);
}
}
}
/**
* Create the trigger.
*
* @param conn the database connection
* @param schema the schema name
* @param table the table name
*/
private static void createTrigger(Connection conn, String schema,
String table) throws SQLException {
createOrDropTrigger(conn, schema, table, true);
}
private static void createOrDropTrigger(Connection conn,
String schema, String table, boolean create) throws SQLException {
try (Statement stat = conn.createStatement()) {
String trigger = StringUtils.quoteIdentifier(schema) + "."
+ StringUtils.quoteIdentifier(TRIGGER_PREFIX + table);
stat.execute("DROP TRIGGER IF EXISTS " + trigger);
if (create) {
boolean multiThread = FullTextTrigger.isMultiThread(conn);
StringBuilder buff = new StringBuilder(
"CREATE TRIGGER IF NOT EXISTS ");
// unless multithread, trigger needs to be called on rollback as well,
// because we use the init connection do to changes in the index
// (not the user connection)
buff.append(trigger).
append(" AFTER INSERT, UPDATE, DELETE");
if(!multiThread) {
buff.append(", ROLLBACK");
}
buff.append(" ON ").
append(StringUtils.quoteIdentifier(schema)).
append('.').
append(StringUtils.quoteIdentifier(table)).
append(" FOR EACH ROW CALL \"").
append(FullText.FullTextTrigger.class.getName()).
append('\"');
stat.execute(buff.toString());
}
}
}
/**
* Add the existing data to the index.
*
* @param conn the database connection
* @param schema the schema name
* @param table the table name
*/
private static void indexExistingRows(Connection conn, String schema,
String table) throws SQLException {
FullText.FullTextTrigger existing = new FullText.FullTextTrigger();
existing.init(conn, schema, null, table, false, Trigger.INSERT);
String sql = "SELECT * FROM " + StringUtils.quoteIdentifier(schema)
+ "." + StringUtils.quoteIdentifier(table);
ResultSet rs = conn.createStatement().executeQuery(sql);
int columnCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getObject(i + 1);
}
existing.fire(conn, null, row);
}
}
private static String quoteString(String data) {
if (data.indexOf('\'') < 0) {
return "'" + data + "'";
}
int len = data.length();
StringBuilder buff = new StringBuilder(len + 2);
buff.append('\'');
for (int i = 0; i < len; i++) {
char ch = data.charAt(i);
if (ch == '\'') {
buff.append(ch);
}
buff.append(ch);
}
buff.append('\'');
return buff.toString();
}
private static void setIgnoreList(FullTextSettings setting,
String commaSeparatedList) {
String[] list = StringUtils.arraySplit(commaSeparatedList, ',', true);
setting.addIgnored(Arrays.asList(list));
}
/**
* Check if a the indexed columns of a row probably have changed. It may
* return true even if the change was minimal (for example from 0.0 to
* 0.00).
*
* @param oldRow the old row
* @param newRow the new row
* @param indexColumns the indexed columns
* @return true if the indexed columns don't match
*/
protected static boolean hasChanged(Object[] oldRow, Object[] newRow,
int[] indexColumns) {
for (int c : indexColumns) {
Object o = oldRow[c], n = newRow[c];
if (o == null) {
if (n != null) {
return true;
}
} else if (!o.equals(n)) {
return true;
}
}
return false;
}
/**
* Trigger updates the index when a inserting, updating, or deleting a row.
*/
public static final class FullTextTrigger implements Trigger {
private FullTextSettings setting;
private IndexInfo index;
private int[] columnTypes;
private final PreparedStatement[] prepStatements = new PreparedStatement[SQL.length];
private boolean useOwnConnection;
private static final int INSERT_WORD = 0;
private static final int INSERT_ROW = 1;
private static final int INSERT_MAP = 2;
private static final int DELETE_ROW = 3;
private static final int DELETE_MAP = 4;
private static final int SELECT_ROW = 5;
private static final String SQL[] = {
"MERGE INTO " + SCHEMA + ".WORDS(NAME) KEY(NAME) VALUES(?)",
"INSERT INTO " + SCHEMA + ".ROWS(HASH, INDEXID, KEY) VALUES(?, ?, ?)",
"INSERT INTO " + SCHEMA + ".MAP(ROWID, WORDID) VALUES(?, ?)",
"DELETE FROM " + SCHEMA + ".ROWS WHERE HASH=? AND INDEXID=? AND KEY=?",
"DELETE FROM " + SCHEMA + ".MAP WHERE ROWID=? AND WORDID=?",
"SELECT ID FROM " + SCHEMA + ".ROWS WHERE HASH=? AND INDEXID=? AND KEY=?"
};
/**
* INTERNAL
*/
@Override
public void init(Connection conn, String schemaName, String triggerName,
String tableName, boolean before, int type) throws SQLException {
setting = FullTextSettings.getInstance(conn);
if (!setting.isInitialized()) {
FullText.init(conn);
}
ArrayList<String> keyList = New.arrayList();
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null,
StringUtils.escapeMetaDataPattern(schemaName),
StringUtils.escapeMetaDataPattern(tableName),
null);
ArrayList<String> columnList = New.arrayList();
while (rs.next()) {
columnList.add(rs.getString("COLUMN_NAME"));
}
columnTypes = new int[columnList.size()];
index = new IndexInfo();
index.schema = schemaName;
index.table = tableName;
index.columns = columnList.toArray(new String[0]);
rs = meta.getColumns(null,
StringUtils.escapeMetaDataPattern(schemaName),
StringUtils.escapeMetaDataPattern(tableName),
null);
for (int i = 0; rs.next(); i++) {
columnTypes[i] = rs.getInt("DATA_TYPE");
}
if (keyList.isEmpty()) {
rs = meta.getPrimaryKeys(null,
StringUtils.escapeMetaDataPattern(schemaName),
tableName);
while (rs.next()) {
keyList.add(rs.getString("COLUMN_NAME"));
}
}
if (keyList.isEmpty()) {
throw throwException("No primary key for table " + tableName);
}
ArrayList<String> indexList = New.arrayList();
PreparedStatement prep = conn.prepareStatement(
"SELECT ID, COLUMNS FROM " + SCHEMA + ".INDEXES" +
" WHERE SCHEMA=? AND TABLE=?");
prep.setString(1, schemaName);
prep.setString(2, tableName);
rs = prep.executeQuery();
if (rs.next()) {
index.id = rs.getInt(1);
String columns = rs.getString(2);
if (columns != null) {
Collections.addAll(indexList, StringUtils.arraySplit(columns, ',', true));
}
}
if (indexList.isEmpty()) {
indexList.addAll(columnList);
}
index.keys = new int[keyList.size()];
setColumns(index.keys, keyList, columnList);
index.indexColumns = new int[indexList.size()];
setColumns(index.indexColumns, indexList, columnList);
setting.addIndexInfo(index);
useOwnConnection = isMultiThread(conn);
if(!useOwnConnection) {
for (int i = 0; i < SQL.length; i++) {
prepStatements[i] = conn.prepareStatement(SQL[i],
Statement.RETURN_GENERATED_KEYS);
}
}
}
/**
* Check whether the database is in multi-threaded mode.
*
* @param conn the connection
* @return true if the multi-threaded mode is used
*/
static boolean isMultiThread(Connection conn)
throws SQLException {
try (Statement stat = conn.createStatement()) {
ResultSet rs = stat.executeQuery(
"SELECT value FROM information_schema.settings" +
" WHERE name = 'MULTI_THREADED'");
return rs.next() && !"0".equals(rs.getString(1));
}
}
/**
* INTERNAL
*/
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)
throws SQLException {
if (oldRow != null) {
if (newRow != null) {
// update
if (hasChanged(oldRow, newRow, index.indexColumns)) {
delete(conn, oldRow);
insert(conn, newRow);
}
} else {
// delete
delete(conn, oldRow);
}
} else if (newRow != null) {
// insert
insert(conn, newRow);
}
}
/**
* INTERNAL
*/
@Override
public void close() {
setting.removeIndexInfo(index);
}
/**
* INTERNAL
*/
@Override
public void remove() {
setting.removeIndexInfo(index);
}
/**
* Add a row to the index.
*
* @param conn to use
* @param row the row
*/
protected void insert(Connection conn, Object[] row) throws SQLException {
PreparedStatement prepInsertRow = null;
PreparedStatement prepInsertMap = null;
try {
String key = getKey(row);
int hash = key.hashCode();
prepInsertRow = getStatement(conn, INSERT_ROW);
prepInsertRow.setInt(1, hash);
prepInsertRow.setInt(2, index.id);
prepInsertRow.setString(3, key);
prepInsertRow.execute();
ResultSet rs = prepInsertRow.getGeneratedKeys();
rs.next();
int rowId = rs.getInt(1);
prepInsertMap = getStatement(conn, INSERT_MAP);
prepInsertMap.setInt(1, rowId);
int[] wordIds = getWordIds(conn, row);
for (int id : wordIds) {
prepInsertMap.setInt(2, id);
prepInsertMap.execute();
}
} finally {
if (useOwnConnection) {
IOUtils.closeSilently(prepInsertRow);
IOUtils.closeSilently(prepInsertMap);
}
}
}
/**
* Delete a row from the index.
*
* @param conn to use
* @param row the row
*/
protected void delete(Connection conn, Object[] row) throws SQLException {
PreparedStatement prepSelectRow = null;
PreparedStatement prepDeleteMap = null;
PreparedStatement prepDeleteRow = null;
try {
String key = getKey(row);
int hash = key.hashCode();
prepSelectRow = getStatement(conn, SELECT_ROW);
prepSelectRow.setInt(1, hash);
prepSelectRow.setInt(2, index.id);
prepSelectRow.setString(3, key);
ResultSet rs = prepSelectRow.executeQuery();
prepDeleteMap = getStatement(conn, DELETE_MAP);
prepDeleteRow = getStatement(conn, DELETE_ROW);
if (rs.next()) {
int rowId = rs.getInt(1);
prepDeleteMap.setInt(1, rowId);
int[] wordIds = getWordIds(conn, row);
for (int id : wordIds) {
prepDeleteMap.setInt(2, id);
prepDeleteMap.executeUpdate();
}
prepDeleteRow.setInt(1, hash);
prepDeleteRow.setInt(2, index.id);
prepDeleteRow.setString(3, key);
prepDeleteRow.executeUpdate();
}
} finally {
if (useOwnConnection) {
IOUtils.closeSilently(prepSelectRow);
IOUtils.closeSilently(prepDeleteMap);
IOUtils.closeSilently(prepDeleteRow);
}
}
}
private int[] getWordIds(Connection conn, Object[] row) throws SQLException {
HashSet<String> words = new HashSet<>();
for (int idx : index.indexColumns) {
int type = columnTypes[idx];
Object data = row[idx];
if (type == Types.CLOB && data != null) {
Reader reader;
if (data instanceof Reader) {
reader = (Reader) data;
} else {
reader = ((Clob) data).getCharacterStream();
}
addWords(setting, words, reader);
} else {
String string = asString(data, type);
addWords(setting, words, string);
}
}
PreparedStatement prepInsertWord = null;
try {
prepInsertWord = getStatement(conn, INSERT_WORD);
int[] wordIds = new int[words.size()];
int i = 0;
for (String word : words) {
int wordId;
Integer wId;
while((wId = setting.getWordId(word)) == null) {
prepInsertWord.setString(1, word);
prepInsertWord.execute();
ResultSet rs = prepInsertWord.getGeneratedKeys();
if (rs.next()) {
wordId = rs.getInt(1);
if (wordId != 0) {
setting.addWord(word, wordId);
wId = wordId;
break;
}
}
}
wordIds[i++] = wId;
}
Arrays.sort(wordIds);
return wordIds;
} finally {
if (useOwnConnection) {
IOUtils.closeSilently(prepInsertWord);
}
}
}
private String getKey(Object[] row) throws SQLException {
StatementBuilder buff = new StatementBuilder();
for (int columnIndex : index.keys) {
buff.appendExceptFirst(" AND ");
buff.append(StringUtils.quoteIdentifier(index.columns[columnIndex]));
Object o = row[columnIndex];
if (o == null) {
buff.append(" IS NULL");
} else {
buff.append('=').append(quoteSQL(o, columnTypes[columnIndex]));
}
}
return buff.toString();
}
private PreparedStatement getStatement(Connection conn, int index) throws SQLException {
return useOwnConnection ?
conn.prepareStatement(SQL[index], Statement.RETURN_GENERATED_KEYS)
: prepStatements[index];
}
}
/**
* INTERNAL
* Close all fulltext settings, freeing up memory.
*/
public static void closeAll() {
FullTextSettings.closeAll();
}
/**
* Throw a SQLException with the given message.
*
* @param message the message
* @return never returns normally
* @throws SQLException the exception
*/
protected static SQLException throwException(String message)
throws SQLException {
throw new SQLException(message, "FULLTEXT");
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/fulltext/FullTextLucene.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.fulltext;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.store.RAMDirectory;
import org.apache.lucene.util.Version;
import org.h2.api.Trigger;
import org.h2.command.Parser;
import org.h2.engine.Session;
import org.h2.expression.ExpressionColumn;
import org.h2.jdbc.JdbcConnection;
import org.h2.store.fs.FileUtils;
import org.h2.tools.SimpleResultSet;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
/**
* This class implements the full text search based on Apache Lucene.
* Most methods can be called using SQL statements as well.
*/
public class FullTextLucene extends FullText {
/**
* Whether the text content should be stored in the Lucene index.
*/
protected static final boolean STORE_DOCUMENT_TEXT_IN_INDEX =
Utils.getProperty("h2.storeDocumentTextInIndex", false);
private static final HashMap<String, IndexAccess> INDEX_ACCESS = new HashMap<>();
private static final String TRIGGER_PREFIX = "FTL_";
private static final String SCHEMA = "FTL";
private static final String LUCENE_FIELD_DATA = "_DATA";
private static final String LUCENE_FIELD_QUERY = "_QUERY";
private static final String LUCENE_FIELD_MODIFIED = "_modified";
private static final String LUCENE_FIELD_COLUMN_PREFIX = "_";
/**
* The prefix for a in-memory path. This prefix is only used internally
* within this class and not related to the database URL.
*/
private static final String IN_MEMORY_PREFIX = "mem:";
/**
* Initializes full text search functionality for this database. This adds
* the following Java functions to the database:
* <ul>
* <li>FTL_CREATE_INDEX(schemaNameString, tableNameString,
* columnListString)</li>
* <li>FTL_SEARCH(queryString, limitInt, offsetInt): result set</li>
* <li>FTL_REINDEX()</li>
* <li>FTL_DROP_ALL()</li>
* </ul>
* It also adds a schema FTL to the database where bookkeeping information
* is stored. This function may be called from a Java application, or by
* using the SQL statements:
*
* <pre>
* CREATE ALIAS IF NOT EXISTS FTL_INIT FOR
* "org.h2.fulltext.FullTextLucene.init";
* CALL FTL_INIT();
* </pre>
*
* @param conn the connection
*/
public static void init(Connection conn) throws SQLException {
try (Statement stat = conn.createStatement()) {
stat.execute("CREATE SCHEMA IF NOT EXISTS " + SCHEMA);
stat.execute("CREATE TABLE IF NOT EXISTS " + SCHEMA +
".INDEXES(SCHEMA VARCHAR, TABLE VARCHAR, " +
"COLUMNS VARCHAR, PRIMARY KEY(SCHEMA, TABLE))");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_CREATE_INDEX FOR \"" +
FullTextLucene.class.getName() + ".createIndex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_DROP_INDEX FOR \"" +
FullTextLucene.class.getName() + ".dropIndex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_SEARCH FOR \"" +
FullTextLucene.class.getName() + ".search\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_SEARCH_DATA FOR \"" +
FullTextLucene.class.getName() + ".searchData\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_REINDEX FOR \"" +
FullTextLucene.class.getName() + ".reindex\"");
stat.execute("CREATE ALIAS IF NOT EXISTS FTL_DROP_ALL FOR \"" +
FullTextLucene.class.getName() + ".dropAll\"");
}
}
/**
* Create a new full text index for a table and column list. Each table may
* only have one index at any time.
*
* @param conn the connection
* @param schema the schema name of the table (case sensitive)
* @param table the table name (case sensitive)
* @param columnList the column list (null for all columns)
*/
public static void createIndex(Connection conn, String schema,
String table, String columnList) throws SQLException {
init(conn);
PreparedStatement prep = conn.prepareStatement("INSERT INTO " + SCHEMA
+ ".INDEXES(SCHEMA, TABLE, COLUMNS) VALUES(?, ?, ?)");
prep.setString(1, schema);
prep.setString(2, table);
prep.setString(3, columnList);
prep.execute();
createTrigger(conn, schema, table);
indexExistingRows(conn, schema, table);
}
/**
* Drop an existing full text index for a table. This method returns
* silently if no index for this table exists.
*
* @param conn the connection
* @param schema the schema name of the table (case sensitive)
* @param table the table name (case sensitive)
*/
public static void dropIndex(Connection conn, String schema, String table)
throws SQLException {
init(conn);
PreparedStatement prep = conn.prepareStatement("DELETE FROM " + SCHEMA
+ ".INDEXES WHERE SCHEMA=? AND TABLE=?");
prep.setString(1, schema);
prep.setString(2, table);
int rowCount = prep.executeUpdate();
if (rowCount != 0) {
reindex(conn);
}
}
/**
* Re-creates the full text index for this database. Calling this method is
* usually not needed, as the index is kept up-to-date automatically.
*
* @param conn the connection
*/
public static void reindex(Connection conn) throws SQLException {
init(conn);
removeAllTriggers(conn, TRIGGER_PREFIX);
removeIndexFiles(conn);
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("SELECT * FROM " + SCHEMA + ".INDEXES");
while (rs.next()) {
String schema = rs.getString("SCHEMA");
String table = rs.getString("TABLE");
createTrigger(conn, schema, table);
indexExistingRows(conn, schema, table);
}
}
/**
* Drops all full text indexes from the database.
*
* @param conn the connection
*/
public static void dropAll(Connection conn) throws SQLException {
Statement stat = conn.createStatement();
stat.execute("DROP SCHEMA IF EXISTS " + SCHEMA + " CASCADE");
removeAllTriggers(conn, TRIGGER_PREFIX);
removeIndexFiles(conn);
}
/**
* Searches from the full text index for this database.
* The returned result set has the following column:
* <ul><li>QUERY (varchar): the query to use to get the data.
* The query does not include 'SELECT * FROM '. Example:
* PUBLIC.TEST WHERE ID = 1
* </li><li>SCORE (float) the relevance score as returned by Lucene.
* </li></ul>
*
* @param conn the connection
* @param text the search query
* @param limit the maximum number of rows or 0 for no limit
* @param offset the offset or 0 for no offset
* @return the result set
*/
public static ResultSet search(Connection conn, String text, int limit,
int offset) throws SQLException {
return search(conn, text, limit, offset, false);
}
/**
* Searches from the full text index for this database. The result contains
* the primary key data as an array. The returned result set has the
* following columns:
* <ul>
* <li>SCHEMA (varchar): the schema name. Example: PUBLIC</li>
* <li>TABLE (varchar): the table name. Example: TEST</li>
* <li>COLUMNS (array of varchar): comma separated list of quoted column
* names. The column names are quoted if necessary. Example: (ID)</li>
* <li>KEYS (array of values): comma separated list of values.
* Example: (1)</li>
* <li>SCORE (float) the relevance score as returned by Lucene.</li>
* </ul>
*
* @param conn the connection
* @param text the search query
* @param limit the maximum number of rows or 0 for no limit
* @param offset the offset or 0 for no offset
* @return the result set
*/
public static ResultSet searchData(Connection conn, String text, int limit,
int offset) throws SQLException {
return search(conn, text, limit, offset, true);
}
/**
* Convert an exception to a fulltext exception.
*
* @param e the original exception
* @return the converted SQL exception
*/
protected static SQLException convertException(Exception e) {
return new SQLException("Error while indexing document", "FULLTEXT", e);
}
/**
* Create the trigger.
*
* @param conn the database connection
* @param schema the schema name
* @param table the table name
*/
private static void createTrigger(Connection conn, String schema,
String table) throws SQLException {
createOrDropTrigger(conn, schema, table, true);
}
private static void createOrDropTrigger(Connection conn,
String schema, String table, boolean create) throws SQLException {
Statement stat = conn.createStatement();
String trigger = StringUtils.quoteIdentifier(schema) + "." +
StringUtils.quoteIdentifier(TRIGGER_PREFIX + table);
stat.execute("DROP TRIGGER IF EXISTS " + trigger);
if (create) {
StringBuilder buff = new StringBuilder(
"CREATE TRIGGER IF NOT EXISTS ");
// the trigger is also called on rollback because transaction
// rollback will not undo the changes in the Lucene index
buff.append(trigger).
append(" AFTER INSERT, UPDATE, DELETE, ROLLBACK ON ").
append(StringUtils.quoteIdentifier(schema)).
append('.').
append(StringUtils.quoteIdentifier(table)).
append(" FOR EACH ROW CALL \"").
append(FullTextLucene.FullTextTrigger.class.getName()).
append('\"');
stat.execute(buff.toString());
}
}
/**
* Get the index writer/searcher wrapper for the given connection.
*
* @param conn the connection
* @return the index access wrapper
*/
protected static IndexAccess getIndexAccess(Connection conn)
throws SQLException {
String path = getIndexPath(conn);
synchronized (INDEX_ACCESS) {
IndexAccess access = INDEX_ACCESS.get(path);
if (access == null) {
try {
Directory indexDir = path.startsWith(IN_MEMORY_PREFIX) ?
new RAMDirectory() : FSDirectory.open(new File(path));
Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
IndexWriterConfig conf = new IndexWriterConfig(Version.LUCENE_30, analyzer);
conf.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
IndexWriter writer = new IndexWriter(indexDir, conf);
//see http://wiki.apache.org/lucene-java/NearRealtimeSearch
access = new IndexAccess(writer);
} catch (IOException e) {
throw convertException(e);
}
INDEX_ACCESS.put(path, access);
}
return access;
}
}
/**
* Get the path of the Lucene index for this database.
*
* @param conn the database connection
* @return the path
*/
protected static String getIndexPath(Connection conn) throws SQLException {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery("CALL DATABASE_PATH()");
rs.next();
String path = rs.getString(1);
if (path == null) {
return IN_MEMORY_PREFIX + conn.getCatalog();
}
int index = path.lastIndexOf(':');
// position 1 means a windows drive letter is used, ignore that
if (index > 1) {
path = path.substring(index + 1);
}
rs.close();
return path;
}
/**
* Add the existing data to the index.
*
* @param conn the database connection
* @param schema the schema name
* @param table the table name
*/
private static void indexExistingRows(Connection conn, String schema,
String table) throws SQLException {
FullTextLucene.FullTextTrigger existing = new FullTextLucene.FullTextTrigger();
existing.init(conn, schema, null, table, false, Trigger.INSERT);
String sql = "SELECT * FROM " + StringUtils.quoteIdentifier(schema)
+ "." + StringUtils.quoteIdentifier(table);
ResultSet rs = conn.createStatement().executeQuery(sql);
int columnCount = rs.getMetaData().getColumnCount();
while (rs.next()) {
Object[] row = new Object[columnCount];
for (int i = 0; i < columnCount; i++) {
row[i] = rs.getObject(i + 1);
}
existing.insert(row, false);
}
existing.commitIndex();
}
private static void removeIndexFiles(Connection conn) throws SQLException {
String path = getIndexPath(conn);
removeIndexAccess(path);
if (!path.startsWith(IN_MEMORY_PREFIX)) {
FileUtils.deleteRecursive(path, false);
}
}
/**
* Close the index writer and searcher and remove them from the index access
* set.
*
* @param indexPath the index path
*/
protected static void removeIndexAccess(String indexPath)
throws SQLException {
synchronized (INDEX_ACCESS) {
try {
IndexAccess access = INDEX_ACCESS.remove(indexPath);
if(access != null) {
access.close();
}
} catch (Exception e) {
throw convertException(e);
}
}
}
/**
* Do the search.
*
* @param conn the database connection
* @param text the query
* @param limit the limit
* @param offset the offset
* @param data whether the raw data should be returned
* @return the result set
*/
protected static ResultSet search(Connection conn, String text,
int limit, int offset, boolean data) throws SQLException {
SimpleResultSet result = createResultSet(data);
if (conn.getMetaData().getURL().startsWith("jdbc:columnlist:")) {
// this is just to query the result set columns
return result;
}
if (text == null || text.trim().length() == 0) {
return result;
}
try {
IndexAccess access = getIndexAccess(conn);
// take a reference as the searcher may change
IndexSearcher searcher = access.getSearcher();
try {
// reuse the same analyzer; it's thread-safe;
// also allows subclasses to control the analyzer used.
Analyzer analyzer = access.writer.getAnalyzer();
QueryParser parser = new QueryParser(Version.LUCENE_30,
LUCENE_FIELD_DATA, analyzer);
Query query = parser.parse(text);
// Lucene 3 insists on a hard limit and will not provide
// a total hits value. Take at least 100 which is
// an optimal limit for Lucene as any more
// will trigger writing results to disk.
int maxResults = (limit == 0 ? 100 : limit) + offset;
TopDocs docs = searcher.search(query, maxResults);
if (limit == 0) {
limit = docs.totalHits;
}
for (int i = 0, len = docs.scoreDocs.length; i < limit
&& i + offset < docs.totalHits
&& i + offset < len; i++) {
ScoreDoc sd = docs.scoreDocs[i + offset];
Document doc = searcher.doc(sd.doc);
float score = sd.score;
String q = doc.get(LUCENE_FIELD_QUERY);
if (data) {
int idx = q.indexOf(" WHERE ");
JdbcConnection c = (JdbcConnection) conn;
Session session = (Session) c.getSession();
Parser p = new Parser(session);
String tab = q.substring(0, idx);
ExpressionColumn expr = (ExpressionColumn) p
.parseExpression(tab);
String schemaName = expr.getOriginalTableAliasName();
String tableName = expr.getColumnName();
q = q.substring(idx + " WHERE ".length());
Object[][] columnData = parseKey(conn, q);
result.addRow(schemaName, tableName, columnData[0],
columnData[1], score);
} else {
result.addRow(q, score);
}
}
} finally {
access.returnSearcher(searcher);
}
} catch (Exception e) {
throw convertException(e);
}
return result;
}
/**
* Trigger updates the index when a inserting, updating, or deleting a row.
*/
public static final class FullTextTrigger implements Trigger {
private String schema;
private String table;
private int[] keys;
private int[] indexColumns;
private String[] columns;
private int[] columnTypes;
private String indexPath;
private IndexAccess indexAccess;
/**
* INTERNAL
*/
@Override
public void init(Connection conn, String schemaName, String triggerName,
String tableName, boolean before, int type) throws SQLException {
this.schema = schemaName;
this.table = tableName;
this.indexPath = getIndexPath(conn);
this.indexAccess = getIndexAccess(conn);
ArrayList<String> keyList = New.arrayList();
DatabaseMetaData meta = conn.getMetaData();
ResultSet rs = meta.getColumns(null,
StringUtils.escapeMetaDataPattern(schemaName),
StringUtils.escapeMetaDataPattern(tableName),
null);
ArrayList<String> columnList = New.arrayList();
while (rs.next()) {
columnList.add(rs.getString("COLUMN_NAME"));
}
columnTypes = new int[columnList.size()];
columns = columnList.toArray(new String[0]);
rs = meta.getColumns(null,
StringUtils.escapeMetaDataPattern(schemaName),
StringUtils.escapeMetaDataPattern(tableName),
null);
for (int i = 0; rs.next(); i++) {
columnTypes[i] = rs.getInt("DATA_TYPE");
}
if (keyList.isEmpty()) {
rs = meta.getPrimaryKeys(null,
StringUtils.escapeMetaDataPattern(schemaName),
tableName);
while (rs.next()) {
keyList.add(rs.getString("COLUMN_NAME"));
}
}
if (keyList.isEmpty()) {
throw throwException("No primary key for table " + tableName);
}
ArrayList<String> indexList = New.arrayList();
PreparedStatement prep = conn.prepareStatement(
"SELECT COLUMNS FROM " + SCHEMA
+ ".INDEXES WHERE SCHEMA=? AND TABLE=?");
prep.setString(1, schemaName);
prep.setString(2, tableName);
rs = prep.executeQuery();
if (rs.next()) {
String cols = rs.getString(1);
if (cols != null) {
Collections.addAll(indexList,
StringUtils.arraySplit(cols, ',', true));
}
}
if (indexList.isEmpty()) {
indexList.addAll(columnList);
}
keys = new int[keyList.size()];
setColumns(keys, keyList, columnList);
indexColumns = new int[indexList.size()];
setColumns(indexColumns, indexList, columnList);
}
/**
* INTERNAL
*/
@Override
public void fire(Connection conn, Object[] oldRow, Object[] newRow)
throws SQLException {
if (oldRow != null) {
if (newRow != null) {
// update
if (hasChanged(oldRow, newRow, indexColumns)) {
delete(oldRow, false);
insert(newRow, true);
}
} else {
// delete
delete(oldRow, true);
}
} else if (newRow != null) {
// insert
insert(newRow, true);
}
}
/**
* INTERNAL
*/
@Override
public void close() throws SQLException {
removeIndexAccess(indexPath);
}
/**
* INTERNAL
*/
@Override
public void remove() {
// ignore
}
/**
* Commit all changes to the Lucene index.
*/
void commitIndex() throws SQLException {
try {
indexAccess.commit();
} catch (IOException e) {
throw convertException(e);
}
}
/**
* Add a row to the index.
*
* @param row the row
* @param commitIndex whether to commit the changes to the Lucene index
*/
protected void insert(Object[] row, boolean commitIndex) throws SQLException {
String query = getQuery(row);
Document doc = new Document();
doc.add(new Field(LUCENE_FIELD_QUERY, query,
Field.Store.YES, Field.Index.NOT_ANALYZED));
long time = System.currentTimeMillis();
doc.add(new Field(LUCENE_FIELD_MODIFIED,
DateTools.timeToString(time, DateTools.Resolution.SECOND),
Field.Store.YES, Field.Index.NOT_ANALYZED));
StatementBuilder buff = new StatementBuilder();
for (int index : indexColumns) {
String columnName = columns[index];
String data = asString(row[index], columnTypes[index]);
// column names that start with _
// must be escaped to avoid conflicts
// with internal field names (_DATA, _QUERY, _modified)
if (columnName.startsWith(LUCENE_FIELD_COLUMN_PREFIX)) {
columnName = LUCENE_FIELD_COLUMN_PREFIX + columnName;
}
doc.add(new Field(columnName, data,
Field.Store.NO, Field.Index.ANALYZED));
buff.appendExceptFirst(" ");
buff.append(data);
}
Field.Store storeText = STORE_DOCUMENT_TEXT_IN_INDEX ?
Field.Store.YES : Field.Store.NO;
doc.add(new Field(LUCENE_FIELD_DATA, buff.toString(), storeText,
Field.Index.ANALYZED));
try {
indexAccess.writer.addDocument(doc);
if (commitIndex) {
commitIndex();
}
} catch (IOException e) {
throw convertException(e);
}
}
/**
* Delete a row from the index.
*
* @param row the row
* @param commitIndex whether to commit the changes to the Lucene index
*/
protected void delete(Object[] row, boolean commitIndex) throws SQLException {
String query = getQuery(row);
try {
Term term = new Term(LUCENE_FIELD_QUERY, query);
indexAccess.writer.deleteDocuments(term);
if (commitIndex) {
commitIndex();
}
} catch (IOException e) {
throw convertException(e);
}
}
private String getQuery(Object[] row) throws SQLException {
StatementBuilder buff = new StatementBuilder();
if (schema != null) {
buff.append(StringUtils.quoteIdentifier(schema)).append('.');
}
buff.append(StringUtils.quoteIdentifier(table)).append(" WHERE ");
for (int columnIndex : keys) {
buff.appendExceptFirst(" AND ");
buff.append(StringUtils.quoteIdentifier(columns[columnIndex]));
Object o = row[columnIndex];
if (o == null) {
buff.append(" IS NULL");
} else {
buff.append('=').append(FullText.quoteSQL(o, columnTypes[columnIndex]));
}
}
return buff.toString();
}
}
/**
* A wrapper for the Lucene writer and searcher.
*/
static final class IndexAccess {
/**
* The index writer.
*/
final IndexWriter writer;
/**
* Map of usage counters for outstanding searchers.
*/
private final Map<IndexSearcher,Integer> counters = new HashMap<>();
/**
* Usage counter for current searcher.
*/
private int counter;
/**
* The index searcher.
*/
private IndexSearcher searcher;
IndexAccess(IndexWriter writer) throws IOException {
this.writer = writer;
IndexReader reader = IndexReader.open(writer, true);
searcher = new IndexSearcher(reader);
}
/**
* Start using the searcher.
*
* @return the searcher
*/
synchronized IndexSearcher getSearcher() {
++counter;
return searcher;
}
/**
* Stop using the searcher.
*
* @param searcher the searcher
*/
synchronized void returnSearcher(IndexSearcher searcher) {
if (this.searcher == searcher) {
--counter;
assert counter >= 0;
} else {
Integer cnt = counters.remove(searcher);
assert cnt != null;
if(--cnt == 0) {
closeSearcher(searcher);
} else {
counters.put(searcher, cnt);
}
}
}
/**
* Commit the changes.
*/
public synchronized void commit() throws IOException {
writer.commit();
if (counter != 0) {
counters.put(searcher, counter);
counter = 0;
} else {
closeSearcher(searcher);
}
// recreate Searcher with the IndexWriter's reader.
searcher = new IndexSearcher(IndexReader.open(writer, true));
}
/**
* Close the index.
*/
public synchronized void close() throws IOException {
for (IndexSearcher searcher : counters.keySet()) {
closeSearcher(searcher);
}
counters.clear();
closeSearcher(searcher);
searcher = null;
writer.close();
}
private static void closeSearcher(IndexSearcher searcher) {
IndexReader indexReader = searcher.getIndexReader();
try { searcher.close(); } catch(IOException ignore) {/**/}
try { indexReader.close(); } catch(IOException ignore) {/**/}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/fulltext/FullTextSettings.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.fulltext;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.h2.util.SoftHashMap;
/**
* The global settings of a full text search.
*/
final class FullTextSettings {
/**
* The settings of open indexes.
*/
private static final Map<String, FullTextSettings> SETTINGS = new HashMap<>();
/**
* Whether this instance has been initialized.
*/
private boolean initialized;
/**
* The set of words not to index (stop words).
*/
private final Set<String> ignoreList = new HashSet<>();
/**
* The set of words / terms.
*/
private final Map<String, Integer> words = new HashMap<>();
/**
* The set of indexes in this database.
*/
private final Map<Integer, IndexInfo> indexes = Collections
.synchronizedMap(new HashMap<Integer, IndexInfo>());
/**
* The prepared statement cache.
*/
private final SoftHashMap<Connection,
SoftHashMap<String, PreparedStatement>> cache =
new SoftHashMap<>();
/**
* The whitespace characters.
*/
private String whitespaceChars = " \t\n\r\f+\"*%&/()=?'!,.;:-_#@|^~`{}[]<>\\";
/**
* Create a new instance.
*/
private FullTextSettings() {
// don't allow construction
}
/**
* Clear set of ignored words
*/
public void clearIgnored() {
synchronized (ignoreList) {
ignoreList.clear();
}
}
/**
* Amend set of ignored words
* @param words to add
*/
public void addIgnored(Iterable<String> words) {
synchronized (ignoreList) {
for (String word : words) {
word = normalizeWord(word);
ignoreList.add(word);
}
}
}
/**
* Clear set of searchable words
*/
public void clearWordList() {
synchronized (words) {
words.clear();
}
}
/**
* Get id for a searchable word
* @param word to find id for
* @return Integer id or null if word is not found
*/
public Integer getWordId(String word) {
synchronized (words) {
return words.get(word);
}
}
/**
* Register searchable word
* @param word to register
* @param id to register with
*/
public void addWord(String word, Integer id) {
synchronized (words) {
if(!words.containsKey(word)) {
words.put(word, id);
}
}
}
/**
* Get the index information for the given index id.
*
* @param indexId the index id
* @return the index info
*/
protected IndexInfo getIndexInfo(int indexId) {
return indexes.get(indexId);
}
/**
* Add an index.
*
* @param index the index
*/
protected void addIndexInfo(IndexInfo index) {
indexes.put(index.id, index);
}
/**
* Convert a word to uppercase. This method returns null if the word is in
* the ignore list.
*
* @param word the word to convert and check
* @return the uppercase version of the word or null
*/
protected String convertWord(String word) {
word = normalizeWord(word);
synchronized (ignoreList) {
if (ignoreList.contains(word)) {
return null;
}
}
return word;
}
/**
* Get or create the fulltext settings for this database.
*
* @param conn the connection
* @return the settings
*/
protected static FullTextSettings getInstance(Connection conn)
throws SQLException {
String path = getIndexPath(conn);
FullTextSettings setting;
synchronized (SETTINGS) {
setting = SETTINGS.get(path);
if (setting == null) {
setting = new FullTextSettings();
SETTINGS.put(path, setting);
}
}
return setting;
}
/**
* Get the file system path.
*
* @param conn the connection
* @return the file system path
*/
private static String getIndexPath(Connection conn) throws SQLException {
Statement stat = conn.createStatement();
ResultSet rs = stat.executeQuery(
"CALL IFNULL(DATABASE_PATH(), 'MEM:' || DATABASE())");
rs.next();
String path = rs.getString(1);
if ("MEM:UNNAMED".equals(path)) {
throw FullText.throwException(
"Fulltext search for private (unnamed) " +
"in-memory databases is not supported.");
}
rs.close();
return path;
}
/**
* Prepare a statement. The statement is cached in a soft reference cache.
*
* @param conn the connection
* @param sql the statement
* @return the prepared statement
*/
protected synchronized PreparedStatement prepare(Connection conn, String sql)
throws SQLException {
SoftHashMap<String, PreparedStatement> c = cache.get(conn);
if (c == null) {
c = new SoftHashMap<>();
cache.put(conn, c);
}
PreparedStatement prep = c.get(sql);
if (prep != null && prep.getConnection().isClosed()) {
prep = null;
}
if (prep == null) {
prep = conn.prepareStatement(sql);
c.put(sql, prep);
}
return prep;
}
/**
* Remove all indexes from the settings.
*/
protected void removeAllIndexes() {
indexes.clear();
}
/**
* Remove an index from the settings.
*
* @param index the index to remove
*/
protected void removeIndexInfo(IndexInfo index) {
indexes.remove(index.id);
}
/**
* Set the initialized flag.
*
* @param b the new value
*/
protected void setInitialized(boolean b) {
this.initialized = b;
}
/**
* Get the initialized flag.
*
* @return whether this instance is initialized
*/
protected boolean isInitialized() {
return initialized;
}
/**
* Close all fulltext settings, freeing up memory.
*/
protected static void closeAll() {
synchronized (SETTINGS) {
SETTINGS.clear();
}
}
protected void setWhitespaceChars(String whitespaceChars) {
this.whitespaceChars = whitespaceChars;
}
protected String getWhitespaceChars() {
return whitespaceChars;
}
private static String normalizeWord(String word) {
// TODO this is locale specific, document
return word.toUpperCase();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/fulltext/IndexInfo.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.fulltext;
/**
* The settings of one full text search index.
*/
public class IndexInfo {
/**
* The index id.
*/
protected int id;
/**
* The schema name.
*/
protected String schema;
/**
* The table name.
*/
protected String table;
/**
* The column indexes of the key columns.
*/
protected int[] keys;
/**
* The column indexes of the index columns.
*/
protected int[] indexColumns;
/**
* The column names.
*/
protected String[] columns;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/AbstractFunctionCursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.value.Value;
/**
* Abstract function cursor. This implementation filters the rows (only returns
* entries that are larger or equal to "first", and smaller than last or equal
* to "last").
*/
abstract class AbstractFunctionCursor implements Cursor {
private final FunctionIndex index;
private final SearchRow first;
private final SearchRow last;
final Session session;
Value[] values;
Row row;
/**
* @param index
* index
* @param first
* first row
* @param last
* last row
* @param session
* session
*/
AbstractFunctionCursor(FunctionIndex index, SearchRow first, SearchRow last, Session session) {
this.index = index;
this.first = first;
this.last = last;
this.session = session;
}
@Override
public Row get() {
if (values == null) {
return null;
}
if (row == null) {
row = session.createRow(values, 1);
}
return row;
}
@Override
public SearchRow getSearchRow() {
return get();
}
@Override
public boolean next() {
final SearchRow first = this.first, last = this.last;
if (first == null && last == null) {
return nextImpl();
}
while (nextImpl()) {
Row current = get();
if (first != null) {
int comp = index.compareRows(current, first);
if (comp < 0) {
continue;
}
}
if (last != null) {
int comp = index.compareRows(current, last);
if (comp > 0) {
continue;
}
}
return true;
}
return false;
}
/**
* Skip to the next row if one is available. This method does not filter.
*
* @return true if another row is available
*/
abstract boolean nextImpl();
@Override
public boolean previous() {
throw DbException.throwInternalError(toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/BaseIndex.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.schema.SchemaObjectBase;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* Most index implementations extend the base index.
*/
public abstract class BaseIndex extends SchemaObjectBase implements Index {
protected IndexColumn[] indexColumns;
protected Column[] columns;
protected int[] columnIds;
protected Table table;
protected IndexType indexType;
protected boolean isMultiVersion;
/**
* Initialize the base index.
*
* @param newTable the table
* @param id the object id
* @param name the index name
* @param newIndexColumns the columns that are indexed or null if this is
* not yet known
* @param newIndexType the index type
*/
protected void initBaseIndex(Table newTable, int id, String name,
IndexColumn[] newIndexColumns, IndexType newIndexType) {
initSchemaObjectBase(newTable.getSchema(), id, name, Trace.INDEX);
this.indexType = newIndexType;
this.table = newTable;
if (newIndexColumns != null) {
this.indexColumns = newIndexColumns;
columns = new Column[newIndexColumns.length];
int len = columns.length;
columnIds = new int[len];
for (int i = 0; i < len; i++) {
Column col = newIndexColumns[i].column;
columns[i] = col;
columnIds[i] = col.getColumnId();
}
}
}
/**
* Check that the index columns are not CLOB or BLOB.
*
* @param columns the columns
*/
protected static void checkIndexColumnTypes(IndexColumn[] columns) {
for (IndexColumn c : columns) {
int type = c.column.getType();
if (type == Value.CLOB || type == Value.BLOB) {
throw DbException.getUnsupportedException(
"Index on BLOB or CLOB column: " + c.column.getCreateSQL());
}
}
}
@Override
public String getDropSQL() {
return null;
}
/**
* Create a duplicate key exception with a message that contains the index
* name.
*
* @param key the key values
* @return the exception
*/
protected DbException getDuplicateKeyException(String key) {
String sql = getName() + " ON " + table.getSQL() +
"(" + getColumnListSQL() + ")";
if (key != null) {
sql += " VALUES " + key;
}
DbException e = DbException.get(ErrorCode.DUPLICATE_KEY_1, sql);
e.setSource(this);
return e;
}
@Override
public String getPlanSQL() {
return getSQL();
}
@Override
public void removeChildrenAndResources(Session session) {
table.removeIndex(this);
remove(session);
database.removeMeta(session, getId());
}
@Override
public boolean canFindNext() {
return false;
}
@Override
public boolean isFindUsingFullTableScan() {
return false;
}
@Override
public Cursor find(TableFilter filter, SearchRow first, SearchRow last) {
return find(filter.getSession(), first, last);
}
/**
* Find a row or a list of rows that is larger and create a cursor to
* iterate over the result. The base implementation doesn't support this
* feature.
*
* @param session the session
* @param higherThan the lower limit (excluding)
* @param last the last row, or null for no limit
* @return the cursor
* @throws DbException always
*/
@Override
public Cursor findNext(Session session, SearchRow higherThan, SearchRow last) {
throw DbException.throwInternalError(toString());
}
/**
* Calculate the cost for the given mask as if this index was a typical
* b-tree range index. This is the estimated cost required to search one
* row, and then iterate over the given number of rows.
*
* @param masks the IndexCondition search masks, one for each column in the
* table
* @param rowCount the number of rows in the index
* @param filters all joined table filters
* @param filter the current table filter index
* @param sortOrder the sort order
* @param isScanIndex whether this is a "table scan" index
* @param allColumnsSet the set of all columns
* @return the estimated cost
*/
protected final long getCostRangeIndex(int[] masks, long rowCount,
TableFilter[] filters, int filter, SortOrder sortOrder,
boolean isScanIndex, HashSet<Column> allColumnsSet) {
rowCount += Constants.COST_ROW_OFFSET;
int totalSelectivity = 0;
long rowsCost = rowCount;
if (masks != null) {
for (int i = 0, len = columns.length; i < len; i++) {
Column column = columns[i];
int index = column.getColumnId();
int mask = masks[index];
if ((mask & IndexCondition.EQUALITY) == IndexCondition.EQUALITY) {
if (i == columns.length - 1 && getIndexType().isUnique()) {
rowsCost = 3;
break;
}
totalSelectivity = 100 - ((100 - totalSelectivity) *
(100 - column.getSelectivity()) / 100);
long distinctRows = rowCount * totalSelectivity / 100;
if (distinctRows <= 0) {
distinctRows = 1;
}
rowsCost = 2 + Math.max(rowCount / distinctRows, 1);
} else if ((mask & IndexCondition.RANGE) == IndexCondition.RANGE) {
rowsCost = 2 + rowCount / 4;
break;
} else if ((mask & IndexCondition.START) == IndexCondition.START) {
rowsCost = 2 + rowCount / 3;
break;
} else if ((mask & IndexCondition.END) == IndexCondition.END) {
rowsCost = rowCount / 3;
break;
} else {
break;
}
}
}
// If the ORDER BY clause matches the ordering of this index,
// it will be cheaper than another index, so adjust the cost
// accordingly.
long sortingCost = 0;
if (sortOrder != null) {
sortingCost = 100 + rowCount / 10;
}
if (sortOrder != null && !isScanIndex) {
boolean sortOrderMatches = true;
int coveringCount = 0;
int[] sortTypes = sortOrder.getSortTypes();
TableFilter tableFilter = filters == null ? null : filters[filter];
for (int i = 0, len = sortTypes.length; i < len; i++) {
if (i >= indexColumns.length) {
// We can still use this index if we are sorting by more
// than it's columns, it's just that the coveringCount
// is lower than with an index that contains
// more of the order by columns.
break;
}
Column col = sortOrder.getColumn(i, tableFilter);
if (col == null) {
sortOrderMatches = false;
break;
}
IndexColumn indexCol = indexColumns[i];
if (!col.equals(indexCol.column)) {
sortOrderMatches = false;
break;
}
int sortType = sortTypes[i];
if (sortType != indexCol.sortType) {
sortOrderMatches = false;
break;
}
coveringCount++;
}
if (sortOrderMatches) {
// "coveringCount" makes sure that when we have two
// or more covering indexes, we choose the one
// that covers more.
sortingCost = 100 - coveringCount;
}
}
// If we have two indexes with the same cost, and one of the indexes can
// satisfy the query without needing to read from the primary table
// (scan index), make that one slightly lower cost.
boolean needsToReadFromScanIndex = true;
if (!isScanIndex && allColumnsSet != null && !allColumnsSet.isEmpty()) {
boolean foundAllColumnsWeNeed = true;
for (Column c : allColumnsSet) {
if (c.getTable() == getTable()) {
boolean found = false;
for (Column c2 : columns) {
if (c == c2) {
found = true;
break;
}
}
if (!found) {
foundAllColumnsWeNeed = false;
break;
}
}
}
if (foundAllColumnsWeNeed) {
needsToReadFromScanIndex = false;
}
}
long rc;
if (isScanIndex) {
rc = rowsCost + sortingCost + 20;
} else if (needsToReadFromScanIndex) {
rc = rowsCost + rowsCost + sortingCost + 20;
} else {
// The (20-x) calculation makes sure that when we pick a covering
// index, we pick the covering index that has the smallest number of
// columns (the more columns we have in index - the higher cost).
// This is faster because a smaller index will fit into fewer data
// blocks.
rc = rowsCost + sortingCost + columns.length;
}
return rc;
}
@Override
public int compareRows(SearchRow rowData, SearchRow compare) {
if (rowData == compare) {
return 0;
}
for (int i = 0, len = indexColumns.length; i < len; i++) {
int index = columnIds[i];
Value v1 = rowData.getValue(index);
Value v2 = compare.getValue(index);
if (v1 == null || v2 == null) {
// can't compare further
return 0;
}
int c = compareValues(v1, v2, indexColumns[i].sortType);
if (c != 0) {
return c;
}
}
return 0;
}
/**
* Check if this row may have duplicates with the same indexed values in the
* current compatibility mode. Duplicates with {@code NULL} values are
* allowed in some modes.
*
* @param searchRow
* the row to check
* @return {@code true} if specified row may have duplicates,
* {@code false otherwise}
*/
protected boolean mayHaveNullDuplicates(SearchRow searchRow) {
switch (database.getMode().uniqueIndexNullsHandling) {
case ALLOW_DUPLICATES_WITH_ANY_NULL:
for (int index : columnIds) {
if (searchRow.getValue(index) == ValueNull.INSTANCE) {
return true;
}
}
return false;
case ALLOW_DUPLICATES_WITH_ALL_NULLS:
for (int index : columnIds) {
if (searchRow.getValue(index) != ValueNull.INSTANCE) {
return false;
}
}
return true;
default:
return false;
}
}
/**
* Compare the positions of two rows.
*
* @param rowData the first row
* @param compare the second row
* @return 0 if both rows are equal, -1 if the first row is smaller,
* otherwise 1
*/
int compareKeys(SearchRow rowData, SearchRow compare) {
long k1 = rowData.getKey();
long k2 = compare.getKey();
if (k1 == k2) {
if (isMultiVersion) {
int v1 = rowData.getVersion();
int v2 = compare.getVersion();
return Integer.compare(v2, v1);
}
return 0;
}
return k1 > k2 ? 1 : -1;
}
private int compareValues(Value a, Value b, int sortType) {
if (a == b) {
return 0;
}
int comp = table.compareTypeSafe(a, b);
if ((sortType & SortOrder.DESCENDING) != 0) {
comp = -comp;
}
return comp;
}
@Override
public int getColumnIndex(Column col) {
for (int i = 0, len = columns.length; i < len; i++) {
if (columns[i].equals(col)) {
return i;
}
}
return -1;
}
@Override
public boolean isFirstColumn(Column column) {
return column.equals(columns[0]);
}
/**
* Get the list of columns as a string.
*
* @return the list of columns
*/
private String getColumnListSQL() {
StatementBuilder buff = new StatementBuilder();
for (IndexColumn c : indexColumns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
return buff.toString();
}
@Override
public String getCreateSQLForCopy(Table targetTable, String quotedName) {
StringBuilder buff = new StringBuilder("CREATE ");
buff.append(indexType.getSQL());
buff.append(' ');
if (table.isHidden()) {
buff.append("IF NOT EXISTS ");
}
buff.append(quotedName);
buff.append(" ON ").append(targetTable.getSQL());
if (comment != null) {
buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment));
}
buff.append('(').append(getColumnListSQL()).append(')');
return buff.toString();
}
@Override
public String getCreateSQL() {
return getCreateSQLForCopy(table, getSQL());
}
@Override
public IndexColumn[] getIndexColumns() {
return indexColumns;
}
@Override
public Column[] getColumns() {
return columns;
}
@Override
public IndexType getIndexType() {
return indexType;
}
@Override
public int getType() {
return DbObject.INDEX;
}
@Override
public Table getTable() {
return table;
}
@Override
public void commit(int operation, Row row) {
// nothing to do
}
void setMultiVersion(boolean multiVersion) {
this.isMultiVersion = multiVersion;
}
@Override
public Row getRow(Session session, long key) {
throw DbException.getUnsupportedException(toString());
}
@Override
public boolean isHidden() {
return table.isHidden();
}
@Override
public boolean isRowIdIndex() {
return false;
}
@Override
public boolean canScan() {
return true;
}
@Override
public void setSortedInsertMode(boolean sortedInsertMode) {
// ignore
}
@Override
public IndexLookupBatch createLookupBatch(TableFilter[] filters, int filter) {
// Lookup batching is not supported.
return null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/Cursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import org.h2.result.Row;
import org.h2.result.SearchRow;
/**
* A cursor is a helper object to iterate through an index.
* For indexes are sorted (such as the b tree index), it can iterate
* to the very end of the index. For other indexes that don't support
* that (such as a hash index), only one row is returned.
* The cursor is initially positioned before the first row, that means
* next() must be called before accessing data.
*
*/
public interface Cursor {
/**
* Get the complete current row.
* All column are available.
*
* @return the complete row
*/
Row get();
/**
* Get the current row.
* Only the data for indexed columns is available in this row.
*
* @return the search row
*/
SearchRow getSearchRow();
/**
* Skip to the next row if one is available.
*
* @return true if another row is available
*/
boolean next();
/**
* Skip to the previous row if one is available.
* No filtering is made here.
*
* @return true if another row is available
*/
boolean previous();
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/FunctionCursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import org.h2.engine.Session;
import org.h2.result.ResultInterface;
import org.h2.result.SearchRow;
/**
* A cursor for a function that returns a result.
*/
public class FunctionCursor extends AbstractFunctionCursor {
private final ResultInterface result;
FunctionCursor(FunctionIndex index, SearchRow first, SearchRow last, Session session, ResultInterface result) {
super(index, first, last, session);
this.result = result;
}
@Override
boolean nextImpl() {
row = null;
if (result != null && result.next()) {
values = result.currentRow();
} else {
values = null;
}
return values != null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/FunctionCursorResultSet.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.SearchRow;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* A cursor for a function that returns a JDBC result set.
*/
public class FunctionCursorResultSet extends AbstractFunctionCursor {
private final ResultSet result;
private final ResultSetMetaData meta;
FunctionCursorResultSet(FunctionIndex index, SearchRow first, SearchRow last, Session session, ResultSet result) {
super(index, first, last, session);
this.result = result;
try {
this.meta = result.getMetaData();
} catch (SQLException e) {
throw DbException.convert(e);
}
}
@Override
boolean nextImpl() {
row = null;
try {
if (result != null && result.next()) {
int columnCount = meta.getColumnCount();
values = new Value[columnCount];
for (int i = 0; i < columnCount; i++) {
int type = DataType.getValueTypeFromResultSet(meta, i + 1);
values[i] = DataType.readValue(session, result, i + 1, type);
}
} else {
values = null;
}
} catch (SQLException e) {
throw DbException.convert(e);
}
return values != null;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/FunctionIndex.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.HashSet;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.FunctionTable;
import org.h2.table.IndexColumn;
import org.h2.table.TableFilter;
/**
* An index for a function that returns a result set. Search in this index
* performs scan over all rows and should be avoided.
*/
public class FunctionIndex extends BaseIndex {
private final FunctionTable functionTable;
public FunctionIndex(FunctionTable functionTable, IndexColumn[] columns) {
initBaseIndex(functionTable, 0, null, columns, IndexType.createNonUnique(true));
this.functionTable = functionTable;
}
@Override
public void close(Session session) {
// nothing to do
}
@Override
public void add(Session session, Row row) {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public void remove(Session session, Row row) {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public boolean isFindUsingFullTableScan() {
return true;
}
@Override
public Cursor find(Session session, SearchRow first, SearchRow last) {
if (functionTable.isBufferResultSetToLocalTemp()) {
return new FunctionCursor(this, first, last, session, functionTable.getResult(session));
}
return new FunctionCursorResultSet(this, first, last, session,
functionTable.getResultSet(session));
}
@Override
public double getCost(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
if (masks != null) {
throw DbException.getUnsupportedException("ALIAS");
}
long expectedRows;
if (functionTable.canGetRowCount()) {
expectedRows = functionTable.getRowCountApproximation();
} else {
expectedRows = database.getSettings().estimatedFunctionTableRows;
}
return expectedRows * 10;
}
@Override
public void remove(Session session) {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public void truncate(Session session) {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public boolean needRebuild() {
return false;
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public boolean canGetFirstOrLast() {
return false;
}
@Override
public Cursor findFirstOrLast(Session session, boolean first) {
throw DbException.getUnsupportedException("ALIAS");
}
@Override
public long getRowCount(Session session) {
return functionTable.getRowCount(session);
}
@Override
public long getRowCountApproximation() {
return functionTable.getRowCountApproximation();
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
@Override
public String getPlanSQL() {
return "function";
}
@Override
public boolean canScan() {
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/HashIndex.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.HashSet;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.RegularTable;
import org.h2.table.TableFilter;
import org.h2.util.ValueHashMap;
import org.h2.value.Value;
/**
* An unique index based on an in-memory hash map.
*/
public class HashIndex extends BaseIndex {
/**
* The index of the indexed column.
*/
private final int indexColumn;
private final RegularTable tableData;
private ValueHashMap<Long> rows;
public HashIndex(RegularTable table, int id, String indexName,
IndexColumn[] columns, IndexType indexType) {
initBaseIndex(table, id, indexName, columns, indexType);
this.indexColumn = columns[0].column.getColumnId();
this.tableData = table;
reset();
}
private void reset() {
rows = ValueHashMap.newInstance();
}
@Override
public void truncate(Session session) {
reset();
}
@Override
public void add(Session session, Row row) {
Value key = row.getValue(indexColumn);
Object old = rows.get(key);
if (old != null) {
// TODO index duplicate key for hash indexes: is this allowed?
throw getDuplicateKeyException(key.toString());
}
rows.put(key, row.getKey());
}
@Override
public void remove(Session session, Row row) {
rows.remove(row.getValue(indexColumn));
}
@Override
public Cursor find(Session session, SearchRow first, SearchRow last) {
if (first == null || last == null) {
// TODO hash index: should additionally check if values are the same
throw DbException.throwInternalError(first + " " + last);
}
Value v = first.getValue(indexColumn);
/*
* Sometimes the incoming search is a similar, but not the same type
* e.g. the search value is INT, but the index column is LONG. In which
* case we need to convert, otherwise the ValueHashMap will not find the
* result.
*/
v = v.convertTo(tableData.getColumn(indexColumn).getType());
Row result;
Long pos = rows.get(v);
if (pos == null) {
result = null;
} else {
result = tableData.getRow(session, pos.intValue());
}
return new SingleRowCursor(result);
}
@Override
public long getRowCount(Session session) {
return getRowCountApproximation();
}
@Override
public long getRowCountApproximation() {
return rows.size();
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
@Override
public void close(Session session) {
// nothing to do
}
@Override
public void remove(Session session) {
// nothing to do
}
@Override
public double getCost(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
for (Column column : columns) {
int index = column.getColumnId();
int mask = masks[index];
if ((mask & IndexCondition.EQUALITY) != IndexCondition.EQUALITY) {
return Long.MAX_VALUE;
}
}
return 2;
}
@Override
public void checkRename() {
// ok
}
@Override
public boolean needRebuild() {
return true;
}
@Override
public boolean canGetFirstOrLast() {
return false;
}
@Override
public Cursor findFirstOrLast(Session session, boolean first) {
throw DbException.getUnsupportedException("HASH");
}
@Override
public boolean canScan() {
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/Index.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.HashSet;
import org.h2.engine.Session;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.schema.SchemaObject;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
/**
* An index. Indexes are used to speed up searching data.
*/
public interface Index extends SchemaObject {
/**
* Get the message to show in a EXPLAIN statement.
*
* @return the plan
*/
String getPlanSQL();
/**
* Close this index.
*
* @param session the session used to write data
*/
void close(Session session);
/**
* Add a row to the index.
*
* @param session the session to use
* @param row the row to add
*/
void add(Session session, Row row);
/**
* Remove a row from the index.
*
* @param session the session
* @param row the row
*/
void remove(Session session, Row row);
/**
* Returns {@code true} if {@code find()} implementation performs scan over all
* index, {@code false} if {@code find()} performs the fast lookup.
*
* @return {@code true} if {@code find()} implementation performs scan over all
* index, {@code false} if {@code find()} performs the fast lookup
*/
boolean isFindUsingFullTableScan();
/**
* Find a row or a list of rows and create a cursor to iterate over the
* result.
*
* @param session the session
* @param first the first row, or null for no limit
* @param last the last row, or null for no limit
* @return the cursor to iterate over the results
*/
Cursor find(Session session, SearchRow first, SearchRow last);
/**
* Find a row or a list of rows and create a cursor to iterate over the
* result.
*
* @param filter the table filter (which possibly knows about additional
* conditions)
* @param first the first row, or null for no limit
* @param last the last row, or null for no limit
* @return the cursor to iterate over the results
*/
Cursor find(TableFilter filter, SearchRow first, SearchRow last);
/**
* Estimate the cost to search for rows given the search mask.
* There is one element per column in the search mask.
* For possible search masks, see IndexCondition.
*
* @param session the session
* @param masks per-column comparison bit masks, null means 'always false',
* see constants in IndexCondition
* @param filters all joined table filters
* @param filter the current table filter index
* @param sortOrder the sort order
* @param allColumnsSet the set of all columns
* @return the estimated cost
*/
double getCost(Session session, int[] masks, TableFilter[] filters, int filter,
SortOrder sortOrder, HashSet<Column> allColumnsSet);
/**
* Remove the index.
*
* @param session the session
*/
void remove(Session session);
/**
* Remove all rows from the index.
*
* @param session the session
*/
void truncate(Session session);
/**
* Check if the index can directly look up the lowest or highest value of a
* column.
*
* @return true if it can
*/
boolean canGetFirstOrLast();
/**
* Check if the index can get the next higher value.
*
* @return true if it can
*/
boolean canFindNext();
/**
* Find a row or a list of rows that is larger and create a cursor to
* iterate over the result.
*
* @param session the session
* @param higherThan the lower limit (excluding)
* @param last the last row, or null for no limit
* @return the cursor
*/
Cursor findNext(Session session, SearchRow higherThan, SearchRow last);
/**
* Find the first (or last) value of this index. The cursor returned is
* positioned on the correct row, or on null if no row has been found.
*
* @param session the session
* @param first true if the first (lowest for ascending indexes) or last
* value should be returned
* @return a cursor (never null)
*/
Cursor findFirstOrLast(Session session, boolean first);
/**
* Check if the index needs to be rebuilt.
* This method is called after opening an index.
*
* @return true if a rebuild is required.
*/
boolean needRebuild();
/**
* Get the row count of this table, for the given session.
*
* @param session the session
* @return the row count
*/
long getRowCount(Session session);
/**
* Get the approximated row count for this table.
*
* @return the approximated row count
*/
long getRowCountApproximation();
/**
* Get the used disk space for this index.
*
* @return the estimated number of bytes
*/
long getDiskSpaceUsed();
/**
* Compare two rows.
*
* @param rowData the first row
* @param compare the second row
* @return 0 if both rows are equal, -1 if the first row is smaller,
* otherwise 1
*/
int compareRows(SearchRow rowData, SearchRow compare);
/**
* Get the index of a column in the list of index columns
*
* @param col the column
* @return the index (0 meaning first column)
*/
int getColumnIndex(Column col);
/**
* Check if the given column is the first for this index
*
* @param column the column
* @return true if the given columns is the first
*/
boolean isFirstColumn(Column column);
/**
* Get the indexed columns as index columns (with ordering information).
*
* @return the index columns
*/
IndexColumn[] getIndexColumns();
/**
* Get the indexed columns.
*
* @return the columns
*/
Column[] getColumns();
/**
* Get the index type.
*
* @return the index type
*/
IndexType getIndexType();
/**
* Get the table on which this index is based.
*
* @return the table
*/
Table getTable();
/**
* Commit the operation for a row. This is only important for multi-version
* indexes. The method is only called if multi-version is enabled.
*
* @param operation the operation type
* @param row the row
*/
void commit(int operation, Row row);
/**
* Get the row with the given key.
*
* @param session the session
* @param key the unique key
* @return the row
*/
Row getRow(Session session, long key);
/**
* Does this index support lookup by row id?
*
* @return true if it does
*/
boolean isRowIdIndex();
/**
* Can this index iterate over all rows?
*
* @return true if it can
*/
boolean canScan();
/**
* Enable or disable the 'sorted insert' optimizations (rows are inserted in
* ascending or descending order) if applicable for this index
* implementation.
*
* @param sortedInsertMode the new value
*/
void setSortedInsertMode(boolean sortedInsertMode);
/**
* Creates new lookup batch. Note that returned {@link IndexLookupBatch}
* instance can be used multiple times.
*
* @param filters the table filters
* @param filter the filter index (0, 1,...)
* @return created batch or {@code null} if batched lookup is not supported
* by this index.
*/
IndexLookupBatch createLookupBatch(TableFilter[] filters, int filter);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/IndexCondition.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import org.h2.command.dml.Query;
import org.h2.engine.Session;
import org.h2.expression.Comparison;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionVisitor;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.table.Column;
import org.h2.table.TableType;
import org.h2.util.StatementBuilder;
import org.h2.value.CompareMode;
import org.h2.value.Value;
/**
* A index condition object is made for each condition that can potentially use
* an index. This class does not extend expression, but in general there is one
* expression that maps to each index condition.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class IndexCondition {
/**
* A bit of a search mask meaning 'equal'.
*/
public static final int EQUALITY = 1;
/**
* A bit of a search mask meaning 'larger or equal'.
*/
public static final int START = 2;
/**
* A bit of a search mask meaning 'smaller or equal'.
*/
public static final int END = 4;
/**
* A search mask meaning 'between'.
*/
public static final int RANGE = START | END;
/**
* A bit of a search mask meaning 'the condition is always false'.
*/
public static final int ALWAYS_FALSE = 8;
/**
* A bit of a search mask meaning 'spatial intersection'.
*/
public static final int SPATIAL_INTERSECTS = 16;
private final Column column;
/**
* see constants in {@link Comparison}
*/
private final int compareType;
private final Expression expression;
private List<Expression> expressionList;
private Query expressionQuery;
/**
* @param compareType the comparison type, see constants in
* {@link Comparison}
*/
private IndexCondition(int compareType, ExpressionColumn column,
Expression expression) {
this.compareType = compareType;
this.column = column == null ? null : column.getColumn();
this.expression = expression;
}
/**
* Create an index condition with the given parameters.
*
* @param compareType the comparison type, see constants in
* {@link Comparison}
* @param column the column
* @param expression the expression
* @return the index condition
*/
public static IndexCondition get(int compareType, ExpressionColumn column,
Expression expression) {
return new IndexCondition(compareType, column, expression);
}
/**
* Create an index condition with the compare type IN_LIST and with the
* given parameters.
*
* @param column the column
* @param list the expression list
* @return the index condition
*/
public static IndexCondition getInList(ExpressionColumn column,
List<Expression> list) {
IndexCondition cond = new IndexCondition(Comparison.IN_LIST, column,
null);
cond.expressionList = list;
return cond;
}
/**
* Create an index condition with the compare type IN_QUERY and with the
* given parameters.
*
* @param column the column
* @param query the select statement
* @return the index condition
*/
public static IndexCondition getInQuery(ExpressionColumn column, Query query) {
IndexCondition cond = new IndexCondition(Comparison.IN_QUERY, column,
null);
cond.expressionQuery = query;
return cond;
}
/**
* Get the current value of the expression.
*
* @param session the session
* @return the value
*/
public Value getCurrentValue(Session session) {
return expression.getValue(session);
}
/**
* Get the current value list of the expression. The value list is of the
* same type as the column, distinct, and sorted.
*
* @param session the session
* @return the value list
*/
public Value[] getCurrentValueList(Session session) {
HashSet<Value> valueSet = new HashSet<>();
for (Expression e : expressionList) {
Value v = e.getValue(session);
v = column.convert(v);
valueSet.add(v);
}
Value[] array = valueSet.toArray(new Value[valueSet.size()]);
final CompareMode mode = session.getDatabase().getCompareMode();
Arrays.sort(array, new Comparator<Value>() {
@Override
public int compare(Value o1, Value o2) {
return o1.compareTo(o2, mode);
}
});
return array;
}
/**
* Get the current result of the expression. The rows may not be of the same
* type, therefore the rows may not be unique.
*
* @return the result
*/
public ResultInterface getCurrentResult() {
return expressionQuery.query(0);
}
/**
* Get the SQL snippet of this comparison.
*
* @return the SQL snippet
*/
public String getSQL() {
if (compareType == Comparison.FALSE) {
return "FALSE";
}
StatementBuilder buff = new StatementBuilder();
buff.append(column.getSQL());
switch (compareType) {
case Comparison.EQUAL:
buff.append(" = ");
break;
case Comparison.EQUAL_NULL_SAFE:
buff.append(" IS ");
break;
case Comparison.BIGGER_EQUAL:
buff.append(" >= ");
break;
case Comparison.BIGGER:
buff.append(" > ");
break;
case Comparison.SMALLER_EQUAL:
buff.append(" <= ");
break;
case Comparison.SMALLER:
buff.append(" < ");
break;
case Comparison.IN_LIST:
buff.append(" IN(");
for (Expression e : expressionList) {
buff.appendExceptFirst(", ");
buff.append(e.getSQL());
}
buff.append(')');
break;
case Comparison.IN_QUERY:
buff.append(" IN(");
buff.append(expressionQuery.getPlanSQL());
buff.append(')');
break;
case Comparison.SPATIAL_INTERSECTS:
buff.append(" && ");
break;
default:
DbException.throwInternalError("type=" + compareType);
}
if (expression != null) {
buff.append(expression.getSQL());
}
return buff.toString();
}
/**
* Get the comparison bit mask.
*
* @param indexConditions all index conditions
* @return the mask
*/
public int getMask(ArrayList<IndexCondition> indexConditions) {
switch (compareType) {
case Comparison.FALSE:
return ALWAYS_FALSE;
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
return EQUALITY;
case Comparison.IN_LIST:
case Comparison.IN_QUERY:
if (indexConditions.size() > 1) {
if (TableType.TABLE != column.getTable().getTableType()) {
// if combined with other conditions,
// IN(..) can only be used for regular tables
// test case:
// create table test(a int, b int, primary key(id, name));
// create unique index c on test(b, a);
// insert into test values(1, 10), (2, 20);
// select * from (select * from test)
// where a=1 and b in(10, 20);
return 0;
}
}
return EQUALITY;
case Comparison.BIGGER_EQUAL:
case Comparison.BIGGER:
return START;
case Comparison.SMALLER_EQUAL:
case Comparison.SMALLER:
return END;
case Comparison.SPATIAL_INTERSECTS:
return SPATIAL_INTERSECTS;
default:
throw DbException.throwInternalError("type=" + compareType);
}
}
/**
* Check if the result is always false.
*
* @return true if the result will always be false
*/
public boolean isAlwaysFalse() {
return compareType == Comparison.FALSE;
}
/**
* Check if this index condition is of the type column larger or equal to
* value.
*
* @return true if this is a start condition
*/
public boolean isStart() {
switch (compareType) {
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
case Comparison.BIGGER_EQUAL:
case Comparison.BIGGER:
return true;
default:
return false;
}
}
/**
* Check if this index condition is of the type column smaller or equal to
* value.
*
* @return true if this is a end condition
*/
public boolean isEnd() {
switch (compareType) {
case Comparison.EQUAL:
case Comparison.EQUAL_NULL_SAFE:
case Comparison.SMALLER_EQUAL:
case Comparison.SMALLER:
return true;
default:
return false;
}
}
/**
* Check if this index condition is of the type spatial column intersects
* value.
*
* @return true if this is a spatial intersects condition
*/
public boolean isSpatialIntersects() {
switch (compareType) {
case Comparison.SPATIAL_INTERSECTS:
return true;
default:
return false;
}
}
public int getCompareType() {
return compareType;
}
/**
* Get the referenced column.
*
* @return the column
*/
public Column getColumn() {
return column;
}
/**
* Get expression.
*
* @return Expression.
*/
public Expression getExpression() {
return expression;
}
/**
* Get expression list.
*
* @return Expression list.
*/
public List<Expression> getExpressionList() {
return expressionList;
}
/**
* Get expression query.
*
* @return Expression query.
*/
public Query getExpressionQuery() {
return expressionQuery;
}
/**
* Check if the expression can be evaluated.
*
* @return true if it can be evaluated
*/
public boolean isEvaluatable() {
if (expression != null) {
return expression
.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR);
}
if (expressionList != null) {
for (Expression e : expressionList) {
if (!e.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
return false;
}
}
return true;
}
return expressionQuery
.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR);
}
@Override
public String toString() {
return "column=" + column +
", compareType=" + compareTypeToString(compareType) +
", expression=" + expression +
", expressionList=" + expressionList +
", expressionQuery=" + expressionQuery;
}
private static String compareTypeToString(int i) {
StatementBuilder s = new StatementBuilder();
if ((i & EQUALITY) == EQUALITY) {
s.appendExceptFirst("&");
s.append("EQUALITY");
}
if ((i & START) == START) {
s.appendExceptFirst("&");
s.append("START");
}
if ((i & END) == END) {
s.appendExceptFirst("&");
s.append("END");
}
if ((i & ALWAYS_FALSE) == ALWAYS_FALSE) {
s.appendExceptFirst("&");
s.append("ALWAYS_FALSE");
}
if ((i & SPATIAL_INTERSECTS) == SPATIAL_INTERSECTS) {
s.appendExceptFirst("&");
s.append("SPATIAL_INTERSECTS");
}
return s.toString();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/IndexCursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.engine.Session;
import org.h2.expression.Comparison;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.value.Value;
import org.h2.value.ValueGeometry;
import org.h2.value.ValueNull;
/**
* The filter used to walk through an index. This class supports IN(..)
* and IN(SELECT ...) optimizations.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class IndexCursor implements Cursor {
private Session session;
private final TableFilter tableFilter;
private Index index;
private Table table;
private IndexColumn[] indexColumns;
private boolean alwaysFalse;
private SearchRow start, end, intersects;
private Cursor cursor;
private Column inColumn;
private int inListIndex;
private Value[] inList;
private ResultInterface inResult;
private HashSet<Value> inResultTested;
public IndexCursor(TableFilter filter) {
this.tableFilter = filter;
}
public void setIndex(Index index) {
this.index = index;
this.table = index.getTable();
Column[] columns = table.getColumns();
indexColumns = new IndexColumn[columns.length];
IndexColumn[] idxCols = index.getIndexColumns();
if (idxCols != null) {
for (int i = 0, len = columns.length; i < len; i++) {
int idx = index.getColumnIndex(columns[i]);
if (idx >= 0) {
indexColumns[i] = idxCols[idx];
}
}
}
}
/**
* Prepare this index cursor to make a lookup in index.
*
* @param s Session.
* @param indexConditions Index conditions.
*/
public void prepare(Session s, ArrayList<IndexCondition> indexConditions) {
this.session = s;
alwaysFalse = false;
start = end = null;
inList = null;
inColumn = null;
inResult = null;
inResultTested = null;
intersects = null;
// don't use enhanced for loop to avoid creating objects
for (IndexCondition condition : indexConditions) {
if (condition.isAlwaysFalse()) {
alwaysFalse = true;
break;
}
// If index can perform only full table scan do not try to use it for regular
// lookups, each such lookup will perform an own table scan.
if (index.isFindUsingFullTableScan()) {
continue;
}
Column column = condition.getColumn();
if (condition.getCompareType() == Comparison.IN_LIST) {
if (start == null && end == null) {
if (canUseIndexForIn(column)) {
this.inColumn = column;
inList = condition.getCurrentValueList(s);
inListIndex = 0;
}
}
} else if (condition.getCompareType() == Comparison.IN_QUERY) {
if (start == null && end == null) {
if (canUseIndexForIn(column)) {
this.inColumn = column;
inResult = condition.getCurrentResult();
}
}
} else {
Value v = condition.getCurrentValue(s);
boolean isStart = condition.isStart();
boolean isEnd = condition.isEnd();
boolean isIntersects = condition.isSpatialIntersects();
int columnId = column.getColumnId();
if (columnId >= 0) {
IndexColumn idxCol = indexColumns[columnId];
if (idxCol != null && (idxCol.sortType & SortOrder.DESCENDING) != 0) {
// if the index column is sorted the other way, we swap
// end and start NULLS_FIRST / NULLS_LAST is not a
// problem, as nulls never match anyway
boolean temp = isStart;
isStart = isEnd;
isEnd = temp;
}
}
if (isStart) {
start = getSearchRow(start, columnId, v, true);
}
if (isEnd) {
end = getSearchRow(end, columnId, v, false);
}
if (isIntersects) {
intersects = getSpatialSearchRow(intersects, columnId, v);
}
// An X=? condition will produce less rows than
// an X IN(..) condition, unless the X IN condition can use the index.
if ((isStart || isEnd) && !canUseIndexFor(inColumn)) {
inColumn = null;
inList = null;
inResult = null;
}
if (!session.getDatabase().getSettings().optimizeIsNull) {
if (isStart && isEnd) {
if (v == ValueNull.INSTANCE) {
// join on a column=NULL is always false
alwaysFalse = true;
}
}
}
}
}
if (inColumn != null) {
start = table.getTemplateRow();
}
}
/**
* Re-evaluate the start and end values of the index search for rows.
*
* @param s the session
* @param indexConditions the index conditions
*/
public void find(Session s, ArrayList<IndexCondition> indexConditions) {
prepare(s, indexConditions);
if (inColumn != null) {
return;
}
if (!alwaysFalse) {
if (intersects != null && index instanceof SpatialIndex) {
cursor = ((SpatialIndex) index).findByGeometry(tableFilter,
start, end, intersects);
} else {
cursor = index.find(tableFilter, start, end);
}
}
}
private boolean canUseIndexForIn(Column column) {
if (inColumn != null) {
// only one IN(..) condition can be used at the same time
return false;
}
return canUseIndexFor(column);
}
private boolean canUseIndexFor(Column column) {
// The first column of the index must match this column,
// or it must be a VIEW index (where the column is null).
// Multiple IN conditions with views are not supported, see
// IndexCondition.getMask.
IndexColumn[] cols = index.getIndexColumns();
if (cols == null) {
return true;
}
IndexColumn idxCol = cols[0];
return idxCol == null || idxCol.column == column;
}
private SearchRow getSpatialSearchRow(SearchRow row, int columnId, Value v) {
if (row == null) {
row = table.getTemplateRow();
} else if (row.getValue(columnId) != null) {
// if an object needs to overlap with both a and b,
// then it needs to overlap with the the union of a and b
// (not the intersection)
ValueGeometry vg = (ValueGeometry) row.getValue(columnId).
convertTo(Value.GEOMETRY);
v = ((ValueGeometry) v.convertTo(Value.GEOMETRY)).
getEnvelopeUnion(vg);
}
if (columnId < 0) {
row.setKey(v.getLong());
} else {
row.setValue(columnId, v);
}
return row;
}
private SearchRow getSearchRow(SearchRow row, int columnId, Value v,
boolean max) {
if (row == null) {
row = table.getTemplateRow();
} else {
v = getMax(row.getValue(columnId), v, max);
}
if (columnId < 0) {
row.setKey(v.getLong());
} else {
row.setValue(columnId, v);
}
return row;
}
private Value getMax(Value a, Value b, boolean bigger) {
if (a == null) {
return b;
} else if (b == null) {
return a;
}
if (session.getDatabase().getSettings().optimizeIsNull) {
// IS NULL must be checked later
if (a == ValueNull.INSTANCE) {
return b;
} else if (b == ValueNull.INSTANCE) {
return a;
}
}
int comp = a.compareTo(b, table.getDatabase().getCompareMode());
if (comp == 0) {
return a;
}
if (a == ValueNull.INSTANCE || b == ValueNull.INSTANCE) {
if (session.getDatabase().getSettings().optimizeIsNull) {
// column IS NULL AND column <op> <not null> is always false
return null;
}
}
if (!bigger) {
comp = -comp;
}
return comp > 0 ? a : b;
}
/**
* Check if the result is empty for sure.
*
* @return true if it is
*/
public boolean isAlwaysFalse() {
return alwaysFalse;
}
/**
* Get start search row.
*
* @return search row
*/
public SearchRow getStart() {
return start;
}
/**
* Get end search row.
*
* @return search row
*/
public SearchRow getEnd() {
return end;
}
@Override
public Row get() {
if (cursor == null) {
return null;
}
return cursor.get();
}
@Override
public SearchRow getSearchRow() {
return cursor.getSearchRow();
}
@Override
public boolean next() {
while (true) {
if (cursor == null) {
nextCursor();
if (cursor == null) {
return false;
}
}
if (cursor.next()) {
return true;
}
cursor = null;
}
}
private void nextCursor() {
if (inList != null) {
while (inListIndex < inList.length) {
Value v = inList[inListIndex++];
if (v != ValueNull.INSTANCE) {
find(v);
break;
}
}
} else if (inResult != null) {
while (inResult.next()) {
Value v = inResult.currentRow()[0];
if (v != ValueNull.INSTANCE) {
if (inResultTested == null) {
inResultTested = new HashSet<>();
}
if (inResultTested.add(v)) {
find(v);
break;
}
}
}
}
}
private void find(Value v) {
v = inColumn.convert(v);
int id = inColumn.getColumnId();
start.setValue(id, v);
cursor = index.find(tableFilter, start, start);
}
@Override
public boolean previous() {
throw DbException.throwInternalError(toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/IndexLookupBatch.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.List;
import java.util.concurrent.Future;
import org.h2.result.SearchRow;
/**
* Support for asynchronous batched lookups in indexes. The flow is the
* following: H2 engine will be calling
* {@link #addSearchRows(SearchRow, SearchRow)} until method
* {@link #isBatchFull()} will return {@code true} or there are no more search
* rows to add. Then method {@link #find()} will be called to execute batched
* lookup. Note that a single instance of {@link IndexLookupBatch} can be reused
* for multiple sequential batched lookups, moreover it can be reused for
* multiple queries for the same prepared statement.
*
* @see Index#createLookupBatch(org.h2.table.TableFilter[], int)
* @author Sergi Vladykin
*/
public interface IndexLookupBatch {
/**
* Add search row pair to the batch.
*
* @param first the first row, or null for no limit
* @param last the last row, or null for no limit
* @return {@code false} if this search row pair is known to produce no
* results and thus the given row pair was not added
* @see Index#find(org.h2.table.TableFilter, SearchRow, SearchRow)
*/
boolean addSearchRows(SearchRow first, SearchRow last);
/**
* Check if this batch is full.
*
* @return {@code true} If batch is full, will not accept any
* more rows and {@link #find()} can be executed.
*/
boolean isBatchFull();
/**
* Execute batched lookup and return future cursor for each provided search
* row pair. Note that this method must return exactly the same number of
* future cursors in result list as number of
* {@link #addSearchRows(SearchRow, SearchRow)} calls has been done before
* {@link #find()} call exactly in the same order.
*
* @return List of future cursors for collected search rows.
*/
List<Future<Cursor>> find();
/**
* Get plan for EXPLAIN.
*
* @return plan
*/
String getPlanSQL();
/**
* Reset this batch to clear state. This method will be called before and
* after each query execution.
*
* @param beforeQuery if it is being called before query execution
*/
void reset(boolean beforeQuery);
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/IndexType.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
/**
* Represents information about the properties of an index
*/
public class IndexType {
private boolean primaryKey, persistent, unique, hash, scan, spatial, affinity;
private boolean belongsToConstraint;
/**
* Create a primary key index.
*
* @param persistent if the index is persistent
* @param hash if a hash index should be used
* @return the index type
*/
public static IndexType createPrimaryKey(boolean persistent, boolean hash) {
IndexType type = new IndexType();
type.primaryKey = true;
type.persistent = persistent;
type.hash = hash;
type.unique = true;
return type;
}
/**
* Create a unique index.
*
* @param persistent if the index is persistent
* @param hash if a hash index should be used
* @return the index type
*/
public static IndexType createUnique(boolean persistent, boolean hash) {
IndexType type = new IndexType();
type.unique = true;
type.persistent = persistent;
type.hash = hash;
return type;
}
/**
* Create a non-unique index.
*
* @param persistent if the index is persistent
* @return the index type
*/
public static IndexType createNonUnique(boolean persistent) {
return createNonUnique(persistent, false, false);
}
/**
* Create a non-unique index.
*
* @param persistent if the index is persistent
* @param hash if a hash index should be used
* @param spatial if a spatial index should be used
* @return the index type
*/
public static IndexType createNonUnique(boolean persistent, boolean hash,
boolean spatial) {
IndexType type = new IndexType();
type.persistent = persistent;
type.hash = hash;
type.spatial = spatial;
return type;
}
/**
* Create an affinity index.
*
* @return the index type
*/
public static IndexType createAffinity() {
IndexType type = new IndexType();
type.affinity = true;
return type;
}
/**
* Create a scan pseudo-index.
*
* @param persistent if the index is persistent
* @return the index type
*/
public static IndexType createScan(boolean persistent) {
IndexType type = new IndexType();
type.persistent = persistent;
type.scan = true;
return type;
}
/**
* Sets if this index belongs to a constraint.
*
* @param belongsToConstraint if the index belongs to a constraint
*/
public void setBelongsToConstraint(boolean belongsToConstraint) {
this.belongsToConstraint = belongsToConstraint;
}
/**
* If the index is created because of a constraint. Such indexes are to be
* dropped once the constraint is dropped.
*
* @return if the index belongs to a constraint
*/
public boolean getBelongsToConstraint() {
return belongsToConstraint;
}
/**
* Is this a hash index?
*
* @return true if it is a hash index
*/
public boolean isHash() {
return hash;
}
/**
* Is this a spatial index?
*
* @return true if it is a spatial index
*/
public boolean isSpatial() {
return spatial;
}
/**
* Is this index persistent?
*
* @return true if it is persistent
*/
public boolean isPersistent() {
return persistent;
}
/**
* Does this index belong to a primary key constraint?
*
* @return true if it references a primary key constraint
*/
public boolean isPrimaryKey() {
return primaryKey;
}
/**
* Is this a unique index?
*
* @return true if it is
*/
public boolean isUnique() {
return unique;
}
/**
* Does this index represent an affinity key?
*
* @return true if it does
*/
public boolean isAffinity() {
return affinity;
}
/**
* Get the SQL snippet to create such an index.
*
* @return the SQL snippet
*/
public String getSQL() {
StringBuilder buff = new StringBuilder();
if (primaryKey) {
buff.append("PRIMARY KEY");
if (hash) {
buff.append(" HASH");
}
} else {
if (unique) {
buff.append("UNIQUE ");
}
if (hash) {
buff.append("HASH ");
}
if (spatial) {
buff.append("SPATIAL ");
}
buff.append("INDEX");
}
return buff.toString();
}
/**
* Is this a table scan pseudo-index?
*
* @return true if it is
*/
public boolean isScan() {
return scan;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/LinkedCursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.table.Column;
import org.h2.table.TableLink;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* The cursor implementation for the linked index.
*/
public class LinkedCursor implements Cursor {
private final TableLink tableLink;
private final PreparedStatement prep;
private final String sql;
private final Session session;
private final ResultSet rs;
private Row current;
LinkedCursor(TableLink tableLink, ResultSet rs, Session session,
String sql, PreparedStatement prep) {
this.session = session;
this.tableLink = tableLink;
this.rs = rs;
this.sql = sql;
this.prep = prep;
}
@Override
public Row get() {
return current;
}
@Override
public SearchRow getSearchRow() {
return current;
}
@Override
public boolean next() {
try {
boolean result = rs.next();
if (!result) {
rs.close();
tableLink.reusePreparedStatement(prep, sql);
current = null;
return false;
}
} catch (SQLException e) {
throw DbException.convert(e);
}
current = tableLink.getTemplateRow();
for (int i = 0; i < current.getColumnCount(); i++) {
Column col = tableLink.getColumn(i);
Value v = DataType.readValue(session, rs, i + 1, col.getType());
current.setValue(i, v);
}
return true;
}
@Override
public boolean previous() {
throw DbException.throwInternalError(toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/LinkedIndex.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.engine.Constants;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.TableFilter;
import org.h2.table.TableLink;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* A linked index is a index for a linked (remote) table.
* It is backed by an index on the remote table which is accessed over JDBC.
*/
public class LinkedIndex extends BaseIndex {
private final TableLink link;
private final String targetTableName;
private long rowCount;
public LinkedIndex(TableLink table, int id, IndexColumn[] columns,
IndexType indexType) {
initBaseIndex(table, id, null, columns, indexType);
link = table;
targetTableName = link.getQualifiedTable();
}
@Override
public String getCreateSQL() {
return null;
}
@Override
public void close(Session session) {
// nothing to do
}
private static boolean isNull(Value v) {
return v == null || v == ValueNull.INSTANCE;
}
@Override
public void add(Session session, Row row) {
ArrayList<Value> params = New.arrayList();
StatementBuilder buff = new StatementBuilder("INSERT INTO ");
buff.append(targetTableName).append(" VALUES(");
for (int i = 0; i < row.getColumnCount(); i++) {
Value v = row.getValue(i);
buff.appendExceptFirst(", ");
if (v == null) {
buff.append("DEFAULT");
} else if (isNull(v)) {
buff.append("NULL");
} else {
buff.append('?');
params.add(v);
}
}
buff.append(')');
String sql = buff.toString();
try {
link.execute(sql, params, true);
rowCount++;
} catch (Exception e) {
throw TableLink.wrapException(sql, e);
}
}
@Override
public Cursor find(Session session, SearchRow first, SearchRow last) {
ArrayList<Value> params = New.arrayList();
StatementBuilder buff = new StatementBuilder("SELECT * FROM ");
buff.append(targetTableName).append(" T");
for (int i = 0; first != null && i < first.getColumnCount(); i++) {
Value v = first.getValue(i);
if (v != null) {
buff.appendOnlyFirst(" WHERE ");
buff.appendExceptFirst(" AND ");
Column col = table.getColumn(i);
buff.append(col.getSQL());
if (v == ValueNull.INSTANCE) {
buff.append(" IS NULL");
} else {
buff.append(">=");
addParameter(buff, col);
params.add(v);
}
}
}
for (int i = 0; last != null && i < last.getColumnCount(); i++) {
Value v = last.getValue(i);
if (v != null) {
buff.appendOnlyFirst(" WHERE ");
buff.appendExceptFirst(" AND ");
Column col = table.getColumn(i);
buff.append(col.getSQL());
if (v == ValueNull.INSTANCE) {
buff.append(" IS NULL");
} else {
buff.append("<=");
addParameter(buff, col);
params.add(v);
}
}
}
String sql = buff.toString();
try {
PreparedStatement prep = link.execute(sql, params, false);
ResultSet rs = prep.getResultSet();
return new LinkedCursor(link, rs, session, sql, prep);
} catch (Exception e) {
throw TableLink.wrapException(sql, e);
}
}
private void addParameter(StatementBuilder buff, Column col) {
if (col.getType() == Value.STRING_FIXED && link.isOracle()) {
// workaround for Oracle
// create table test(id int primary key, name char(15));
// insert into test values(1, 'Hello')
// select * from test where name = ? -- where ? = "Hello" > no rows
buff.append("CAST(? AS CHAR(").append(col.getPrecision()).append("))");
} else {
buff.append('?');
}
}
@Override
public double getCost(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
return 100 + getCostRangeIndex(masks, rowCount +
Constants.COST_ROW_OFFSET, filters, filter, sortOrder, false, allColumnsSet);
}
@Override
public void remove(Session session) {
// nothing to do
}
@Override
public void truncate(Session session) {
// nothing to do
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("LINKED");
}
@Override
public boolean needRebuild() {
return false;
}
@Override
public boolean canGetFirstOrLast() {
return false;
}
@Override
public Cursor findFirstOrLast(Session session, boolean first) {
// TODO optimization: could get the first or last value (in any case;
// maybe not optimized)
throw DbException.getUnsupportedException("LINKED");
}
@Override
public void remove(Session session, Row row) {
ArrayList<Value> params = New.arrayList();
StatementBuilder buff = new StatementBuilder("DELETE FROM ");
buff.append(targetTableName).append(" WHERE ");
for (int i = 0; i < row.getColumnCount(); i++) {
buff.appendExceptFirst("AND ");
Column col = table.getColumn(i);
buff.append(col.getSQL());
Value v = row.getValue(i);
if (isNull(v)) {
buff.append(" IS NULL ");
} else {
buff.append('=');
addParameter(buff, col);
params.add(v);
buff.append(' ');
}
}
String sql = buff.toString();
try {
PreparedStatement prep = link.execute(sql, params, false);
int count = prep.executeUpdate();
link.reusePreparedStatement(prep, sql);
rowCount -= count;
} catch (Exception e) {
throw TableLink.wrapException(sql, e);
}
}
/**
* Update a row using a UPDATE statement. This method is to be called if the
* emit updates option is enabled.
*
* @param oldRow the old data
* @param newRow the new data
*/
public void update(Row oldRow, Row newRow) {
ArrayList<Value> params = New.arrayList();
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(targetTableName).append(" SET ");
for (int i = 0; i < newRow.getColumnCount(); i++) {
buff.appendExceptFirst(", ");
buff.append(table.getColumn(i).getSQL()).append('=');
Value v = newRow.getValue(i);
if (v == null) {
buff.append("DEFAULT");
} else {
buff.append('?');
params.add(v);
}
}
buff.append(" WHERE ");
buff.resetCount();
for (int i = 0; i < oldRow.getColumnCount(); i++) {
Column col = table.getColumn(i);
buff.appendExceptFirst(" AND ");
buff.append(col.getSQL());
Value v = oldRow.getValue(i);
if (isNull(v)) {
buff.append(" IS NULL");
} else {
buff.append('=');
params.add(v);
addParameter(buff, col);
}
}
String sql = buff.toString();
try {
link.execute(sql, params, true);
} catch (Exception e) {
throw TableLink.wrapException(sql, e);
}
}
@Override
public long getRowCount(Session session) {
return rowCount;
}
@Override
public long getRowCountApproximation() {
return rowCount;
}
@Override
public long getDiskSpaceUsed() {
return 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/MetaCursor.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.ArrayList;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
/**
* An index for a meta data table.
* This index can only scan through all rows, search is not supported.
*/
public class MetaCursor implements Cursor {
private Row current;
private final ArrayList<Row> rows;
private int index;
MetaCursor(ArrayList<Row> rows) {
this.rows = rows;
}
@Override
public Row get() {
return current;
}
@Override
public SearchRow getSearchRow() {
return current;
}
@Override
public boolean next() {
current = index >= rows.size() ? null : rows.get(index++);
return current != null;
}
@Override
public boolean previous() {
throw DbException.throwInternalError(toString());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/index/MetaIndex.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.index;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.Row;
import org.h2.result.SearchRow;
import org.h2.result.SortOrder;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.MetaTable;
import org.h2.table.TableFilter;
/**
* The index implementation for meta data tables.
*/
public class MetaIndex extends BaseIndex {
private final MetaTable meta;
private final boolean scan;
public MetaIndex(MetaTable meta, IndexColumn[] columns, boolean scan) {
initBaseIndex(meta, 0, null, columns, IndexType.createNonUnique(true));
this.meta = meta;
this.scan = scan;
}
@Override
public void close(Session session) {
// nothing to do
}
@Override
public void add(Session session, Row row) {
throw DbException.getUnsupportedException("META");
}
@Override
public void remove(Session session, Row row) {
throw DbException.getUnsupportedException("META");
}
@Override
public Cursor find(Session session, SearchRow first, SearchRow last) {
ArrayList<Row> rows = meta.generateRows(session, first, last);
return new MetaCursor(rows);
}
@Override
public double getCost(Session session, int[] masks,
TableFilter[] filters, int filter, SortOrder sortOrder,
HashSet<Column> allColumnsSet) {
if (scan) {
return 10 * MetaTable.ROW_COUNT_APPROXIMATION;
}
return getCostRangeIndex(masks, MetaTable.ROW_COUNT_APPROXIMATION,
filters, filter, sortOrder, false, allColumnsSet);
}
@Override
public void truncate(Session session) {
throw DbException.getUnsupportedException("META");
}
@Override
public void remove(Session session) {
throw DbException.getUnsupportedException("META");
}
@Override
public int getColumnIndex(Column col) {
if (scan) {
// the scan index cannot use any columns
return -1;
}
return super.getColumnIndex(col);
}
@Override
public boolean isFirstColumn(Column column) {
if (scan) {
return false;
}
return super.isFirstColumn(column);
}
@Override
public void checkRename() {
throw DbException.getUnsupportedException("META");
}
@Override
public boolean needRebuild() {
return false;
}
@Override
public String getCreateSQL() {
return null;
}
@Override
public boolean canGetFirstOrLast() {
return false;
}
@Override
public Cursor findFirstOrLast(Session session, boolean first) {
throw DbException.getUnsupportedException("META");
}
@Override
public long getRowCount(Session session) {
return MetaTable.ROW_COUNT_APPROXIMATION;
}
@Override
public long getRowCountApproximation() {
return MetaTable.ROW_COUNT_APPROXIMATION;
}
@Override
public long getDiskSpaceUsed() {
return meta.getDiskSpaceUsed();
}
@Override
public String getPlanSQL() {
return "meta";
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.