use of org.h2.command.dml.Set in project h2database by h2database.
the class Parser method parseSetBinaryCollation.
private Set parseSetBinaryCollation() {
Set command = new Set(session, SetTypes.BINARY_COLLATION);
String name = readAliasIdentifier();
command.setString(name);
if (equalsToken(name, CompareMode.UNSIGNED) || equalsToken(name, CompareMode.SIGNED)) {
return command;
}
throw DbException.getInvalidValueException("BINARY_COLLATION", name);
}
use of org.h2.command.dml.Set in project h2database by h2database.
the class Parser method readTerm.
private Expression readTerm() {
Expression r;
switch(currentTokenType) {
case AT:
read();
r = new Variable(session, readAliasIdentifier());
if (readIf(":=")) {
Expression value = readExpression();
Function function = Function.getFunction(database, "SET");
function.setParameter(0, r);
function.setParameter(1, value);
r = function;
}
break;
case PARAMETER:
r = readParameter();
break;
case KEYWORD:
if (isToken("SELECT") || isToken("FROM") || isToken("WITH")) {
Query query = parseSelect();
r = new Subquery(query);
} else {
throw getSyntaxError();
}
break;
case IDENTIFIER:
String name = currentToken;
if (currentTokenQuoted) {
read();
if (readIf("(")) {
r = readFunction(null, name);
} else if (readIf(".")) {
r = readTermObjectDot(name);
} else {
r = new ExpressionColumn(database, null, null, name);
}
} else {
read();
if (readIf(".")) {
r = readTermObjectDot(name);
} else if (equalsToken("CASE", name)) {
// CASE must be processed before (,
// otherwise CASE(3) would be a function call, which it is
// not
r = readCase();
} else if (readIf("(")) {
r = readFunction(null, name);
} else if (equalsToken("CURRENT_USER", name)) {
r = readFunctionWithoutParameters("USER");
} else if (equalsToken("CURRENT_TIMESTAMP", name)) {
r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
} else if (equalsToken("SYSDATE", name)) {
r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
} else if (equalsToken("SYSTIMESTAMP", name)) {
r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
} else if (equalsToken("CURRENT_DATE", name)) {
r = readFunctionWithoutParameters("CURRENT_DATE");
} else if (equalsToken("TODAY", name)) {
r = readFunctionWithoutParameters("CURRENT_DATE");
} else if (equalsToken("CURRENT_TIME", name)) {
r = readFunctionWithoutParameters("CURRENT_TIME");
} else if (equalsToken("SYSTIME", name)) {
r = readFunctionWithoutParameters("CURRENT_TIME");
} else if (equalsToken("CURRENT", name)) {
if (readIf("TIMESTAMP")) {
r = readFunctionWithoutParameters("CURRENT_TIMESTAMP");
} else if (readIf("TIME")) {
r = readFunctionWithoutParameters("CURRENT_TIME");
} else if (readIf("DATE")) {
r = readFunctionWithoutParameters("CURRENT_DATE");
} else {
r = new ExpressionColumn(database, null, null, name);
}
} else if (equalsToken("NEXT", name) && readIf("VALUE")) {
read("FOR");
Sequence sequence = readSequence();
r = new SequenceValue(sequence);
} else if (equalsToken("TIME", name)) {
boolean without = readIf("WITHOUT");
if (without) {
read("TIME");
read("ZONE");
}
if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
if (without) {
throw getSyntaxError();
}
r = new ExpressionColumn(database, null, null, name);
} else {
String time = currentValue.getString();
read();
r = ValueExpression.get(ValueTime.parse(time));
}
} else if (equalsToken("TIMESTAMP", name)) {
if (readIf("WITH")) {
read("TIME");
read("ZONE");
if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
throw getSyntaxError();
}
String timestamp = currentValue.getString();
read();
r = ValueExpression.get(ValueTimestampTimeZone.parse(timestamp));
} else {
boolean without = readIf("WITHOUT");
if (without) {
read("TIME");
read("ZONE");
}
if (currentTokenType != VALUE || currentValue.getType() != Value.STRING) {
if (without) {
throw getSyntaxError();
}
r = new ExpressionColumn(database, null, null, name);
} else {
String timestamp = currentValue.getString();
read();
r = ValueExpression.get(ValueTimestamp.parse(timestamp, database.getMode()));
}
}
} else if (currentTokenType == VALUE && currentValue.getType() == Value.STRING) {
if (equalsToken("DATE", name) || equalsToken("D", name)) {
String date = currentValue.getString();
read();
r = ValueExpression.get(ValueDate.parse(date));
} else if (equalsToken("T", name)) {
String time = currentValue.getString();
read();
r = ValueExpression.get(ValueTime.parse(time));
} else if (equalsToken("TS", name)) {
String timestamp = currentValue.getString();
read();
r = ValueExpression.get(ValueTimestamp.parse(timestamp, database.getMode()));
} else if (equalsToken("X", name)) {
read();
byte[] buffer = StringUtils.convertHexToBytes(currentValue.getString());
r = ValueExpression.get(ValueBytes.getNoCopy(buffer));
} else if (equalsToken("E", name)) {
String text = currentValue.getString();
// the PostgreSQL ODBC driver uses
// LIKE E'PROJECT\\_DATA' instead of LIKE
// 'PROJECT\_DATA'
// N: SQL-92 "National Language" strings
text = StringUtils.replaceAll(text, "\\\\", "\\");
read();
r = ValueExpression.get(ValueString.get(text));
} else if (equalsToken("N", name)) {
// SQL-92 "National Language" strings
String text = currentValue.getString();
read();
r = ValueExpression.get(ValueString.get(text));
} else {
r = new ExpressionColumn(database, null, null, name);
}
} else {
r = new ExpressionColumn(database, null, null, name);
}
}
break;
case MINUS:
read();
if (currentTokenType == VALUE) {
r = ValueExpression.get(currentValue.negate());
if (r.getType() == Value.LONG && r.getValue(session).getLong() == Integer.MIN_VALUE) {
// convert Integer.MIN_VALUE to type 'int'
// (Integer.MAX_VALUE+1 is of type 'long')
r = ValueExpression.get(ValueInt.get(Integer.MIN_VALUE));
} else if (r.getType() == Value.DECIMAL && r.getValue(session).getBigDecimal().compareTo(ValueLong.MIN_BD) == 0) {
// convert Long.MIN_VALUE to type 'long'
// (Long.MAX_VALUE+1 is of type 'decimal')
r = ValueExpression.get(ValueLong.MIN);
}
read();
} else {
r = new Operation(OpType.NEGATE, readTerm(), null);
}
break;
case PLUS:
read();
r = readTerm();
break;
case OPEN:
read();
if (readIf(")")) {
r = new ExpressionList(new Expression[0]);
} else {
r = readExpression();
if (readIf(",")) {
ArrayList<Expression> list = New.arrayList();
list.add(r);
while (!readIf(")")) {
r = readExpression();
list.add(r);
if (!readIf(",")) {
read(")");
break;
}
}
r = new ExpressionList(list.toArray(new Expression[0]));
} else {
read(")");
}
}
break;
case TRUE:
read();
r = ValueExpression.get(ValueBoolean.TRUE);
break;
case FALSE:
read();
r = ValueExpression.get(ValueBoolean.FALSE);
break;
case ROWNUM:
read();
if (readIf("(")) {
read(")");
}
if (currentSelect == null && currentPrepared == null) {
throw getSyntaxError();
}
r = new Rownum(currentSelect == null ? currentPrepared : currentSelect);
break;
case NULL:
read();
r = ValueExpression.getNull();
break;
case VALUE:
r = ValueExpression.get(currentValue);
read();
break;
default:
throw getSyntaxError();
}
if (readIf("[")) {
Function function = Function.getFunction(database, "ARRAY_GET");
function.setParameter(0, r);
r = readExpression();
r = new Operation(OpType.PLUS, r, ValueExpression.get(ValueInt.get(1)));
function.setParameter(1, r);
r = function;
read("]");
}
if (readIf("::")) {
// PostgreSQL compatibility
if (isToken("PG_CATALOG")) {
read("PG_CATALOG");
read(".");
}
if (readIf("REGCLASS")) {
FunctionAlias f = findFunctionAlias(Constants.SCHEMA_MAIN, "PG_GET_OID");
if (f == null) {
throw getSyntaxError();
}
Expression[] args = { r };
r = new JavaFunction(f, args);
} else {
Column col = parseColumnWithType(null);
Function function = Function.getFunction(database, "CAST");
function.setDataType(col);
function.setParameter(0, r);
r = function;
}
}
return r;
}
use of org.h2.command.dml.Set in project h2database by h2database.
the class Parser method parsePrepared.
private Prepared parsePrepared() {
int start = lastParseIndex;
Prepared c = null;
String token = currentToken;
if (token.length() == 0) {
c = new NoOperation(session);
} else {
char first = token.charAt(0);
switch(first) {
case '?':
// read the ? as a parameter
readTerm();
// this is an 'out' parameter - set a dummy value
parameters.get(0).setValue(ValueNull.INSTANCE);
read("=");
read("CALL");
c = parseCall();
break;
case '(':
c = parseSelect();
break;
case 'a':
case 'A':
if (readIf("ALTER")) {
c = parseAlter();
} else if (readIf("ANALYZE")) {
c = parseAnalyze();
}
break;
case 'b':
case 'B':
if (readIf("BACKUP")) {
c = parseBackup();
} else if (readIf("BEGIN")) {
c = parseBegin();
}
break;
case 'c':
case 'C':
if (readIf("COMMIT")) {
c = parseCommit();
} else if (readIf("CREATE")) {
c = parseCreate();
} else if (readIf("CALL")) {
c = parseCall();
} else if (readIf("CHECKPOINT")) {
c = parseCheckpoint();
} else if (readIf("COMMENT")) {
c = parseComment();
}
break;
case 'd':
case 'D':
if (readIf("DELETE")) {
c = parseDelete();
} else if (readIf("DROP")) {
c = parseDrop();
} else if (readIf("DECLARE")) {
// support for DECLARE GLOBAL TEMPORARY TABLE...
c = parseCreate();
} else if (readIf("DEALLOCATE")) {
c = parseDeallocate();
}
break;
case 'e':
case 'E':
if (readIf("EXPLAIN")) {
c = parseExplain();
} else if (readIf("EXECUTE")) {
c = parseExecute();
}
break;
case 'f':
case 'F':
if (isToken("FROM")) {
c = parseSelect();
}
break;
case 'g':
case 'G':
if (readIf("GRANT")) {
c = parseGrantRevoke(CommandInterface.GRANT);
}
break;
case 'h':
case 'H':
if (readIf("HELP")) {
c = parseHelp();
}
break;
case 'i':
case 'I':
if (readIf("INSERT")) {
c = parseInsert();
}
break;
case 'm':
case 'M':
if (readIf("MERGE")) {
c = parseMerge();
}
break;
case 'p':
case 'P':
if (readIf("PREPARE")) {
c = parsePrepare();
}
break;
case 'r':
case 'R':
if (readIf("ROLLBACK")) {
c = parseRollback();
} else if (readIf("REVOKE")) {
c = parseGrantRevoke(CommandInterface.REVOKE);
} else if (readIf("RUNSCRIPT")) {
c = parseRunScript();
} else if (readIf("RELEASE")) {
c = parseReleaseSavepoint();
} else if (readIf("REPLACE")) {
c = parseReplace();
}
break;
case 's':
case 'S':
if (isToken("SELECT")) {
c = parseSelect();
} else if (readIf("SET")) {
c = parseSet();
} else if (readIf("SAVEPOINT")) {
c = parseSavepoint();
} else if (readIf("SCRIPT")) {
c = parseScript();
} else if (readIf("SHUTDOWN")) {
c = parseShutdown();
} else if (readIf("SHOW")) {
c = parseShow();
}
break;
case 't':
case 'T':
if (readIf("TRUNCATE")) {
c = parseTruncate();
}
break;
case 'u':
case 'U':
if (readIf("UPDATE")) {
c = parseUpdate();
} else if (readIf("USE")) {
c = parseUse();
}
break;
case 'v':
case 'V':
if (readIf("VALUES")) {
c = parseValues();
}
break;
case 'w':
case 'W':
if (readIf("WITH")) {
c = parseWithStatementOrQuery();
}
break;
case ';':
c = new NoOperation(session);
break;
default:
throw getSyntaxError();
}
if (indexedParameterList != null) {
for (int i = 0, size = indexedParameterList.size(); i < size; i++) {
if (indexedParameterList.get(i) == null) {
indexedParameterList.set(i, new Parameter(i));
}
}
parameters = indexedParameterList;
}
if (readIf("{")) {
do {
int index = (int) readLong() - 1;
if (index < 0 || index >= parameters.size()) {
throw getSyntaxError();
}
Parameter p = parameters.get(index);
if (p == null) {
throw getSyntaxError();
}
read(":");
Expression expr = readExpression();
expr = expr.optimize(session);
p.setValue(expr.getValue(session));
} while (readIf(","));
read("}");
for (Parameter p : parameters) {
p.checkSet();
}
parameters.clear();
}
}
if (c == null) {
throw getSyntaxError();
}
setSQL(c, null, start);
return c;
}
use of org.h2.command.dml.Set in project h2database by h2database.
the class AlterTableAddConstraint method tryUpdate.
/**
* Try to execute the statement.
*
* @return the update count
*/
private int tryUpdate() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
Table table = getSchema().findTableOrView(session, tableName);
if (table == null) {
if (ifTableExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
if (getSchema().findConstraint(session, constraintName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
}
session.getUser().checkRight(table, Right.ALL);
db.lockMeta(session);
table.lock(session, true, true);
Constraint constraint;
switch(type) {
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY:
{
IndexColumn.mapColumns(indexColumns, table);
index = table.findPrimaryKey();
ArrayList<Constraint> constraints = table.getConstraints();
for (int i = 0; constraints != null && i < constraints.size(); i++) {
Constraint c = constraints.get(i);
if (Constraint.Type.PRIMARY_KEY == c.getConstraintType()) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
if (index != null) {
// if there is an index, it must match with the one declared
// we don't test ascending / descending
IndexColumn[] pkCols = index.getIndexColumns();
if (pkCols.length != indexColumns.length) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
for (int i = 0; i < pkCols.length; i++) {
if (pkCols[i].column != indexColumns[i].column) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
}
if (index == null) {
IndexType indexType = IndexType.createPrimaryKey(table.isPersistIndexes(), primaryKeyHash);
String indexName = table.getSchema().getUniqueIndexName(session, table, Constants.PREFIX_PRIMARY_KEY);
int id = getObjectId();
try {
index = table.addIndex(session, indexName, id, indexColumns, indexType, true, null);
} finally {
getSchema().freeUniqueName(indexName);
}
}
index.getIndexType().setBelongsToConstraint(true);
int constraintId = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique pk = new ConstraintUnique(getSchema(), constraintId, name, table, true);
pk.setColumns(indexColumns);
pk.setIndex(index, true);
constraint = pk;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE:
{
IndexColumn.mapColumns(indexColumns, table);
boolean isOwner = false;
if (index != null && canUseUniqueIndex(index, table, indexColumns)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getUniqueIndex(table, indexColumns);
if (index == null) {
index = createIndex(table, indexColumns, true);
isOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintUnique unique = new ConstraintUnique(getSchema(), id, name, table, false);
unique.setColumns(indexColumns);
unique.setIndex(index, isOwner);
constraint = unique;
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK:
{
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
TableFilter filter = new TableFilter(session, table, null, false, null, 0, null);
checkExpression.mapColumns(filter, 0);
checkExpression = checkExpression.optimize(session);
check.setExpression(checkExpression);
check.setTableFilter(filter);
constraint = check;
if (checkExisting) {
check.checkExistingData(session);
}
break;
}
case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL:
{
Table refTable = refSchema.resolveTableOrView(session, refTableName);
if (refTable == null) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, refTableName);
}
session.getUser().checkRight(refTable, Right.ALL);
if (!refTable.canReference()) {
throw DbException.getUnsupportedException("Reference " + refTable.getSQL());
}
boolean isOwner = false;
IndexColumn.mapColumns(indexColumns, table);
if (index != null && canUseIndex(index, table, indexColumns, false)) {
isOwner = true;
index.getIndexType().setBelongsToConstraint(true);
} else {
index = getIndex(table, indexColumns, false);
if (index == null) {
index = createIndex(table, indexColumns, false);
isOwner = true;
}
}
if (refIndexColumns == null) {
Index refIdx = refTable.getPrimaryKey();
refIndexColumns = refIdx.getIndexColumns();
} else {
IndexColumn.mapColumns(refIndexColumns, refTable);
}
if (refIndexColumns.length != indexColumns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
boolean isRefOwner = false;
if (refIndex != null && refIndex.getTable() == refTable && canUseIndex(refIndex, refTable, refIndexColumns, false)) {
isRefOwner = true;
refIndex.getIndexType().setBelongsToConstraint(true);
} else {
refIndex = null;
}
if (refIndex == null) {
refIndex = getIndex(refTable, refIndexColumns, false);
if (refIndex == null) {
refIndex = createIndex(refTable, refIndexColumns, true);
isRefOwner = true;
}
}
int id = getObjectId();
String name = generateConstraintName(table);
ConstraintReferential refConstraint = new ConstraintReferential(getSchema(), id, name, table);
refConstraint.setColumns(indexColumns);
refConstraint.setIndex(index, isOwner);
refConstraint.setRefTable(refTable);
refConstraint.setRefColumns(refIndexColumns);
refConstraint.setRefIndex(refIndex, isRefOwner);
if (checkExisting) {
refConstraint.checkExistingData(session);
}
refTable.addConstraint(refConstraint);
refConstraint.setDeleteAction(deleteAction);
refConstraint.setUpdateAction(updateAction);
constraint = refConstraint;
break;
}
default:
throw DbException.throwInternalError("type=" + type);
}
// parent relationship is already set with addConstraint
constraint.setComment(comment);
if (table.isTemporary() && !table.isGlobalTemporary()) {
session.addLocalTempTableConstraint(constraint);
} else {
db.addSchemaObject(session, constraint);
}
table.addConstraint(constraint);
return 0;
}
use of org.h2.command.dml.Set in project h2database by h2database.
the class Parser method parseInsertGivenTable.
private Insert parseInsertGivenTable(Insert command, Table table) {
Column[] columns = null;
if (readIf("(")) {
if (isSelect()) {
command.setQuery(parseSelect());
read(")");
return command;
}
columns = parseColumnList(table);
command.setColumns(columns);
}
if (readIf("DIRECT")) {
command.setInsertFromSelect(true);
}
if (readIf("SORTED")) {
command.setSortedInsertMode(true);
}
if (readIf("DEFAULT")) {
read("VALUES");
Expression[] expr = {};
command.addRow(expr);
} else if (readIf("VALUES")) {
read("(");
do {
ArrayList<Expression> values = New.arrayList();
if (!readIf(")")) {
do {
if (readIf("DEFAULT")) {
values.add(null);
} else {
values.add(readExpression());
}
} while (readIfMore(false));
}
command.addRow(values.toArray(new Expression[0]));
// the following condition will allow (..),; and (..);
} while (readIf(",") && readIf("("));
} else if (readIf("SET")) {
if (columns != null) {
throw getSyntaxError();
}
ArrayList<Column> columnList = New.arrayList();
ArrayList<Expression> values = New.arrayList();
do {
columnList.add(parseColumn(table));
read("=");
Expression expression;
if (readIf("DEFAULT")) {
expression = ValueExpression.getDefault();
} else {
expression = readExpression();
}
values.add(expression);
} while (readIf(","));
command.setColumns(columnList.toArray(new Column[0]));
command.addRow(values.toArray(new Expression[0]));
} else {
command.setQuery(parseSelect());
}
return null;
}
Aggregations