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/bnf/BnfVisitor.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.bnf;
import java.util.ArrayList;
/**
* The visitor interface for BNF rules.
*/
public interface BnfVisitor {
/**
* Visit a rule element.
*
* @param keyword whether this is a keyword
* @param name the element name
* @param link the linked rule if it's not a keyword
*/
void visitRuleElement(boolean keyword, String name, Rule link);
/**
* Visit a repeat rule.
*
* @param comma whether the comma is repeated as well
* @param rule the element to repeat
*/
void visitRuleRepeat(boolean comma, Rule rule);
/**
* Visit a fixed rule.
*
* @param type the type
*/
void visitRuleFixed(int type);
/**
* Visit a rule list.
*
* @param or true for OR, false for AND
* @param list the rules
*/
void visitRuleList(boolean or, ArrayList<Rule> list);
/**
* Visit an optional rule.
*
* @param rule the rule
*/
void visitRuleOptional(Rule rule);
}
|
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/bnf/Rule.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.bnf;
import java.util.HashMap;
/**
* Represents a BNF rule.
*/
public interface Rule {
/**
* Update cross references.
*
* @param ruleMap the reference map
*/
void setLinks(HashMap<String, RuleHead> ruleMap);
/**
* Add the next possible token(s). If there was a match, the query in the
* sentence is updated (the matched token is removed).
*
* @param sentence the sentence context
* @return true if a full match
*/
boolean autoComplete(Sentence sentence);
/**
* Call the visit method in the given visitor.
*
* @param visitor the visitor
*/
void accept(BnfVisitor 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/bnf/RuleElement.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.bnf;
import java.util.HashMap;
import org.h2.util.StringUtils;
/**
* A single terminal rule in a BNF object.
*/
public class RuleElement implements Rule {
private final boolean keyword;
private final String name;
private Rule link;
private final int type;
public RuleElement(String name, String topic) {
this.name = name;
this.keyword = name.length() == 1 ||
name.equals(StringUtils.toUpperEnglish(name));
topic = StringUtils.toLowerEnglish(topic);
this.type = topic.startsWith("function") ?
Sentence.FUNCTION : Sentence.KEYWORD;
}
@Override
public void accept(BnfVisitor visitor) {
visitor.visitRuleElement(keyword, name, link);
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
if (link != null) {
link.setLinks(ruleMap);
}
if (keyword) {
return;
}
String test = Bnf.getRuleMapKey(name);
for (int i = 0; i < test.length(); i++) {
String t = test.substring(i);
RuleHead r = ruleMap.get(t);
if (r != null) {
link = r.getRule();
return;
}
}
throw new AssertionError("Unknown " + name + "/" + test);
}
@Override
public boolean autoComplete(Sentence sentence) {
sentence.stopIfRequired();
if (keyword) {
String query = sentence.getQuery();
String q = query.trim();
String up = sentence.getQueryUpper().trim();
if (up.startsWith(name)) {
query = query.substring(name.length());
while (!"_".equals(name) && Bnf.startWithSpace(query)) {
query = query.substring(1);
}
sentence.setQuery(query);
return true;
} else if (q.length() == 0 || name.startsWith(up)) {
if (q.length() < name.length()) {
sentence.add(name, name.substring(q.length()), type);
}
}
return false;
}
return link.autoComplete(sentence);
}
}
|
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/bnf/RuleFixed.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.bnf;
import java.util.HashMap;
/**
* Represents a hard coded terminal rule in a BNF object.
*/
public class RuleFixed implements Rule {
public static final int YMD = 0, HMS = 1, NANOS = 2;
public static final int ANY_EXCEPT_SINGLE_QUOTE = 3;
public static final int ANY_EXCEPT_DOUBLE_QUOTE = 4;
public static final int ANY_UNTIL_EOL = 5;
public static final int ANY_UNTIL_END = 6;
public static final int ANY_WORD = 7;
public static final int ANY_EXCEPT_2_DOLLAR = 8;
public static final int HEX_START = 10, CONCAT = 11;
public static final int AZ_UNDERSCORE = 12, AF = 13, DIGIT = 14;
public static final int OPEN_BRACKET = 15, CLOSE_BRACKET = 16;
private final int type;
RuleFixed(int type) {
this.type = type;
}
@Override
public void accept(BnfVisitor visitor) {
visitor.visitRuleFixed(type);
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
// nothing to do
}
@Override
public boolean autoComplete(Sentence sentence) {
sentence.stopIfRequired();
String query = sentence.getQuery();
String s = query;
boolean removeTrailingSpaces = false;
switch (type) {
case YMD:
while (s.length() > 0 && "0123456789-".indexOf(s.charAt(0)) >= 0) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("2006-01-01", "1", Sentence.KEYWORD);
}
// needed for timestamps
removeTrailingSpaces = true;
break;
case HMS:
while (s.length() > 0 && "0123456789:".indexOf(s.charAt(0)) >= 0) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("12:00:00", "1", Sentence.KEYWORD);
}
break;
case NANOS:
while (s.length() > 0 && Character.isDigit(s.charAt(0))) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("nanoseconds", "0", Sentence.KEYWORD);
}
removeTrailingSpaces = true;
break;
case ANY_EXCEPT_SINGLE_QUOTE:
while (true) {
while (s.length() > 0 && s.charAt(0) != '\'') {
s = s.substring(1);
}
if (s.startsWith("''")) {
s = s.substring(2);
} else {
break;
}
}
if (s.length() == 0) {
sentence.add("anything", "Hello World", Sentence.KEYWORD);
sentence.add("'", "'", Sentence.KEYWORD);
}
break;
case ANY_EXCEPT_2_DOLLAR:
while (s.length() > 0 && !s.startsWith("$$")) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("anything", "Hello World", Sentence.KEYWORD);
sentence.add("$$", "$$", Sentence.KEYWORD);
}
break;
case ANY_EXCEPT_DOUBLE_QUOTE:
while (true) {
while (s.length() > 0 && s.charAt(0) != '\"') {
s = s.substring(1);
}
if (s.startsWith("\"\"")) {
s = s.substring(2);
} else {
break;
}
}
if (s.length() == 0) {
sentence.add("anything", "identifier", Sentence.KEYWORD);
sentence.add("\"", "\"", Sentence.KEYWORD);
}
break;
case ANY_WORD:
while (s.length() > 0 && !Bnf.startWithSpace(s)) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("anything", "anything", Sentence.KEYWORD);
}
break;
case HEX_START:
if (s.startsWith("0X") || s.startsWith("0x")) {
s = s.substring(2);
} else if ("0".equals(s)) {
sentence.add("0x", "x", Sentence.KEYWORD);
} else if (s.length() == 0) {
sentence.add("0x", "0x", Sentence.KEYWORD);
}
break;
case CONCAT:
if (s.equals("|")) {
sentence.add("||", "|", Sentence.KEYWORD);
} else if (s.startsWith("||")) {
s = s.substring(2);
} else if (s.length() == 0) {
sentence.add("||", "||", Sentence.KEYWORD);
}
removeTrailingSpaces = true;
break;
case AZ_UNDERSCORE:
if (s.length() > 0 &&
(Character.isLetter(s.charAt(0)) || s.charAt(0) == '_')) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("character", "A", Sentence.KEYWORD);
}
break;
case AF:
if (s.length() > 0) {
char ch = Character.toUpperCase(s.charAt(0));
if (ch >= 'A' && ch <= 'F') {
s = s.substring(1);
}
}
if (s.length() == 0) {
sentence.add("hex character", "0A", Sentence.KEYWORD);
}
break;
case DIGIT:
if (s.length() > 0 && Character.isDigit(s.charAt(0))) {
s = s.substring(1);
}
if (s.length() == 0) {
sentence.add("digit", "1", Sentence.KEYWORD);
}
break;
case OPEN_BRACKET:
if (s.length() == 0) {
sentence.add("[", "[", Sentence.KEYWORD);
} else if (s.charAt(0) == '[') {
s = s.substring(1);
}
removeTrailingSpaces = true;
break;
case CLOSE_BRACKET:
if (s.length() == 0) {
sentence.add("]", "]", Sentence.KEYWORD);
} else if (s.charAt(0) == ']') {
s = s.substring(1);
}
removeTrailingSpaces = true;
break;
// no autocomplete support for comments
// (comments are not reachable in the bnf tree)
case ANY_UNTIL_EOL:
case ANY_UNTIL_END:
default:
throw new AssertionError("type="+type);
}
if (!s.equals(query)) {
// can not always remove spaces here, because a repeat
// rule for a-z would remove multiple words
// but we have to remove spaces after '||'
// and after ']'
if (removeTrailingSpaces) {
while (Bnf.startWithSpace(s)) {
s = s.substring(1);
}
}
sentence.setQuery(s);
return true;
}
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/bnf/RuleHead.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.bnf;
/**
* Represents the head of a BNF rule.
*/
public class RuleHead {
private final String section;
private final String topic;
private Rule rule;
RuleHead(String section, String topic, Rule rule) {
this.section = section;
this.topic = topic;
this.rule = rule;
}
public String getTopic() {
return topic;
}
public Rule getRule() {
return rule;
}
void setRule(Rule rule) {
this.rule = rule;
}
public String getSection() {
return section;
}
}
|
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/bnf/RuleList.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.bnf;
import java.util.ArrayList;
import java.util.HashMap;
import org.h2.util.New;
/**
* Represents a sequence of BNF rules, or a list of alternative rules.
*/
public class RuleList implements Rule {
private final boolean or;
private final ArrayList<Rule> list;
private boolean mapSet;
public RuleList(Rule first, Rule next, boolean or) {
list = New.arrayList();
if (first instanceof RuleList && ((RuleList) first).or == or) {
list.addAll(((RuleList) first).list);
} else {
list.add(first);
}
if (next instanceof RuleList && ((RuleList) next).or == or) {
list.addAll(((RuleList) next).list);
} else {
list.add(next);
}
this.or = or;
}
@Override
public void accept(BnfVisitor visitor) {
visitor.visitRuleList(or, list);
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
if (!mapSet) {
for (Rule r : list) {
r.setLinks(ruleMap);
}
mapSet = true;
}
}
@Override
public boolean autoComplete(Sentence sentence) {
sentence.stopIfRequired();
String old = sentence.getQuery();
if (or) {
for (Rule r : list) {
sentence.setQuery(old);
if (r.autoComplete(sentence)) {
return true;
}
}
return false;
}
for (Rule r : list) {
if (!r.autoComplete(sentence)) {
sentence.setQuery(old);
return false;
}
}
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/bnf/RuleOptional.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.bnf;
import java.util.HashMap;
/**
* Represents an optional BNF rule.
*/
public class RuleOptional implements Rule {
private final Rule rule;
private boolean mapSet;
public RuleOptional(Rule rule) {
this.rule = rule;
}
@Override
public void accept(BnfVisitor visitor) {
visitor.visitRuleOptional(rule);
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
if (!mapSet) {
rule.setLinks(ruleMap);
mapSet = true;
}
}
@Override
public boolean autoComplete(Sentence sentence) {
sentence.stopIfRequired();
rule.autoComplete(sentence);
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/bnf/RuleRepeat.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.bnf;
import java.util.HashMap;
/**
* Represents a loop in a BNF object.
*/
public class RuleRepeat implements Rule {
private final Rule rule;
private final boolean comma;
public RuleRepeat(Rule rule, boolean comma) {
this.rule = rule;
this.comma = comma;
}
@Override
public void accept(BnfVisitor visitor) {
visitor.visitRuleRepeat(comma, rule);
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
// not required, because it's already linked
}
@Override
public boolean autoComplete(Sentence sentence) {
sentence.stopIfRequired();
while (rule.autoComplete(sentence)) {
// nothing to do
}
String s = sentence.getQuery();
while (Bnf.startWithSpace(s)) {
s = s.substring(1);
}
sentence.setQuery(s);
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/bnf/Sentence.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.bnf;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import org.h2.bnf.context.DbSchema;
import org.h2.bnf.context.DbTableOrView;
import org.h2.util.StringUtils;
/**
* A query context object. It contains the list of table and alias objects.
* Used for autocomplete.
*/
public class Sentence {
/**
* This token type means the possible choices of the item depend on the
* context. For example the item represents a table name of the current
* database.
*/
public static final int CONTEXT = 0;
/**
* The token type for a keyword.
*/
public static final int KEYWORD = 1;
/**
* The token type for a function name.
*/
public static final int FUNCTION = 2;
private static final long MAX_PROCESSING_TIME = 100;
/**
* The map of next tokens in the form type#tokenName token.
*/
private final HashMap<String, String> next = new HashMap<>();
/**
* The complete query string.
*/
private String query;
/**
* The uppercase version of the query string.
*/
private String queryUpper;
private long stopAtNs;
private DbSchema lastMatchedSchema;
private DbTableOrView lastMatchedTable;
private DbTableOrView lastTable;
private HashSet<DbTableOrView> tables;
private HashMap<String, DbTableOrView> aliases;
/**
* Start the timer to make sure processing doesn't take too long.
*/
public void start() {
stopAtNs = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(MAX_PROCESSING_TIME);
}
/**
* Check if it's time to stop processing.
* Processing auto-complete shouldn't take more than a few milliseconds.
* If processing is stopped, this methods throws an IllegalStateException
*/
public void stopIfRequired() {
if (System.nanoTime() > stopAtNs) {
throw new IllegalStateException();
}
}
/**
* Add a word to the set of next tokens.
*
* @param n the token name
* @param string an example text
* @param type the token type
*/
public void add(String n, String string, int type) {
next.put(type+"#"+n, string);
}
/**
* Add an alias name and object
*
* @param alias the alias name
* @param table the alias table
*/
public void addAlias(String alias, DbTableOrView table) {
if (aliases == null) {
aliases = new HashMap<>();
}
aliases.put(alias, table);
}
/**
* Add a table.
*
* @param table the table
*/
public void addTable(DbTableOrView table) {
lastTable = table;
if (tables == null) {
tables = new HashSet<>();
}
tables.add(table);
}
/**
* Get the set of tables.
*
* @return the set of tables
*/
public HashSet<DbTableOrView> getTables() {
return tables;
}
/**
* Get the alias map.
*
* @return the alias map
*/
public HashMap<String, DbTableOrView> getAliases() {
return aliases;
}
/**
* Get the last added table.
*
* @return the last table
*/
public DbTableOrView getLastTable() {
return lastTable;
}
/**
* Get the last matched schema if the last match was a schema.
*
* @return the last schema or null
*/
public DbSchema getLastMatchedSchema() {
return lastMatchedSchema;
}
/**
* Set the last matched schema if the last match was a schema,
* or null if it was not.
*
* @param schema the last matched schema or null
*/
public void setLastMatchedSchema(DbSchema schema) {
this.lastMatchedSchema = schema;
}
/**
* Set the last matched table if the last match was a table.
*
* @param table the last matched table or null
*/
public void setLastMatchedTable(DbTableOrView table) {
this.lastMatchedTable = table;
}
/**
* Get the last matched table if the last match was a table.
*
* @return the last table or null
*/
public DbTableOrView getLastMatchedTable() {
return lastMatchedTable;
}
/**
* Set the query string.
*
* @param query the query string
*/
public void setQuery(String query) {
if (!Objects.equals(this.query, query)) {
this.query = query;
this.queryUpper = StringUtils.toUpperEnglish(query);
}
}
/**
* Get the query string.
*
* @return the query
*/
public String getQuery() {
return query;
}
/**
* Get the uppercase version of the query string.
*
* @return the uppercase query
*/
public String getQueryUpper() {
return queryUpper;
}
/**
* Get the map of next tokens.
*
* @return the next token map
*/
public HashMap<String, String> getNext() {
return next;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbColumn.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.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* Keeps the meta data information of a column.
* This class is used by the H2 Console.
*/
public class DbColumn {
private final String name;
private final String quotedName;
private final String dataType;
private final int position;
private DbColumn(DbContents contents, ResultSet rs, boolean procedureColumn)
throws SQLException {
name = rs.getString("COLUMN_NAME");
quotedName = contents.quoteIdentifier(name);
String type = rs.getString("TYPE_NAME");
// a procedures column size is identified by PRECISION, for table this
// is COLUMN_SIZE
String precisionColumnName;
if (procedureColumn) {
precisionColumnName = "PRECISION";
} else {
precisionColumnName = "COLUMN_SIZE";
}
int precision = rs.getInt(precisionColumnName);
position = rs.getInt("ORDINAL_POSITION");
boolean isSQLite = contents.isSQLite();
if (precision > 0 && !isSQLite) {
type += "(" + precision;
String scaleColumnName;
if (procedureColumn) {
scaleColumnName = "SCALE";
} else {
scaleColumnName = "DECIMAL_DIGITS";
}
int prec = rs.getInt(scaleColumnName);
if (prec > 0) {
type += ", " + prec;
}
type += ")";
}
if (rs.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls) {
type += " NOT NULL";
}
dataType = type;
}
/**
* Create a column from a DatabaseMetaData.getProcedureColumns row.
*
* @param contents the database contents
* @param rs the result set
* @return the column
*/
public static DbColumn getProcedureColumn(DbContents contents, ResultSet rs)
throws SQLException {
return new DbColumn(contents, rs, true);
}
/**
* Create a column from a DatabaseMetaData.getColumns row.
*
* @param contents the database contents
* @param rs the result set
* @return the column
*/
public static DbColumn getColumn(DbContents contents, ResultSet rs)
throws SQLException {
return new DbColumn(contents, rs, false);
}
/**
* @return The data type name (including precision and the NOT NULL flag if
* applicable).
*/
public String getDataType() {
return dataType;
}
/**
* @return The column name.
*/
public String getName() {
return name;
}
/**
* @return The quoted table name.
*/
public String getQuotedName() {
return quotedName;
}
/**
* @return Column index
*/
public int getPosition() {
return position;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbContents.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.bnf.context;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.command.Parser;
import org.h2.util.New;
import org.h2.util.StringUtils;
/**
* Keeps meta data information about a database.
* This class is used by the H2 Console.
*/
public class DbContents {
private DbSchema[] schemas;
private DbSchema defaultSchema;
private boolean isOracle;
private boolean isH2;
private boolean isPostgreSQL;
private boolean isDerby;
private boolean isSQLite;
private boolean isH2ModeMySQL;
private boolean isMySQL;
private boolean isFirebird;
private boolean isMSSQLServer;
private boolean isDB2;
/**
* @return The default schema.
*/
public DbSchema getDefaultSchema() {
return defaultSchema;
}
/**
* @return True if this is an Apache Derby database.
*/
public boolean isDerby() {
return isDerby;
}
/**
* @return True if this is a Firebird database.
*/
public boolean isFirebird() {
return isFirebird;
}
/**
* @return True if this is a H2 database.
*/
public boolean isH2() {
return isH2;
}
/**
* @return True if this is a H2 database in MySQL mode.
*/
public boolean isH2ModeMySQL() {
return isH2ModeMySQL;
}
/**
* @return True if this is a MS SQL Server database.
*/
public boolean isMSSQLServer() {
return isMSSQLServer;
}
/**
* @return True if this is a MySQL database.
*/
public boolean isMySQL() {
return isMySQL;
}
/**
* @return True if this is an Oracle database.
*/
public boolean isOracle() {
return isOracle;
}
/**
* @return True if this is a PostgreSQL database.
*/
public boolean isPostgreSQL() {
return isPostgreSQL;
}
/**
* @return True if this is an SQLite database.
*/
public boolean isSQLite() {
return isSQLite;
}
/**
* @return True if this is an IBM DB2 database.
*/
public boolean isDB2() {
return isDB2;
}
/**
* @return The list of schemas.
*/
public DbSchema[] getSchemas() {
return schemas;
}
/**
* Read the contents of this database from the database meta data.
*
* @param url the database URL
* @param conn the connection
*/
public synchronized void readContents(String url, Connection conn)
throws SQLException {
isH2 = url.startsWith("jdbc:h2:");
if (isH2) {
PreparedStatement prep = conn.prepareStatement(
"SELECT UPPER(VALUE) FROM INFORMATION_SCHEMA.SETTINGS " +
"WHERE NAME=?");
prep.setString(1, "MODE");
ResultSet rs = prep.executeQuery();
rs.next();
if ("MYSQL".equals(rs.getString(1))) {
isH2ModeMySQL = true;
}
rs.close();
prep.close();
}
isDB2 = url.startsWith("jdbc:db2:");
isSQLite = url.startsWith("jdbc:sqlite:");
isOracle = url.startsWith("jdbc:oracle:");
// the Vertica engine is based on PostgreSQL
isPostgreSQL = url.startsWith("jdbc:postgresql:") || url.startsWith("jdbc:vertica:");
// isHSQLDB = url.startsWith("jdbc:hsqldb:");
isMySQL = url.startsWith("jdbc:mysql:");
isDerby = url.startsWith("jdbc:derby:");
isFirebird = url.startsWith("jdbc:firebirdsql:");
isMSSQLServer = url.startsWith("jdbc:sqlserver:");
DatabaseMetaData meta = conn.getMetaData();
String defaultSchemaName = getDefaultSchemaName(meta);
String[] schemaNames = getSchemaNames(meta);
schemas = new DbSchema[schemaNames.length];
for (int i = 0; i < schemaNames.length; i++) {
String schemaName = schemaNames[i];
boolean isDefault = defaultSchemaName == null ||
defaultSchemaName.equals(schemaName);
DbSchema schema = new DbSchema(this, schemaName, isDefault);
if (isDefault) {
defaultSchema = schema;
}
schemas[i] = schema;
String[] tableTypes = { "TABLE", "SYSTEM TABLE", "VIEW",
"SYSTEM VIEW", "TABLE LINK", "SYNONYM", "EXTERNAL" };
schema.readTables(meta, tableTypes);
if (!isPostgreSQL && !isDB2) {
schema.readProcedures(meta);
}
}
if (defaultSchema == null) {
String best = null;
for (DbSchema schema : schemas) {
if ("dbo".equals(schema.name)) {
// MS SQL Server
defaultSchema = schema;
break;
}
if (defaultSchema == null ||
best == null ||
schema.name.length() < best.length()) {
best = schema.name;
defaultSchema = schema;
}
}
}
}
private String[] getSchemaNames(DatabaseMetaData meta) throws SQLException {
if (isMySQL || isSQLite) {
return new String[] { "" };
} else if (isFirebird) {
return new String[] { null };
}
ResultSet rs = meta.getSchemas();
ArrayList<String> schemaList = New.arrayList();
while (rs.next()) {
String schema = rs.getString("TABLE_SCHEM");
String[] ignoreNames = null;
if (isOracle) {
ignoreNames = new String[] { "CTXSYS", "DIP", "DBSNMP",
"DMSYS", "EXFSYS", "FLOWS_020100", "FLOWS_FILES",
"MDDATA", "MDSYS", "MGMT_VIEW", "OLAPSYS", "ORDSYS",
"ORDPLUGINS", "OUTLN", "SI_INFORMTN_SCHEMA", "SYS",
"SYSMAN", "SYSTEM", "TSMSYS", "WMSYS", "XDB" };
} else if (isMSSQLServer) {
ignoreNames = new String[] { "sys", "db_accessadmin",
"db_backupoperator", "db_datareader", "db_datawriter",
"db_ddladmin", "db_denydatareader",
"db_denydatawriter", "db_owner", "db_securityadmin" };
} else if (isDB2) {
ignoreNames = new String[] { "NULLID", "SYSFUN",
"SYSIBMINTERNAL", "SYSIBMTS", "SYSPROC", "SYSPUBLIC",
// not empty, but not sure what they contain
"SYSCAT", "SYSIBM", "SYSIBMADM",
"SYSSTAT", "SYSTOOLS",
};
}
if (ignoreNames != null) {
for (String ignore : ignoreNames) {
if (ignore.equals(schema)) {
schema = null;
break;
}
}
}
if (schema == null) {
continue;
}
schemaList.add(schema);
}
rs.close();
return schemaList.toArray(new String[0]);
}
private String getDefaultSchemaName(DatabaseMetaData meta) {
String defaultSchemaName = "";
try {
if (isOracle) {
return meta.getUserName();
} else if (isPostgreSQL) {
return "public";
} else if (isMySQL) {
return "";
} else if (isDerby) {
return StringUtils.toUpperEnglish(meta.getUserName());
} else if (isFirebird) {
return null;
}
ResultSet rs = meta.getSchemas();
int index = rs.findColumn("IS_DEFAULT");
while (rs.next()) {
if (rs.getBoolean(index)) {
defaultSchemaName = rs.getString("TABLE_SCHEM");
}
}
} catch (SQLException e) {
// IS_DEFAULT not found
}
return defaultSchemaName;
}
/**
* Add double quotes around an identifier if required.
* For the H2 database, all identifiers are quoted.
*
* @param identifier the identifier
* @return the quoted identifier
*/
public String quoteIdentifier(String identifier) {
if (identifier == null) {
return null;
}
if (isH2 && !isH2ModeMySQL) {
return Parser.quoteIdentifier(identifier);
}
return StringUtils.toUpperEnglish(identifier);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbContextRule.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.bnf.context;
import java.util.HashMap;
import java.util.HashSet;
import org.h2.bnf.Bnf;
import org.h2.bnf.BnfVisitor;
import org.h2.bnf.Rule;
import org.h2.bnf.RuleElement;
import org.h2.bnf.RuleHead;
import org.h2.bnf.RuleList;
import org.h2.bnf.Sentence;
import org.h2.message.DbException;
import org.h2.util.ParserUtil;
import org.h2.util.StringUtils;
/**
* A BNF terminal rule that is linked to the database context information.
* This class is used by the H2 Console, to support auto-complete.
*/
public class DbContextRule implements Rule {
public static final int COLUMN = 0, TABLE = 1, TABLE_ALIAS = 2;
public static final int NEW_TABLE_ALIAS = 3;
public static final int COLUMN_ALIAS = 4, SCHEMA = 5, PROCEDURE = 6;
private final DbContents contents;
private final int type;
private String columnType;
/**
* BNF terminal rule Constructor
* @param contents Extract rule from this component
* @param type Rule type, one of
* {@link DbContextRule#COLUMN},
* {@link DbContextRule#TABLE},
* {@link DbContextRule#TABLE_ALIAS},
* {@link DbContextRule#NEW_TABLE_ALIAS},
* {@link DbContextRule#COLUMN_ALIAS},
* {@link DbContextRule#SCHEMA}
*/
public DbContextRule(DbContents contents, int type) {
this.contents = contents;
this.type = type;
}
/**
* @param columnType COLUMN Auto completion can be filtered by column type
*/
public void setColumnType(String columnType) {
this.columnType = columnType;
}
@Override
public void setLinks(HashMap<String, RuleHead> ruleMap) {
// nothing to do
}
@Override
public void accept(BnfVisitor visitor) {
// nothing to do
}
@Override
public boolean autoComplete(Sentence sentence) {
String query = sentence.getQuery(), s = query;
String up = sentence.getQueryUpper();
switch (type) {
case SCHEMA: {
DbSchema[] schemas = contents.getSchemas();
String best = null;
DbSchema bestSchema = null;
for (DbSchema schema: schemas) {
String name = StringUtils.toUpperEnglish(schema.name);
if (up.startsWith(name)) {
if (best == null || name.length() > best.length()) {
best = name;
bestSchema = schema;
}
} else if (s.length() == 0 || name.startsWith(up)) {
if (s.length() < name.length()) {
sentence.add(name, name.substring(s.length()), type);
sentence.add(schema.quotedName + ".",
schema.quotedName.substring(s.length()) + ".",
Sentence.CONTEXT);
}
}
}
if (best != null) {
sentence.setLastMatchedSchema(bestSchema);
s = s.substring(best.length());
}
break;
}
case TABLE: {
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.getDefaultSchema();
}
DbTableOrView[] tables = schema.getTables();
String best = null;
DbTableOrView bestTable = null;
for (DbTableOrView table : tables) {
String compare = up;
String name = StringUtils.toUpperEnglish(table.getName());
if (table.getQuotedName().length() > name.length()) {
name = table.getQuotedName();
compare = query;
}
if (compare.startsWith(name)) {
if (best == null || name.length() > best.length()) {
best = name;
bestTable = table;
}
} else if (s.length() == 0 || name.startsWith(compare)) {
if (s.length() < name.length()) {
sentence.add(table.getQuotedName(),
table.getQuotedName().substring(s.length()),
Sentence.CONTEXT);
}
}
}
if (best != null) {
sentence.setLastMatchedTable(bestTable);
sentence.addTable(bestTable);
s = s.substring(best.length());
}
break;
}
case NEW_TABLE_ALIAS:
s = autoCompleteTableAlias(sentence, true);
break;
case TABLE_ALIAS:
s = autoCompleteTableAlias(sentence, false);
break;
case COLUMN_ALIAS: {
int i = 0;
if (query.indexOf(' ') < 0) {
break;
}
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
break;
}
String alias = up.substring(0, i);
if (ParserUtil.isKeyword(alias)) {
break;
}
s = s.substring(alias.length());
break;
}
case COLUMN: {
HashSet<DbTableOrView> set = sentence.getTables();
String best = null;
DbTableOrView last = sentence.getLastMatchedTable();
if (last != null && last.getColumns() != null) {
for (DbColumn column : last.getColumns()) {
String compare = up;
String name = StringUtils.toUpperEnglish(column.getName());
if (column.getQuotedName().length() > name.length()) {
name = column.getQuotedName();
compare = query;
}
if (compare.startsWith(name) &&
(columnType == null ||
column.getDataType().contains(columnType))) {
String b = s.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
} else if (s.length() == 0 || name.startsWith(compare)) {
if (s.length() < name.length()) {
sentence.add(column.getName(),
column.getName().substring(s.length()),
Sentence.CONTEXT);
}
}
}
}
}
for (DbSchema schema : contents.getSchemas()) {
for (DbTableOrView table : schema.getTables()) {
if (table != last && set != null && !set.contains(table)) {
continue;
}
if (table == null || table.getColumns() == null) {
continue;
}
for (DbColumn column : table.getColumns()) {
String name = StringUtils.toUpperEnglish(column
.getName());
if (columnType == null
|| column.getDataType().contains(columnType)) {
if (up.startsWith(name)) {
String b = s.substring(name.length());
if (best == null || b.length() < best.length()) {
best = b;
}
} else if (s.length() == 0 || name.startsWith(up)) {
if (s.length() < name.length()) {
sentence.add(column.getName(),
column.getName().substring(s.length()),
Sentence.CONTEXT);
}
}
}
}
}
}
if (best != null) {
s = best;
}
break;
}
case PROCEDURE:
autoCompleteProcedure(sentence);
break;
default:
throw DbException.throwInternalError("type=" + type);
}
if (!s.equals(query)) {
while (Bnf.startWithSpace(s)) {
s = s.substring(1);
}
sentence.setQuery(s);
return true;
}
return false;
}
private void autoCompleteProcedure(Sentence sentence) {
DbSchema schema = sentence.getLastMatchedSchema();
if (schema == null) {
schema = contents.getDefaultSchema();
}
String incompleteSentence = sentence.getQueryUpper();
String incompleteFunctionName = incompleteSentence;
if (incompleteSentence.contains("(")) {
incompleteFunctionName = incompleteSentence.substring(0,
incompleteSentence.indexOf('(')).trim();
}
// Common elements
RuleElement openBracket = new RuleElement("(", "Function");
RuleElement closeBracket = new RuleElement(")", "Function");
RuleElement comma = new RuleElement(",", "Function");
// Fetch all elements
for (DbProcedure procedure : schema.getProcedures()) {
final String procName = procedure.getName();
if (procName.startsWith(incompleteFunctionName)) {
// That's it, build a RuleList from this function
RuleElement procedureElement = new RuleElement(procName,
"Function");
RuleList rl = new RuleList(procedureElement, openBracket, false);
// Go further only if the user use open bracket
if (incompleteSentence.contains("(")) {
for (DbColumn parameter : procedure.getParameters()) {
if (parameter.getPosition() > 1) {
rl = new RuleList(rl, comma, false);
}
DbContextRule columnRule = new DbContextRule(contents,
COLUMN);
String parameterType = parameter.getDataType();
// Remove precision
if (parameterType.contains("(")) {
parameterType = parameterType.substring(0,
parameterType.indexOf('('));
}
columnRule.setColumnType(parameterType);
rl = new RuleList(rl, columnRule, false);
}
rl = new RuleList(rl, closeBracket , false);
}
rl.autoComplete(sentence);
}
}
}
private static String autoCompleteTableAlias(Sentence sentence,
boolean newAlias) {
String s = sentence.getQuery();
String up = sentence.getQueryUpper();
int i = 0;
for (; i < up.length(); i++) {
char ch = up.charAt(i);
if (ch != '_' && !Character.isLetterOrDigit(ch)) {
break;
}
}
if (i == 0) {
return s;
}
String alias = up.substring(0, i);
if ("SET".equals(alias) || ParserUtil.isKeyword(alias)) {
return s;
}
if (newAlias) {
sentence.addAlias(alias, sentence.getLastTable());
}
HashMap<String, DbTableOrView> map = sentence.getAliases();
if ((map != null && map.containsKey(alias)) ||
(sentence.getLastTable() == null)) {
if (newAlias && s.length() == alias.length()) {
return s;
}
s = s.substring(alias.length());
if (s.length() == 0) {
sentence.add(alias + ".", ".", Sentence.CONTEXT);
}
return s;
}
HashSet<DbTableOrView> tables = sentence.getTables();
if (tables != null) {
String best = null;
for (DbTableOrView table : tables) {
String tableName =
StringUtils.toUpperEnglish(table.getName());
if (alias.startsWith(tableName) &&
(best == null || tableName.length() > best.length())) {
sentence.setLastMatchedTable(table);
best = tableName;
} else if (s.length() == 0 || tableName.startsWith(alias)) {
sentence.add(tableName + ".",
tableName.substring(s.length()) + ".",
Sentence.CONTEXT);
}
}
if (best != null) {
s = s.substring(best.length());
if (s.length() == 0) {
sentence.add(alias + ".", ".", Sentence.CONTEXT);
}
return s;
}
}
return s;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbProcedure.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.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.util.New;
/**
* Contains meta data information about a procedure.
* This class is used by the H2 Console.
*/
public class DbProcedure {
private final DbSchema schema;
private final String name;
private final String quotedName;
private final boolean returnsResult;
private DbColumn[] parameters;
public DbProcedure(DbSchema schema, ResultSet rs) throws SQLException {
this.schema = schema;
name = rs.getString("PROCEDURE_NAME");
returnsResult = rs.getShort("PROCEDURE_TYPE") ==
DatabaseMetaData.procedureReturnsResult;
quotedName = schema.getContents().quoteIdentifier(name);
}
/**
* @return The schema this table belongs to.
*/
public DbSchema getSchema() {
return schema;
}
/**
* @return The column list.
*/
public DbColumn[] getParameters() {
return parameters;
}
/**
* @return The table name.
*/
public String getName() {
return name;
}
/**
* @return The quoted table name.
*/
public String getQuotedName() {
return quotedName;
}
/**
* @return True if this function return a value
*/
public boolean isReturnsResult() {
return returnsResult;
}
/**
* Read the column for this table from the database meta data.
*
* @param meta the database meta data
*/
void readParameters(DatabaseMetaData meta) throws SQLException {
ResultSet rs = meta.getProcedureColumns(null, schema.name, name, null);
ArrayList<DbColumn> list = New.arrayList();
while (rs.next()) {
DbColumn column = DbColumn.getProcedureColumn(schema.getContents(), rs);
if (column.getPosition() > 0) {
// Not the return type
list.add(column);
}
}
rs.close();
parameters = new DbColumn[list.size()];
// Store the parameter in the good position [1-n]
for (int i = 0; i < parameters.length; i++) {
DbColumn column = list.get(i);
if (column.getPosition() > 0
&& column.getPosition() <= parameters.length) {
parameters[column.getPosition() - 1] = column;
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbSchema.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.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.engine.SysProperties;
import org.h2.util.New;
import org.h2.util.StringUtils;
/**
* Contains meta data information about a database schema.
* This class is used by the H2 Console.
*/
public class DbSchema {
/**
* The schema name.
*/
public final String name;
/**
* True if this is the default schema for this database.
*/
public final boolean isDefault;
/**
* True if this is a system schema (for example the INFORMATION_SCHEMA).
*/
public final boolean isSystem;
/**
* The quoted schema name.
*/
public final String quotedName;
/**
* The database content container.
*/
private final DbContents contents;
/**
* The table list.
*/
private DbTableOrView[] tables;
/**
* The procedures list.
*/
private DbProcedure[] procedures;
DbSchema(DbContents contents, String name, boolean isDefault) {
this.contents = contents;
this.name = name;
this.quotedName = contents.quoteIdentifier(name);
this.isDefault = isDefault;
if (name == null) {
// firebird
isSystem = true;
} else if ("INFORMATION_SCHEMA".equals(name)) {
isSystem = true;
} else if (!contents.isH2() &&
StringUtils.toUpperEnglish(name).startsWith("INFO")) {
isSystem = true;
} else if (contents.isPostgreSQL() &&
StringUtils.toUpperEnglish(name).startsWith("PG_")) {
isSystem = true;
} else if (contents.isDerby() && name.startsWith("SYS")) {
isSystem = true;
} else {
isSystem = false;
}
}
/**
* @return The database content container.
*/
public DbContents getContents() {
return contents;
}
/**
* @return The table list.
*/
public DbTableOrView[] getTables() {
return tables;
}
/**
* @return The procedure list.
*/
public DbProcedure[] getProcedures() {
return procedures;
}
/**
* Read all tables for this schema from the database meta data.
*
* @param meta the database meta data
* @param tableTypes the table types to read
*/
public void readTables(DatabaseMetaData meta, String[] tableTypes)
throws SQLException {
ResultSet rs = meta.getTables(null, name, null, tableTypes);
ArrayList<DbTableOrView> list = New.arrayList();
while (rs.next()) {
DbTableOrView table = new DbTableOrView(this, rs);
if (contents.isOracle() && table.getName().indexOf('$') > 0) {
continue;
}
list.add(table);
}
rs.close();
tables = list.toArray(new DbTableOrView[0]);
if (tables.length < SysProperties.CONSOLE_MAX_TABLES_LIST_COLUMNS) {
for (DbTableOrView tab : tables) {
try {
tab.readColumns(meta);
} catch (SQLException e) {
// MySQL:
// View '...' references invalid table(s) or column(s)
// or function(s) or definer/invoker of view
// lack rights to use them HY000/1356
// ignore
}
}
}
}
/**
* Read all procedures in the dataBase.
* @param meta the database meta data
* @throws SQLException Error while fetching procedures
*/
public void readProcedures(DatabaseMetaData meta) throws SQLException {
ResultSet rs = meta.getProcedures(null, name, null);
ArrayList<DbProcedure> list = New.arrayList();
while (rs.next()) {
list.add(new DbProcedure(this, rs));
}
rs.close();
procedures = list.toArray(new DbProcedure[0]);
if (procedures.length < SysProperties.CONSOLE_MAX_PROCEDURES_LIST_COLUMNS) {
for (DbProcedure procedure : procedures) {
procedure.readParameters(meta);
}
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/bnf/context/DbTableOrView.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.bnf.context;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.util.New;
/**
* Contains meta data information about a table or a view.
* This class is used by the H2 Console.
*/
public class DbTableOrView {
/**
* The schema this table belongs to.
*/
private final DbSchema schema;
/**
* The table name.
*/
private final String name;
/**
* The quoted table name.
*/
private final String quotedName;
/**
* True if this represents a view.
*/
private final boolean isView;
/**
* The column list.
*/
private DbColumn[] columns;
public DbTableOrView(DbSchema schema, ResultSet rs) throws SQLException {
this.schema = schema;
name = rs.getString("TABLE_NAME");
String type = rs.getString("TABLE_TYPE");
isView = "VIEW".equals(type);
quotedName = schema.getContents().quoteIdentifier(name);
}
/**
* @return The schema this table belongs to.
*/
public DbSchema getSchema() {
return schema;
}
/**
* @return The column list.
*/
public DbColumn[] getColumns() {
return columns;
}
/**
* @return The table name.
*/
public String getName() {
return name;
}
/**
* @return True if this represents a view.
*/
public boolean isView() {
return isView;
}
/**
* @return The quoted table name.
*/
public String getQuotedName() {
return quotedName;
}
/**
* Read the column for this table from the database meta data.
*
* @param meta the database meta data
*/
public void readColumns(DatabaseMetaData meta) throws SQLException {
ResultSet rs = meta.getColumns(null, schema.name, name, null);
ArrayList<DbColumn> list = New.arrayList();
while (rs.next()) {
DbColumn column = DbColumn.getColumn(schema.getContents(), rs);
list.add(column);
}
rs.close();
columns = list.toArray(new DbColumn[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/command/Command.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.command;
import java.sql.SQLException;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.ParameterInterface;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.ResultInterface;
import org.h2.result.ResultWithGeneratedKeys;
import org.h2.util.MathUtils;
/**
* Represents a SQL statement. This object is only used on the server side.
*/
public abstract class Command implements CommandInterface {
/**
* The session.
*/
protected final Session session;
/**
* The last start time.
*/
protected long startTimeNanos;
/**
* The trace module.
*/
private final Trace trace;
/**
* If this query was canceled.
*/
private volatile boolean cancel;
private final String sql;
private boolean canReuse;
Command(Parser parser, String sql) {
this.session = parser.getSession();
this.sql = sql;
trace = session.getDatabase().getTrace(Trace.COMMAND);
}
/**
* Check if this command is transactional.
* If it is not, then it forces the current transaction to commit.
*
* @return true if it is
*/
public abstract boolean isTransactional();
/**
* Check if this command is a query.
*
* @return true if it is
*/
@Override
public abstract boolean isQuery();
/**
* Prepare join batching.
*/
public abstract void prepareJoinBatch();
/**
* Get the list of parameters.
*
* @return the list of parameters
*/
@Override
public abstract ArrayList<? extends ParameterInterface> getParameters();
/**
* Check if this command is read only.
*
* @return true if it is
*/
public abstract boolean isReadOnly();
/**
* Get an empty result set containing the meta data.
*
* @return an empty result set
*/
public abstract ResultInterface queryMeta();
/**
* Execute an updating statement (for example insert, delete, or update), if
* this is possible.
*
* @return the update count
* @throws DbException if the command is not an updating statement
*/
public int update() {
throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_QUERY);
}
/**
* Execute a query statement, if this is possible.
*
* @param maxrows the maximum number of rows returned
* @return the local result set
* @throws DbException if the command is not a query
*/
public ResultInterface query(@SuppressWarnings("unused") int maxrows) {
throw DbException.get(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY);
}
@Override
public final ResultInterface getMetaData() {
return queryMeta();
}
/**
* Start the stopwatch.
*/
void start() {
if (trace.isInfoEnabled() || session.getDatabase().getQueryStatistics()) {
startTimeNanos = System.nanoTime();
}
}
void setProgress(int state) {
session.getDatabase().setProgress(state, sql, 0, 0);
}
/**
* Check if this command has been canceled, and throw an exception if yes.
*
* @throws DbException if the statement has been canceled
*/
protected void checkCanceled() {
if (cancel) {
cancel = false;
throw DbException.get(ErrorCode.STATEMENT_WAS_CANCELED);
}
}
@Override
public void stop() {
session.endStatement();
session.setCurrentCommand(null, false);
if (!isTransactional()) {
session.commit(true);
} else if (session.getAutoCommit()) {
session.commit(false);
} else if (session.getDatabase().isMultiThreaded()) {
Database db = session.getDatabase();
if (db != null) {
if (db.getLockMode() == Constants.LOCK_MODE_READ_COMMITTED) {
session.unlockReadLocks();
}
}
}
if (trace.isInfoEnabled() && startTimeNanos > 0) {
long timeMillis = (System.nanoTime() - startTimeNanos) / 1000 / 1000;
if (timeMillis > Constants.SLOW_QUERY_LIMIT_MS) {
trace.info("slow query: {0} ms", timeMillis);
}
}
}
/**
* Execute a query and return the result.
* This method prepares everything and calls {@link #query(int)} finally.
*
* @param maxrows the maximum number of rows to return
* @param scrollable if the result set must be scrollable (ignored)
* @return the result set
*/
@Override
public ResultInterface executeQuery(int maxrows, boolean scrollable) {
startTimeNanos = 0;
long start = 0;
Database database = session.getDatabase();
Object sync = database.isMultiThreaded() ? (Object) session : (Object) database;
session.waitIfExclusiveModeEnabled();
boolean callStop = true;
boolean writing = !isReadOnly();
if (writing) {
while (!database.beforeWriting()) {
// wait
}
}
synchronized (sync) {
session.setCurrentCommand(this, false);
try {
while (true) {
database.checkPowerOff();
try {
ResultInterface result = query(maxrows);
callStop = !result.isLazy();
return result;
} catch (DbException e) {
start = filterConcurrentUpdate(e, start);
} catch (OutOfMemoryError e) {
callStop = false;
// there is a serious problem:
// the transaction may be applied partially
// in this case we need to panic:
// close the database
database.shutdownImmediately();
throw DbException.convert(e);
} catch (Throwable e) {
throw DbException.convert(e);
}
}
} catch (DbException e) {
e = e.addSQL(sql);
SQLException s = e.getSQLException();
database.exceptionThrown(s, sql);
if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
callStop = false;
database.shutdownImmediately();
throw e;
}
database.checkPowerOff();
throw e;
} finally {
if (callStop) {
stop();
}
if (writing) {
database.afterWriting();
}
}
}
}
@Override
public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
long start = 0;
Database database = session.getDatabase();
Object sync = database.isMultiThreaded() ? (Object) session : (Object) database;
session.waitIfExclusiveModeEnabled();
boolean callStop = true;
boolean writing = !isReadOnly();
if (writing) {
while (!database.beforeWriting()) {
// wait
}
}
synchronized (sync) {
Session.Savepoint rollback = session.setSavepoint();
session.setCurrentCommand(this, generatedKeysRequest);
try {
while (true) {
database.checkPowerOff();
try {
int updateCount = update();
if (!Boolean.FALSE.equals(generatedKeysRequest)) {
return new ResultWithGeneratedKeys.WithKeys(updateCount,
session.getGeneratedKeys().getKeys(session));
}
return ResultWithGeneratedKeys.of(updateCount);
} catch (DbException e) {
start = filterConcurrentUpdate(e, start);
} catch (OutOfMemoryError e) {
callStop = false;
database.shutdownImmediately();
throw DbException.convert(e);
} catch (Throwable e) {
throw DbException.convert(e);
}
}
} catch (DbException e) {
e = e.addSQL(sql);
SQLException s = e.getSQLException();
database.exceptionThrown(s, sql);
if (s.getErrorCode() == ErrorCode.OUT_OF_MEMORY) {
callStop = false;
database.shutdownImmediately();
throw e;
}
database.checkPowerOff();
if (s.getErrorCode() == ErrorCode.DEADLOCK_1) {
session.rollback();
} else {
session.rollbackTo(rollback, false);
}
throw e;
} finally {
try {
if (callStop) {
stop();
}
} finally {
if (writing) {
database.afterWriting();
}
}
}
}
}
private long filterConcurrentUpdate(DbException e, long start) {
int errorCode = e.getErrorCode();
if (errorCode != ErrorCode.CONCURRENT_UPDATE_1 &&
errorCode != ErrorCode.ROW_NOT_FOUND_IN_PRIMARY_INDEX &&
errorCode != ErrorCode.ROW_NOT_FOUND_WHEN_DELETING_1) {
throw e;
}
long now = System.nanoTime() / 1_000_000;
if (start != 0 && now - start > session.getLockTimeout()) {
throw DbException.get(ErrorCode.LOCK_TIMEOUT_1, e.getCause(), "");
}
Database database = session.getDatabase();
int sleep = 1 + MathUtils.randomInt(10);
while (true) {
try {
if (database.isMultiThreaded()) {
Thread.sleep(sleep);
} else {
database.wait(sleep);
}
} catch (InterruptedException e1) {
// ignore
}
long slept = System.nanoTime() / 1_000_000 - now;
if (slept >= sleep) {
break;
}
}
return start == 0 ? now : start;
}
@Override
public void close() {
canReuse = true;
}
@Override
public void cancel() {
this.cancel = true;
}
@Override
public String toString() {
return sql + Trace.formatParams(getParameters());
}
public boolean isCacheable() {
return false;
}
/**
* Whether the command is already closed (in which case it can be re-used).
*
* @return true if it can be re-used
*/
public boolean canReuse() {
return canReuse;
}
/**
* The command is now re-used, therefore reset the canReuse flag, and the
* parameter values.
*/
public void reuse() {
canReuse = false;
ArrayList<? extends ParameterInterface> parameters = getParameters();
for (ParameterInterface param : parameters) {
param.setValue(null, true);
}
}
public void setCanReuse(boolean canReuse) {
this.canReuse = canReuse;
}
}
|
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/command/CommandContainer.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.command;
import java.util.ArrayList;
import org.h2.api.DatabaseEventListener;
import org.h2.command.dml.Explain;
import org.h2.command.dml.Query;
import org.h2.expression.Parameter;
import org.h2.expression.ParameterInterface;
import org.h2.result.ResultInterface;
import org.h2.table.TableView;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* Represents a single SQL statements.
* It wraps a prepared statement.
*/
public class CommandContainer extends Command {
private Prepared prepared;
private boolean readOnlyKnown;
private boolean readOnly;
CommandContainer(Parser parser, String sql, Prepared prepared) {
super(parser, sql);
prepared.setCommand(this);
this.prepared = prepared;
}
@Override
public ArrayList<? extends ParameterInterface> getParameters() {
return prepared.getParameters();
}
@Override
public boolean isTransactional() {
return prepared.isTransactional();
}
@Override
public boolean isQuery() {
return prepared.isQuery();
}
@Override
public void prepareJoinBatch() {
if (session.isJoinBatchEnabled()) {
prepareJoinBatch(prepared);
}
}
private static void prepareJoinBatch(Prepared prepared) {
if (prepared.isQuery()) {
int type = prepared.getType();
if (type == CommandInterface.SELECT) {
((Query) prepared).prepareJoinBatch();
} else if (type == CommandInterface.EXPLAIN ||
type == CommandInterface.EXPLAIN_ANALYZE) {
prepareJoinBatch(((Explain) prepared).getCommand());
}
}
}
private void recompileIfRequired() {
if (prepared.needRecompile()) {
// TODO test with 'always recompile'
prepared.setModificationMetaId(0);
String sql = prepared.getSQL();
ArrayList<Parameter> oldParams = prepared.getParameters();
Parser parser = new Parser(session);
prepared = parser.parse(sql);
long mod = prepared.getModificationMetaId();
prepared.setModificationMetaId(0);
ArrayList<Parameter> newParams = prepared.getParameters();
for (int i = 0, size = newParams.size(); i < size; i++) {
Parameter old = oldParams.get(i);
if (old.isValueSet()) {
Value v = old.getValue(session);
Parameter p = newParams.get(i);
p.setValue(v);
}
}
prepared.prepare();
prepared.setModificationMetaId(mod);
prepareJoinBatch();
}
}
@Override
public int update() {
recompileIfRequired();
setProgress(DatabaseEventListener.STATE_STATEMENT_START);
start();
session.setLastScopeIdentity(ValueNull.INSTANCE);
prepared.checkParameters();
int updateCount = prepared.update();
prepared.trace(startTimeNanos, updateCount);
setProgress(DatabaseEventListener.STATE_STATEMENT_END);
return updateCount;
}
@Override
public ResultInterface query(int maxrows) {
recompileIfRequired();
setProgress(DatabaseEventListener.STATE_STATEMENT_START);
start();
prepared.checkParameters();
ResultInterface result = prepared.query(maxrows);
prepared.trace(startTimeNanos, result.isLazy() ? 0 : result.getRowCount());
setProgress(DatabaseEventListener.STATE_STATEMENT_END);
return result;
}
@Override
public void stop() {
super.stop();
// Clean up after the command was run in the session.
// Must restart query (and dependency construction) to reuse.
if (prepared.getCteCleanups() != null) {
for (TableView view : prepared.getCteCleanups()) {
// check if view was previously deleted as their name is set to
// null
if (view.getName() != null) {
session.removeLocalTempTable(view);
}
}
}
}
@Override
public boolean canReuse() {
return super.canReuse() && prepared.getCteCleanups() == null;
}
@Override
public boolean isReadOnly() {
if (!readOnlyKnown) {
readOnly = prepared.isReadOnly();
readOnlyKnown = true;
}
return readOnly;
}
@Override
public ResultInterface queryMeta() {
return prepared.queryMeta();
}
@Override
public boolean isCacheable() {
return prepared.isCacheable();
}
@Override
public int getCommandType() {
return prepared.getType();
}
}
|
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/command/CommandInterface.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.command;
import java.util.ArrayList;
import org.h2.expression.ParameterInterface;
import org.h2.result.ResultInterface;
import org.h2.result.ResultWithGeneratedKeys;
/**
* Represents a SQL statement.
*/
public interface CommandInterface {
/**
* The type for unknown statement.
*/
int UNKNOWN = 0;
// ddl operations
/**
* The type of a ALTER INDEX RENAME statement.
*/
int ALTER_INDEX_RENAME = 1;
/**
* The type of a ALTER SCHEMA RENAME statement.
*/
int ALTER_SCHEMA_RENAME = 2;
/**
* The type of a ALTER TABLE ADD CHECK statement.
*/
int ALTER_TABLE_ADD_CONSTRAINT_CHECK = 3;
/**
* The type of a ALTER TABLE ADD UNIQUE statement.
*/
int ALTER_TABLE_ADD_CONSTRAINT_UNIQUE = 4;
/**
* The type of a ALTER TABLE ADD FOREIGN KEY statement.
*/
int ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL = 5;
/**
* The type of a ALTER TABLE ADD PRIMARY KEY statement.
*/
int ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY = 6;
/**
* The type of a ALTER TABLE ADD statement.
*/
int ALTER_TABLE_ADD_COLUMN = 7;
/**
* The type of a ALTER TABLE ALTER COLUMN SET NOT NULL statement.
*/
int ALTER_TABLE_ALTER_COLUMN_NOT_NULL = 8;
/**
* The type of a ALTER TABLE ALTER COLUMN SET NULL statement.
*/
int ALTER_TABLE_ALTER_COLUMN_NULL = 9;
/**
* The type of a ALTER TABLE ALTER COLUMN SET DEFAULT statement.
*/
int ALTER_TABLE_ALTER_COLUMN_DEFAULT = 10;
/**
* The type of an ALTER TABLE ALTER COLUMN statement that changes the column
* data type.
*/
int ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE = 11;
/**
* The type of a ALTER TABLE DROP COLUMN statement.
*/
int ALTER_TABLE_DROP_COLUMN = 12;
/**
* The type of a ALTER TABLE ALTER COLUMN SELECTIVITY statement.
*/
int ALTER_TABLE_ALTER_COLUMN_SELECTIVITY = 13;
/**
* The type of a ALTER TABLE DROP CONSTRAINT statement.
*/
int ALTER_TABLE_DROP_CONSTRAINT = 14;
/**
* The type of a ALTER TABLE RENAME statement.
*/
int ALTER_TABLE_RENAME = 15;
/**
* The type of a ALTER TABLE ALTER COLUMN RENAME statement.
*/
int ALTER_TABLE_ALTER_COLUMN_RENAME = 16;
/**
* The type of a ALTER USER ADMIN statement.
*/
int ALTER_USER_ADMIN = 17;
/**
* The type of a ALTER USER RENAME statement.
*/
int ALTER_USER_RENAME = 18;
/**
* The type of a ALTER USER SET PASSWORD statement.
*/
int ALTER_USER_SET_PASSWORD = 19;
/**
* The type of a ALTER VIEW statement.
*/
int ALTER_VIEW = 20;
/**
* The type of a ANALYZE statement.
*/
int ANALYZE = 21;
/**
* The type of a CREATE AGGREGATE statement.
*/
int CREATE_AGGREGATE = 22;
/**
* The type of a CREATE CONSTANT statement.
*/
int CREATE_CONSTANT = 23;
/**
* The type of a CREATE ALIAS statement.
*/
int CREATE_ALIAS = 24;
/**
* The type of a CREATE INDEX statement.
*/
int CREATE_INDEX = 25;
/**
* The type of a CREATE LINKED TABLE statement.
*/
int CREATE_LINKED_TABLE = 26;
/**
* The type of a CREATE ROLE statement.
*/
int CREATE_ROLE = 27;
/**
* The type of a CREATE SCHEMA statement.
*/
int CREATE_SCHEMA = 28;
/**
* The type of a CREATE SEQUENCE statement.
*/
int CREATE_SEQUENCE = 29;
/**
* The type of a CREATE TABLE statement.
*/
int CREATE_TABLE = 30;
/**
* The type of a CREATE TRIGGER statement.
*/
int CREATE_TRIGGER = 31;
/**
* The type of a CREATE USER statement.
*/
int CREATE_USER = 32;
/**
* The type of a CREATE DOMAIN statement.
*/
int CREATE_DOMAIN = 33;
/**
* The type of a CREATE VIEW statement.
*/
int CREATE_VIEW = 34;
/**
* The type of a DEALLOCATE statement.
*/
int DEALLOCATE = 35;
/**
* The type of a DROP AGGREGATE statement.
*/
int DROP_AGGREGATE = 36;
/**
* The type of a DROP CONSTANT statement.
*/
int DROP_CONSTANT = 37;
/**
* The type of a DROP ALL OBJECTS statement.
*/
int DROP_ALL_OBJECTS = 38;
/**
* The type of a DROP ALIAS statement.
*/
int DROP_ALIAS = 39;
/**
* The type of a DROP INDEX statement.
*/
int DROP_INDEX = 40;
/**
* The type of a DROP ROLE statement.
*/
int DROP_ROLE = 41;
/**
* The type of a DROP SCHEMA statement.
*/
int DROP_SCHEMA = 42;
/**
* The type of a DROP SEQUENCE statement.
*/
int DROP_SEQUENCE = 43;
/**
* The type of a DROP TABLE statement.
*/
int DROP_TABLE = 44;
/**
* The type of a DROP TRIGGER statement.
*/
int DROP_TRIGGER = 45;
/**
* The type of a DROP USER statement.
*/
int DROP_USER = 46;
/**
* The type of a DROP DOMAIN statement.
*/
int DROP_DOMAIN = 47;
/**
* The type of a DROP VIEW statement.
*/
int DROP_VIEW = 48;
/**
* The type of a GRANT statement.
*/
int GRANT = 49;
/**
* The type of a REVOKE statement.
*/
int REVOKE = 50;
/**
* The type of a PREPARE statement.
*/
int PREPARE = 51;
/**
* The type of a COMMENT statement.
*/
int COMMENT = 52;
/**
* The type of a TRUNCATE TABLE statement.
*/
int TRUNCATE_TABLE = 53;
// dml operations
/**
* The type of a ALTER SEQUENCE statement.
*/
int ALTER_SEQUENCE = 54;
/**
* The type of a ALTER TABLE SET REFERENTIAL_INTEGRITY statement.
*/
int ALTER_TABLE_SET_REFERENTIAL_INTEGRITY = 55;
/**
* The type of a BACKUP statement.
*/
int BACKUP = 56;
/**
* The type of a CALL statement.
*/
int CALL = 57;
/**
* The type of a DELETE statement.
*/
int DELETE = 58;
/**
* The type of a EXECUTE statement.
*/
int EXECUTE = 59;
/**
* The type of a EXPLAIN statement.
*/
int EXPLAIN = 60;
/**
* The type of a INSERT statement.
*/
int INSERT = 61;
/**
* The type of a MERGE statement.
*/
int MERGE = 62;
/**
* The type of a REPLACE statement.
*/
int REPLACE = 63;
/**
* The type of a no operation statement.
*/
int NO_OPERATION = 63;
/**
* The type of a RUNSCRIPT statement.
*/
int RUNSCRIPT = 64;
/**
* The type of a SCRIPT statement.
*/
int SCRIPT = 65;
/**
* The type of a SELECT statement.
*/
int SELECT = 66;
/**
* The type of a SET statement.
*/
int SET = 67;
/**
* The type of a UPDATE statement.
*/
int UPDATE = 68;
// transaction commands
/**
* The type of a SET AUTOCOMMIT statement.
*/
int SET_AUTOCOMMIT_TRUE = 69;
/**
* The type of a SET AUTOCOMMIT statement.
*/
int SET_AUTOCOMMIT_FALSE = 70;
/**
* The type of a COMMIT statement.
*/
int COMMIT = 71;
/**
* The type of a ROLLBACK statement.
*/
int ROLLBACK = 72;
/**
* The type of a CHECKPOINT statement.
*/
int CHECKPOINT = 73;
/**
* The type of a SAVEPOINT statement.
*/
int SAVEPOINT = 74;
/**
* The type of a ROLLBACK TO SAVEPOINT statement.
*/
int ROLLBACK_TO_SAVEPOINT = 75;
/**
* The type of a CHECKPOINT SYNC statement.
*/
int CHECKPOINT_SYNC = 76;
/**
* The type of a PREPARE COMMIT statement.
*/
int PREPARE_COMMIT = 77;
/**
* The type of a COMMIT TRANSACTION statement.
*/
int COMMIT_TRANSACTION = 78;
/**
* The type of a ROLLBACK TRANSACTION statement.
*/
int ROLLBACK_TRANSACTION = 79;
/**
* The type of a SHUTDOWN statement.
*/
int SHUTDOWN = 80;
/**
* The type of a SHUTDOWN IMMEDIATELY statement.
*/
int SHUTDOWN_IMMEDIATELY = 81;
/**
* The type of a SHUTDOWN COMPACT statement.
*/
int SHUTDOWN_COMPACT = 82;
/**
* The type of a BEGIN {WORK|TRANSACTION} statement.
*/
int BEGIN = 83;
/**
* The type of a SHUTDOWN DEFRAG statement.
*/
int SHUTDOWN_DEFRAG = 84;
/**
* The type of a ALTER TABLE RENAME CONSTRAINT statement.
*/
int ALTER_TABLE_RENAME_CONSTRAINT = 85;
/**
* The type of a EXPLAIN ANALYZE statement.
*/
int EXPLAIN_ANALYZE = 86;
/**
* The type of a ALTER TABLE ALTER COLUMN SET INVISIBLE statement.
*/
int ALTER_TABLE_ALTER_COLUMN_VISIBILITY = 87;
/**
* The type of a CREATE SYNONYM statement.
*/
int CREATE_SYNONYM = 88;
/**
* The type of a DROP SYNONYM statement.
*/
int DROP_SYNONYM = 89;
/**
* The type of a ALTER TABLE ALTER COLUMN SET ON UPDATE statement.
*/
int ALTER_TABLE_ALTER_COLUMN_ON_UPDATE = 90;
/**
* Get command type.
*
* @return one of the constants above
*/
int getCommandType();
/**
* Check if this is a query.
*
* @return true if it is a query
*/
boolean isQuery();
/**
* Get the parameters (if any).
*
* @return the parameters
*/
ArrayList<? extends ParameterInterface> getParameters();
/**
* Execute the query.
*
* @param maxRows the maximum number of rows returned
* @param scrollable if the result set must be scrollable
* @return the result
*/
ResultInterface executeQuery(int maxRows, boolean scrollable);
/**
* Execute the statement
*
* @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 the update count
*/
ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest);
/**
* Stop the command execution, release all locks and resources
*/
void stop();
/**
* Close the statement.
*/
void close();
/**
* Cancel the statement if it is still processing.
*/
void cancel();
/**
* Get an empty result set containing the meta data of the result.
*
* @return the empty result
*/
ResultInterface getMetaData();
}
|
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/command/CommandList.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.command;
import java.util.ArrayList;
import org.h2.expression.ParameterInterface;
import org.h2.result.ResultInterface;
/**
* Represents a list of SQL statements.
*/
class CommandList extends Command {
private final Command command;
private final String remaining;
CommandList(Parser parser, String sql, Command c, String remaining) {
super(parser, sql);
this.command = c;
this.remaining = remaining;
}
@Override
public ArrayList<? extends ParameterInterface> getParameters() {
return command.getParameters();
}
private void executeRemaining() {
Command remainingCommand = session.prepareLocal(remaining);
if (remainingCommand.isQuery()) {
remainingCommand.query(0);
} else {
remainingCommand.update();
}
}
@Override
public int update() {
int updateCount = command.executeUpdate(false).getUpdateCount();
executeRemaining();
return updateCount;
}
@Override
public void prepareJoinBatch() {
command.prepareJoinBatch();
}
@Override
public ResultInterface query(int maxrows) {
ResultInterface result = command.query(maxrows);
executeRemaining();
return result;
}
@Override
public boolean isQuery() {
return command.isQuery();
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public ResultInterface queryMeta() {
return command.queryMeta();
}
@Override
public int getCommandType() {
return command.getCommandType();
}
}
|
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/command/CommandRemote.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.command;
import java.io.IOException;
import java.util.ArrayList;
import org.h2.engine.Constants;
import org.h2.engine.GeneratedKeysMode;
import org.h2.engine.SessionRemote;
import org.h2.engine.SysProperties;
import org.h2.expression.ParameterInterface;
import org.h2.expression.ParameterRemote;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.ResultInterface;
import org.h2.result.ResultRemote;
import org.h2.result.ResultWithGeneratedKeys;
import org.h2.util.New;
import org.h2.value.Transfer;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* Represents the client-side part of a SQL statement.
* This class is not used in embedded mode.
*/
public class CommandRemote implements CommandInterface {
private final ArrayList<Transfer> transferList;
private final ArrayList<ParameterInterface> parameters;
private final Trace trace;
private final String sql;
private final int fetchSize;
private SessionRemote session;
private int id;
private boolean isQuery;
private int cmdType = UNKNOWN;
private boolean readonly;
private final int created;
public CommandRemote(SessionRemote session,
ArrayList<Transfer> transferList, String sql, int fetchSize) {
this.transferList = transferList;
trace = session.getTrace();
this.sql = sql;
parameters = New.arrayList();
prepare(session, true);
// set session late because prepare might fail - in this case we don't
// need to close the object
this.session = session;
this.fetchSize = fetchSize;
created = session.getLastReconnect();
}
@Override
public void stop() {
// Must never be called, because remote result is not lazy.
throw DbException.throwInternalError();
}
private void prepare(SessionRemote s, boolean createParams) {
id = s.getNextId();
for (int i = 0, count = 0; i < transferList.size(); i++) {
try {
Transfer transfer = transferList.get(i);
boolean v16 = s.getClientVersion() >= Constants.TCP_PROTOCOL_VERSION_16;
if (createParams) {
s.traceOperation(v16 ? "SESSION_PREPARE_READ_PARAMS2"
: "SESSION_PREPARE_READ_PARAMS", id);
transfer.writeInt(
v16 ? SessionRemote.SESSION_PREPARE_READ_PARAMS2
: SessionRemote.SESSION_PREPARE_READ_PARAMS)
.writeInt(id).writeString(sql);
} else {
s.traceOperation("SESSION_PREPARE", id);
transfer.writeInt(SessionRemote.SESSION_PREPARE).
writeInt(id).writeString(sql);
}
s.done(transfer);
isQuery = transfer.readBoolean();
readonly = transfer.readBoolean();
cmdType = v16 && createParams ? transfer.readInt() : UNKNOWN;
int paramCount = transfer.readInt();
if (createParams) {
parameters.clear();
for (int j = 0; j < paramCount; j++) {
ParameterRemote p = new ParameterRemote(j);
p.readMetaData(transfer);
parameters.add(p);
}
}
} catch (IOException e) {
s.removeServer(e, i--, ++count);
}
}
}
@Override
public boolean isQuery() {
return isQuery;
}
@Override
public ArrayList<ParameterInterface> getParameters() {
return parameters;
}
private void prepareIfRequired() {
if (session.getLastReconnect() != created) {
// in this case we need to prepare again in every case
id = Integer.MIN_VALUE;
}
session.checkClosed();
if (id <= session.getCurrentId() - SysProperties.SERVER_CACHED_OBJECTS) {
// object is too old - we need to prepare again
prepare(session, false);
}
}
@Override
public ResultInterface getMetaData() {
synchronized (session) {
if (!isQuery) {
return null;
}
int objectId = session.getNextId();
ResultRemote result = null;
for (int i = 0, count = 0; i < transferList.size(); i++) {
prepareIfRequired();
Transfer transfer = transferList.get(i);
try {
session.traceOperation("COMMAND_GET_META_DATA", id);
transfer.writeInt(SessionRemote.COMMAND_GET_META_DATA).
writeInt(id).writeInt(objectId);
session.done(transfer);
int columnCount = transfer.readInt();
result = new ResultRemote(session, transfer, objectId,
columnCount, Integer.MAX_VALUE);
break;
} catch (IOException e) {
session.removeServer(e, i--, ++count);
}
}
session.autoCommitIfCluster();
return result;
}
}
@Override
public ResultInterface executeQuery(int maxRows, boolean scrollable) {
checkParameters();
synchronized (session) {
int objectId = session.getNextId();
ResultRemote result = null;
for (int i = 0, count = 0; i < transferList.size(); i++) {
prepareIfRequired();
Transfer transfer = transferList.get(i);
try {
session.traceOperation("COMMAND_EXECUTE_QUERY", id);
transfer.writeInt(SessionRemote.COMMAND_EXECUTE_QUERY).
writeInt(id).writeInt(objectId).writeInt(maxRows);
int fetch;
if (session.isClustered() || scrollable) {
fetch = Integer.MAX_VALUE;
} else {
fetch = fetchSize;
}
transfer.writeInt(fetch);
sendParameters(transfer);
session.done(transfer);
int columnCount = transfer.readInt();
if (result != null) {
result.close();
result = null;
}
result = new ResultRemote(session, transfer, objectId, columnCount, fetch);
if (readonly) {
break;
}
} catch (IOException e) {
session.removeServer(e, i--, ++count);
}
}
session.autoCommitIfCluster();
session.readSessionState();
return result;
}
}
@Override
public ResultWithGeneratedKeys executeUpdate(Object generatedKeysRequest) {
checkParameters();
boolean supportsGeneratedKeys = session.isSupportsGeneratedKeys();
boolean readGeneratedKeys = supportsGeneratedKeys && !Boolean.FALSE.equals(generatedKeysRequest);
int objectId = readGeneratedKeys ? session.getNextId() : 0;
synchronized (session) {
int updateCount = 0;
ResultRemote generatedKeys = null;
boolean autoCommit = false;
for (int i = 0, count = 0; i < transferList.size(); i++) {
prepareIfRequired();
Transfer transfer = transferList.get(i);
try {
session.traceOperation("COMMAND_EXECUTE_UPDATE", id);
transfer.writeInt(SessionRemote.COMMAND_EXECUTE_UPDATE).writeInt(id);
sendParameters(transfer);
if (supportsGeneratedKeys) {
int mode = GeneratedKeysMode.valueOf(generatedKeysRequest);
transfer.writeInt(mode);
switch (mode) {
case GeneratedKeysMode.COLUMN_NUMBERS: {
int[] keys = (int[]) generatedKeysRequest;
transfer.writeInt(keys.length);
for (int key : keys) {
transfer.writeInt(key);
}
break;
}
case GeneratedKeysMode.COLUMN_NAMES: {
String[] keys = (String[]) generatedKeysRequest;
transfer.writeInt(keys.length);
for (String key : keys) {
transfer.writeString(key);
}
break;
}
}
}
session.done(transfer);
updateCount = transfer.readInt();
autoCommit = transfer.readBoolean();
if (readGeneratedKeys) {
int columnCount = transfer.readInt();
if (generatedKeys != null) {
generatedKeys.close();
generatedKeys = null;
}
generatedKeys = new ResultRemote(session, transfer, objectId, columnCount, Integer.MAX_VALUE);
}
} catch (IOException e) {
session.removeServer(e, i--, ++count);
}
}
session.setAutoCommitFromServer(autoCommit);
session.autoCommitIfCluster();
session.readSessionState();
if (generatedKeys != null) {
return new ResultWithGeneratedKeys.WithKeys(updateCount, generatedKeys);
}
return ResultWithGeneratedKeys.of(updateCount);
}
}
private void checkParameters() {
if (cmdType != EXPLAIN) {
for (ParameterInterface p : parameters) {
p.checkSet();
}
}
}
private void sendParameters(Transfer transfer) throws IOException {
int len = parameters.size();
transfer.writeInt(len);
for (ParameterInterface p : parameters) {
Value pVal = p.getParamValue();
if (pVal == null && cmdType == EXPLAIN) {
pVal = ValueNull.INSTANCE;
}
transfer.writeValue(pVal);
}
}
@Override
public void close() {
if (session == null || session.isClosed()) {
return;
}
synchronized (session) {
session.traceOperation("COMMAND_CLOSE", id);
for (Transfer transfer : transferList) {
try {
transfer.writeInt(SessionRemote.COMMAND_CLOSE).writeInt(id);
} catch (IOException e) {
trace.error(e, "close");
}
}
}
session = null;
try {
for (ParameterInterface p : parameters) {
Value v = p.getParamValue();
if (v != null) {
v.remove();
}
}
} catch (DbException e) {
trace.error(e, "close");
}
parameters.clear();
}
/**
* Cancel this current statement.
*/
@Override
public void cancel() {
session.cancelStatement(id);
}
@Override
public String toString() {
return sql + Trace.formatParams(getParameters());
}
@Override
public int getCommandType() {
return cmdType;
}
}
|
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/command/Parser.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
*
* Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
* Support for the operator "&&" as an alias for SPATIAL_INTERSECTS
*/
package org.h2.command;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.Charset;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.ddl.AlterIndexRename;
import org.h2.command.ddl.AlterSchemaRename;
import org.h2.command.ddl.AlterTableAddConstraint;
import org.h2.command.ddl.AlterTableAlterColumn;
import org.h2.command.ddl.AlterTableDropConstraint;
import org.h2.command.ddl.AlterTableRename;
import org.h2.command.ddl.AlterTableRenameColumn;
import org.h2.command.ddl.AlterTableRenameConstraint;
import org.h2.command.ddl.AlterUser;
import org.h2.command.ddl.AlterView;
import org.h2.command.ddl.Analyze;
import org.h2.command.ddl.CommandWithColumns;
import org.h2.command.ddl.CreateAggregate;
import org.h2.command.ddl.CreateConstant;
import org.h2.command.ddl.CreateFunctionAlias;
import org.h2.command.ddl.CreateIndex;
import org.h2.command.ddl.CreateLinkedTable;
import org.h2.command.ddl.CreateRole;
import org.h2.command.ddl.CreateSchema;
import org.h2.command.ddl.CreateSequence;
import org.h2.command.ddl.CreateSynonym;
import org.h2.command.ddl.CreateTable;
import org.h2.command.ddl.CreateTrigger;
import org.h2.command.ddl.CreateUser;
import org.h2.command.ddl.CreateUserDataType;
import org.h2.command.ddl.CreateView;
import org.h2.command.ddl.DeallocateProcedure;
import org.h2.command.ddl.DefineCommand;
import org.h2.command.ddl.DropAggregate;
import org.h2.command.ddl.DropConstant;
import org.h2.command.ddl.DropDatabase;
import org.h2.command.ddl.DropFunctionAlias;
import org.h2.command.ddl.DropIndex;
import org.h2.command.ddl.DropRole;
import org.h2.command.ddl.DropSchema;
import org.h2.command.ddl.DropSequence;
import org.h2.command.ddl.DropSynonym;
import org.h2.command.ddl.DropTable;
import org.h2.command.ddl.DropTrigger;
import org.h2.command.ddl.DropUser;
import org.h2.command.ddl.DropUserDataType;
import org.h2.command.ddl.DropView;
import org.h2.command.ddl.GrantRevoke;
import org.h2.command.ddl.PrepareProcedure;
import org.h2.command.ddl.SchemaCommand;
import org.h2.command.ddl.SetComment;
import org.h2.command.ddl.TruncateTable;
import org.h2.command.dml.AlterSequence;
import org.h2.command.dml.AlterTableSet;
import org.h2.command.dml.BackupCommand;
import org.h2.command.dml.Call;
import org.h2.command.dml.Delete;
import org.h2.command.dml.ExecuteProcedure;
import org.h2.command.dml.Explain;
import org.h2.command.dml.Insert;
import org.h2.command.dml.Merge;
import org.h2.command.dml.MergeUsing;
import org.h2.command.dml.NoOperation;
import org.h2.command.dml.Query;
import org.h2.command.dml.Replace;
import org.h2.command.dml.RunScriptCommand;
import org.h2.command.dml.ScriptCommand;
import org.h2.command.dml.Select;
import org.h2.command.dml.SelectOrderBy;
import org.h2.command.dml.SelectUnion;
import org.h2.command.dml.Set;
import org.h2.command.dml.SetTypes;
import org.h2.command.dml.TransactionCommand;
import org.h2.command.dml.Update;
import org.h2.constraint.ConstraintActionType;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.FunctionAlias;
import org.h2.engine.Mode;
import org.h2.engine.Mode.ModeEnum;
import org.h2.engine.Procedure;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.engine.User;
import org.h2.engine.UserAggregate;
import org.h2.engine.UserDataType;
import org.h2.expression.Aggregate;
import org.h2.expression.Aggregate.AggregateType;
import org.h2.expression.Alias;
import org.h2.expression.CompareLike;
import org.h2.expression.Comparison;
import org.h2.expression.ConditionAndOr;
import org.h2.expression.ConditionExists;
import org.h2.expression.ConditionIn;
import org.h2.expression.ConditionInParameter;
import org.h2.expression.ConditionInSelect;
import org.h2.expression.ConditionNot;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionList;
import org.h2.expression.Function;
import org.h2.expression.FunctionCall;
import org.h2.expression.JavaAggregate;
import org.h2.expression.JavaFunction;
import org.h2.expression.Operation;
import org.h2.expression.Operation.OpType;
import org.h2.expression.Parameter;
import org.h2.expression.Rownum;
import org.h2.expression.SequenceValue;
import org.h2.expression.Subquery;
import org.h2.expression.TableFunction;
import org.h2.expression.ValueExpression;
import org.h2.expression.Variable;
import org.h2.expression.Wildcard;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.SortOrder;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
import org.h2.table.Column;
import org.h2.table.FunctionTable;
import org.h2.table.IndexColumn;
import org.h2.table.IndexHints;
import org.h2.table.RangeTable;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.table.TableFilter.TableFilterVisitor;
import org.h2.table.TableView;
import org.h2.util.DateTimeFunctions;
import org.h2.util.MathUtils;
import org.h2.util.New;
import org.h2.util.ParserUtil;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.CompareMode;
import org.h2.value.DataType;
import org.h2.value.Value;
import org.h2.value.ValueBoolean;
import org.h2.value.ValueBytes;
import org.h2.value.ValueDate;
import org.h2.value.ValueDecimal;
import org.h2.value.ValueEnum;
import org.h2.value.ValueInt;
import org.h2.value.ValueLong;
import org.h2.value.ValueNull;
import org.h2.value.ValueString;
import org.h2.value.ValueTime;
import org.h2.value.ValueTimestamp;
import org.h2.value.ValueTimestampTimeZone;
/**
* The parser is used to convert a SQL statement string to an command object.
*
* @author Thomas Mueller
* @author Noel Grandin
* @author Nicolas Fortin, Atelier SIG, IRSTV FR CNRS 24888
*/
public class Parser {
private static final String WITH_STATEMENT_SUPPORTS_LIMITED_SUB_STATEMENTS =
"WITH statement supports only SELECT, CREATE TABLE, INSERT, UPDATE, MERGE or DELETE statements";
// used during the tokenizer phase
private static final int CHAR_END = 1, CHAR_VALUE = 2, CHAR_QUOTED = 3;
private static final int CHAR_NAME = 4, CHAR_SPECIAL_1 = 5,
CHAR_SPECIAL_2 = 6;
private static final int CHAR_STRING = 7, CHAR_DOT = 8,
CHAR_DOLLAR_QUOTED_STRING = 9;
// this are token types
private static final int KEYWORD = ParserUtil.KEYWORD;
private static final int IDENTIFIER = ParserUtil.IDENTIFIER;
private static final int NULL = ParserUtil.NULL;
private static final int TRUE = ParserUtil.TRUE;
private static final int FALSE = ParserUtil.FALSE;
private static final int ROWNUM = ParserUtil.ROWNUM;
private static final int PARAMETER = 10, END = 11, VALUE = 12;
private static final int EQUAL = 13, BIGGER_EQUAL = 14, BIGGER = 15;
private static final int SMALLER = 16, SMALLER_EQUAL = 17, NOT_EQUAL = 18;
private static final int AT = 19;
private static final int MINUS = 20, PLUS = 21, STRING_CONCAT = 22;
private static final int OPEN = 23, CLOSE = 24;
private static final int SPATIAL_INTERSECTS = 25;
private static final Comparator<TableFilter> TABLE_FILTER_COMPARATOR =
new Comparator<TableFilter>() {
@Override
public int compare(TableFilter o1, TableFilter o2) {
return o1 == o2 ? 0 : compareTableFilters(o1, o2);
}
};
private final Database database;
private final Session session;
/**
* @see org.h2.engine.DbSettings#databaseToUpper
*/
private final boolean identifiersToUpper;
/** indicates character-type for each char in sqlCommand */
private int[] characterTypes;
private int currentTokenType;
private String currentToken;
private boolean currentTokenQuoted;
private Value currentValue;
private String originalSQL;
/** copy of originalSQL, with comments blanked out */
private String sqlCommand;
/** cached array if chars from sqlCommand */
private char[] sqlCommandChars;
/** index into sqlCommand of previous token */
private int lastParseIndex;
/** index into sqlCommand of current token */
private int parseIndex;
private CreateView createView;
private Prepared currentPrepared;
private Select currentSelect;
private ArrayList<Parameter> parameters;
private String schemaName;
private ArrayList<String> expectedList;
private boolean rightsChecked;
private boolean recompileAlways;
private boolean literalsChecked;
private ArrayList<Parameter> indexedParameterList;
private int orderInFrom;
private ArrayList<Parameter> suppliedParameterList;
public Parser(Session session) {
this.database = session.getDatabase();
this.identifiersToUpper = database.getSettings().databaseToUpper;
this.session = session;
}
/**
* Parse the statement and prepare it for execution.
*
* @param sql the SQL statement to parse
* @return the prepared object
*/
public Prepared prepare(String sql) {
Prepared p = parse(sql);
p.prepare();
if (currentTokenType != END) {
throw getSyntaxError();
}
return p;
}
/**
* Parse a statement or a list of statements, and prepare it for execution.
*
* @param sql the SQL statement to parse
* @return the command object
*/
public Command prepareCommand(String sql) {
try {
Prepared p = parse(sql);
boolean hasMore = isToken(";");
if (!hasMore && currentTokenType != END) {
throw getSyntaxError();
}
p.prepare();
Command c = new CommandContainer(this, sql, p);
if (hasMore) {
String remaining = originalSQL.substring(parseIndex);
if (remaining.trim().length() != 0) {
c = new CommandList(this, sql, c, remaining);
}
}
return c;
} catch (DbException e) {
throw e.addSQL(originalSQL);
}
}
/**
* Parse the statement, but don't prepare it for execution.
*
* @param sql the SQL statement to parse
* @return the prepared object
*/
Prepared parse(String sql) {
Prepared p;
try {
// first, try the fast variant
p = parse(sql, false);
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.SYNTAX_ERROR_1) {
// now, get the detailed exception
p = parse(sql, true);
} else {
throw e.addSQL(sql);
}
}
p.setPrepareAlways(recompileAlways);
p.setParameterList(parameters);
return p;
}
private Prepared parse(String sql, boolean withExpectedList) {
initialize(sql);
if (withExpectedList) {
expectedList = New.arrayList();
} else {
expectedList = null;
}
parameters = New.arrayList();
currentSelect = null;
currentPrepared = null;
createView = null;
recompileAlways = false;
indexedParameterList = suppliedParameterList;
read();
return 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;
}
private DbException getSyntaxError() {
if (expectedList == null || expectedList.isEmpty()) {
return DbException.getSyntaxError(sqlCommand, parseIndex);
}
StatementBuilder buff = new StatementBuilder();
for (String e : expectedList) {
buff.appendExceptFirst(", ");
buff.append(e);
}
return DbException.getSyntaxError(sqlCommand, parseIndex,
buff.toString());
}
private Prepared parseBackup() {
BackupCommand command = new BackupCommand(session);
read("TO");
command.setFileName(readExpression());
return command;
}
private Prepared parseAnalyze() {
Analyze command = new Analyze(session);
if (readIf("TABLE")) {
Table table = readTableOrView();
command.setTable(table);
}
if (readIf("SAMPLE_SIZE")) {
command.setTop(readPositiveInt());
}
return command;
}
private TransactionCommand parseBegin() {
TransactionCommand command;
if (!readIf("WORK")) {
readIf("TRANSACTION");
}
command = new TransactionCommand(session, CommandInterface.BEGIN);
return command;
}
private TransactionCommand parseCommit() {
TransactionCommand command;
if (readIf("TRANSACTION")) {
command = new TransactionCommand(session,
CommandInterface.COMMIT_TRANSACTION);
command.setTransactionName(readUniqueIdentifier());
return command;
}
command = new TransactionCommand(session,
CommandInterface.COMMIT);
readIf("WORK");
return command;
}
private TransactionCommand parseShutdown() {
int type = CommandInterface.SHUTDOWN;
if (readIf("IMMEDIATELY")) {
type = CommandInterface.SHUTDOWN_IMMEDIATELY;
} else if (readIf("COMPACT")) {
type = CommandInterface.SHUTDOWN_COMPACT;
} else if (readIf("DEFRAG")) {
type = CommandInterface.SHUTDOWN_DEFRAG;
} else {
readIf("SCRIPT");
}
return new TransactionCommand(session, type);
}
private TransactionCommand parseRollback() {
TransactionCommand command;
if (readIf("TRANSACTION")) {
command = new TransactionCommand(session,
CommandInterface.ROLLBACK_TRANSACTION);
command.setTransactionName(readUniqueIdentifier());
return command;
}
if (readIf("TO")) {
read("SAVEPOINT");
command = new TransactionCommand(session,
CommandInterface.ROLLBACK_TO_SAVEPOINT);
command.setSavepointName(readUniqueIdentifier());
} else {
readIf("WORK");
command = new TransactionCommand(session,
CommandInterface.ROLLBACK);
}
return command;
}
private Prepared parsePrepare() {
if (readIf("COMMIT")) {
TransactionCommand command = new TransactionCommand(session,
CommandInterface.PREPARE_COMMIT);
command.setTransactionName(readUniqueIdentifier());
return command;
}
String procedureName = readAliasIdentifier();
if (readIf("(")) {
ArrayList<Column> list = New.arrayList();
for (int i = 0;; i++) {
Column column = parseColumnForTable("C" + i, true);
list.add(column);
if (readIf(")")) {
break;
}
read(",");
}
}
read("AS");
Prepared prep = parsePrepared();
PrepareProcedure command = new PrepareProcedure(session);
command.setProcedureName(procedureName);
command.setPrepared(prep);
return command;
}
private TransactionCommand parseSavepoint() {
TransactionCommand command = new TransactionCommand(session,
CommandInterface.SAVEPOINT);
command.setSavepointName(readUniqueIdentifier());
return command;
}
private Prepared parseReleaseSavepoint() {
Prepared command = new NoOperation(session);
readIf("SAVEPOINT");
readUniqueIdentifier();
return command;
}
private Schema findSchema(String schemaName) {
if (schemaName == null) {
return null;
}
Schema schema = database.findSchema(schemaName);
if (schema == null) {
if (equalsToken("SESSION", schemaName)) {
// for local temporary tables
schema = database.getSchema(session.getCurrentSchemaName());
} else if (database.getMode().sysDummy1 &&
"SYSIBM".equals(schemaName)) {
// IBM DB2 and Apache Derby compatibility: SYSIBM.SYSDUMMY1
schema = database.getSchema(session.getCurrentSchemaName());
}
}
return schema;
}
private Schema getSchema(String schemaName) {
if (schemaName == null) {
return null;
}
Schema schema = findSchema(schemaName);
if (schema == null) {
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
}
return schema;
}
private Schema getSchema() {
return getSchema(schemaName);
}
/*
* Gets the current schema for scenarios that need a guaranteed, non-null schema object.
*
* This routine is solely here
* because of the function readIdentifierWithSchema(String defaultSchemaName) - which
* is often called with a null parameter (defaultSchemaName) - then 6 lines into the function
* that routine nullifies the state field schemaName - which I believe is a bug.
*
* There are about 7 places where "readIdentifierWithSchema(null)" is called in this file.
*
* In other words when is it legal to not have an active schema defined by schemaName ?
* I don't think it's ever a valid case. I don't understand when that would be allowed.
* I spent a long time trying to figure this out.
* As another proof of this point, the command "SET SCHEMA=NULL" is not a valid command.
*
* I did try to fix this in readIdentifierWithSchema(String defaultSchemaName)
* - but every fix I tried cascaded so many unit test errors - so
* I gave up. I think this needs a bigger effort to fix his, as part of bigger, dedicated story.
*
*/
private Schema getSchemaWithDefault() {
if (schemaName == null) {
schemaName = session.getCurrentSchemaName();
}
return getSchema(schemaName);
}
private Column readTableColumn(TableFilter filter) {
String tableAlias = null;
String columnName = readColumnIdentifier();
if (readIf(".")) {
tableAlias = columnName;
columnName = readColumnIdentifier();
if (readIf(".")) {
String schema = tableAlias;
tableAlias = columnName;
columnName = readColumnIdentifier();
if (readIf(".")) {
String catalogName = schema;
schema = tableAlias;
tableAlias = columnName;
columnName = readColumnIdentifier();
if (!equalsToken(catalogName, database.getShortName())) {
throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1,
catalogName);
}
}
if (!equalsToken(schema, filter.getTable().getSchema()
.getName())) {
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schema);
}
}
if (!equalsToken(tableAlias, filter.getTableAlias())) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1,
tableAlias);
}
}
if (database.getSettings().rowId) {
if (Column.ROWID.equals(columnName)) {
return filter.getRowIdColumn();
}
}
return filter.getTable().getColumn(columnName);
}
private Update parseUpdate() {
Update command = new Update(session);
currentPrepared = command;
int start = lastParseIndex;
TableFilter filter = readSimpleTableFilter(0, null);
command.setTableFilter(filter);
parseUpdateSetClause(command, filter, start);
return command;
}
private void parseUpdateSetClause(Update command, TableFilter filter, int start) {
read("SET");
if (readIf("(")) {
ArrayList<Column> columns = New.arrayList();
do {
Column column = readTableColumn(filter);
columns.add(column);
} while (readIfMore(true));
read("=");
Expression expression = readExpression();
if (columns.size() == 1) {
// the expression is parsed as a simple value
command.setAssignment(columns.get(0), expression);
} else {
for (int i = 0, size = columns.size(); i < size; i++) {
Column column = columns.get(i);
Function f = Function.getFunction(database, "ARRAY_GET");
f.setParameter(0, expression);
f.setParameter(1, ValueExpression.get(ValueInt.get(i + 1)));
f.doneWithParameters();
command.setAssignment(column, f);
}
}
} else {
do {
Column column = readTableColumn(filter);
read("=");
Expression expression;
if (readIf("DEFAULT")) {
expression = ValueExpression.getDefault();
} else {
expression = readExpression();
}
command.setAssignment(column, expression);
} while (readIf(","));
}
if (readIf("WHERE")) {
Expression condition = readExpression();
command.setCondition(condition);
}
if (readIf("ORDER")) {
// for MySQL compatibility
// (this syntax is supported, but ignored)
read("BY");
parseSimpleOrderList();
}
if (readIf("LIMIT")) {
Expression limit = readTerm().optimize(session);
command.setLimit(limit);
}
setSQL(command, "UPDATE", start);
}
private TableFilter readSimpleTableFilter(int orderInFrom, Collection<String> excludeTokens) {
Table table = readTableOrView();
String alias = null;
if (readIf("AS")) {
alias = readAliasIdentifier();
} else if (currentTokenType == IDENTIFIER) {
if (!equalsTokenIgnoreCase(currentToken, "SET")
&& (excludeTokens == null || !isTokenInList(excludeTokens))) {
// SET is not a keyword (PostgreSQL supports it as a table name)
alias = readAliasIdentifier();
}
}
return new TableFilter(session, table, alias, rightsChecked,
currentSelect, orderInFrom, null);
}
private Delete parseDelete() {
Delete command = new Delete(session);
Expression limit = null;
if (readIf("TOP")) {
limit = readTerm().optimize(session);
}
currentPrepared = command;
int start = lastParseIndex;
if (!readIf("FROM") && database.getMode().getEnum() == ModeEnum.MySQL) {
readIdentifierWithSchema();
read("FROM");
}
TableFilter filter = readSimpleTableFilter(0, null);
command.setTableFilter(filter);
parseDeleteGivenTable(command, limit, start);
return command;
}
private void parseDeleteGivenTable(Delete command, Expression limit, int start) {
if (readIf("WHERE")) {
Expression condition = readExpression();
command.setCondition(condition);
}
if (readIf("LIMIT") && limit == null) {
limit = readTerm().optimize(session);
}
command.setLimit(limit);
setSQL(command, "DELETE", start);
}
private IndexColumn[] parseIndexColumnList() {
ArrayList<IndexColumn> columns = New.arrayList();
do {
IndexColumn column = new IndexColumn();
column.columnName = readColumnIdentifier();
columns.add(column);
if (readIf("ASC")) {
// ignore
} else if (readIf("DESC")) {
column.sortType = SortOrder.DESCENDING;
}
if (readIf("NULLS")) {
if (readIf("FIRST")) {
column.sortType |= SortOrder.NULLS_FIRST;
} else {
read("LAST");
column.sortType |= SortOrder.NULLS_LAST;
}
}
} while (readIfMore(true));
return columns.toArray(new IndexColumn[0]);
}
private String[] parseColumnList() {
ArrayList<String> columns = New.arrayList();
do {
String columnName = readColumnIdentifier();
columns.add(columnName);
} while (readIfMore(false));
return columns.toArray(new String[0]);
}
private Column[] parseColumnList(Table table) {
ArrayList<Column> columns = New.arrayList();
HashSet<Column> set = new HashSet<>();
if (!readIf(")")) {
do {
Column column = parseColumn(table);
if (!set.add(column)) {
throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1,
column.getSQL());
}
columns.add(column);
} while (readIfMore(false));
}
return columns.toArray(new Column[0]);
}
private Column parseColumn(Table table) {
String id = readColumnIdentifier();
if (database.getSettings().rowId && Column.ROWID.equals(id)) {
return table.getRowIdColumn();
}
return table.getColumn(id);
}
/**
* Read comma or closing brace.
*
* @param strict
* if {@code false} additional comma before brace is allowed
* @return {@code true} if comma is read, {@code false} if brace is read
*/
private boolean readIfMore(boolean strict) {
if (readIf(",")) {
return strict || !readIf(")");
}
read(")");
return false;
}
private Prepared parseHelp() {
StringBuilder buff = new StringBuilder(
"SELECT * FROM INFORMATION_SCHEMA.HELP");
int i = 0;
ArrayList<Value> paramValues = New.arrayList();
while (currentTokenType != END) {
String s = currentToken;
read();
if (i == 0) {
buff.append(" WHERE ");
} else {
buff.append(" AND ");
}
i++;
buff.append("UPPER(TOPIC) LIKE ?");
paramValues.add(ValueString.get("%" + s + "%"));
}
return prepare(session, buff.toString(), paramValues);
}
private Prepared parseShow() {
ArrayList<Value> paramValues = New.arrayList();
StringBuilder buff = new StringBuilder("SELECT ");
if (readIf("CLIENT_ENCODING")) {
// for PostgreSQL compatibility
buff.append("'UNICODE' AS CLIENT_ENCODING FROM DUAL");
} else if (readIf("DEFAULT_TRANSACTION_ISOLATION")) {
// for PostgreSQL compatibility
buff.append("'read committed' AS DEFAULT_TRANSACTION_ISOLATION " +
"FROM DUAL");
} else if (readIf("TRANSACTION")) {
// for PostgreSQL compatibility
read("ISOLATION");
read("LEVEL");
buff.append("'read committed' AS TRANSACTION_ISOLATION " +
"FROM DUAL");
} else if (readIf("DATESTYLE")) {
// for PostgreSQL compatibility
buff.append("'ISO' AS DATESTYLE FROM DUAL");
} else if (readIf("SERVER_VERSION")) {
// for PostgreSQL compatibility
buff.append("'" + Constants.PG_VERSION + "' AS SERVER_VERSION FROM DUAL");
} else if (readIf("SERVER_ENCODING")) {
// for PostgreSQL compatibility
buff.append("'UTF8' AS SERVER_ENCODING FROM DUAL");
} else if (readIf("TABLES")) {
// for MySQL compatibility
String schema = Constants.SCHEMA_MAIN;
if (readIf("FROM")) {
schema = readUniqueIdentifier();
}
buff.append("TABLE_NAME, TABLE_SCHEMA FROM "
+ "INFORMATION_SCHEMA.TABLES "
+ "WHERE TABLE_SCHEMA=? ORDER BY TABLE_NAME");
paramValues.add(ValueString.get(schema));
} else if (readIf("COLUMNS")) {
// for MySQL compatibility
read("FROM");
String tableName = readIdentifierWithSchema();
String schemaName = getSchema().getName();
paramValues.add(ValueString.get(tableName));
if (readIf("FROM")) {
schemaName = readUniqueIdentifier();
}
buff.append("C.COLUMN_NAME FIELD, "
+ "C.TYPE_NAME || '(' || C.NUMERIC_PRECISION || ')' TYPE, "
+ "C.IS_NULLABLE \"NULL\", "
+ "CASE (SELECT MAX(I.INDEX_TYPE_NAME) FROM "
+ "INFORMATION_SCHEMA.INDEXES I "
+ "WHERE I.TABLE_SCHEMA=C.TABLE_SCHEMA "
+ "AND I.TABLE_NAME=C.TABLE_NAME "
+ "AND I.COLUMN_NAME=C.COLUMN_NAME)"
+ "WHEN 'PRIMARY KEY' THEN 'PRI' "
+ "WHEN 'UNIQUE INDEX' THEN 'UNI' ELSE '' END KEY, "
+ "IFNULL(COLUMN_DEFAULT, 'NULL') DEFAULT "
+ "FROM INFORMATION_SCHEMA.COLUMNS C "
+ "WHERE C.TABLE_NAME=? AND C.TABLE_SCHEMA=? "
+ "ORDER BY C.ORDINAL_POSITION");
paramValues.add(ValueString.get(schemaName));
} else if (readIf("DATABASES") || readIf("SCHEMAS")) {
// for MySQL compatibility
buff.append("SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA");
}
boolean b = session.getAllowLiterals();
try {
// need to temporarily enable it, in case we are in
// ALLOW_LITERALS_NUMBERS mode
session.setAllowLiterals(true);
return prepare(session, buff.toString(), paramValues);
} finally {
session.setAllowLiterals(b);
}
}
private static Prepared prepare(Session s, String sql,
ArrayList<Value> paramValues) {
Prepared prep = s.prepare(sql);
ArrayList<Parameter> params = prep.getParameters();
if (params != null) {
for (int i = 0, size = params.size(); i < size; i++) {
Parameter p = params.get(i);
p.setValue(paramValues.get(i));
}
}
return prep;
}
private boolean isSelect() {
int start = lastParseIndex;
while (readIf("(")) {
// need to read ahead, it could be a nested union:
// ((select 1) union (select 1))
}
boolean select = isToken("SELECT") || isToken("FROM") || isToken("WITH");
parseIndex = start;
read();
return select;
}
private Prepared parseMerge() {
Merge command = new Merge(session);
currentPrepared = command;
int start = lastParseIndex;
read("INTO");
List<String> excludeIdentifiers = Arrays.asList("USING", "KEY", "VALUES");
TableFilter targetTableFilter = readSimpleTableFilter(0, excludeIdentifiers);
command.setTargetTableFilter(targetTableFilter);
Table table = command.getTargetTable();
if (readIf("USING")) {
return parseMergeUsing(command, start);
}
if (readIf("(")) {
if (isSelect()) {
command.setQuery(parseSelect());
read(")");
return command;
}
Column[] columns = parseColumnList(table);
command.setColumns(columns);
}
if (readIf("KEY")) {
read("(");
Column[] keys = parseColumnList(table);
command.setKeys(keys);
}
if (readIf("VALUES")) {
do {
ArrayList<Expression> values = New.arrayList();
read("(");
if (!readIf(")")) {
do {
if (readIf("DEFAULT")) {
values.add(null);
} else {
values.add(readExpression());
}
} while (readIfMore(false));
}
command.addRow(values.toArray(new Expression[0]));
} while (readIf(","));
} else {
command.setQuery(parseSelect());
}
return command;
}
private MergeUsing parseMergeUsing(Merge oldCommand, int start) {
MergeUsing command = new MergeUsing(oldCommand);
currentPrepared = command;
if (readIf("(")) {
/* a select query is supplied */
if (isSelect()) {
command.setQuery(parseSelect());
read(")");
}
command.setQueryAlias(readFromAlias(null, Collections.singletonList("ON")));
String[] querySQLOutput = {null};
List<Column> columnTemplateList = TableView.createQueryColumnTemplateList(null, command.getQuery(),
querySQLOutput);
TableView temporarySourceTableView = createCTEView(
command.getQueryAlias(), querySQLOutput[0],
columnTemplateList, false/* no recursion */,
false/* do not add to session */,
false /* isPersistent */,
session);
TableFilter sourceTableFilter = new TableFilter(session,
temporarySourceTableView, command.getQueryAlias(),
rightsChecked, (Select) command.getQuery(), 0, null);
command.setSourceTableFilter(sourceTableFilter);
} else {
/* Its a table name, simulate a query by building a select query for the table */
List<String> excludeIdentifiers = Collections.singletonList("ON");
TableFilter sourceTableFilter = readSimpleTableFilter(0, excludeIdentifiers);
command.setSourceTableFilter(sourceTableFilter);
StringBuilder buff = new StringBuilder("SELECT * FROM ")
.append(sourceTableFilter.getTable().getName());
if (sourceTableFilter.getTableAlias() != null) {
buff.append(" AS ").append(sourceTableFilter.getTableAlias());
}
Prepared preparedQuery = prepare(session, buff.toString(), null/*paramValues*/);
command.setQuery((Select) preparedQuery);
}
read("ON");
read("(");
Expression condition = readExpression();
command.setOnCondition(condition);
read(")");
if (readIfAll("WHEN", "MATCHED", "THEN")) {
int startMatched = lastParseIndex;
if (readIf("UPDATE")) {
Update updateCommand = new Update(session);
//currentPrepared = updateCommand;
TableFilter filter = command.getTargetTableFilter();
updateCommand.setTableFilter(filter);
parseUpdateSetClause(updateCommand, filter, startMatched);
command.setUpdateCommand(updateCommand);
}
startMatched = lastParseIndex;
if (readIf("DELETE")) {
Delete deleteCommand = new Delete(session);
TableFilter filter = command.getTargetTableFilter();
deleteCommand.setTableFilter(filter);
parseDeleteGivenTable(deleteCommand, null, startMatched);
command.setDeleteCommand(deleteCommand);
}
}
if (readIfAll("WHEN", "NOT", "MATCHED", "THEN")) {
if (readIf("INSERT")) {
Insert insertCommand = new Insert(session);
insertCommand.setTable(command.getTargetTable());
parseInsertGivenTable(insertCommand, command.getTargetTable());
command.setInsertCommand(insertCommand);
}
}
setSQL(command, "MERGE", start);
// build and prepare the targetMatchQuery ready to test each rows
// existence in the target table (using source row to match)
StringBuilder targetMatchQuerySQL = new StringBuilder(
"SELECT _ROWID_ FROM " + command.getTargetTable().getName());
if (command.getTargetTableFilter().getTableAlias() != null) {
targetMatchQuerySQL.append(" AS ").append(command.getTargetTableFilter().getTableAlias());
}
targetMatchQuerySQL
.append(" WHERE ").append(command.getOnCondition().getSQL());
command.setTargetMatchQuery(
(Select) parse(targetMatchQuerySQL.toString()));
return command;
}
private Insert parseInsert() {
Insert command = new Insert(session);
currentPrepared = command;
if (database.getMode().onDuplicateKeyUpdate && readIf("IGNORE")) {
command.setIgnore(true);
}
read("INTO");
Table table = readTableOrView();
command.setTable(table);
Insert returnedCommand = parseInsertGivenTable(command, table);
if (returnedCommand != null) {
return returnedCommand;
}
if (database.getMode().onDuplicateKeyUpdate) {
if (readIf("ON")) {
read("DUPLICATE");
read("KEY");
read("UPDATE");
do {
Column column = parseColumn(table);
read("=");
Expression expression;
if (readIf("DEFAULT")) {
expression = ValueExpression.getDefault();
} else {
expression = readExpression();
}
command.addAssignmentForDuplicate(column, expression);
} while (readIf(","));
}
}
if (database.getMode().isolationLevelInSelectOrInsertStatement) {
parseIsolationClause();
}
return command;
}
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;
}
/**
* MySQL compatibility. REPLACE is similar to MERGE.
*/
private Replace parseReplace() {
Replace command = new Replace(session);
currentPrepared = command;
read("INTO");
Table table = readTableOrView();
command.setTable(table);
if (readIf("(")) {
if (isSelect()) {
command.setQuery(parseSelect());
read(")");
return command;
}
Column[] columns = parseColumnList(table);
command.setColumns(columns);
}
if (readIf("VALUES")) {
do {
ArrayList<Expression> values = New.arrayList();
read("(");
if (!readIf(")")) {
do {
if (readIf("DEFAULT")) {
values.add(null);
} else {
values.add(readExpression());
}
} while (readIfMore(false));
}
command.addRow(values.toArray(new Expression[0]));
} while (readIf(","));
} else {
command.setQuery(parseSelect());
}
return command;
}
private TableFilter readTableFilter() {
Table table;
String alias = null;
if (readIf("(")) {
if (isSelect()) {
Query query = parseSelectUnion();
read(")");
query.setParameterList(new ArrayList<>(parameters));
query.init();
Session s;
if (createView != null) {
s = database.getSystemSession();
} else {
s = session;
}
alias = session.getNextSystemIdentifier(sqlCommand);
table = TableView.createTempView(s, session.getUser(), alias,
query, currentSelect);
} else {
TableFilter top;
top = readTableFilter();
top = readJoin(top);
read(")");
alias = readFromAlias(null);
if (alias != null) {
top.setAlias(alias);
ArrayList<String> derivedColumnNames = readDerivedColumnNames();
if (derivedColumnNames != null) {
top.setDerivedColumns(derivedColumnNames);
}
}
return top;
}
} else if (readIf("VALUES")) {
table = parseValuesTable(0).getTable();
} else {
String tableName = readIdentifierWithSchema(null);
Schema schema = getSchema();
boolean foundLeftBracket = readIf("(");
if (foundLeftBracket && readIf("INDEX")) {
// Sybase compatibility with
// "select * from test (index table1_index)"
readIdentifierWithSchema(null);
read(")");
foundLeftBracket = false;
}
if (foundLeftBracket) {
Schema mainSchema = database.getSchema(Constants.SCHEMA_MAIN);
if (equalsToken(tableName, RangeTable.NAME)
|| equalsToken(tableName, RangeTable.ALIAS)) {
Expression min = readExpression();
read(",");
Expression max = readExpression();
if (readIf(",")) {
Expression step = readExpression();
read(")");
table = new RangeTable(mainSchema, min, max, step,
false);
} else {
read(")");
table = new RangeTable(mainSchema, min, max, false);
}
} else {
Expression expr = readFunction(schema, tableName);
if (!(expr instanceof FunctionCall)) {
throw getSyntaxError();
}
FunctionCall call = (FunctionCall) expr;
if (!call.isDeterministic()) {
recompileAlways = true;
}
table = new FunctionTable(mainSchema, session, expr, call);
}
} else if (equalsToken("DUAL", tableName)) {
table = getDualTable(false);
} else if (database.getMode().sysDummy1 &&
equalsToken("SYSDUMMY1", tableName)) {
table = getDualTable(false);
} else {
table = readTableOrView(tableName);
}
}
ArrayList<String> derivedColumnNames = null;
IndexHints indexHints = null;
// for backward compatibility, handle case where USE is a table alias
if (readIf("USE")) {
if (readIf("INDEX")) {
indexHints = parseIndexHints(table);
} else {
alias = "USE";
derivedColumnNames = readDerivedColumnNames();
}
} else {
alias = readFromAlias(alias);
if (alias != null) {
derivedColumnNames = readDerivedColumnNames();
// if alias present, a second chance to parse index hints
if (readIf("USE")) {
read("INDEX");
indexHints = parseIndexHints(table);
}
}
}
// inherit alias for CTE as views from table name
if (table.isView() && table.isTableExpression() && alias == null) {
alias = table.getName();
}
TableFilter filter = new TableFilter(session, table, alias, rightsChecked,
currentSelect, orderInFrom++, indexHints);
if (derivedColumnNames != null) {
filter.setDerivedColumns(derivedColumnNames);
}
return filter;
}
private IndexHints parseIndexHints(Table table) {
if (table == null) {
throw getSyntaxError();
}
read("(");
LinkedHashSet<String> indexNames = new LinkedHashSet<>();
if (!readIf(")")) {
do {
String indexName = readIdentifierWithSchema();
Index index = table.getIndex(indexName);
indexNames.add(index.getName());
} while (readIfMore(true));
}
return IndexHints.createUseIndexHints(indexNames);
}
private String readFromAlias(String alias, List<String> excludeIdentifiers) {
if (readIf("AS")) {
alias = readAliasIdentifier();
} else if (currentTokenType == IDENTIFIER && !isTokenInList(excludeIdentifiers)) {
alias = readAliasIdentifier();
}
return alias;
}
private String readFromAlias(String alias) {
// left and right are not keywords (because they are functions as
// well)
List<String> excludeIdentifiers = Arrays.asList("LEFT", "RIGHT", "FULL");
return readFromAlias(alias, excludeIdentifiers);
}
private ArrayList<String> readDerivedColumnNames() {
if (readIf("(")) {
ArrayList<String> derivedColumnNames = New.arrayList();
do {
derivedColumnNames.add(readAliasIdentifier());
} while (readIfMore(true));
return derivedColumnNames;
}
return null;
}
private Prepared parseTruncate() {
read("TABLE");
Table table = readTableOrView();
TruncateTable command = new TruncateTable(session);
command.setTable(table);
return command;
}
private boolean readIfExists(boolean ifExists) {
if (readIf("IF")) {
read("EXISTS");
ifExists = true;
}
return ifExists;
}
private Prepared parseComment() {
int type = 0;
read("ON");
boolean column = false;
if (readIf("TABLE") || readIf("VIEW")) {
type = DbObject.TABLE_OR_VIEW;
} else if (readIf("COLUMN")) {
column = true;
type = DbObject.TABLE_OR_VIEW;
} else if (readIf("CONSTANT")) {
type = DbObject.CONSTANT;
} else if (readIf("CONSTRAINT")) {
type = DbObject.CONSTRAINT;
} else if (readIf("ALIAS")) {
type = DbObject.FUNCTION_ALIAS;
} else if (readIf("INDEX")) {
type = DbObject.INDEX;
} else if (readIf("ROLE")) {
type = DbObject.ROLE;
} else if (readIf("SCHEMA")) {
type = DbObject.SCHEMA;
} else if (readIf("SEQUENCE")) {
type = DbObject.SEQUENCE;
} else if (readIf("TRIGGER")) {
type = DbObject.TRIGGER;
} else if (readIf("USER")) {
type = DbObject.USER;
} else if (readIf("DOMAIN")) {
type = DbObject.USER_DATATYPE;
} else {
throw getSyntaxError();
}
SetComment command = new SetComment(session);
String objectName;
if (column) {
// can't use readIdentifierWithSchema() because
// it would not read schema.table.column correctly
// if the db name is equal to the schema name
ArrayList<String> list = New.arrayList();
do {
list.add(readUniqueIdentifier());
} while (readIf("."));
schemaName = session.getCurrentSchemaName();
if (list.size() == 4) {
if (!equalsToken(database.getShortName(), list.remove(0))) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"database name");
}
}
if (list.size() == 3) {
schemaName = list.remove(0);
}
if (list.size() != 2) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"table.column");
}
objectName = list.get(0);
command.setColumn(true);
command.setColumnName(list.get(1));
} else {
objectName = readIdentifierWithSchema();
}
command.setSchemaName(schemaName);
command.setObjectName(objectName);
command.setObjectType(type);
read("IS");
command.setCommentExpression(readExpression());
return command;
}
private Prepared parseDrop() {
if (readIf("TABLE")) {
boolean ifExists = readIfExists(false);
String tableName = readIdentifierWithSchema();
DropTable command = new DropTable(session, getSchema());
command.setTableName(tableName);
while (readIf(",")) {
tableName = readIdentifierWithSchema();
DropTable next = new DropTable(session, getSchema());
next.setTableName(tableName);
command.addNextDropTable(next);
}
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
if (readIf("CASCADE")) {
command.setDropAction(ConstraintActionType.CASCADE);
readIf("CONSTRAINTS");
} else if (readIf("RESTRICT")) {
command.setDropAction(ConstraintActionType.RESTRICT);
} else if (readIf("IGNORE")) {
command.setDropAction(ConstraintActionType.SET_DEFAULT);
}
return command;
} else if (readIf("INDEX")) {
boolean ifExists = readIfExists(false);
String indexName = readIdentifierWithSchema();
DropIndex command = new DropIndex(session, getSchema());
command.setIndexName(indexName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
//Support for MySQL: DROP INDEX index_name ON tbl_name
if (readIf("ON")) {
readIdentifierWithSchema();
}
return command;
} else if (readIf("USER")) {
boolean ifExists = readIfExists(false);
DropUser command = new DropUser(session);
command.setUserName(readUniqueIdentifier());
ifExists = readIfExists(ifExists);
readIf("CASCADE");
command.setIfExists(ifExists);
return command;
} else if (readIf("SEQUENCE")) {
boolean ifExists = readIfExists(false);
String sequenceName = readIdentifierWithSchema();
DropSequence command = new DropSequence(session, getSchema());
command.setSequenceName(sequenceName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
} else if (readIf("CONSTANT")) {
boolean ifExists = readIfExists(false);
String constantName = readIdentifierWithSchema();
DropConstant command = new DropConstant(session, getSchema());
command.setConstantName(constantName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
} else if (readIf("TRIGGER")) {
boolean ifExists = readIfExists(false);
String triggerName = readIdentifierWithSchema();
DropTrigger command = new DropTrigger(session, getSchema());
command.setTriggerName(triggerName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
} else if (readIf("VIEW")) {
boolean ifExists = readIfExists(false);
String viewName = readIdentifierWithSchema();
DropView command = new DropView(session, getSchema());
command.setViewName(viewName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
ConstraintActionType dropAction = parseCascadeOrRestrict();
if (dropAction != null) {
command.setDropAction(dropAction);
}
return command;
} else if (readIf("ROLE")) {
boolean ifExists = readIfExists(false);
DropRole command = new DropRole(session);
command.setRoleName(readUniqueIdentifier());
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
} else if (readIf("ALIAS")) {
boolean ifExists = readIfExists(false);
String aliasName = readIdentifierWithSchema();
DropFunctionAlias command = new DropFunctionAlias(session,
getSchema());
command.setAliasName(aliasName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
} else if (readIf("SCHEMA")) {
boolean ifExists = readIfExists(false);
DropSchema command = new DropSchema(session);
command.setSchemaName(readUniqueIdentifier());
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
if (readIf("CASCADE")) {
command.setDropAction(ConstraintActionType.CASCADE);
} else if (readIf("RESTRICT")) {
command.setDropAction(ConstraintActionType.RESTRICT);
}
return command;
} else if (readIf("ALL")) {
read("OBJECTS");
DropDatabase command = new DropDatabase(session);
command.setDropAllObjects(true);
if (readIf("DELETE")) {
read("FILES");
command.setDeleteFiles(true);
}
return command;
} else if (readIf("DOMAIN")) {
return parseDropUserDataType();
} else if (readIf("TYPE")) {
return parseDropUserDataType();
} else if (readIf("DATATYPE")) {
return parseDropUserDataType();
} else if (readIf("AGGREGATE")) {
return parseDropAggregate();
} else if (readIf("SYNONYM")) {
boolean ifExists = readIfExists(false);
String synonymName = readIdentifierWithSchema();
DropSynonym command = new DropSynonym(session, getSchema());
command.setSynonymName(synonymName);
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
}
throw getSyntaxError();
}
private DropUserDataType parseDropUserDataType() {
boolean ifExists = readIfExists(false);
DropUserDataType command = new DropUserDataType(session);
command.setTypeName(readUniqueIdentifier());
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
}
private DropAggregate parseDropAggregate() {
boolean ifExists = readIfExists(false);
DropAggregate command = new DropAggregate(session);
command.setName(readUniqueIdentifier());
ifExists = readIfExists(ifExists);
command.setIfExists(ifExists);
return command;
}
private TableFilter readJoin(TableFilter top) {
TableFilter last = top;
while (true) {
TableFilter join;
if (readIf("RIGHT")) {
readIf("OUTER");
read("JOIN");
// the right hand side is the 'inner' table usually
join = readTableFilter();
join = readJoin(join);
Expression on = null;
if (readIf("ON")) {
on = readExpression();
}
addJoin(join, top, true, on);
top = join;
} else if (readIf("LEFT")) {
readIf("OUTER");
read("JOIN");
join = readTableFilter();
join = readJoin(join);
Expression on = null;
if (readIf("ON")) {
on = readExpression();
}
addJoin(top, join, true, on);
} else if (readIf("FULL")) {
throw getSyntaxError();
} else if (readIf("INNER")) {
read("JOIN");
join = readTableFilter();
top = readJoin(top);
Expression on = null;
if (readIf("ON")) {
on = readExpression();
}
addJoin(top, join, false, on);
} else if (readIf("JOIN")) {
join = readTableFilter();
top = readJoin(top);
Expression on = null;
if (readIf("ON")) {
on = readExpression();
}
addJoin(top, join, false, on);
} else if (readIf("CROSS")) {
read("JOIN");
join = readTableFilter();
addJoin(top, join, false, null);
} else if (readIf("NATURAL")) {
read("JOIN");
join = readTableFilter();
Column[] tableCols = last.getTable().getColumns();
Column[] joinCols = join.getTable().getColumns();
String tableSchema = last.getTable().getSchema().getName();
String joinSchema = join.getTable().getSchema().getName();
Expression on = null;
for (Column tc : tableCols) {
String tableColumnName = tc.getName();
for (Column c : joinCols) {
String joinColumnName = c.getName();
if (equalsToken(tableColumnName, joinColumnName)) {
join.addNaturalJoinColumn(c);
Expression tableExpr = new ExpressionColumn(
database, tableSchema,
last.getTableAlias(), tableColumnName);
Expression joinExpr = new ExpressionColumn(
database, joinSchema, join.getTableAlias(),
joinColumnName);
Expression equal = new Comparison(session,
Comparison.EQUAL, tableExpr, joinExpr);
if (on == null) {
on = equal;
} else {
on = new ConditionAndOr(ConditionAndOr.AND, on,
equal);
}
}
}
}
addJoin(top, join, false, on);
} else {
break;
}
last = join;
}
return top;
}
/**
* Add one join to another. This method creates nested join between them if
* required.
*
* @param top parent join
* @param join child join
* @param outer if child join is an outer join
* @param on the join condition
* @see TableFilter#addJoin(TableFilter, boolean, Expression)
*/
private void addJoin(TableFilter top, TableFilter join, boolean outer, Expression on) {
if (join.getJoin() != null) {
String joinTable = Constants.PREFIX_JOIN + parseIndex;
TableFilter n = new TableFilter(session, getDualTable(true),
joinTable, rightsChecked, currentSelect, join.getOrderInFrom(),
null);
n.setNestedJoin(join);
join = n;
}
top.addJoin(join, outer, on);
}
private Prepared parseExecute() {
ExecuteProcedure command = new ExecuteProcedure(session);
String procedureName = readAliasIdentifier();
Procedure p = session.getProcedure(procedureName);
if (p == null) {
throw DbException.get(ErrorCode.FUNCTION_ALIAS_NOT_FOUND_1,
procedureName);
}
command.setProcedure(p);
if (readIf("(")) {
for (int i = 0;; i++) {
command.setExpression(i, readExpression());
if (readIf(")")) {
break;
}
read(",");
}
}
return command;
}
private DeallocateProcedure parseDeallocate() {
readIf("PLAN");
String procedureName = readAliasIdentifier();
DeallocateProcedure command = new DeallocateProcedure(session);
command.setProcedureName(procedureName);
return command;
}
private Explain parseExplain() {
Explain command = new Explain(session);
if (readIf("ANALYZE")) {
command.setExecuteCommand(true);
} else {
if (readIf("PLAN")) {
readIf("FOR");
}
}
if (isToken("SELECT") || isToken("FROM") || isToken("(") || isToken("WITH")) {
Query query = parseSelect();
query.setNeverLazy(true);
command.setCommand(query);
} else if (readIf("DELETE")) {
command.setCommand(parseDelete());
} else if (readIf("UPDATE")) {
command.setCommand(parseUpdate());
} else if (readIf("INSERT")) {
command.setCommand(parseInsert());
} else if (readIf("MERGE")) {
command.setCommand(parseMerge());
} else {
throw getSyntaxError();
}
return command;
}
private Query parseSelect() {
Query command = null;
int paramIndex = parameters.size();
command = parseSelectUnion();
ArrayList<Parameter> params = New.arrayList();
for (int i = paramIndex, size = parameters.size(); i < size; i++) {
params.add(parameters.get(i));
}
command.setParameterList(params);
command.init();
return command;
}
private Prepared parseWithStatementOrQuery() {
int paramIndex = parameters.size();
Prepared command = parseWith();
ArrayList<Parameter> params = New.arrayList();
for (int i = paramIndex, size = parameters.size(); i < size; i++) {
params.add(parameters.get(i));
}
command.setParameterList(params);
if (command instanceof Query) {
Query query = (Query) command;
query.init();
}
return command;
}
private Query parseSelectUnion() {
int start = lastParseIndex;
Query command = parseSelectSub();
return parseSelectUnionExtension(command, start, false);
}
private Query parseSelectUnionExtension(Query command, int start,
boolean unionOnly) {
while (true) {
if (readIf("UNION")) {
SelectUnion union = new SelectUnion(session, command);
if (readIf("ALL")) {
union.setUnionType(SelectUnion.UnionType.UNION_ALL);
} else {
readIf("DISTINCT");
union.setUnionType(SelectUnion.UnionType.UNION);
}
union.setRight(parseSelectSub());
command = union;
} else if (readIf("MINUS") || readIf("EXCEPT")) {
SelectUnion union = new SelectUnion(session, command);
union.setUnionType(SelectUnion.UnionType.EXCEPT);
union.setRight(parseSelectSub());
command = union;
} else if (readIf("INTERSECT")) {
SelectUnion union = new SelectUnion(session, command);
union.setUnionType(SelectUnion.UnionType.INTERSECT);
union.setRight(parseSelectSub());
command = union;
} else {
break;
}
}
if (!unionOnly) {
parseEndOfQuery(command);
}
setSQL(command, null, start);
return command;
}
private void parseEndOfQuery(Query command) {
if (readIf("ORDER")) {
read("BY");
Select oldSelect = currentSelect;
if (command instanceof Select) {
currentSelect = (Select) command;
}
ArrayList<SelectOrderBy> orderList = New.arrayList();
do {
boolean canBeNumber = true;
if (readIf("=")) {
canBeNumber = false;
}
SelectOrderBy order = new SelectOrderBy();
Expression expr = readExpression();
if (canBeNumber && expr instanceof ValueExpression &&
expr.getType() == Value.INT) {
order.columnIndexExpr = expr;
} else if (expr instanceof Parameter) {
recompileAlways = true;
order.columnIndexExpr = expr;
} else {
order.expression = expr;
}
if (readIf("DESC")) {
order.descending = true;
} else {
readIf("ASC");
}
if (readIf("NULLS")) {
if (readIf("FIRST")) {
order.nullsFirst = true;
} else {
read("LAST");
order.nullsLast = true;
}
}
orderList.add(order);
} while (readIf(","));
command.setOrder(orderList);
currentSelect = oldSelect;
}
// make sure aggregate functions will not work here
Select temp = currentSelect;
currentSelect = null;
// http://sqlpro.developpez.com/SQL2008/
if (readIf("OFFSET")) {
command.setOffset(readExpression().optimize(session));
if (!readIf("ROW")) {
readIf("ROWS");
}
}
if (readIf("FETCH")) {
if (!readIf("FIRST")) {
read("NEXT");
}
if (readIf("ROW")) {
command.setLimit(ValueExpression.get(ValueInt.get(1)));
} else {
Expression limit = readExpression().optimize(session);
command.setLimit(limit);
if (!readIf("ROW")) {
read("ROWS");
}
}
read("ONLY");
}
currentSelect = temp;
if (readIf("LIMIT")) {
temp = currentSelect;
// make sure aggregate functions will not work here
currentSelect = null;
Expression limit = readExpression().optimize(session);
command.setLimit(limit);
if (readIf("OFFSET")) {
Expression offset = readExpression().optimize(session);
command.setOffset(offset);
} else if (readIf(",")) {
// MySQL: [offset, ] rowcount
Expression offset = limit;
limit = readExpression().optimize(session);
command.setOffset(offset);
command.setLimit(limit);
}
if (readIf("SAMPLE_SIZE")) {
Expression sampleSize = readExpression().optimize(session);
command.setSampleSize(sampleSize);
}
currentSelect = temp;
}
if (readIf("FOR")) {
if (readIf("UPDATE")) {
if (readIf("OF")) {
do {
readIdentifierWithSchema();
} while (readIf(","));
} else if (readIf("NOWAIT")) {
// TODO parser: select for update nowait: should not wait
}
command.setForUpdate(true);
} else if (readIf("READ") || readIf("FETCH")) {
read("ONLY");
}
}
if (database.getMode().isolationLevelInSelectOrInsertStatement) {
parseIsolationClause();
}
}
/**
* DB2 isolation clause
*/
private void parseIsolationClause() {
if (readIf("WITH")) {
if (readIf("RR") || readIf("RS")) {
// concurrent-access-resolution clause
if (readIf("USE")) {
read("AND");
read("KEEP");
if (readIf("SHARE") || readIf("UPDATE") ||
readIf("EXCLUSIVE")) {
// ignore
}
read("LOCKS");
}
} else if (readIf("CS") || readIf("UR")) {
// ignore
}
}
}
private Query parseSelectSub() {
if (readIf("(")) {
Query command = parseSelectUnion();
read(")");
return command;
}
if (readIf("WITH")) {
Query query = null;
try {
query = (Query) parseWith();
} catch (ClassCastException e) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1,
"WITH statement supports only SELECT (query) in this context");
}
// recursive can not be lazy
query.setNeverLazy(true);
return query;
}
return parseSelectSimple();
}
private void parseSelectSimpleFromPart(Select command) {
do {
TableFilter filter = readTableFilter();
parseJoinTableFilter(filter, command);
} while (readIf(","));
// Parser can reorder joined table filters, need to explicitly sort them
// to get the order as it was in the original query.
if (session.isForceJoinOrder()) {
sortTableFilters(command.getTopFilters());
}
}
private static void sortTableFilters(ArrayList<TableFilter> filters) {
if (filters.size() < 2) {
return;
}
// Most probably we are already sorted correctly.
boolean sorted = true;
TableFilter prev = filters.get(0);
for (int i = 1; i < filters.size(); i++) {
TableFilter next = filters.get(i);
if (compareTableFilters(prev, next) > 0) {
sorted = false;
break;
}
prev = next;
}
// If not, then sort manually.
if (!sorted) {
Collections.sort(filters, TABLE_FILTER_COMPARATOR);
}
}
/**
* Find out which of the table filters appears first in the "from" clause.
*
* @param o1 the first table filter
* @param o2 the second table filter
* @return -1 if o1 appears first, and 1 if o2 appears first
*/
static int compareTableFilters(TableFilter o1, TableFilter o2) {
assert o1.getOrderInFrom() != o2.getOrderInFrom();
return o1.getOrderInFrom() > o2.getOrderInFrom() ? 1 : -1;
}
private void parseJoinTableFilter(TableFilter top, final Select command) {
top = readJoin(top);
command.addTableFilter(top, true);
boolean isOuter = false;
while (true) {
TableFilter n = top.getNestedJoin();
if (n != null) {
n.visit(new TableFilterVisitor() {
@Override
public void accept(TableFilter f) {
command.addTableFilter(f, false);
}
});
}
TableFilter join = top.getJoin();
if (join == null) {
break;
}
isOuter = isOuter | join.isJoinOuter();
if (isOuter) {
command.addTableFilter(join, false);
} else {
// make flat so the optimizer can work better
Expression on = join.getJoinCondition();
if (on != null) {
command.addCondition(on);
}
join.removeJoinCondition();
top.removeJoin();
command.addTableFilter(join, true);
}
top = join;
}
}
private void parseSelectSimpleSelectPart(Select command) {
Select temp = currentSelect;
// make sure aggregate functions will not work in TOP and LIMIT
currentSelect = null;
if (readIf("TOP")) {
// can't read more complex expressions here because
// SELECT TOP 1 +? A FROM TEST could mean
// SELECT TOP (1+?) A FROM TEST or
// SELECT TOP 1 (+?) AS A FROM TEST
Expression limit = readTerm().optimize(session);
command.setLimit(limit);
} else if (readIf("LIMIT")) {
Expression offset = readTerm().optimize(session);
command.setOffset(offset);
Expression limit = readTerm().optimize(session);
command.setLimit(limit);
}
currentSelect = temp;
if (readIf("DISTINCT")) {
command.setDistinct(true);
} else {
readIf("ALL");
}
ArrayList<Expression> expressions = New.arrayList();
do {
if (readIf("*")) {
expressions.add(new Wildcard(null, null));
} else {
Expression expr = readExpression();
if (readIf("AS") || currentTokenType == IDENTIFIER) {
String alias = readAliasIdentifier();
boolean aliasColumnName = database.getSettings().aliasColumnName;
aliasColumnName |= database.getMode().aliasColumnName;
expr = new Alias(expr, alias, aliasColumnName);
}
expressions.add(expr);
}
} while (readIf(","));
command.setExpressions(expressions);
}
private Select parseSelectSimple() {
boolean fromFirst;
if (readIf("SELECT")) {
fromFirst = false;
} else if (readIf("FROM")) {
fromFirst = true;
} else {
throw getSyntaxError();
}
Select command = new Select(session);
int start = lastParseIndex;
Select oldSelect = currentSelect;
currentSelect = command;
currentPrepared = command;
if (fromFirst) {
parseSelectSimpleFromPart(command);
read("SELECT");
parseSelectSimpleSelectPart(command);
} else {
parseSelectSimpleSelectPart(command);
if (!readIf("FROM")) {
// select without FROM: convert to SELECT ... FROM
// SYSTEM_RANGE(1,1)
Table dual = getDualTable(false);
TableFilter filter = new TableFilter(session, dual, null,
rightsChecked, currentSelect, 0,
null);
command.addTableFilter(filter, true);
} else {
parseSelectSimpleFromPart(command);
}
}
if (readIf("WHERE")) {
Expression condition = readExpression();
command.addCondition(condition);
}
// the group by is read for the outer select (or not a select)
// so that columns that are not grouped can be used
currentSelect = oldSelect;
if (readIf("GROUP")) {
read("BY");
command.setGroupQuery();
ArrayList<Expression> list = New.arrayList();
do {
Expression expr = readExpression();
list.add(expr);
} while (readIf(","));
command.setGroupBy(list);
}
currentSelect = command;
if (readIf("HAVING")) {
command.setGroupQuery();
Expression condition = readExpression();
command.setHaving(condition);
}
command.setParameterList(parameters);
currentSelect = oldSelect;
setSQL(command, "SELECT", start);
return command;
}
private Table getDualTable(boolean noColumns) {
Schema main = database.findSchema(Constants.SCHEMA_MAIN);
Expression one = ValueExpression.get(ValueLong.get(1));
return new RangeTable(main, one, one, noColumns);
}
private void setSQL(Prepared command, String start, int startIndex) {
String sql = originalSQL.substring(startIndex, lastParseIndex).trim();
if (start != null) {
sql = start + " " + sql;
}
command.setSQL(sql);
}
private Expression readExpression() {
Expression r = readAnd();
while (readIf("OR")) {
r = new ConditionAndOr(ConditionAndOr.OR, r, readAnd());
}
return r;
}
private Expression readAnd() {
Expression r = readCondition();
while (readIf("AND")) {
r = new ConditionAndOr(ConditionAndOr.AND, r, readCondition());
}
return r;
}
private Expression readCondition() {
if (readIf("NOT")) {
return new ConditionNot(readCondition());
}
if (readIf("EXISTS")) {
read("(");
Query query = parseSelect();
// can not reduce expression because it might be a union except
// query with distinct
read(")");
return new ConditionExists(query);
}
if (readIf("INTERSECTS")) {
read("(");
Expression r1 = readConcat();
read(",");
Expression r2 = readConcat();
read(")");
return new Comparison(session, Comparison.SPATIAL_INTERSECTS, r1,
r2);
}
Expression r = readConcat();
while (true) {
// special case: NOT NULL is not part of an expression (as in CREATE
// TABLE TEST(ID INT DEFAULT 0 NOT NULL))
int backup = parseIndex;
boolean not = false;
if (readIf("NOT")) {
not = true;
if (isToken("NULL")) {
// this really only works for NOT NULL!
parseIndex = backup;
currentToken = "NOT";
break;
}
}
if (readIf("LIKE")) {
Expression b = readConcat();
Expression esc = null;
if (readIf("ESCAPE")) {
esc = readConcat();
}
recompileAlways = true;
r = new CompareLike(database, r, b, esc, false);
} else if (readIf("ILIKE")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X", Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
Expression b = readConcat();
Expression esc = null;
if (readIf("ESCAPE")) {
esc = readConcat();
}
recompileAlways = true;
r = new CompareLike(database, r, b, esc, false);
} else if (readIf("REGEXP")) {
Expression b = readConcat();
recompileAlways = true;
r = new CompareLike(database, r, b, null, true);
} else if (readIf("IS")) {
if (readIf("NOT")) {
if (readIf("NULL")) {
r = new Comparison(session, Comparison.IS_NOT_NULL, r,
null);
} else if (readIf("DISTINCT")) {
read("FROM");
r = new Comparison(session, Comparison.EQUAL_NULL_SAFE,
r, readConcat());
} else {
r = new Comparison(session,
Comparison.NOT_EQUAL_NULL_SAFE, r, readConcat());
}
} else if (readIf("NULL")) {
r = new Comparison(session, Comparison.IS_NULL, r, null);
} else if (readIf("DISTINCT")) {
read("FROM");
r = new Comparison(session, Comparison.NOT_EQUAL_NULL_SAFE,
r, readConcat());
} else {
r = new Comparison(session, Comparison.EQUAL_NULL_SAFE, r,
readConcat());
}
} else if (readIf("IN")) {
read("(");
if (readIf(")")) {
if (database.getMode().prohibitEmptyInPredicate) {
throw getSyntaxError();
}
r = ValueExpression.get(ValueBoolean.FALSE);
} else {
if (isSelect()) {
Query query = parseSelect();
// can not be lazy because we have to call
// method ResultInterface.containsDistinct
// which is not supported for lazy execution
query.setNeverLazy(true);
r = new ConditionInSelect(database, r, query, false,
Comparison.EQUAL);
} else {
ArrayList<Expression> v = New.arrayList();
Expression last;
do {
last = readExpression();
v.add(last);
} while (readIf(","));
if (v.size() == 1 && (last instanceof Subquery)) {
Subquery s = (Subquery) last;
Query q = s.getQuery();
r = new ConditionInSelect(database, r, q, false,
Comparison.EQUAL);
} else {
r = new ConditionIn(database, r, v);
}
}
read(")");
}
} else if (readIf("BETWEEN")) {
Expression low = readConcat();
read("AND");
Expression high = readConcat();
Expression condLow = new Comparison(session,
Comparison.SMALLER_EQUAL, low, r);
Expression condHigh = new Comparison(session,
Comparison.BIGGER_EQUAL, high, r);
r = new ConditionAndOr(ConditionAndOr.AND, condLow, condHigh);
} else {
int compareType = getCompareType(currentTokenType);
if (compareType < 0) {
break;
}
read();
if (readIf("ALL")) {
read("(");
Query query = parseSelect();
r = new ConditionInSelect(database, r, query, true,
compareType);
read(")");
} else if (readIf("ANY") || readIf("SOME")) {
read("(");
if (currentTokenType == PARAMETER && compareType == 0) {
Parameter p = readParameter();
r = new ConditionInParameter(database, r, p);
} else {
Query query = parseSelect();
r = new ConditionInSelect(database, r, query, false,
compareType);
}
read(")");
} else {
Expression right = readConcat();
if (SysProperties.OLD_STYLE_OUTER_JOIN &&
readIf("(") && readIf("+") && readIf(")")) {
// support for a subset of old-fashioned Oracle outer
// join with (+)
if (r instanceof ExpressionColumn &&
right instanceof ExpressionColumn) {
ExpressionColumn leftCol = (ExpressionColumn) r;
ExpressionColumn rightCol = (ExpressionColumn) right;
ArrayList<TableFilter> filters = currentSelect
.getTopFilters();
for (TableFilter f : filters) {
while (f != null) {
leftCol.mapColumns(f, 0);
rightCol.mapColumns(f, 0);
f = f.getJoin();
}
}
TableFilter leftFilter = leftCol.getTableFilter();
TableFilter rightFilter = rightCol.getTableFilter();
r = new Comparison(session, compareType, r, right);
if (leftFilter != null && rightFilter != null) {
int idx = filters.indexOf(rightFilter);
if (idx >= 0) {
filters.remove(idx);
leftFilter.addJoin(rightFilter, true, r);
} else {
rightFilter.mapAndAddFilter(r);
}
r = ValueExpression.get(ValueBoolean.TRUE);
}
}
} else {
r = new Comparison(session, compareType, r, right);
}
}
}
if (not) {
r = new ConditionNot(r);
}
}
return r;
}
private Expression readConcat() {
Expression r = readSum();
while (true) {
if (readIf("||")) {
r = new Operation(OpType.CONCAT, r, readSum());
} else if (readIf("~")) {
if (readIf("*")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X",
Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
}
r = new CompareLike(database, r, readSum(), null, true);
} else if (readIf("!~")) {
if (readIf("*")) {
Function function = Function.getFunction(database, "CAST");
function.setDataType(new Column("X",
Value.STRING_IGNORECASE));
function.setParameter(0, r);
r = function;
}
r = new ConditionNot(new CompareLike(database, r, readSum(),
null, true));
} else {
return r;
}
}
}
private Expression readSum() {
Expression r = readFactor();
while (true) {
if (readIf("+")) {
r = new Operation(OpType.PLUS, r, readFactor());
} else if (readIf("-")) {
r = new Operation(OpType.MINUS, r, readFactor());
} else {
return r;
}
}
}
private Expression readFactor() {
Expression r = readTerm();
while (true) {
if (readIf("*")) {
r = new Operation(OpType.MULTIPLY, r, readTerm());
} else if (readIf("/")) {
r = new Operation(OpType.DIVIDE, r, readTerm());
} else if (readIf("%")) {
r = new Operation(OpType.MODULUS, r, readTerm());
} else {
return r;
}
}
}
private Expression readAggregate(AggregateType aggregateType, String aggregateName) {
if (currentSelect == null) {
throw getSyntaxError();
}
currentSelect.setGroupQuery();
Aggregate r;
if (aggregateType == AggregateType.COUNT) {
if (readIf("*")) {
r = new Aggregate(AggregateType.COUNT_ALL, null, currentSelect,
false);
} else {
boolean distinct = readIf("DISTINCT");
Expression on = readExpression();
if (on instanceof Wildcard && !distinct) {
// PostgreSQL compatibility: count(t.*)
r = new Aggregate(AggregateType.COUNT_ALL, null, currentSelect,
false);
} else {
r = new Aggregate(AggregateType.COUNT, on, currentSelect,
distinct);
}
}
} else if (aggregateType == AggregateType.GROUP_CONCAT) {
boolean distinct = readIf("DISTINCT");
if (equalsToken("GROUP_CONCAT", aggregateName)) {
r = new Aggregate(AggregateType.GROUP_CONCAT,
readExpression(), currentSelect, distinct);
if (readIf("ORDER")) {
read("BY");
r.setGroupConcatOrder(parseSimpleOrderList());
}
if (readIf("SEPARATOR")) {
r.setGroupConcatSeparator(readExpression());
}
} else if (equalsToken("STRING_AGG", aggregateName)) {
// PostgreSQL compatibility: string_agg(expression, delimiter)
r = new Aggregate(AggregateType.GROUP_CONCAT,
readExpression(), currentSelect, distinct);
read(",");
r.setGroupConcatSeparator(readExpression());
if (readIf("ORDER")) {
read("BY");
r.setGroupConcatOrder(parseSimpleOrderList());
}
} else {
r = null;
}
} else if (aggregateType == AggregateType.ARRAY_AGG) {
boolean distinct = readIf("DISTINCT");
r = new Aggregate(AggregateType.ARRAY_AGG,
readExpression(), currentSelect, distinct);
if (readIf("ORDER")) {
read("BY");
r.setArrayAggOrder(parseSimpleOrderList());
}
} else {
boolean distinct = readIf("DISTINCT");
r = new Aggregate(aggregateType, readExpression(), currentSelect,
distinct);
}
read(")");
if (r != null && readIf("FILTER")) {
read("(");
read("WHERE");
Expression condition = readExpression();
read(")");
r.setFilterCondition(condition);
}
return r;
}
private ArrayList<SelectOrderBy> parseSimpleOrderList() {
ArrayList<SelectOrderBy> orderList = New.arrayList();
do {
SelectOrderBy order = new SelectOrderBy();
order.expression = readExpression();
if (readIf("DESC")) {
order.descending = true;
} else {
readIf("ASC");
}
orderList.add(order);
} while (readIf(","));
return orderList;
}
private JavaFunction readJavaFunction(Schema schema, String functionName) {
FunctionAlias functionAlias = null;
if (schema != null) {
functionAlias = schema.findFunction(functionName);
} else {
functionAlias = findFunctionAlias(session.getCurrentSchemaName(),
functionName);
}
if (functionAlias == null) {
throw DbException.get(ErrorCode.FUNCTION_NOT_FOUND_1, functionName);
}
Expression[] args;
ArrayList<Expression> argList = New.arrayList();
int numArgs = 0;
while (!readIf(")")) {
if (numArgs++ > 0) {
read(",");
}
argList.add(readExpression());
}
args = argList.toArray(new Expression[0]);
return new JavaFunction(functionAlias, args);
}
private JavaAggregate readJavaAggregate(UserAggregate aggregate) {
ArrayList<Expression> params = New.arrayList();
do {
params.add(readExpression());
} while (readIfMore(true));
Expression filterCondition;
if (readIf("FILTER")) {
read("(");
read("WHERE");
filterCondition = readExpression();
read(")");
} else {
filterCondition = null;
}
Expression[] list = params.toArray(new Expression[0]);
JavaAggregate agg = new JavaAggregate(aggregate, list, currentSelect, filterCondition);
currentSelect.setGroupQuery();
return agg;
}
private AggregateType getAggregateType(String name) {
if (!identifiersToUpper) {
// if not yet converted to uppercase, do it now
name = StringUtils.toUpperEnglish(name);
}
return Aggregate.getAggregateType(name);
}
private Expression readFunction(Schema schema, String name) {
if (schema != null) {
return readJavaFunction(schema, name);
}
AggregateType agg = getAggregateType(name);
if (agg != null) {
return readAggregate(agg, name);
}
Function function = Function.getFunction(database, name);
if (function == null) {
UserAggregate aggregate = database.findAggregate(name);
if (aggregate != null) {
return readJavaAggregate(aggregate);
}
return readJavaFunction(null, name);
}
switch (function.getFunctionType()) {
case Function.CAST: {
function.setParameter(0, readExpression());
read("AS");
Column type = parseColumnWithType(null);
function.setDataType(type);
read(")");
break;
}
case Function.CONVERT: {
if (database.getMode().swapConvertFunctionParameters) {
Column type = parseColumnWithType(null);
function.setDataType(type);
read(",");
function.setParameter(0, readExpression());
read(")");
} else {
function.setParameter(0, readExpression());
read(",");
Column type = parseColumnWithType(null);
function.setDataType(type);
read(")");
}
break;
}
case Function.EXTRACT: {
function.setParameter(0,
ValueExpression.get(ValueString.get(currentToken)));
read();
read("FROM");
function.setParameter(1, readExpression());
read(")");
break;
}
case Function.DATE_ADD:
case Function.DATE_DIFF: {
if (DateTimeFunctions.isDatePart(currentToken)) {
function.setParameter(0,
ValueExpression.get(ValueString.get(currentToken)));
read();
} else {
function.setParameter(0, readExpression());
}
read(",");
function.setParameter(1, readExpression());
read(",");
function.setParameter(2, readExpression());
read(")");
break;
}
case Function.SUBSTRING: {
// Different variants include:
// SUBSTRING(X,1)
// SUBSTRING(X,1,1)
// SUBSTRING(X FROM 1 FOR 1) -- Postgres
// SUBSTRING(X FROM 1) -- Postgres
// SUBSTRING(X FOR 1) -- Postgres
function.setParameter(0, readExpression());
if (readIf("FROM")) {
function.setParameter(1, readExpression());
if (readIf("FOR")) {
function.setParameter(2, readExpression());
}
} else if (readIf("FOR")) {
function.setParameter(1, ValueExpression.get(ValueInt.get(0)));
function.setParameter(2, readExpression());
} else {
read(",");
function.setParameter(1, readExpression());
if (readIf(",")) {
function.setParameter(2, readExpression());
}
}
read(")");
break;
}
case Function.POSITION: {
// can't read expression because IN would be read too early
function.setParameter(0, readConcat());
if (!readIf(",")) {
read("IN");
}
function.setParameter(1, readExpression());
read(")");
break;
}
case Function.TRIM: {
Expression space = null;
if (readIf("LEADING")) {
function = Function.getFunction(database, "LTRIM");
if (!readIf("FROM")) {
space = readExpression();
read("FROM");
}
} else if (readIf("TRAILING")) {
function = Function.getFunction(database, "RTRIM");
if (!readIf("FROM")) {
space = readExpression();
read("FROM");
}
} else if (readIf("BOTH")) {
if (!readIf("FROM")) {
space = readExpression();
read("FROM");
}
}
Expression p0 = readExpression();
if (readIf(",")) {
space = readExpression();
} else if (readIf("FROM")) {
space = p0;
p0 = readExpression();
}
function.setParameter(0, p0);
if (space != null) {
function.setParameter(1, space);
}
read(")");
break;
}
case Function.TABLE:
case Function.TABLE_DISTINCT: {
int i = 0;
ArrayList<Column> columns = New.arrayList();
do {
String columnName = readAliasIdentifier();
Column column = parseColumnWithType(columnName);
columns.add(column);
read("=");
function.setParameter(i, readExpression());
i++;
} while (readIfMore(true));
TableFunction tf = (TableFunction) function;
tf.setColumns(columns);
break;
}
case Function.ROW_NUMBER:
read(")");
read("OVER");
read("(");
read(")");
if (currentSelect == null && currentPrepared == null) {
throw getSyntaxError();
}
return new Rownum(currentSelect == null ? currentPrepared
: currentSelect);
default:
if (!readIf(")")) {
int i = 0;
do {
function.setParameter(i++, readExpression());
} while (readIfMore(true));
}
}
function.doneWithParameters();
return function;
}
private Expression readFunctionWithoutParameters(String name) {
if (readIf("(")) {
read(")");
}
if (database.isAllowBuiltinAliasOverride()) {
FunctionAlias functionAlias = database.getSchema(session.getCurrentSchemaName()).findFunction(name);
if (functionAlias != null) {
return new JavaFunction(functionAlias, new Expression[0]);
}
}
Function function = Function.getFunction(database, name);
function.doneWithParameters();
return function;
}
private Expression readWildcardOrSequenceValue(String schema,
String objectName) {
if (readIf("*")) {
return new Wildcard(schema, objectName);
}
if (schema == null) {
schema = session.getCurrentSchemaName();
}
if (readIf("NEXTVAL")) {
Sequence sequence = findSequence(schema, objectName);
if (sequence != null) {
return new SequenceValue(sequence);
}
} else if (readIf("CURRVAL")) {
Sequence sequence = findSequence(schema, objectName);
if (sequence != null) {
Function function = Function.getFunction(database, "CURRVAL");
function.setParameter(0, ValueExpression.get(ValueString
.get(sequence.getSchema().getName())));
function.setParameter(1, ValueExpression.get(ValueString
.get(sequence.getName())));
function.doneWithParameters();
return function;
}
}
return null;
}
private Expression readTermObjectDot(String objectName) {
Expression expr = readWildcardOrSequenceValue(null, objectName);
if (expr != null) {
return expr;
}
String name = readColumnIdentifier();
Schema s = database.findSchema(objectName);
if ((!SysProperties.OLD_STYLE_OUTER_JOIN || s != null) && readIf("(")) {
// only if the token before the dot is a valid schema name,
// otherwise the old style Oracle outer join doesn't work:
// t.x = t2.x(+)
// this additional check is not required
// if the old style outer joins are not supported
return readFunction(s, name);
} else if (readIf(".")) {
String schema = objectName;
objectName = name;
expr = readWildcardOrSequenceValue(schema, objectName);
if (expr != null) {
return expr;
}
name = readColumnIdentifier();
if (readIf("(")) {
String databaseName = schema;
if (!equalsToken(database.getShortName(), databaseName)) {
throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1,
databaseName);
}
schema = objectName;
return readFunction(database.getSchema(schema), name);
} else if (readIf(".")) {
String databaseName = schema;
if (!equalsToken(database.getShortName(), databaseName)) {
throw DbException.get(ErrorCode.DATABASE_NOT_FOUND_1,
databaseName);
}
schema = objectName;
objectName = name;
expr = readWildcardOrSequenceValue(schema, objectName);
if (expr != null) {
return expr;
}
name = readColumnIdentifier();
return new ExpressionColumn(database, schema, objectName, name);
}
return new ExpressionColumn(database, schema, objectName, name);
}
return new ExpressionColumn(database, null, objectName, name);
}
private Parameter readParameter() {
// there must be no space between ? and the number
boolean indexed = Character.isDigit(sqlCommandChars[parseIndex]);
Parameter p;
if (indexed) {
readParameterIndex();
if (indexedParameterList == null) {
if (parameters == null) {
// this can occur when parsing expressions only (for
// example check constraints)
throw getSyntaxError();
} else if (!parameters.isEmpty()) {
throw DbException
.get(ErrorCode.CANNOT_MIX_INDEXED_AND_UNINDEXED_PARAMS);
}
indexedParameterList = New.arrayList();
}
int index = currentValue.getInt() - 1;
if (index < 0 || index >= Constants.MAX_PARAMETER_INDEX) {
throw DbException.getInvalidValueException(
"parameter index", index);
}
if (indexedParameterList.size() <= index) {
indexedParameterList.ensureCapacity(index + 1);
while (indexedParameterList.size() <= index) {
indexedParameterList.add(null);
}
}
p = indexedParameterList.get(index);
if (p == null) {
p = new Parameter(index);
indexedParameterList.set(index, p);
}
read();
} else {
read();
if (indexedParameterList != null) {
throw DbException
.get(ErrorCode.CANNOT_MIX_INDEXED_AND_UNINDEXED_PARAMS);
}
p = new Parameter(parameters.size());
}
parameters.add(p);
return p;
}
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;
}
private Expression readCase() {
if (readIf("END")) {
readIf("CASE");
return ValueExpression.getNull();
}
if (readIf("ELSE")) {
Expression elsePart = readExpression().optimize(session);
read("END");
readIf("CASE");
return elsePart;
}
int i;
Function function;
if (readIf("WHEN")) {
function = Function.getFunction(database, "CASE");
function.setParameter(0, null);
i = 1;
do {
function.setParameter(i++, readExpression());
read("THEN");
function.setParameter(i++, readExpression());
} while (readIf("WHEN"));
} else {
Expression expr = readExpression();
if (readIf("END")) {
readIf("CASE");
return ValueExpression.getNull();
}
if (readIf("ELSE")) {
Expression elsePart = readExpression().optimize(session);
read("END");
readIf("CASE");
return elsePart;
}
function = Function.getFunction(database, "CASE");
function.setParameter(0, expr);
i = 1;
read("WHEN");
do {
function.setParameter(i++, readExpression());
read("THEN");
function.setParameter(i++, readExpression());
} while (readIf("WHEN"));
}
if (readIf("ELSE")) {
function.setParameter(i, readExpression());
}
read("END");
readIf("CASE");
function.doneWithParameters();
return function;
}
private int readPositiveInt() {
int v = readInt();
if (v < 0) {
throw DbException.getInvalidValueException("positive integer", v);
}
return v;
}
private int readInt() {
boolean minus = false;
if (currentTokenType == MINUS) {
minus = true;
read();
} else if (currentTokenType == PLUS) {
read();
}
if (currentTokenType != VALUE) {
throw DbException.getSyntaxError(sqlCommand, parseIndex, "integer");
}
if (minus) {
// must do that now, otherwise Integer.MIN_VALUE would not work
currentValue = currentValue.negate();
}
int i = currentValue.getInt();
read();
return i;
}
private long readLong() {
boolean minus = false;
if (currentTokenType == MINUS) {
minus = true;
read();
} else if (currentTokenType == PLUS) {
read();
}
if (currentTokenType != VALUE) {
throw DbException.getSyntaxError(sqlCommand, parseIndex, "long");
}
if (minus) {
// must do that now, otherwise Long.MIN_VALUE would not work
currentValue = currentValue.negate();
}
long i = currentValue.getLong();
read();
return i;
}
private boolean readBooleanSetting() {
if (currentTokenType == VALUE) {
boolean result = currentValue.getBoolean();
read();
return result;
}
if (readIf("TRUE") || readIf("ON")) {
return true;
} else if (readIf("FALSE") || readIf("OFF")) {
return false;
} else {
throw getSyntaxError();
}
}
private String readString() {
Expression expr = readExpression().optimize(session);
if (!(expr instanceof ValueExpression)) {
throw DbException.getSyntaxError(sqlCommand, parseIndex, "string");
}
return expr.getValue(session).getString();
}
// TODO: why does this function allow defaultSchemaName=null - which resets
// the parser schemaName for everyone ?
private String readIdentifierWithSchema(String defaultSchemaName) {
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
String s = currentToken;
read();
schemaName = defaultSchemaName;
if (readIf(".")) {
schemaName = s;
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
s = currentToken;
read();
}
if (equalsToken(".", currentToken)) {
if (equalsToken(schemaName, database.getShortName())) {
read(".");
schemaName = s;
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
s = currentToken;
read();
}
}
return s;
}
private String readIdentifierWithSchema() {
return readIdentifierWithSchema(session.getCurrentSchemaName());
}
private String readAliasIdentifier() {
return readColumnIdentifier();
}
private String readUniqueIdentifier() {
return readColumnIdentifier();
}
private String readColumnIdentifier() {
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
String s = currentToken;
read();
return s;
}
private void read(String expected) {
if (currentTokenQuoted || !equalsToken(expected, currentToken)) {
addExpected(expected);
throw getSyntaxError();
}
read();
}
private boolean readIf(String token) {
if (!currentTokenQuoted && equalsToken(token, currentToken)) {
read();
return true;
}
addExpected(token);
return false;
}
/*
* Reads every token in list, in order - returns true if all are found.
* If any are not found, returns false - AND resets parsing back to state when called.
*/
private boolean readIfAll(String... tokens) {
// save parse location in case we have to fail this test
int start = lastParseIndex;
for (String token: tokens) {
if (!currentTokenQuoted && equalsToken(token, currentToken)) {
read();
} else {
// read failed - revert parse location to before when called
parseIndex = start;
read();
return false;
}
}
return true;
}
private boolean isToken(String token) {
boolean result = equalsToken(token, currentToken) &&
!currentTokenQuoted;
if (result) {
return true;
}
addExpected(token);
return false;
}
private boolean equalsToken(String a, String b) {
if (a == null) {
return b == null;
} else
return a.equals(b) || !identifiersToUpper && a.equalsIgnoreCase(b);
}
private static boolean equalsTokenIgnoreCase(String a, String b) {
if (a == null) {
return b == null;
} else
return a.equals(b) || a.equalsIgnoreCase(b);
}
private boolean isTokenInList(Collection<String> upperCaseTokenList) {
String upperCaseCurrentToken = currentToken.toUpperCase();
return upperCaseTokenList.contains(upperCaseCurrentToken);
}
private void addExpected(String token) {
if (expectedList != null) {
expectedList.add(token);
}
}
private void read() {
currentTokenQuoted = false;
if (expectedList != null) {
expectedList.clear();
}
int[] types = characterTypes;
lastParseIndex = parseIndex;
int i = parseIndex;
int type = types[i];
while (type == 0) {
type = types[++i];
}
int start = i;
char[] chars = sqlCommandChars;
char c = chars[i++];
currentToken = "";
switch (type) {
case CHAR_NAME:
while (true) {
type = types[i];
if (type != CHAR_NAME && type != CHAR_VALUE) {
break;
}
i++;
}
currentToken = StringUtils.cache(sqlCommand.substring(
start, i));
currentTokenType = getTokenType(currentToken);
parseIndex = i;
return;
case CHAR_QUOTED: {
String result = null;
while (true) {
for (int begin = i;; i++) {
if (chars[i] == '\"') {
if (result == null) {
result = sqlCommand.substring(begin, i);
} else {
result += sqlCommand.substring(begin - 1, i);
}
break;
}
}
if (chars[++i] != '\"') {
break;
}
i++;
}
currentToken = StringUtils.cache(result);
parseIndex = i;
currentTokenQuoted = true;
currentTokenType = IDENTIFIER;
return;
}
case CHAR_SPECIAL_2:
if (types[i] == CHAR_SPECIAL_2) {
i++;
}
currentToken = sqlCommand.substring(start, i);
currentTokenType = getSpecialType(currentToken);
parseIndex = i;
return;
case CHAR_SPECIAL_1:
currentToken = sqlCommand.substring(start, i);
currentTokenType = getSpecialType(currentToken);
parseIndex = i;
return;
case CHAR_VALUE:
if (c == '0' && chars[i] == 'X') {
// hex number
long number = 0;
start += 2;
i++;
while (true) {
c = chars[i];
if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) {
checkLiterals(false);
currentValue = ValueInt.get((int) number);
currentTokenType = VALUE;
currentToken = "0";
parseIndex = i;
return;
}
number = (number << 4) + c -
(c >= 'A' ? ('A' - 0xa) : ('0'));
if (number > Integer.MAX_VALUE) {
readHexDecimal(start, i);
return;
}
i++;
}
}
long number = c - '0';
while (true) {
c = chars[i];
if (c < '0' || c > '9') {
if (c == '.' || c == 'E' || c == 'L') {
readDecimal(start, i);
break;
}
checkLiterals(false);
currentValue = ValueInt.get((int) number);
currentTokenType = VALUE;
currentToken = "0";
parseIndex = i;
break;
}
number = number * 10 + (c - '0');
if (number > Integer.MAX_VALUE) {
readDecimal(start, i);
break;
}
i++;
}
return;
case CHAR_DOT:
if (types[i] != CHAR_VALUE) {
currentTokenType = KEYWORD;
currentToken = ".";
parseIndex = i;
return;
}
readDecimal(i - 1, i);
return;
case CHAR_STRING: {
String result = null;
while (true) {
for (int begin = i;; i++) {
if (chars[i] == '\'') {
if (result == null) {
result = sqlCommand.substring(begin, i);
} else {
result += sqlCommand.substring(begin - 1, i);
}
break;
}
}
if (chars[++i] != '\'') {
break;
}
i++;
}
currentToken = "'";
checkLiterals(true);
currentValue = ValueString.get(StringUtils.cache(result),
database.getMode().treatEmptyStringsAsNull);
parseIndex = i;
currentTokenType = VALUE;
return;
}
case CHAR_DOLLAR_QUOTED_STRING: {
String result = null;
int begin = i - 1;
while (types[i] == CHAR_DOLLAR_QUOTED_STRING) {
i++;
}
result = sqlCommand.substring(begin, i);
currentToken = "'";
checkLiterals(true);
currentValue = ValueString.get(StringUtils.cache(result),
database.getMode().treatEmptyStringsAsNull);
parseIndex = i;
currentTokenType = VALUE;
return;
}
case CHAR_END:
currentToken = "";
currentTokenType = END;
parseIndex = i;
return;
default:
throw getSyntaxError();
}
}
private void readParameterIndex() {
int i = parseIndex;
char[] chars = sqlCommandChars;
char c = chars[i++];
long number = c - '0';
while (true) {
c = chars[i];
if (c < '0' || c > '9') {
currentValue = ValueInt.get((int) number);
currentTokenType = VALUE;
currentToken = "0";
parseIndex = i;
break;
}
number = number * 10 + (c - '0');
if (number > Integer.MAX_VALUE) {
throw DbException.getInvalidValueException(
"parameter index", number);
}
i++;
}
}
private void checkLiterals(boolean text) {
if (!literalsChecked && !session.getAllowLiterals()) {
int allowed = database.getAllowLiterals();
if (allowed == Constants.ALLOW_LITERALS_NONE ||
(text && allowed != Constants.ALLOW_LITERALS_ALL)) {
throw DbException.get(ErrorCode.LITERALS_ARE_NOT_ALLOWED);
}
}
}
private void readHexDecimal(int start, int i) {
char[] chars = sqlCommandChars;
char c;
do {
c = chars[++i];
} while ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'));
parseIndex = i;
String sub = sqlCommand.substring(start, i);
BigDecimal bd = new BigDecimal(new BigInteger(sub, 16));
checkLiterals(false);
currentValue = ValueDecimal.get(bd);
currentTokenType = VALUE;
}
private void readDecimal(int start, int i) {
char[] chars = sqlCommandChars;
int[] types = characterTypes;
// go until the first non-number
while (true) {
int t = types[i];
if (t != CHAR_DOT && t != CHAR_VALUE) {
break;
}
i++;
}
boolean containsE = false;
if (chars[i] == 'E' || chars[i] == 'e') {
containsE = true;
i++;
if (chars[i] == '+' || chars[i] == '-') {
i++;
}
if (types[i] != CHAR_VALUE) {
throw getSyntaxError();
}
while (types[++i] == CHAR_VALUE) {
// go until the first non-number
}
}
parseIndex = i;
String sub = sqlCommand.substring(start, i);
checkLiterals(false);
if (!containsE && sub.indexOf('.') < 0) {
BigInteger bi = new BigInteger(sub);
if (bi.compareTo(ValueLong.MAX_BI) <= 0) {
// parse constants like "10000000L"
if (chars[i] == 'L') {
parseIndex++;
}
currentValue = ValueLong.get(bi.longValue());
currentTokenType = VALUE;
return;
}
}
BigDecimal bd;
try {
bd = new BigDecimal(sub);
} catch (NumberFormatException e) {
throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, e, sub);
}
currentValue = ValueDecimal.get(bd);
currentTokenType = VALUE;
}
public Session getSession() {
return session;
}
private void initialize(String sql) {
if (sql == null) {
sql = "";
}
originalSQL = sql;
sqlCommand = sql;
int len = sql.length() + 1;
char[] command = new char[len];
int[] types = new int[len];
len--;
sql.getChars(0, len, command, 0);
boolean changed = false;
command[len] = ' ';
int startLoop = 0;
int lastType = 0;
for (int i = 0; i < len; i++) {
char c = command[i];
int type = 0;
switch (c) {
case '/':
if (command[i + 1] == '*') {
// block comment
changed = true;
command[i] = ' ';
command[i + 1] = ' ';
startLoop = i;
i += 2;
checkRunOver(i, len, startLoop);
while (command[i] != '*' || command[i + 1] != '/') {
command[i++] = ' ';
checkRunOver(i, len, startLoop);
}
command[i] = ' ';
command[i + 1] = ' ';
i++;
} else if (command[i + 1] == '/') {
// single line comment
changed = true;
startLoop = i;
while (true) {
c = command[i];
if (c == '\n' || c == '\r' || i >= len - 1) {
break;
}
command[i++] = ' ';
checkRunOver(i, len, startLoop);
}
} else {
type = CHAR_SPECIAL_1;
}
break;
case '-':
if (command[i + 1] == '-') {
// single line comment
changed = true;
startLoop = i;
while (true) {
c = command[i];
if (c == '\n' || c == '\r' || i >= len - 1) {
break;
}
command[i++] = ' ';
checkRunOver(i, len, startLoop);
}
} else {
type = CHAR_SPECIAL_1;
}
break;
case '$':
if (command[i + 1] == '$' && (i == 0 || command[i - 1] <= ' ')) {
// dollar quoted string
changed = true;
command[i] = ' ';
command[i + 1] = ' ';
startLoop = i;
i += 2;
checkRunOver(i, len, startLoop);
while (command[i] != '$' || command[i + 1] != '$') {
types[i++] = CHAR_DOLLAR_QUOTED_STRING;
checkRunOver(i, len, startLoop);
}
command[i] = ' ';
command[i + 1] = ' ';
i++;
} else {
if (lastType == CHAR_NAME || lastType == CHAR_VALUE) {
// $ inside an identifier is supported
type = CHAR_NAME;
} else {
// but not at the start, to support PostgreSQL $1
type = CHAR_SPECIAL_1;
}
}
break;
case '(':
case ')':
case '{':
case '}':
case '*':
case ',':
case ';':
case '+':
case '%':
case '?':
case '@':
case ']':
type = CHAR_SPECIAL_1;
break;
case '!':
case '<':
case '>':
case '|':
case '=':
case ':':
case '&':
case '~':
type = CHAR_SPECIAL_2;
break;
case '.':
type = CHAR_DOT;
break;
case '\'':
type = types[i] = CHAR_STRING;
startLoop = i;
while (command[++i] != '\'') {
checkRunOver(i, len, startLoop);
}
break;
case '[':
if (database.getMode().squareBracketQuotedNames) {
// SQL Server alias for "
command[i] = '"';
changed = true;
type = types[i] = CHAR_QUOTED;
startLoop = i;
while (command[++i] != ']') {
checkRunOver(i, len, startLoop);
}
command[i] = '"';
} else {
type = CHAR_SPECIAL_1;
}
break;
case '`':
// MySQL alias for ", but not case sensitive
command[i] = '"';
changed = true;
type = types[i] = CHAR_QUOTED;
startLoop = i;
while (command[++i] != '`') {
checkRunOver(i, len, startLoop);
c = command[i];
command[i] = Character.toUpperCase(c);
}
command[i] = '"';
break;
case '\"':
type = types[i] = CHAR_QUOTED;
startLoop = i;
while (command[++i] != '\"') {
checkRunOver(i, len, startLoop);
}
break;
case '_':
type = CHAR_NAME;
break;
case '#':
if (database.getMode().supportPoundSymbolForColumnNames) {
type = CHAR_NAME;
} else {
type = CHAR_SPECIAL_1;
}
break;
default:
if (c >= 'a' && c <= 'z') {
if (identifiersToUpper) {
command[i] = (char) (c - ('a' - 'A'));
changed = true;
}
type = CHAR_NAME;
} else if (c >= 'A' && c <= 'Z') {
type = CHAR_NAME;
} else if (c >= '0' && c <= '9') {
type = CHAR_VALUE;
} else {
if (c <= ' ' || Character.isSpaceChar(c)) {
// whitespace
} else if (Character.isJavaIdentifierPart(c)) {
type = CHAR_NAME;
if (identifiersToUpper) {
char u = Character.toUpperCase(c);
if (u != c) {
command[i] = u;
changed = true;
}
}
} else {
type = CHAR_SPECIAL_1;
}
}
}
types[i] = type;
lastType = type;
}
sqlCommandChars = command;
types[len] = CHAR_END;
characterTypes = types;
if (changed) {
sqlCommand = new String(command);
}
parseIndex = 0;
}
private void checkRunOver(int i, int len, int startLoop) {
if (i >= len) {
parseIndex = startLoop;
throw getSyntaxError();
}
}
private int getSpecialType(String s) {
char c0 = s.charAt(0);
if (s.length() == 1) {
switch (c0) {
case '?':
case '$':
return PARAMETER;
case '@':
return AT;
case '+':
return PLUS;
case '-':
return MINUS;
case '{':
case '}':
case '*':
case '/':
case '%':
case ';':
case ',':
case ':':
case '[':
case ']':
case '~':
return KEYWORD;
case '(':
return OPEN;
case ')':
return CLOSE;
case '<':
return SMALLER;
case '>':
return BIGGER;
case '=':
return EQUAL;
default:
break;
}
} else if (s.length() == 2) {
char c1 = s.charAt(1);
switch (c0) {
case ':':
if (c1 == ':' || c1 == '=') {
return KEYWORD;
}
break;
case '>':
if (c1 == '=') {
return BIGGER_EQUAL;
}
break;
case '<':
if (c1 == '=') {
return SMALLER_EQUAL;
} else if (c1 == '>') {
return NOT_EQUAL;
}
break;
case '!':
if (c1 == '=') {
return NOT_EQUAL;
} else if (c1 == '~') {
return KEYWORD;
}
break;
case '|':
if (c1 == '|') {
return STRING_CONCAT;
}
break;
case '&':
if (c1 == '&') {
return SPATIAL_INTERSECTS;
}
break;
}
}
throw getSyntaxError();
}
private int getTokenType(String s) {
int len = s.length();
if (len == 0) {
throw getSyntaxError();
}
if (!identifiersToUpper) {
// if not yet converted to uppercase, do it now
s = StringUtils.toUpperEnglish(s);
}
return getSaveTokenType(s, false);
}
private boolean isKeyword(String s) {
if (!identifiersToUpper) {
// if not yet converted to uppercase, do it now
s = StringUtils.toUpperEnglish(s);
}
return ParserUtil.isKeyword(s);
}
private static int getSaveTokenType(String s, boolean functionsAsKeywords) {
return ParserUtil.getSaveTokenType(s, functionsAsKeywords);
}
private Column parseColumnForTable(String columnName,
boolean defaultNullable) {
Column column;
boolean isIdentity = readIf("IDENTITY");
if (isIdentity || readIf("BIGSERIAL")) {
// Check if any of them are disallowed in the current Mode
if (isIdentity && database.getMode().
disallowedTypes.contains("IDENTITY")) {
throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1,
currentToken);
}
column = new Column(columnName, Value.LONG);
column.setOriginalSQL("IDENTITY");
parseAutoIncrement(column);
// PostgreSQL compatibility
if (!database.getMode().serialColumnIsNotPK) {
column.setPrimaryKey(true);
}
} else if (readIf("SERIAL")) {
column = new Column(columnName, Value.INT);
column.setOriginalSQL("SERIAL");
parseAutoIncrement(column);
// PostgreSQL compatibility
if (!database.getMode().serialColumnIsNotPK) {
column.setPrimaryKey(true);
}
} else {
column = parseColumnWithType(columnName);
}
if (readIf("INVISIBLE")) {
column.setVisible(false);
} else if (readIf("VISIBLE")) {
column.setVisible(true);
}
NullConstraintType nullConstraint = parseNotNullConstraint();
switch (nullConstraint) {
case NULL_IS_ALLOWED:
column.setNullable(true);
break;
case NULL_IS_NOT_ALLOWED:
column.setNullable(false);
break;
case NO_NULL_CONSTRAINT_FOUND:
// domains may be defined as not nullable
column.setNullable(defaultNullable & column.isNullable());
break;
default:
throw DbException.get(ErrorCode.UNKNOWN_MODE_1,
"Internal Error - unhandled case: " + nullConstraint.name());
}
if (readIf("AS")) {
if (isIdentity) {
getSyntaxError();
}
Expression expr = readExpression();
column.setComputedExpression(expr);
} else if (readIf("DEFAULT")) {
Expression defaultExpression = readExpression();
column.setDefaultExpression(session, defaultExpression);
} else if (readIf("GENERATED")) {
if (!readIf("ALWAYS")) {
read("BY");
read("DEFAULT");
}
read("AS");
read("IDENTITY");
long start = 1, increment = 1;
if (readIf("(")) {
read("START");
readIf("WITH");
start = readLong();
readIf(",");
if (readIf("INCREMENT")) {
readIf("BY");
increment = readLong();
}
read(")");
}
column.setPrimaryKey(true);
column.setAutoIncrement(true, start, increment);
}
if (readIf("ON")) {
read("UPDATE");
Expression onUpdateExpression = readExpression();
column.setOnUpdateExpression(session, onUpdateExpression);
}
if (NullConstraintType.NULL_IS_NOT_ALLOWED == parseNotNullConstraint()) {
column.setNullable(false);
}
if (readIf("AUTO_INCREMENT") || readIf("BIGSERIAL") || readIf("SERIAL")) {
parseAutoIncrement(column);
parseNotNullConstraint();
} else if (readIf("IDENTITY")) {
parseAutoIncrement(column);
column.setPrimaryKey(true);
parseNotNullConstraint();
}
if (readIf("NULL_TO_DEFAULT")) {
column.setConvertNullToDefault(true);
}
if (readIf("SEQUENCE")) {
Sequence sequence = readSequence();
column.setSequence(sequence);
}
if (readIf("SELECTIVITY")) {
int value = readPositiveInt();
column.setSelectivity(value);
}
String comment = readCommentIf();
if (comment != null) {
column.setComment(comment);
}
return column;
}
private void parseAutoIncrement(Column column) {
long start = 1, increment = 1;
if (readIf("(")) {
start = readLong();
if (readIf(",")) {
increment = readLong();
}
read(")");
}
column.setAutoIncrement(true, start, increment);
}
private String readCommentIf() {
if (readIf("COMMENT")) {
readIf("IS");
return readString();
}
return null;
}
private Column parseColumnWithType(String columnName) {
String original = currentToken;
boolean regular = false;
int originalScale = -1;
if (readIf("LONG")) {
if (readIf("RAW")) {
original += " RAW";
}
} else if (readIf("DOUBLE")) {
if (readIf("PRECISION")) {
original += " PRECISION";
}
} else if (readIf("CHARACTER")) {
if (readIf("VARYING")) {
original += " VARYING";
}
} else if (readIf("TIME")) {
if (readIf("(")) {
originalScale = readPositiveInt();
if (originalScale > ValueTime.MAXIMUM_SCALE) {
throw DbException.get(ErrorCode.INVALID_VALUE_SCALE_PRECISION, Integer.toString(originalScale));
}
read(")");
}
if (readIf("WITHOUT")) {
read("TIME");
read("ZONE");
original += " WITHOUT TIME ZONE";
}
} else if (readIf("TIMESTAMP")) {
if (readIf("(")) {
originalScale = readPositiveInt();
// Allow non-standard TIMESTAMP(..., ...) syntax
if (readIf(",")) {
originalScale = readPositiveInt();
}
if (originalScale > ValueTimestamp.MAXIMUM_SCALE) {
throw DbException.get(ErrorCode.INVALID_VALUE_SCALE_PRECISION, Integer.toString(originalScale));
}
read(")");
}
if (readIf("WITH")) {
read("TIME");
read("ZONE");
original += " WITH TIME ZONE";
} else if (readIf("WITHOUT")) {
read("TIME");
read("ZONE");
original += " WITHOUT TIME ZONE";
}
} else {
regular = true;
}
long precision = -1;
int displaySize = -1;
String[] enumerators = null;
int scale = -1;
String comment = null;
Column templateColumn = null;
DataType dataType;
if (!identifiersToUpper) {
original = StringUtils.toUpperEnglish(original);
}
UserDataType userDataType = database.findUserDataType(original);
if (userDataType != null) {
templateColumn = userDataType.getColumn();
dataType = DataType.getDataType(templateColumn.getType());
comment = templateColumn.getComment();
original = templateColumn.getOriginalSQL();
precision = templateColumn.getPrecision();
displaySize = templateColumn.getDisplaySize();
scale = templateColumn.getScale();
enumerators = templateColumn.getEnumerators();
} else {
Mode mode = database.getMode();
dataType = DataType.getTypeByName(original, mode);
if (dataType == null || mode.disallowedTypes.contains(original)) {
throw DbException.get(ErrorCode.UNKNOWN_DATA_TYPE_1,
currentToken);
}
}
if (database.getIgnoreCase() && dataType.type == Value.STRING &&
!equalsToken("VARCHAR_CASESENSITIVE", original)) {
original = "VARCHAR_IGNORECASE";
dataType = DataType.getTypeByName(original, database.getMode());
}
if (regular) {
read();
}
precision = precision == -1 ? dataType.defaultPrecision : precision;
displaySize = displaySize == -1 ? dataType.defaultDisplaySize
: displaySize;
scale = scale == -1 ? dataType.defaultScale : scale;
if (dataType.supportsPrecision || dataType.supportsScale) {
int t = dataType.type;
if (t == Value.TIME || t == Value.TIMESTAMP || t == Value.TIMESTAMP_TZ) {
if (originalScale >= 0) {
scale = originalScale;
switch (t) {
case Value.TIME:
if (original.equals("TIME WITHOUT TIME ZONE")) {
original = "TIME(" + originalScale + ") WITHOUT TIME ZONE";
} else {
original = original + '(' + originalScale + ')';
}
precision = displaySize = ValueTime.getDisplaySize(originalScale);
break;
case Value.TIMESTAMP:
if (original.equals("TIMESTAMP WITHOUT TIME ZONE")) {
original = "TIMESTAMP(" + originalScale + ") WITHOUT TIME ZONE";
} else {
original = original + '(' + originalScale + ')';
}
precision = displaySize = ValueTimestamp.getDisplaySize(originalScale);
break;
case Value.TIMESTAMP_TZ:
original = "TIMESTAMP(" + originalScale + ") WITH TIME ZONE";
precision = displaySize = ValueTimestampTimeZone.getDisplaySize(originalScale);
break;
}
}
} else if (readIf("(")) {
if (!readIf("MAX")) {
long p = readLong();
if (readIf("K")) {
p *= 1024;
} else if (readIf("M")) {
p *= 1024 * 1024;
} else if (readIf("G")) {
p *= 1024 * 1024 * 1024;
}
if (p > Long.MAX_VALUE) {
p = Long.MAX_VALUE;
}
original += "(" + p;
// Oracle syntax
if (!readIf("CHAR")) {
readIf("BYTE");
}
if (dataType.supportsScale) {
if (readIf(",")) {
scale = readInt();
original += ", " + scale;
} else {
scale = 0;
}
}
precision = p;
displaySize = MathUtils.convertLongToInt(precision);
original += ")";
}
read(")");
}
} else if (dataType.type == Value.DOUBLE && original.equals("FLOAT")) {
if (readIf("(")) {
int p = readPositiveInt();
read(")");
if (p > 53) {
throw DbException.get(ErrorCode.INVALID_VALUE_SCALE_PRECISION, Integer.toString(p));
}
if (p <= 24) {
dataType = DataType.getDataType(Value.FLOAT);
}
original = original + '(' + p + ')';
}
} else if (dataType.type == Value.ENUM) {
if (readIf("(")) {
java.util.List<String> enumeratorList = new ArrayList<>();
original += '(';
String enumerator0 = readString();
enumeratorList.add(enumerator0);
original += "'" + enumerator0 + "'";
while (readIfMore(true)) {
original += ',';
String enumeratorN = readString();
original += "'" + enumeratorN + "'";
enumeratorList.add(enumeratorN);
}
original += ')';
enumerators = enumeratorList.toArray(new String[0]);
}
try {
ValueEnum.check(enumerators);
} catch (DbException e) {
throw e.addSQL(original);
}
} else if (readIf("(")) {
// Support for MySQL: INT(11), MEDIUMINT(8) and so on.
// Just ignore the precision.
readPositiveInt();
read(")");
}
if (readIf("FOR")) {
read("BIT");
read("DATA");
if (dataType.type == Value.STRING) {
dataType = DataType.getTypeByName("BINARY", database.getMode());
}
}
// MySQL compatibility
readIf("UNSIGNED");
int type = dataType.type;
if (scale > precision) {
throw DbException.get(ErrorCode.INVALID_VALUE_SCALE_PRECISION,
Integer.toString(scale), Long.toString(precision));
}
Column column = new Column(columnName, type, precision, scale,
displaySize, enumerators);
if (templateColumn != null) {
column.setNullable(templateColumn.isNullable());
column.setDefaultExpression(session,
templateColumn.getDefaultExpression());
int selectivity = templateColumn.getSelectivity();
if (selectivity != Constants.SELECTIVITY_DEFAULT) {
column.setSelectivity(selectivity);
}
Expression checkConstraint = templateColumn.getCheckConstraint(
session, columnName);
column.addCheckConstraint(session, checkConstraint);
}
column.setComment(comment);
column.setOriginalSQL(original);
return column;
}
private Prepared parseCreate() {
boolean orReplace = false;
if (readIf("OR")) {
read("REPLACE");
orReplace = true;
}
boolean force = readIf("FORCE");
if (readIf("VIEW")) {
return parseCreateView(force, orReplace);
} else if (readIf("ALIAS")) {
return parseCreateFunctionAlias(force);
} else if (readIf("SEQUENCE")) {
return parseCreateSequence();
} else if (readIf("USER")) {
return parseCreateUser();
} else if (readIf("TRIGGER")) {
return parseCreateTrigger(force);
} else if (readIf("ROLE")) {
return parseCreateRole();
} else if (readIf("SCHEMA")) {
return parseCreateSchema();
} else if (readIf("CONSTANT")) {
return parseCreateConstant();
} else if (readIf("DOMAIN")) {
return parseCreateUserDataType();
} else if (readIf("TYPE")) {
return parseCreateUserDataType();
} else if (readIf("DATATYPE")) {
return parseCreateUserDataType();
} else if (readIf("AGGREGATE")) {
return parseCreateAggregate(force);
} else if (readIf("LINKED")) {
return parseCreateLinkedTable(false, false, force);
}
// tables or linked tables
boolean memory = false, cached = false;
if (readIf("MEMORY")) {
memory = true;
} else if (readIf("CACHED")) {
cached = true;
}
if (readIf("LOCAL")) {
read("TEMPORARY");
if (readIf("LINKED")) {
return parseCreateLinkedTable(true, false, force);
}
read("TABLE");
return parseCreateTable(true, false, cached);
} else if (readIf("GLOBAL")) {
read("TEMPORARY");
if (readIf("LINKED")) {
return parseCreateLinkedTable(true, true, force);
}
read("TABLE");
return parseCreateTable(true, true, cached);
} else if (readIf("TEMP") || readIf("TEMPORARY")) {
if (readIf("LINKED")) {
return parseCreateLinkedTable(true, true, force);
}
read("TABLE");
return parseCreateTable(true, true, cached);
} else if (readIf("TABLE")) {
if (!cached && !memory) {
cached = database.getDefaultTableType() == Table.TYPE_CACHED;
}
return parseCreateTable(false, false, cached);
} else if (readIf("SYNONYM")) {
return parseCreateSynonym(orReplace);
} else {
boolean hash = false, primaryKey = false;
boolean unique = false, spatial = false;
String indexName = null;
Schema oldSchema = null;
boolean ifNotExists = false;
if (readIf("PRIMARY")) {
read("KEY");
if (readIf("HASH")) {
hash = true;
}
primaryKey = true;
if (!isToken("ON")) {
ifNotExists = readIfNotExists();
indexName = readIdentifierWithSchema(null);
oldSchema = getSchema();
}
} else {
if (readIf("UNIQUE")) {
unique = true;
}
if (readIf("HASH")) {
hash = true;
}
if (readIf("SPATIAL")) {
spatial = true;
}
if (readIf("INDEX")) {
if (!isToken("ON")) {
ifNotExists = readIfNotExists();
indexName = readIdentifierWithSchema(null);
oldSchema = getSchema();
}
} else {
throw getSyntaxError();
}
}
read("ON");
String tableName = readIdentifierWithSchema();
checkSchema(oldSchema);
CreateIndex command = new CreateIndex(session, getSchema());
command.setIfNotExists(ifNotExists);
command.setPrimaryKey(primaryKey);
command.setTableName(tableName);
command.setUnique(unique);
command.setIndexName(indexName);
command.setComment(readCommentIf());
read("(");
command.setIndexColumns(parseIndexColumnList());
if (readIf("USING")) {
if (hash) {
throw getSyntaxError();
}
if (spatial) {
throw getSyntaxError();
}
if (readIf("BTREE")) {
// default
} else if (readIf("RTREE")) {
spatial = true;
} else if (readIf("HASH")) {
hash = true;
} else {
throw getSyntaxError();
}
}
command.setHash(hash);
command.setSpatial(spatial);
return command;
}
}
/**
* @return true if we expect to see a TABLE clause
*/
private boolean addRoleOrRight(GrantRevoke command) {
if (readIf("SELECT")) {
command.addRight(Right.SELECT);
return true;
} else if (readIf("DELETE")) {
command.addRight(Right.DELETE);
return true;
} else if (readIf("INSERT")) {
command.addRight(Right.INSERT);
return true;
} else if (readIf("UPDATE")) {
command.addRight(Right.UPDATE);
return true;
} else if (readIf("ALL")) {
command.addRight(Right.ALL);
return true;
} else if (readIf("ALTER")) {
read("ANY");
read("SCHEMA");
command.addRight(Right.ALTER_ANY_SCHEMA);
command.addTable(null);
return false;
} else if (readIf("CONNECT")) {
// ignore this right
return true;
} else if (readIf("RESOURCE")) {
// ignore this right
return true;
} else {
command.addRoleName(readUniqueIdentifier());
return false;
}
}
private GrantRevoke parseGrantRevoke(int operationType) {
GrantRevoke command = new GrantRevoke(session);
command.setOperationType(operationType);
boolean tableClauseExpected = addRoleOrRight(command);
while (readIf(",")) {
addRoleOrRight(command);
if (command.isRightMode() && command.isRoleMode()) {
throw DbException
.get(ErrorCode.ROLES_AND_RIGHT_CANNOT_BE_MIXED);
}
}
if (tableClauseExpected) {
if (readIf("ON")) {
if (readIf("SCHEMA")) {
Schema schema = database.getSchema(readAliasIdentifier());
command.setSchema(schema);
} else {
do {
Table table = readTableOrView();
command.addTable(table);
} while (readIf(","));
}
}
}
if (operationType == CommandInterface.GRANT) {
read("TO");
} else {
read("FROM");
}
command.setGranteeName(readUniqueIdentifier());
return command;
}
private Select parseValues() {
Select command = new Select(session);
currentSelect = command;
TableFilter filter = parseValuesTable(0);
ArrayList<Expression> list = New.arrayList();
list.add(new Wildcard(null, null));
command.setExpressions(list);
command.addTableFilter(filter, true);
command.init();
return command;
}
private TableFilter parseValuesTable(int orderInFrom) {
Schema mainSchema = database.getSchema(Constants.SCHEMA_MAIN);
TableFunction tf = (TableFunction) Function.getFunction(database,
"TABLE");
ArrayList<Column> columns = New.arrayList();
ArrayList<ArrayList<Expression>> rows = New.arrayList();
do {
int i = 0;
ArrayList<Expression> row = New.arrayList();
boolean multiColumn = readIf("(");
do {
Expression expr = readExpression();
expr = expr.optimize(session);
int type = expr.getType();
long prec;
int scale, displaySize;
Column column;
String columnName = "C" + (i + 1);
if (rows.isEmpty()) {
if (type == Value.UNKNOWN) {
type = Value.STRING;
}
DataType dt = DataType.getDataType(type);
prec = dt.defaultPrecision;
scale = dt.defaultScale;
displaySize = dt.defaultDisplaySize;
column = new Column(columnName, type, prec, scale,
displaySize);
columns.add(column);
}
prec = expr.getPrecision();
scale = expr.getScale();
displaySize = expr.getDisplaySize();
if (i >= columns.size()) {
throw DbException
.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
Column c = columns.get(i);
type = Value.getHigherOrder(c.getType(), type);
prec = Math.max(c.getPrecision(), prec);
scale = Math.max(c.getScale(), scale);
displaySize = Math.max(c.getDisplaySize(), displaySize);
column = new Column(columnName, type, prec, scale, displaySize);
columns.set(i, column);
row.add(expr);
i++;
} while (multiColumn && readIfMore(true));
rows.add(row);
} while (readIf(","));
int columnCount = columns.size();
int rowCount = rows.size();
for (ArrayList<Expression> row : rows) {
if (row.size() != columnCount) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
for (int i = 0; i < columnCount; i++) {
Column c = columns.get(i);
if (c.getType() == Value.UNKNOWN) {
c = new Column(c.getName(), Value.STRING, 0, 0, 0);
columns.set(i, c);
}
Expression[] array = new Expression[rowCount];
for (int j = 0; j < rowCount; j++) {
array[j] = rows.get(j).get(i);
}
ExpressionList list = new ExpressionList(array);
tf.setParameter(i, list);
}
tf.setColumns(columns);
tf.doneWithParameters();
Table table = new FunctionTable(mainSchema, session, tf, tf);
return new TableFilter(session, table, null,
rightsChecked, currentSelect, orderInFrom,
null);
}
private Call parseCall() {
Call command = new Call(session);
currentPrepared = command;
command.setExpression(readExpression());
return command;
}
private CreateRole parseCreateRole() {
CreateRole command = new CreateRole(session);
command.setIfNotExists(readIfNotExists());
command.setRoleName(readUniqueIdentifier());
return command;
}
private CreateSchema parseCreateSchema() {
CreateSchema command = new CreateSchema(session);
command.setIfNotExists(readIfNotExists());
command.setSchemaName(readUniqueIdentifier());
if (readIf("AUTHORIZATION")) {
command.setAuthorization(readUniqueIdentifier());
} else {
command.setAuthorization(session.getUser().getName());
}
if (readIf("WITH")) {
command.setTableEngineParams(readTableEngineParams());
}
return command;
}
private ArrayList<String> readTableEngineParams() {
ArrayList<String> tableEngineParams = New.arrayList();
do {
tableEngineParams.add(readUniqueIdentifier());
} while (readIf(","));
return tableEngineParams;
}
private CreateSequence parseCreateSequence() {
boolean ifNotExists = readIfNotExists();
String sequenceName = readIdentifierWithSchema();
CreateSequence command = new CreateSequence(session, getSchema());
command.setIfNotExists(ifNotExists);
command.setSequenceName(sequenceName);
while (true) {
if (readIf("START")) {
readIf("WITH");
command.setStartWith(readExpression());
} else if (readIf("INCREMENT")) {
readIf("BY");
command.setIncrement(readExpression());
} else if (readIf("MINVALUE")) {
command.setMinValue(readExpression());
} else if (readIf("NOMINVALUE")) {
command.setMinValue(null);
} else if (readIf("MAXVALUE")) {
command.setMaxValue(readExpression());
} else if (readIf("NOMAXVALUE")) {
command.setMaxValue(null);
} else if (readIf("CYCLE")) {
command.setCycle(true);
} else if (readIf("NOCYCLE")) {
command.setCycle(false);
} else if (readIf("NO")) {
if (readIf("MINVALUE")) {
command.setMinValue(null);
} else if (readIf("MAXVALUE")) {
command.setMaxValue(null);
} else if (readIf("CYCLE")) {
command.setCycle(false);
} else if (readIf("CACHE")) {
command.setCacheSize(ValueExpression.get(ValueLong.get(1)));
} else {
break;
}
} else if (readIf("CACHE")) {
command.setCacheSize(readExpression());
} else if (readIf("NOCACHE")) {
command.setCacheSize(ValueExpression.get(ValueLong.get(1)));
} else if (readIf("BELONGS_TO_TABLE")) {
command.setBelongsToTable(true);
} else if (readIf("ORDER")) {
// Oracle compatibility
} else {
break;
}
}
return command;
}
private boolean readIfNotExists() {
if (readIf("IF")) {
read("NOT");
read("EXISTS");
return true;
}
return false;
}
private boolean readIfAffinity() {
return readIf("AFFINITY") || readIf("SHARD");
}
private CreateConstant parseCreateConstant() {
boolean ifNotExists = readIfNotExists();
String constantName = readIdentifierWithSchema();
Schema schema = getSchema();
if (isKeyword(constantName)) {
throw DbException.get(ErrorCode.CONSTANT_ALREADY_EXISTS_1,
constantName);
}
read("VALUE");
Expression expr = readExpression();
CreateConstant command = new CreateConstant(session, schema);
command.setConstantName(constantName);
command.setExpression(expr);
command.setIfNotExists(ifNotExists);
return command;
}
private CreateAggregate parseCreateAggregate(boolean force) {
boolean ifNotExists = readIfNotExists();
CreateAggregate command = new CreateAggregate(session);
command.setForce(force);
String name = readIdentifierWithSchema();
if (isKeyword(name) || Function.getFunction(database, name) != null ||
getAggregateType(name) != null) {
throw DbException.get(ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1,
name);
}
command.setName(name);
command.setSchema(getSchema());
command.setIfNotExists(ifNotExists);
read("FOR");
command.setJavaClassMethod(readUniqueIdentifier());
return command;
}
private CreateUserDataType parseCreateUserDataType() {
boolean ifNotExists = readIfNotExists();
CreateUserDataType command = new CreateUserDataType(session);
command.setTypeName(readUniqueIdentifier());
read("AS");
Column col = parseColumnForTable("VALUE", true);
if (readIf("CHECK")) {
Expression expr = readExpression();
col.addCheckConstraint(session, expr);
}
col.rename(null);
command.setColumn(col);
command.setIfNotExists(ifNotExists);
return command;
}
private CreateTrigger parseCreateTrigger(boolean force) {
boolean ifNotExists = readIfNotExists();
String triggerName = readIdentifierWithSchema(null);
Schema schema = getSchema();
boolean insteadOf, isBefore;
if (readIf("INSTEAD")) {
read("OF");
isBefore = true;
insteadOf = true;
} else if (readIf("BEFORE")) {
insteadOf = false;
isBefore = true;
} else {
read("AFTER");
insteadOf = false;
isBefore = false;
}
int typeMask = 0;
boolean onRollback = false;
do {
if (readIf("INSERT")) {
typeMask |= Trigger.INSERT;
} else if (readIf("UPDATE")) {
typeMask |= Trigger.UPDATE;
} else if (readIf("DELETE")) {
typeMask |= Trigger.DELETE;
} else if (readIf("SELECT")) {
typeMask |= Trigger.SELECT;
} else if (readIf("ROLLBACK")) {
onRollback = true;
} else {
throw getSyntaxError();
}
} while (readIf(","));
read("ON");
String tableName = readIdentifierWithSchema();
checkSchema(schema);
CreateTrigger command = new CreateTrigger(session, getSchema());
command.setForce(force);
command.setTriggerName(triggerName);
command.setIfNotExists(ifNotExists);
command.setInsteadOf(insteadOf);
command.setBefore(isBefore);
command.setOnRollback(onRollback);
command.setTypeMask(typeMask);
command.setTableName(tableName);
if (readIf("FOR")) {
read("EACH");
read("ROW");
command.setRowBased(true);
} else {
command.setRowBased(false);
}
if (readIf("QUEUE")) {
command.setQueueSize(readPositiveInt());
}
command.setNoWait(readIf("NOWAIT"));
if (readIf("AS")) {
command.setTriggerSource(readString());
} else {
read("CALL");
command.setTriggerClassName(readUniqueIdentifier());
}
return command;
}
private CreateUser parseCreateUser() {
CreateUser command = new CreateUser(session);
command.setIfNotExists(readIfNotExists());
command.setUserName(readUniqueIdentifier());
command.setComment(readCommentIf());
if (readIf("PASSWORD")) {
command.setPassword(readExpression());
} else if (readIf("SALT")) {
command.setSalt(readExpression());
read("HASH");
command.setHash(readExpression());
} else if (readIf("IDENTIFIED")) {
read("BY");
// uppercase if not quoted
command.setPassword(ValueExpression.get(ValueString
.get(readColumnIdentifier())));
} else {
throw getSyntaxError();
}
if (readIf("ADMIN")) {
command.setAdmin(true);
}
return command;
}
private CreateFunctionAlias parseCreateFunctionAlias(boolean force) {
boolean ifNotExists = readIfNotExists();
final boolean newAliasSameNameAsBuiltin = Function.getFunction(database, currentToken) != null;
String aliasName;
if (database.isAllowBuiltinAliasOverride() && newAliasSameNameAsBuiltin) {
aliasName = currentToken;
schemaName = session.getCurrentSchemaName();
read();
} else {
aliasName = readIdentifierWithSchema();
}
if (database.isAllowBuiltinAliasOverride() && newAliasSameNameAsBuiltin) {
// fine
} else if (isKeyword(aliasName) ||
Function.getFunction(database, aliasName) != null ||
getAggregateType(aliasName) != null) {
throw DbException.get(ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1,
aliasName);
}
CreateFunctionAlias command = new CreateFunctionAlias(session,
getSchema());
command.setForce(force);
command.setAliasName(aliasName);
command.setIfNotExists(ifNotExists);
command.setDeterministic(readIf("DETERMINISTIC"));
command.setBufferResultSetToLocalTemp(!readIf("NOBUFFER"));
if (readIf("AS")) {
command.setSource(readString());
} else {
read("FOR");
command.setJavaClassMethod(readUniqueIdentifier());
}
return command;
}
private Prepared parseWith() {
List<TableView> viewsCreated = new ArrayList<>();
readIf("RECURSIVE");
// this WITH statement might not be a temporary view - allow optional keyword to
// tell us that this keyword. This feature will not be documented - H2 internal use only.
boolean isPersistent = readIf("PERSISTENT");
// this WITH statement is not a temporary view - it is part of a persistent view
// as in CREATE VIEW abc AS WITH my_cte - this auto detects that condition
if (session.isParsingCreateView()) {
isPersistent = true;
}
do {
viewsCreated.add(parseSingleCommonTableExpression(isPersistent));
} while (readIf(","));
Prepared p = null;
// reverse the order of constructed CTE views - as the destruction order
// (since later created view may depend on previously created views -
// we preserve that dependency order in the destruction sequence )
// used in setCteCleanups
Collections.reverse(viewsCreated);
if (isToken("SELECT")) {
Query query = parseSelectUnion();
query.setPrepareAlways(true);
query.setNeverLazy(true);
p = query;
} else if (readIf("INSERT")) {
p = parseInsert();
p.setPrepareAlways(true);
} else if (readIf("UPDATE")) {
p = parseUpdate();
p.setPrepareAlways(true);
} else if (readIf("MERGE")) {
p = parseMerge();
p.setPrepareAlways(true);
} else if (readIf("DELETE")) {
p = parseDelete();
p.setPrepareAlways(true);
} else if (readIf("CREATE")) {
if (!isToken("TABLE")) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1,
WITH_STATEMENT_SUPPORTS_LIMITED_SUB_STATEMENTS);
}
p = parseCreate();
p.setPrepareAlways(true);
} else {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1,
WITH_STATEMENT_SUPPORTS_LIMITED_SUB_STATEMENTS);
}
// clean up temporary views starting with last to first (in case of
// dependencies) - but only if they are not persistent
if (!isPersistent) {
p.setCteCleanups(viewsCreated);
}
return p;
}
private TableView parseSingleCommonTableExpression(boolean isPersistent) {
String cteViewName = readIdentifierWithSchema();
Schema schema = getSchema();
Table recursiveTable = null;
ArrayList<Column> columns = New.arrayList();
String[] cols = null;
// column names are now optional - they can be inferred from the named
// query, if not supplied by user
if (readIf("(")) {
cols = parseColumnList();
for (String c : cols) {
// we don't really know the type of the column, so STRING will
// have to do, UNKNOWN does not work here
columns.add(new Column(c, Value.STRING));
}
}
Table oldViewFound = null;
if (isPersistent) {
oldViewFound = getSchema().findTableOrView(session, cteViewName);
} else {
oldViewFound = session.findLocalTempTable(cteViewName);
}
// this persistent check conflicts with check 10 lines down
if (oldViewFound != null) {
if (!(oldViewFound instanceof TableView)) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1,
cteViewName);
}
TableView tv = (TableView) oldViewFound;
if (!tv.isTableExpression()) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1,
cteViewName);
}
if (isPersistent) {
oldViewFound.lock(session, true, true);
database.removeSchemaObject(session, oldViewFound);
} else {
session.removeLocalTempTable(oldViewFound);
}
oldViewFound = null;
}
/*
* This table is created as a workaround because recursive table
* expressions need to reference something that look like themselves to
* work (its removed after creation in this method). Only create table
* data and table if we don't have a working CTE already.
*/
recursiveTable = TableView.createShadowTableForRecursiveTableExpression(
isPersistent, session, cteViewName, schema, columns, database);
List<Column> columnTemplateList;
String[] querySQLOutput = {null};
try {
read("AS");
read("(");
Query withQuery = parseSelect();
if (isPersistent) {
withQuery.session = session;
}
read(")");
columnTemplateList = TableView.createQueryColumnTemplateList(cols, withQuery, querySQLOutput);
} finally {
TableView.destroyShadowTableForRecursiveExpression(isPersistent, session, recursiveTable);
}
return createCTEView(cteViewName,
querySQLOutput[0], columnTemplateList,
true/* allowRecursiveQueryDetection */,
true/* add to session */,
isPersistent, session);
}
private TableView createCTEView(String cteViewName, String querySQL,
List<Column> columnTemplateList, boolean allowRecursiveQueryDetection,
boolean addViewToSession, boolean isPersistent, Session targetSession) {
Database db = targetSession.getDatabase();
Schema schema = getSchemaWithDefault();
int id = db.allocateObjectId();
Column[] columnTemplateArray = columnTemplateList.toArray(new Column[0]);
// No easy way to determine if this is a recursive query up front, so we just compile
// it twice - once without the flag set, and if we didn't see a recursive term,
// then we just compile it again.
TableView view;
synchronized (targetSession) {
view = new TableView(schema, id, cteViewName, querySQL,
parameters, columnTemplateArray, targetSession,
allowRecursiveQueryDetection, false /* literalsChecked */, true /* isTableExpression */,
isPersistent);
if (!view.isRecursiveQueryDetected() && allowRecursiveQueryDetection) {
if (isPersistent) {
db.addSchemaObject(targetSession, view);
view.lock(targetSession, true, true);
targetSession.getDatabase().removeSchemaObject(targetSession, view);
} else {
session.removeLocalTempTable(view);
}
view = new TableView(schema, id, cteViewName, querySQL, parameters,
columnTemplateArray, targetSession,
false/* assume recursive */, false /* literalsChecked */, true /* isTableExpression */,
isPersistent);
}
// both removeSchemaObject and removeLocalTempTable hold meta locks
targetSession.getDatabase().unlockMeta(targetSession);
}
view.setTableExpression(true);
view.setTemporary(!isPersistent);
view.setHidden(true);
view.setOnCommitDrop(false);
if (addViewToSession) {
if (isPersistent) {
db.addSchemaObject(targetSession, view);
view.unlock(targetSession);
db.unlockMeta(targetSession);
} else {
targetSession.addLocalTempTable(view);
}
}
return view;
}
private CreateView parseCreateView(boolean force, boolean orReplace) {
boolean ifNotExists = readIfNotExists();
boolean isTableExpression = readIf("TABLE_EXPRESSION");
String viewName = readIdentifierWithSchema();
CreateView command = new CreateView(session, getSchema());
this.createView = command;
command.setViewName(viewName);
command.setIfNotExists(ifNotExists);
command.setComment(readCommentIf());
command.setOrReplace(orReplace);
command.setForce(force);
command.setTableExpression(isTableExpression);
if (readIf("(")) {
String[] cols = parseColumnList();
command.setColumnNames(cols);
}
String select = StringUtils.cache(sqlCommand
.substring(parseIndex));
read("AS");
try {
Query query;
session.setParsingCreateView(true, viewName);
try {
query = parseSelect();
query.prepare();
} finally {
session.setParsingCreateView(false, viewName);
}
command.setSelect(query);
} catch (DbException e) {
if (force) {
command.setSelectSQL(select);
while (currentTokenType != END) {
read();
}
} else {
throw e;
}
}
return command;
}
private TransactionCommand parseCheckpoint() {
TransactionCommand command;
if (readIf("SYNC")) {
command = new TransactionCommand(session,
CommandInterface.CHECKPOINT_SYNC);
} else {
command = new TransactionCommand(session,
CommandInterface.CHECKPOINT);
}
return command;
}
private Prepared parseAlter() {
if (readIf("TABLE")) {
return parseAlterTable();
} else if (readIf("USER")) {
return parseAlterUser();
} else if (readIf("INDEX")) {
return parseAlterIndex();
} else if (readIf("SCHEMA")) {
return parseAlterSchema();
} else if (readIf("SEQUENCE")) {
return parseAlterSequence();
} else if (readIf("VIEW")) {
return parseAlterView();
}
throw getSyntaxError();
}
private void checkSchema(Schema old) {
if (old != null && getSchema() != old) {
throw DbException.get(ErrorCode.SCHEMA_NAME_MUST_MATCH);
}
}
private AlterIndexRename parseAlterIndex() {
boolean ifExists = readIfExists(false);
String indexName = readIdentifierWithSchema();
Schema old = getSchema();
AlterIndexRename command = new AlterIndexRename(session);
command.setOldSchema(old);
command.setOldName(indexName);
command.setIfExists(ifExists);
read("RENAME");
read("TO");
String newName = readIdentifierWithSchema(old.getName());
checkSchema(old);
command.setNewName(newName);
return command;
}
private AlterView parseAlterView() {
AlterView command = new AlterView(session);
boolean ifExists = readIfExists(false);
command.setIfExists(ifExists);
String viewName = readIdentifierWithSchema();
Table tableView = getSchema().findTableOrView(session, viewName);
if (!(tableView instanceof TableView) && !ifExists) {
throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
}
TableView view = (TableView) tableView;
command.setView(view);
read("RECOMPILE");
return command;
}
private Prepared parseAlterSchema() {
boolean ifExists = readIfExists(false);
String schemaName = readIdentifierWithSchema();
Schema old = getSchema();
read("RENAME");
read("TO");
String newName = readIdentifierWithSchema(old.getName());
Schema schema = findSchema(schemaName);
if (schema == null) {
if (ifExists) {
return new NoOperation(session);
}
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
}
AlterSchemaRename command = new AlterSchemaRename(session);
command.setOldSchema(schema);
checkSchema(old);
command.setNewName(newName);
return command;
}
private AlterSequence parseAlterSequence() {
boolean ifExists = readIfExists(false);
String sequenceName = readIdentifierWithSchema();
AlterSequence command = new AlterSequence(session, getSchema());
command.setSequenceName(sequenceName);
command.setIfExists(ifExists);
while (true) {
if (readIf("RESTART")) {
read("WITH");
command.setStartWith(readExpression());
} else if (readIf("INCREMENT")) {
read("BY");
command.setIncrement(readExpression());
} else if (readIf("MINVALUE")) {
command.setMinValue(readExpression());
} else if (readIf("NOMINVALUE")) {
command.setMinValue(null);
} else if (readIf("MAXVALUE")) {
command.setMaxValue(readExpression());
} else if (readIf("NOMAXVALUE")) {
command.setMaxValue(null);
} else if (readIf("CYCLE")) {
command.setCycle(true);
} else if (readIf("NOCYCLE")) {
command.setCycle(false);
} else if (readIf("NO")) {
if (readIf("MINVALUE")) {
command.setMinValue(null);
} else if (readIf("MAXVALUE")) {
command.setMaxValue(null);
} else if (readIf("CYCLE")) {
command.setCycle(false);
} else if (readIf("CACHE")) {
command.setCacheSize(ValueExpression.get(ValueLong.get(1)));
} else {
break;
}
} else if (readIf("CACHE")) {
command.setCacheSize(readExpression());
} else if (readIf("NOCACHE")) {
command.setCacheSize(ValueExpression.get(ValueLong.get(1)));
} else {
break;
}
}
return command;
}
private AlterUser parseAlterUser() {
String userName = readUniqueIdentifier();
if (readIf("SET")) {
AlterUser command = new AlterUser(session);
command.setType(CommandInterface.ALTER_USER_SET_PASSWORD);
command.setUser(database.getUser(userName));
if (readIf("PASSWORD")) {
command.setPassword(readExpression());
} else if (readIf("SALT")) {
command.setSalt(readExpression());
read("HASH");
command.setHash(readExpression());
} else {
throw getSyntaxError();
}
return command;
} else if (readIf("RENAME")) {
read("TO");
AlterUser command = new AlterUser(session);
command.setType(CommandInterface.ALTER_USER_RENAME);
command.setUser(database.getUser(userName));
String newName = readUniqueIdentifier();
command.setNewName(newName);
return command;
} else if (readIf("ADMIN")) {
AlterUser command = new AlterUser(session);
command.setType(CommandInterface.ALTER_USER_ADMIN);
User user = database.getUser(userName);
command.setUser(user);
if (readIf("TRUE")) {
command.setAdmin(true);
} else if (readIf("FALSE")) {
command.setAdmin(false);
} else {
throw getSyntaxError();
}
return command;
}
throw getSyntaxError();
}
private void readIfEqualOrTo() {
if (!readIf("=")) {
readIf("TO");
}
}
private Prepared parseSet() {
if (readIf("@")) {
Set command = new Set(session, SetTypes.VARIABLE);
command.setString(readAliasIdentifier());
readIfEqualOrTo();
command.setExpression(readExpression());
return command;
} else if (readIf("AUTOCOMMIT")) {
readIfEqualOrTo();
boolean value = readBooleanSetting();
int setting = value ? CommandInterface.SET_AUTOCOMMIT_TRUE
: CommandInterface.SET_AUTOCOMMIT_FALSE;
return new TransactionCommand(session, setting);
} else if (readIf("MVCC")) {
readIfEqualOrTo();
boolean value = readBooleanSetting();
Set command = new Set(session, SetTypes.MVCC);
command.setInt(value ? 1 : 0);
return command;
} else if (readIf("EXCLUSIVE")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.EXCLUSIVE);
command.setExpression(readExpression());
return command;
} else if (readIf("IGNORECASE")) {
readIfEqualOrTo();
boolean value = readBooleanSetting();
Set command = new Set(session, SetTypes.IGNORECASE);
command.setInt(value ? 1 : 0);
return command;
} else if (readIf("PASSWORD")) {
readIfEqualOrTo();
AlterUser command = new AlterUser(session);
command.setType(CommandInterface.ALTER_USER_SET_PASSWORD);
command.setUser(session.getUser());
command.setPassword(readExpression());
return command;
} else if (readIf("SALT")) {
readIfEqualOrTo();
AlterUser command = new AlterUser(session);
command.setType(CommandInterface.ALTER_USER_SET_PASSWORD);
command.setUser(session.getUser());
command.setSalt(readExpression());
read("HASH");
command.setHash(readExpression());
return command;
} else if (readIf("MODE")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.MODE);
command.setString(readAliasIdentifier());
return command;
} else if (readIf("COMPRESS_LOB")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.COMPRESS_LOB);
if (currentTokenType == VALUE) {
command.setString(readString());
} else {
command.setString(readUniqueIdentifier());
}
return command;
} else if (readIf("DATABASE")) {
readIfEqualOrTo();
read("COLLATION");
return parseSetCollation();
} else if (readIf("COLLATION")) {
readIfEqualOrTo();
return parseSetCollation();
} else if (readIf("BINARY_COLLATION")) {
readIfEqualOrTo();
return parseSetBinaryCollation();
} else if (readIf("CLUSTER")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.CLUSTER);
command.setString(readString());
return command;
} else if (readIf("DATABASE_EVENT_LISTENER")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.DATABASE_EVENT_LISTENER);
command.setString(readString());
return command;
} else if (readIf("ALLOW_LITERALS")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.ALLOW_LITERALS);
if (readIf("NONE")) {
command.setInt(Constants.ALLOW_LITERALS_NONE);
} else if (readIf("ALL")) {
command.setInt(Constants.ALLOW_LITERALS_ALL);
} else if (readIf("NUMBERS")) {
command.setInt(Constants.ALLOW_LITERALS_NUMBERS);
} else {
command.setInt(readPositiveInt());
}
return command;
} else if (readIf("DEFAULT_TABLE_TYPE")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.DEFAULT_TABLE_TYPE);
if (readIf("MEMORY")) {
command.setInt(Table.TYPE_MEMORY);
} else if (readIf("CACHED")) {
command.setInt(Table.TYPE_CACHED);
} else {
command.setInt(readPositiveInt());
}
return command;
} else if (readIf("CREATE")) {
readIfEqualOrTo();
// Derby compatibility (CREATE=TRUE in the database URL)
read();
return new NoOperation(session);
} else if (readIf("HSQLDB.DEFAULT_TABLE_TYPE")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("PAGE_STORE")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("CACHE_TYPE")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("FILE_LOCK")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("DB_CLOSE_ON_EXIT")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("AUTO_SERVER")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("AUTO_SERVER_PORT")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("AUTO_RECONNECT")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("ASSERT")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("ACCESS_MODE_DATA")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("OPEN_NEW")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("JMX")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("PAGE_SIZE")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("RECOVER")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("NAMES")) {
// Quercus PHP MySQL driver compatibility
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("SCOPE_GENERATED_KEYS")) {
readIfEqualOrTo();
read();
return new NoOperation(session);
} else if (readIf("SCHEMA")) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.SCHEMA);
command.setString(readAliasIdentifier());
return command;
} else if (readIf("DATESTYLE")) {
// PostgreSQL compatibility
readIfEqualOrTo();
if (!readIf("ISO")) {
String s = readString();
if (!equalsToken(s, "ISO")) {
throw getSyntaxError();
}
}
return new NoOperation(session);
} else if (readIf("SEARCH_PATH") ||
readIf(SetTypes.getTypeName(SetTypes.SCHEMA_SEARCH_PATH))) {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.SCHEMA_SEARCH_PATH);
ArrayList<String> list = New.arrayList();
list.add(readAliasIdentifier());
while (readIf(",")) {
list.add(readAliasIdentifier());
}
command.setStringArray(list.toArray(new String[0]));
return command;
} else if (readIf("JAVA_OBJECT_SERIALIZER")) {
readIfEqualOrTo();
return parseSetJavaObjectSerializer();
} else {
if (isToken("LOGSIZE")) {
// HSQLDB compatibility
currentToken = SetTypes.getTypeName(SetTypes.MAX_LOG_SIZE);
}
if (isToken("FOREIGN_KEY_CHECKS")) {
// MySQL compatibility
currentToken = SetTypes
.getTypeName(SetTypes.REFERENTIAL_INTEGRITY);
}
int type = SetTypes.getType(currentToken);
if (type < 0) {
throw getSyntaxError();
}
read();
readIfEqualOrTo();
Set command = new Set(session, type);
command.setExpression(readExpression());
return command;
}
}
private Prepared parseUse() {
readIfEqualOrTo();
Set command = new Set(session, SetTypes.SCHEMA);
command.setString(readAliasIdentifier());
return command;
}
private Set parseSetCollation() {
Set command = new Set(session, SetTypes.COLLATION);
String name = readAliasIdentifier();
command.setString(name);
if (equalsToken(name, CompareMode.OFF)) {
return command;
}
Collator coll = CompareMode.getCollator(name);
if (coll == null) {
throw DbException.getInvalidValueException("collation", name);
}
if (readIf("STRENGTH")) {
if (readIf("PRIMARY")) {
command.setInt(Collator.PRIMARY);
} else if (readIf("SECONDARY")) {
command.setInt(Collator.SECONDARY);
} else if (readIf("TERTIARY")) {
command.setInt(Collator.TERTIARY);
} else if (readIf("IDENTICAL")) {
command.setInt(Collator.IDENTICAL);
}
} else {
command.setInt(coll.getStrength());
}
return command;
}
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);
}
private Set parseSetJavaObjectSerializer() {
Set command = new Set(session, SetTypes.JAVA_OBJECT_SERIALIZER);
String name = readString();
command.setString(name);
return command;
}
private RunScriptCommand parseRunScript() {
RunScriptCommand command = new RunScriptCommand(session);
read("FROM");
command.setFileNameExpr(readExpression());
if (readIf("COMPRESSION")) {
command.setCompressionAlgorithm(readUniqueIdentifier());
}
if (readIf("CIPHER")) {
command.setCipher(readUniqueIdentifier());
if (readIf("PASSWORD")) {
command.setPassword(readExpression());
}
}
if (readIf("CHARSET")) {
command.setCharset(Charset.forName(readString()));
}
return command;
}
private ScriptCommand parseScript() {
ScriptCommand command = new ScriptCommand(session);
boolean data = true, passwords = true, settings = true;
boolean dropTables = false, simple = false;
if (readIf("SIMPLE")) {
simple = true;
}
if (readIf("NODATA")) {
data = false;
}
if (readIf("NOPASSWORDS")) {
passwords = false;
}
if (readIf("NOSETTINGS")) {
settings = false;
}
if (readIf("DROP")) {
dropTables = true;
}
if (readIf("BLOCKSIZE")) {
long blockSize = readLong();
command.setLobBlockSize(blockSize);
}
command.setData(data);
command.setPasswords(passwords);
command.setSettings(settings);
command.setDrop(dropTables);
command.setSimple(simple);
if (readIf("TO")) {
command.setFileNameExpr(readExpression());
if (readIf("COMPRESSION")) {
command.setCompressionAlgorithm(readUniqueIdentifier());
}
if (readIf("CIPHER")) {
command.setCipher(readUniqueIdentifier());
if (readIf("PASSWORD")) {
command.setPassword(readExpression());
}
}
if (readIf("CHARSET")) {
command.setCharset(Charset.forName(readString()));
}
}
if (readIf("SCHEMA")) {
HashSet<String> schemaNames = new HashSet<>();
do {
schemaNames.add(readUniqueIdentifier());
} while (readIf(","));
command.setSchemaNames(schemaNames);
} else if (readIf("TABLE")) {
ArrayList<Table> tables = New.arrayList();
do {
tables.add(readTableOrView());
} while (readIf(","));
command.setTables(tables);
}
return command;
}
private Table readTableOrView() {
return readTableOrView(readIdentifierWithSchema(null));
}
private Table readTableOrView(String tableName) {
// same algorithm than readSequence
if (schemaName != null) {
return getSchema().getTableOrView(session, tableName);
}
Table table = database.getSchema(session.getCurrentSchemaName())
.resolveTableOrView(session, tableName);
if (table != null) {
return table;
}
String[] schemaNames = session.getSchemaSearchPath();
if (schemaNames != null) {
for (String name : schemaNames) {
Schema s = database.getSchema(name);
table = s.resolveTableOrView(session, tableName);
if (table != null) {
return table;
}
}
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
private FunctionAlias findFunctionAlias(String schema, String aliasName) {
FunctionAlias functionAlias = database.getSchema(schema).findFunction(
aliasName);
if (functionAlias != null) {
return functionAlias;
}
String[] schemaNames = session.getSchemaSearchPath();
if (schemaNames != null) {
for (String n : schemaNames) {
functionAlias = database.getSchema(n).findFunction(aliasName);
if (functionAlias != null) {
return functionAlias;
}
}
}
return null;
}
private Sequence findSequence(String schema, String sequenceName) {
Sequence sequence = database.getSchema(schema).findSequence(
sequenceName);
if (sequence != null) {
return sequence;
}
String[] schemaNames = session.getSchemaSearchPath();
if (schemaNames != null) {
for (String n : schemaNames) {
sequence = database.getSchema(n).findSequence(sequenceName);
if (sequence != null) {
return sequence;
}
}
}
return null;
}
private Sequence readSequence() {
// same algorithm as readTableOrView
String sequenceName = readIdentifierWithSchema(null);
if (schemaName != null) {
return getSchema().getSequence(sequenceName);
}
Sequence sequence = findSequence(session.getCurrentSchemaName(),
sequenceName);
if (sequence != null) {
return sequence;
}
throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, sequenceName);
}
private Prepared parseAlterTable() {
boolean ifTableExists = readIfExists(false);
String tableName = readIdentifierWithSchema();
Schema schema = getSchema();
if (readIf("ADD")) {
Prepared command = parseAlterTableAddConstraintIf(tableName,
schema, ifTableExists);
if (command != null) {
return command;
}
return parseAlterTableAddColumn(tableName, schema, ifTableExists);
} else if (readIf("SET")) {
read("REFERENTIAL_INTEGRITY");
int type = CommandInterface.ALTER_TABLE_SET_REFERENTIAL_INTEGRITY;
boolean value = readBooleanSetting();
AlterTableSet command = new AlterTableSet(session,
schema, type, value);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
if (readIf("CHECK")) {
command.setCheckExisting(true);
} else if (readIf("NOCHECK")) {
command.setCheckExisting(false);
}
return command;
} else if (readIf("RENAME")) {
if (readIf("COLUMN")) {
// PostgreSQL syntax
String columnName = readColumnIdentifier();
read("TO");
AlterTableRenameColumn command = new AlterTableRenameColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumnName(columnName);
String newName = readColumnIdentifier();
command.setNewColumnName(newName);
return command;
} else if (readIf("CONSTRAINT")) {
String constraintName = readIdentifierWithSchema(schema.getName());
checkSchema(schema);
read("TO");
AlterTableRenameConstraint command = new AlterTableRenameConstraint(
session, schema);
command.setConstraintName(constraintName);
String newName = readColumnIdentifier();
command.setNewConstraintName(newName);
return commandIfTableExists(schema, tableName, ifTableExists, command);
} else {
read("TO");
String newName = readIdentifierWithSchema(schema.getName());
checkSchema(schema);
AlterTableRename command = new AlterTableRename(session,
getSchema());
command.setOldTableName(tableName);
command.setNewTableName(newName);
command.setIfTableExists(ifTableExists);
command.setHidden(readIf("HIDDEN"));
return command;
}
} else if (readIf("DROP")) {
if (readIf("CONSTRAINT")) {
boolean ifExists = readIfExists(false);
String constraintName = readIdentifierWithSchema(schema.getName());
ifExists = readIfExists(ifExists);
checkSchema(schema);
AlterTableDropConstraint command = new AlterTableDropConstraint(
session, getSchema(), ifExists);
command.setConstraintName(constraintName);
return commandIfTableExists(schema, tableName, ifTableExists, command);
} else if (readIf("FOREIGN")) {
// MySQL compatibility
read("KEY");
String constraintName = readIdentifierWithSchema(schema.getName());
checkSchema(schema);
AlterTableDropConstraint command = new AlterTableDropConstraint(
session, getSchema(), false);
command.setConstraintName(constraintName);
return commandIfTableExists(schema, tableName, ifTableExists, command);
} else if (readIf("INDEX")) {
// MySQL compatibility
String indexOrConstraintName = readIdentifierWithSchema();
final SchemaCommand command;
if (schema.findIndex(session, indexOrConstraintName) != null) {
DropIndex dropIndexCommand = new DropIndex(session, getSchema());
dropIndexCommand.setIndexName(indexOrConstraintName);
command = dropIndexCommand;
} else {
AlterTableDropConstraint dropCommand = new AlterTableDropConstraint(
session, getSchema(), false/*ifExists*/);
dropCommand.setConstraintName(indexOrConstraintName);
command = dropCommand;
}
return commandIfTableExists(schema, tableName, ifTableExists, command);
} else if (readIf("PRIMARY")) {
read("KEY");
Table table = tableIfTableExists(schema, tableName, ifTableExists);
if (table == null) {
return new NoOperation(session);
}
Index idx = table.getPrimaryKey();
DropIndex command = new DropIndex(session, schema);
command.setIndexName(idx.getName());
return command;
} else {
readIf("COLUMN");
boolean ifExists = readIfExists(false);
ArrayList<Column> columnsToRemove = New.arrayList();
Table table = tableIfTableExists(schema, tableName, ifTableExists);
// For Oracle compatibility - open bracket required
boolean openingBracketDetected = readIf("(");
do {
String columnName = readColumnIdentifier();
if (table != null) {
if (!ifExists || table.doesColumnExist(columnName)) {
Column column = table.getColumn(columnName);
columnsToRemove.add(column);
}
}
} while (readIf(","));
if (openingBracketDetected) {
// For Oracle compatibility - close bracket
read(")");
}
if (table == null || columnsToRemove.isEmpty()) {
return new NoOperation(session);
}
AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
command.setType(CommandInterface.ALTER_TABLE_DROP_COLUMN);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setColumnsToRemove(columnsToRemove);
return command;
}
} else if (readIf("CHANGE")) {
// MySQL compatibility
readIf("COLUMN");
String columnName = readColumnIdentifier();
String newColumnName = readColumnIdentifier();
Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
boolean nullable = column == null ? true : column.isNullable();
// new column type ignored. RENAME and MODIFY are
// a single command in MySQL but two different commands in H2.
parseColumnForTable(newColumnName, nullable);
AlterTableRenameColumn command = new AlterTableRenameColumn(session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumnName(columnName);
command.setNewColumnName(newColumnName);
return command;
} else if (readIf("MODIFY")) {
// MySQL compatibility (optional)
readIf("COLUMN");
// Oracle specifies (but will not require) an opening parenthesis
boolean hasOpeningBracket = readIf("(");
String columnName = readColumnIdentifier();
AlterTableAlterColumn command = null;
NullConstraintType nullConstraint = parseNotNullConstraint();
switch (nullConstraint) {
case NULL_IS_ALLOWED:
case NULL_IS_NOT_ALLOWED:
command = new AlterTableAlterColumn(session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
command.setOldColumn(column);
if (nullConstraint == NullConstraintType.NULL_IS_ALLOWED) {
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
} else {
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL);
}
break;
case NO_NULL_CONSTRAINT_FOUND:
command = parseAlterTableAlterColumnType(schema, tableName, columnName, ifTableExists);
break;
default:
throw DbException.get(ErrorCode.UNKNOWN_MODE_1,
"Internal Error - unhandled case: " + nullConstraint.name());
}
if(hasOpeningBracket) {
read(")");
}
return command;
} else if (readIf("ALTER")) {
readIf("COLUMN");
String columnName = readColumnIdentifier();
Column column = columnIfTableExists(schema, tableName, columnName, ifTableExists);
if (readIf("RENAME")) {
read("TO");
AlterTableRenameColumn command = new AlterTableRenameColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumnName(columnName);
String newName = readColumnIdentifier();
command.setNewColumnName(newName);
return command;
} else if (readIf("DROP")) {
// PostgreSQL compatibility
if (readIf("DEFAULT")) {
AlterTableAlterColumn command = new AlterTableAlterColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumn(column);
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT);
command.setDefaultExpression(null);
return command;
}
if (readIf("ON")) {
read("UPDATE");
AlterTableAlterColumn command = new AlterTableAlterColumn(session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumn(column);
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE);
command.setDefaultExpression(null);
return command;
}
read("NOT");
read("NULL");
AlterTableAlterColumn command = new AlterTableAlterColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumn(column);
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
return command;
} else if (readIf("TYPE")) {
// PostgreSQL compatibility
return parseAlterTableAlterColumnType(schema, tableName,
columnName, ifTableExists);
} else if (readIf("SET")) {
if (readIf("DATA")) {
// Derby compatibility
read("TYPE");
return parseAlterTableAlterColumnType(schema, tableName, columnName,
ifTableExists);
}
AlterTableAlterColumn command = new AlterTableAlterColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setOldColumn(column);
NullConstraintType nullConstraint = parseNotNullConstraint();
switch (nullConstraint) {
case NULL_IS_ALLOWED:
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL);
break;
case NULL_IS_NOT_ALLOWED:
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL);
break;
case NO_NULL_CONSTRAINT_FOUND:
if (readIf("DEFAULT")) {
Expression defaultExpression = readExpression();
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT);
command.setDefaultExpression(defaultExpression);
} else if (readIf("ON")) {
read("UPDATE");
Expression onUpdateExpression = readExpression();
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE);
command.setDefaultExpression(onUpdateExpression);
} else if (readIf("INVISIBLE")) {
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY);
command.setVisible(false);
} else if (readIf("VISIBLE")) {
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY);
command.setVisible(true);
}
break;
default:
throw DbException.get(ErrorCode.UNKNOWN_MODE_1,
"Internal Error - unhandled case: " + nullConstraint.name());
}
return command;
} else if (readIf("RESTART")) {
readIf("WITH");
Expression start = readExpression();
AlterSequence command = new AlterSequence(session, schema);
command.setColumn(column);
command.setStartWith(start);
return commandIfTableExists(schema, tableName, ifTableExists, command);
} else if (readIf("SELECTIVITY")) {
AlterTableAlterColumn command = new AlterTableAlterColumn(
session, schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_SELECTIVITY);
command.setOldColumn(column);
command.setSelectivity(readExpression());
return command;
} else {
return parseAlterTableAlterColumnType(schema, tableName,
columnName, ifTableExists);
}
}
throw getSyntaxError();
}
private Table tableIfTableExists(Schema schema, String tableName, boolean ifTableExists) {
Table table = schema.resolveTableOrView(session, tableName);
if (table == null && !ifTableExists) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
return table;
}
private Column columnIfTableExists(Schema schema, String tableName,
String columnName, boolean ifTableExists) {
Table table = tableIfTableExists(schema, tableName, ifTableExists);
return table == null ? null : table.getColumn(columnName);
}
private Prepared commandIfTableExists(Schema schema, String tableName,
boolean ifTableExists, Prepared commandIfTableExists) {
return tableIfTableExists(schema, tableName, ifTableExists) == null
? new NoOperation(session)
: commandIfTableExists;
}
private AlterTableAlterColumn parseAlterTableAlterColumnType(Schema schema,
String tableName, String columnName, boolean ifTableExists) {
Column oldColumn = columnIfTableExists(schema, tableName, columnName, ifTableExists);
Column newColumn = parseColumnForTable(columnName,
oldColumn == null ? true : oldColumn.isNullable());
AlterTableAlterColumn command = new AlterTableAlterColumn(session,
schema);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setType(CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE);
command.setOldColumn(oldColumn);
command.setNewColumn(newColumn);
return command;
}
private AlterTableAlterColumn parseAlterTableAddColumn(String tableName,
Schema schema, boolean ifTableExists) {
readIf("COLUMN");
AlterTableAlterColumn command = new AlterTableAlterColumn(session,
schema);
command.setType(CommandInterface.ALTER_TABLE_ADD_COLUMN);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
if (readIf("(")) {
command.setIfNotExists(false);
do {
parseTableColumnDefinition(command, schema, tableName);
} while (readIfMore(true));
} else {
boolean ifNotExists = readIfNotExists();
command.setIfNotExists(ifNotExists);
parseTableColumnDefinition(command, schema, tableName);
}
if (readIf("BEFORE")) {
command.setAddBefore(readColumnIdentifier());
} else if (readIf("AFTER")) {
command.setAddAfter(readColumnIdentifier());
} else if (readIf("FIRST")) {
command.setAddFirst();
}
return command;
}
private ConstraintActionType parseAction() {
ConstraintActionType result = parseCascadeOrRestrict();
if (result != null) {
return result;
}
if (readIf("NO")) {
read("ACTION");
return ConstraintActionType.RESTRICT;
}
read("SET");
if (readIf("NULL")) {
return ConstraintActionType.SET_NULL;
}
read("DEFAULT");
return ConstraintActionType.SET_DEFAULT;
}
private ConstraintActionType parseCascadeOrRestrict() {
if (readIf("CASCADE")) {
return ConstraintActionType.CASCADE;
} else if (readIf("RESTRICT")) {
return ConstraintActionType.RESTRICT;
} else {
return null;
}
}
private DefineCommand parseAlterTableAddConstraintIf(String tableName,
Schema schema, boolean ifTableExists) {
String constraintName = null, comment = null;
boolean ifNotExists = false;
boolean allowIndexDefinition = database.getMode().indexDefinitionInCreateTable;
boolean allowAffinityKey = database.getMode().allowAffinityKey;
if (readIf("CONSTRAINT")) {
ifNotExists = readIfNotExists();
constraintName = readIdentifierWithSchema(schema.getName());
checkSchema(schema);
comment = readCommentIf();
allowIndexDefinition = true;
}
if (readIf("PRIMARY")) {
read("KEY");
AlterTableAddConstraint command = new AlterTableAddConstraint(
session, schema, ifNotExists);
command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
command.setComment(comment);
command.setConstraintName(constraintName);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
if (readIf("HASH")) {
command.setPrimaryKeyHash(true);
}
read("(");
command.setIndexColumns(parseIndexColumnList());
if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema();
command.setIndex(getSchema().findIndex(session, indexName));
}
return command;
} else if (allowIndexDefinition && (isToken("INDEX") || isToken("KEY"))) {
// MySQL
// need to read ahead, as it could be a column name
int start = lastParseIndex;
read();
if (DataType.getTypeByName(currentToken, database.getMode()) != null) {
// known data type
parseIndex = start;
read();
return null;
}
CreateIndex command = new CreateIndex(session, schema);
command.setComment(comment);
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
if (!readIf("(")) {
command.setIndexName(readUniqueIdentifier());
read("(");
}
command.setIndexColumns(parseIndexColumnList());
// MySQL compatibility
if (readIf("USING")) {
read("BTREE");
}
return command;
} else if (allowAffinityKey && readIfAffinity()) {
read("KEY");
read("(");
CreateIndex command = createAffinityIndex(schema, tableName, parseIndexColumnList());
command.setIfTableExists(ifTableExists);
return command;
}
AlterTableAddConstraint command;
if (readIf("CHECK")) {
command = new AlterTableAddConstraint(session, schema, ifNotExists);
command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK);
command.setCheckExpression(readExpression());
} else if (readIf("UNIQUE")) {
readIf("KEY");
readIf("INDEX");
command = new AlterTableAddConstraint(session, schema, ifNotExists);
command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE);
if (!readIf("(")) {
constraintName = readUniqueIdentifier();
read("(");
}
command.setIndexColumns(parseIndexColumnList());
if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema();
command.setIndex(getSchema().findIndex(session, indexName));
}
// MySQL compatibility
if (readIf("USING")) {
read("BTREE");
}
} else if (readIf("FOREIGN")) {
command = new AlterTableAddConstraint(session, schema, ifNotExists);
command.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL);
read("KEY");
read("(");
command.setIndexColumns(parseIndexColumnList());
if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema();
command.setIndex(schema.findIndex(session, indexName));
}
read("REFERENCES");
parseReferences(command, schema, tableName);
} else {
if (constraintName != null) {
throw getSyntaxError();
}
return null;
}
if (readIf("NOCHECK")) {
command.setCheckExisting(false);
} else {
readIf("CHECK");
command.setCheckExisting(true);
}
command.setTableName(tableName);
command.setIfTableExists(ifTableExists);
command.setConstraintName(constraintName);
command.setComment(comment);
return command;
}
private void parseReferences(AlterTableAddConstraint command,
Schema schema, String tableName) {
if (readIf("(")) {
command.setRefTableName(schema, tableName);
command.setRefIndexColumns(parseIndexColumnList());
} else {
String refTableName = readIdentifierWithSchema(schema.getName());
command.setRefTableName(getSchema(), refTableName);
if (readIf("(")) {
command.setRefIndexColumns(parseIndexColumnList());
}
}
if (readIf("INDEX")) {
String indexName = readIdentifierWithSchema();
command.setRefIndex(getSchema().findIndex(session, indexName));
}
while (readIf("ON")) {
if (readIf("DELETE")) {
command.setDeleteAction(parseAction());
} else {
read("UPDATE");
command.setUpdateAction(parseAction());
}
}
if (readIf("NOT")) {
read("DEFERRABLE");
} else {
readIf("DEFERRABLE");
}
}
private CreateLinkedTable parseCreateLinkedTable(boolean temp,
boolean globalTemp, boolean force) {
read("TABLE");
boolean ifNotExists = readIfNotExists();
String tableName = readIdentifierWithSchema();
CreateLinkedTable command = new CreateLinkedTable(session, getSchema());
command.setTemporary(temp);
command.setGlobalTemporary(globalTemp);
command.setForce(force);
command.setIfNotExists(ifNotExists);
command.setTableName(tableName);
command.setComment(readCommentIf());
read("(");
command.setDriver(readString());
read(",");
command.setUrl(readString());
read(",");
command.setUser(readString());
read(",");
command.setPassword(readString());
read(",");
String originalTable = readString();
if (readIf(",")) {
command.setOriginalSchema(originalTable);
originalTable = readString();
}
command.setOriginalTable(originalTable);
read(")");
if (readIf("EMIT")) {
read("UPDATES");
command.setEmitUpdates(true);
} else if (readIf("READONLY")) {
command.setReadOnly(true);
}
return command;
}
private CreateTable parseCreateTable(boolean temp, boolean globalTemp,
boolean persistIndexes) {
boolean ifNotExists = readIfNotExists();
String tableName = readIdentifierWithSchema();
if (temp && globalTemp && equalsToken("SESSION", schemaName)) {
// support weird syntax: declare global temporary table session.xy
// (...) not logged
schemaName = session.getCurrentSchemaName();
globalTemp = false;
}
Schema schema = getSchema();
CreateTable command = new CreateTable(session, schema);
command.setPersistIndexes(persistIndexes);
command.setTemporary(temp);
command.setGlobalTemporary(globalTemp);
command.setIfNotExists(ifNotExists);
command.setTableName(tableName);
command.setComment(readCommentIf());
if (readIf("(")) {
if (!readIf(")")) {
do {
parseTableColumnDefinition(command, schema, tableName);
} while (readIfMore(false));
}
}
// Allows "COMMENT='comment'" in DDL statements (MySQL syntax)
if (readIf("COMMENT")) {
if (readIf("=")) {
// read the complete string comment, but nothing with it for now
readString();
}
}
if (readIf("ENGINE")) {
if (readIf("=")) {
// map MySQL engine types onto H2 behavior
String tableEngine = readUniqueIdentifier();
if ("InnoDb".equalsIgnoreCase(tableEngine)) {
// ok
} else if (!"MyISAM".equalsIgnoreCase(tableEngine)) {
throw DbException.getUnsupportedException(tableEngine);
}
} else {
command.setTableEngine(readUniqueIdentifier());
}
}
if (readIf("WITH")) {
command.setTableEngineParams(readTableEngineParams());
}
// MySQL compatibility
if (readIf("AUTO_INCREMENT")) {
read("=");
if (currentTokenType != VALUE ||
currentValue.getType() != Value.INT) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"integer");
}
read();
}
readIf("DEFAULT");
if (readIf("CHARSET")) {
read("=");
if (!readIf("UTF8")) {
read("UTF8MB4");
}
}
if (temp) {
if (readIf("ON")) {
read("COMMIT");
if (readIf("DROP")) {
command.setOnCommitDrop();
} else if (readIf("DELETE")) {
read("ROWS");
command.setOnCommitTruncate();
}
} else if (readIf("NOT")) {
if (readIf("PERSISTENT")) {
command.setPersistData(false);
} else {
read("LOGGED");
}
}
if (readIf("TRANSACTIONAL")) {
command.setTransactional(true);
}
} else if (!persistIndexes && readIf("NOT")) {
read("PERSISTENT");
command.setPersistData(false);
}
if (readIf("HIDDEN")) {
command.setHidden(true);
}
if (readIf("AS")) {
if (readIf("SORTED")) {
command.setSortedInsertMode(true);
}
command.setQuery(parseSelect());
}
// for MySQL compatibility
if (readIf("ROW_FORMAT")) {
if (readIf("=")) {
readColumnIdentifier();
}
}
return command;
}
private void parseTableColumnDefinition(CommandWithColumns command, Schema schema, String tableName) {
DefineCommand c = parseAlterTableAddConstraintIf(tableName,
schema, false);
if (c != null) {
command.addConstraintCommand(c);
} else {
String columnName = readColumnIdentifier();
Column column = parseColumnForTable(columnName, true);
if (column.isAutoIncrement() && column.isPrimaryKey()) {
column.setPrimaryKey(false);
IndexColumn[] cols = { new IndexColumn() };
cols[0].columnName = column.getName();
AlterTableAddConstraint pk = new AlterTableAddConstraint(
session, schema, false);
pk.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
pk.setTableName(tableName);
pk.setIndexColumns(cols);
command.addConstraintCommand(pk);
}
command.addColumn(column);
String constraintName = null;
if (readIf("CONSTRAINT")) {
constraintName = readColumnIdentifier();
}
// For compatibility with Apache Ignite.
boolean allowAffinityKey = database.getMode().allowAffinityKey;
boolean affinity = allowAffinityKey && readIfAffinity();
if (readIf("PRIMARY")) {
read("KEY");
boolean hash = readIf("HASH");
IndexColumn[] cols = { new IndexColumn() };
cols[0].columnName = column.getName();
AlterTableAddConstraint pk = new AlterTableAddConstraint(
session, schema, false);
pk.setConstraintName(constraintName);
pk.setPrimaryKeyHash(hash);
pk.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY);
pk.setTableName(tableName);
pk.setIndexColumns(cols);
command.addConstraintCommand(pk);
if (readIf("AUTO_INCREMENT")) {
parseAutoIncrement(column);
}
if (affinity) {
CreateIndex idx = createAffinityIndex(schema, tableName, cols);
command.addConstraintCommand(idx);
}
} else if (affinity) {
read("KEY");
IndexColumn[] cols = { new IndexColumn() };
cols[0].columnName = column.getName();
CreateIndex idx = createAffinityIndex(schema, tableName, cols);
command.addConstraintCommand(idx);
} else if (readIf("UNIQUE")) {
AlterTableAddConstraint unique = new AlterTableAddConstraint(
session, schema, false);
unique.setConstraintName(constraintName);
unique.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE);
IndexColumn[] cols = { new IndexColumn() };
cols[0].columnName = columnName;
unique.setIndexColumns(cols);
unique.setTableName(tableName);
command.addConstraintCommand(unique);
}
if (NullConstraintType.NULL_IS_NOT_ALLOWED == parseNotNullConstraint()) {
column.setNullable(false);
}
if (readIf("CHECK")) {
Expression expr = readExpression();
column.addCheckConstraint(session, expr);
}
if (readIf("REFERENCES")) {
AlterTableAddConstraint ref = new AlterTableAddConstraint(
session, schema, false);
ref.setConstraintName(constraintName);
ref.setType(CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL);
IndexColumn[] cols = { new IndexColumn() };
cols[0].columnName = columnName;
ref.setIndexColumns(cols);
ref.setTableName(tableName);
parseReferences(ref, schema, tableName);
command.addConstraintCommand(ref);
}
}
}
/**
* Enumeration describing null constraints
*/
private enum NullConstraintType {
NULL_IS_ALLOWED, NULL_IS_NOT_ALLOWED, NO_NULL_CONSTRAINT_FOUND
}
private NullConstraintType parseNotNullConstraint() {
NullConstraintType nullConstraint = NullConstraintType.NO_NULL_CONSTRAINT_FOUND;
if (isToken("NOT") || isToken("NULL")) {
if (readIf("NOT")) {
read("NULL");
nullConstraint = NullConstraintType.NULL_IS_NOT_ALLOWED;
} else {
read("NULL");
nullConstraint = NullConstraintType.NULL_IS_ALLOWED;
}
if (database.getMode().getEnum() == ModeEnum.Oracle) {
if (readIf("ENABLE")) {
// Leave constraint 'as is'
readIf("VALIDATE");
// Turn off constraint, allow NULLs
if (readIf("NOVALIDATE")) {
nullConstraint = NullConstraintType.NULL_IS_ALLOWED;
}
}
// Turn off constraint, allow NULLs
if (readIf("DISABLE")) {
nullConstraint = NullConstraintType.NULL_IS_ALLOWED;
// ignore validate
readIf("VALIDATE");
// ignore novalidate
readIf("NOVALIDATE");
}
}
}
return nullConstraint;
}
private CreateSynonym parseCreateSynonym(boolean orReplace) {
boolean ifNotExists = readIfNotExists();
String name = readIdentifierWithSchema();
Schema synonymSchema = getSchema();
read("FOR");
String tableName = readIdentifierWithSchema();
Schema targetSchema = getSchema();
CreateSynonym command = new CreateSynonym(session, synonymSchema);
command.setName(name);
command.setSynonymFor(tableName);
command.setSynonymForSchema(targetSchema);
command.setComment(readCommentIf());
command.setIfNotExists(ifNotExists);
command.setOrReplace(orReplace);
return command;
}
private CreateIndex createAffinityIndex(Schema schema, String tableName, IndexColumn[] indexColumns) {
CreateIndex idx = new CreateIndex(session, schema);
idx.setTableName(tableName);
idx.setIndexColumns(indexColumns);
idx.setAffinity(true);
return idx;
}
private static int getCompareType(int tokenType) {
switch (tokenType) {
case EQUAL:
return Comparison.EQUAL;
case BIGGER_EQUAL:
return Comparison.BIGGER_EQUAL;
case BIGGER:
return Comparison.BIGGER;
case SMALLER:
return Comparison.SMALLER;
case SMALLER_EQUAL:
return Comparison.SMALLER_EQUAL;
case NOT_EQUAL:
return Comparison.NOT_EQUAL;
case SPATIAL_INTERSECTS:
return Comparison.SPATIAL_INTERSECTS;
default:
return -1;
}
}
/**
* Add double quotes around an identifier if required.
*
* @param s the identifier
* @return the quoted identifier
*/
public static String quoteIdentifier(String s) {
if (s == null) {
return "\"\"";
}
if (ParserUtil.isSimpleIdentifier(s, false)) {
return s;
}
return StringUtils.quoteIdentifier(s);
}
public void setLiteralsChecked(boolean literalsChecked) {
this.literalsChecked = literalsChecked;
}
public void setRightsChecked(boolean rightsChecked) {
this.rightsChecked = rightsChecked;
}
public void setSuppliedParameterList(ArrayList<Parameter> suppliedParameterList) {
this.suppliedParameterList = suppliedParameterList;
}
/**
* Parse a SQL code snippet that represents an expression.
*
* @param sql the code snippet
* @return the expression object
*/
public Expression parseExpression(String sql) {
parameters = New.arrayList();
initialize(sql);
read();
return readExpression();
}
/**
* Parse a SQL code snippet that represents a table name.
*
* @param sql the code snippet
* @return the table object
*/
public Table parseTableName(String sql) {
parameters = New.arrayList();
initialize(sql);
read();
return readTableOrView();
}
@Override
public String toString() {
return StringUtils.addAsterisk(sqlCommand, parseIndex);
}
}
|
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/command/Prepared.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.command;
import java.util.ArrayList;
import java.util.List;
import org.h2.api.DatabaseEventListener;
import org.h2.api.ErrorCode;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.Parameter;
import org.h2.message.DbException;
import org.h2.message.Trace;
import org.h2.result.ResultInterface;
import org.h2.table.TableView;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
/**
* A prepared statement.
*/
public abstract class Prepared {
/**
* The session.
*/
protected Session session;
/**
* The SQL string.
*/
protected String sqlStatement;
/**
* Whether to create a new object (for indexes).
*/
protected boolean create = true;
/**
* The list of parameters.
*/
protected ArrayList<Parameter> parameters;
/**
* If the query should be prepared before each execution. This is set for
* queries with LIKE ?, because the query plan depends on the parameter
* value.
*/
protected boolean prepareAlways;
private long modificationMetaId;
private Command command;
private int objectId;
private int currentRowNumber;
private int rowScanCount;
/**
* Common table expressions (CTE) in queries require us to create temporary views,
* which need to be cleaned up once a command is done executing.
*/
private List<TableView> cteCleanups;
/**
* Create a new object.
*
* @param session the session
*/
public Prepared(Session session) {
this.session = session;
modificationMetaId = session.getDatabase().getModificationMetaId();
}
/**
* Check if this command is transactional.
* If it is not, then it forces the current transaction to commit.
*
* @return true if it is
*/
public abstract boolean isTransactional();
/**
* Get an empty result set containing the meta data.
*
* @return the result set
*/
public abstract ResultInterface queryMeta();
/**
* Get the command type as defined in CommandInterface
*
* @return the statement type
*/
public abstract int getType();
/**
* Check if this command is read only.
*
* @return true if it is
*/
public boolean isReadOnly() {
return false;
}
/**
* Check if the statement needs to be re-compiled.
*
* @return true if it must
*/
public boolean needRecompile() {
Database db = session.getDatabase();
if (db == null) {
throw DbException.get(ErrorCode.CONNECTION_BROKEN_1, "database closed");
}
// parser: currently, compiling every create/drop/... twice
// because needRecompile return true even for the first execution
return prepareAlways ||
modificationMetaId < db.getModificationMetaId() ||
db.getSettings().recompileAlways;
}
/**
* Get the meta data modification id of the database when this statement was
* compiled.
*
* @return the meta data modification id
*/
long getModificationMetaId() {
return modificationMetaId;
}
/**
* Set the meta data modification id of this statement.
*
* @param id the new id
*/
void setModificationMetaId(long id) {
this.modificationMetaId = id;
}
/**
* Set the parameter list of this statement.
*
* @param parameters the parameter list
*/
public void setParameterList(ArrayList<Parameter> parameters) {
this.parameters = parameters;
}
/**
* Get the parameter list.
*
* @return the parameter list
*/
public ArrayList<Parameter> getParameters() {
return parameters;
}
/**
* Check if all parameters have been set.
*
* @throws DbException if any parameter has not been set
*/
protected void checkParameters() {
if (parameters != null) {
for (Parameter param : parameters) {
param.checkSet();
}
}
}
/**
* Set the command.
*
* @param command the new command
*/
public void setCommand(Command command) {
this.command = command;
}
/**
* Check if this object is a query.
*
* @return true if it is
*/
public boolean isQuery() {
return false;
}
/**
* Prepare this statement.
*/
public void prepare() {
// nothing to do
}
/**
* Execute the statement.
*
* @return the update count
* @throws DbException if it is a query
*/
public int update() {
throw DbException.get(ErrorCode.METHOD_NOT_ALLOWED_FOR_QUERY);
}
/**
* Execute the query.
*
* @param maxrows the maximum number of rows to return
* @return the result set
* @throws DbException if it is not a query
*/
@SuppressWarnings("unused")
public ResultInterface query(int maxrows) {
throw DbException.get(ErrorCode.METHOD_ONLY_ALLOWED_FOR_QUERY);
}
/**
* Set the SQL statement.
*
* @param sql the SQL statement
*/
public void setSQL(String sql) {
this.sqlStatement = sql;
}
/**
* Get the SQL statement.
*
* @return the SQL statement
*/
public String getSQL() {
return sqlStatement;
}
/**
* Get the object id to use for the database object that is created in this
* statement. This id is only set when the object is persistent.
* If not set, this method returns 0.
*
* @return the object id or 0 if not set
*/
protected int getCurrentObjectId() {
return objectId;
}
/**
* Get the current object id, or get a new id from the database. The object
* id is used when creating new database object (CREATE statement).
*
* @return the object id
*/
protected int getObjectId() {
int id = objectId;
if (id == 0) {
id = session.getDatabase().allocateObjectId();
} else {
objectId = 0;
}
return id;
}
/**
* Get the SQL statement with the execution plan.
*
* @return the execution plan
*/
public String getPlanSQL() {
return null;
}
/**
* Check if this statement was canceled.
*
* @throws DbException if it was canceled
*/
public void checkCanceled() {
session.checkCanceled();
Command c = command != null ? command : session.getCurrentCommand();
if (c != null) {
c.checkCanceled();
}
}
/**
* Set the object id for this statement.
*
* @param i the object id
*/
public void setObjectId(int i) {
this.objectId = i;
this.create = false;
}
/**
* Set the session for this statement.
*
* @param currentSession the new session
*/
public void setSession(Session currentSession) {
this.session = currentSession;
}
/**
* Print information about the statement executed if info trace level is
* enabled.
*
* @param startTimeNanos when the statement was started
* @param rowCount the query or update row count
*/
void trace(long startTimeNanos, int rowCount) {
if (session.getTrace().isInfoEnabled() && startTimeNanos > 0) {
long deltaTimeNanos = System.nanoTime() - startTimeNanos;
String params = Trace.formatParams(parameters);
session.getTrace().infoSQL(sqlStatement, params, rowCount,
deltaTimeNanos / 1000 / 1000);
}
// startTime_nanos can be zero for the command that actually turns on
// statistics
if (session.getDatabase().getQueryStatistics() && startTimeNanos != 0) {
long deltaTimeNanos = System.nanoTime() - startTimeNanos;
session.getDatabase().getQueryStatisticsData().
update(toString(), deltaTimeNanos, rowCount);
}
}
/**
* Set the prepare always flag.
* If set, the statement is re-compiled whenever it is executed.
*
* @param prepareAlways the new value
*/
public void setPrepareAlways(boolean prepareAlways) {
this.prepareAlways = prepareAlways;
}
/**
* Set the current row number.
*
* @param rowNumber the row number
*/
protected void setCurrentRowNumber(int rowNumber) {
if ((++rowScanCount & 127) == 0) {
checkCanceled();
}
this.currentRowNumber = rowNumber;
setProgress();
}
/**
* Get the current row number.
*
* @return the row number
*/
public int getCurrentRowNumber() {
return currentRowNumber;
}
/**
* Notifies query progress via the DatabaseEventListener
*/
private void setProgress() {
if ((currentRowNumber & 127) == 0) {
session.getDatabase().setProgress(
DatabaseEventListener.STATE_STATEMENT_PROGRESS,
sqlStatement, currentRowNumber, 0);
}
}
/**
* Convert the statement to a String.
*
* @return the SQL statement
*/
@Override
public String toString() {
return sqlStatement;
}
/**
* Get the SQL snippet of the value list.
*
* @param values the value list
* @return the SQL snippet
*/
protected static String getSQL(Value[] values) {
StatementBuilder buff = new StatementBuilder();
for (Value v : values) {
buff.appendExceptFirst(", ");
if (v != null) {
buff.append(v.getSQL());
}
}
return buff.toString();
}
/**
* Get the SQL snippet of the expression list.
*
* @param list the expression list
* @return the SQL snippet
*/
protected static String getSQL(Expression[] list) {
StatementBuilder buff = new StatementBuilder();
for (Expression e : list) {
buff.appendExceptFirst(", ");
if (e != null) {
buff.append(e.getSQL());
}
}
return buff.toString();
}
/**
* Set the SQL statement of the exception to the given row.
*
* @param e the exception
* @param rowId the row number
* @param values the values of the row
* @return the exception
*/
protected DbException setRow(DbException e, int rowId, String values) {
StringBuilder buff = new StringBuilder();
if (sqlStatement != null) {
buff.append(sqlStatement);
}
buff.append(" -- ");
if (rowId > 0) {
buff.append("row #").append(rowId + 1).append(' ');
}
buff.append('(').append(values).append(')');
return e.addSQL(buff.toString());
}
public boolean isCacheable() {
return false;
}
/**
* @return the temporary views created for CTE's.
*/
public List<TableView> getCteCleanups() {
return cteCleanups;
}
/**
* Set the temporary views created for CTE's.
*
* @param cteCleanups the temporary views
*/
public void setCteCleanups(List<TableView> cteCleanups) {
this.cteCleanups = cteCleanups;
}
public Session getSession() {
return session;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterIndexRename.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* ALTER INDEX RENAME
*/
public class AlterIndexRename extends DefineCommand {
private boolean ifExists;
private Schema oldSchema;
private String oldIndexName;
private Index oldIndex;
private String newIndexName;
public AlterIndexRename(Session session) {
super(session);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setOldSchema(Schema old) {
oldSchema = old;
}
public void setOldName(String name) {
oldIndexName = name;
}
public void setNewName(String name) {
newIndexName = name;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
oldIndex = oldSchema.findIndex(session, oldIndexName);
if (oldIndex == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1,
newIndexName);
}
return 0;
}
if (oldSchema.findIndex(session, newIndexName) != null ||
newIndexName.equals(oldIndexName)) {
throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1,
newIndexName);
}
session.getUser().checkRight(oldIndex.getTable(), Right.ALL);
db.renameSchemaObject(session, oldIndex, newIndexName);
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_INDEX_RENAME;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterSchemaRename.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import java.util.ArrayList;
/**
* This class represents the statement
* ALTER SCHEMA RENAME
*/
public class AlterSchemaRename extends DefineCommand {
private Schema oldSchema;
private String newSchemaName;
public AlterSchemaRename(Session session) {
super(session);
}
public void setOldSchema(Schema schema) {
oldSchema = schema;
}
public void setNewName(String name) {
newSchemaName = name;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
if (!oldSchema.canDrop()) {
throw DbException.get(ErrorCode.SCHEMA_CAN_NOT_BE_DROPPED_1,
oldSchema.getName());
}
if (db.findSchema(newSchemaName) != null ||
newSchemaName.equals(oldSchema.getName())) {
throw DbException.get(ErrorCode.SCHEMA_ALREADY_EXISTS_1,
newSchemaName);
}
session.getUser().checkSchemaAdmin();
db.renameDatabaseObject(session, oldSchema, newSchemaName);
ArrayList<SchemaObject> all = db.getAllSchemaObjects();
for (SchemaObject schemaObject : all) {
db.updateMeta(session, schemaObject);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_SCHEMA_RENAME;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableAddConstraint.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.command.ddl;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintActionType;
import org.h2.constraint.ConstraintCheck;
import org.h2.constraint.ConstraintReferential;
import org.h2.constraint.ConstraintUnique;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
/**
* This class represents the statement
* ALTER TABLE ADD CONSTRAINT
*/
public class AlterTableAddConstraint extends SchemaCommand {
private int type;
private String constraintName;
private String tableName;
private IndexColumn[] indexColumns;
private ConstraintActionType deleteAction = ConstraintActionType.RESTRICT;
private ConstraintActionType updateAction = ConstraintActionType.RESTRICT;
private Schema refSchema;
private String refTableName;
private IndexColumn[] refIndexColumns;
private Expression checkExpression;
private Index index, refIndex;
private String comment;
private boolean checkExisting;
private boolean primaryKeyHash;
private boolean ifTableExists;
private final boolean ifNotExists;
private final ArrayList<Index> createdIndexes = New.arrayList();
public AlterTableAddConstraint(Session session, Schema schema,
boolean ifNotExists) {
super(session, schema);
this.ifNotExists = ifNotExists;
}
public void setIfTableExists(boolean b) {
ifTableExists = b;
}
private String generateConstraintName(Table table) {
if (constraintName == null) {
constraintName = getSchema().getUniqueConstraintName(
session, table);
}
return constraintName;
}
@Override
public int update() {
try {
return tryUpdate();
} catch (DbException e) {
for (Index index : createdIndexes) {
session.getDatabase().removeSchemaObject(session, index);
}
throw e;
} finally {
getSchema().freeUniqueName(constraintName);
}
}
/**
* 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;
}
private Index createIndex(Table t, IndexColumn[] cols, boolean unique) {
int indexId = getObjectId();
IndexType indexType;
if (unique) {
// for unique constraints
indexType = IndexType.createUnique(t.isPersistIndexes(), false);
} else {
// constraints
indexType = IndexType.createNonUnique(t.isPersistIndexes());
}
indexType.setBelongsToConstraint(true);
String prefix = constraintName == null ? "CONSTRAINT" : constraintName;
String indexName = t.getSchema().getUniqueIndexName(session, t,
prefix + "_INDEX_");
try {
Index index = t.addIndex(session, indexName, indexId, cols,
indexType, true, null);
createdIndexes.add(index);
return index;
} finally {
getSchema().freeUniqueName(indexName);
}
}
public void setDeleteAction(ConstraintActionType action) {
this.deleteAction = action;
}
public void setUpdateAction(ConstraintActionType action) {
this.updateAction = action;
}
private static Index getUniqueIndex(Table t, IndexColumn[] cols) {
if (t.getIndexes() == null) {
return null;
}
for (Index idx : t.getIndexes()) {
if (canUseUniqueIndex(idx, t, cols)) {
return idx;
}
}
return null;
}
private static Index getIndex(Table t, IndexColumn[] cols, boolean moreColumnOk) {
if (t.getIndexes() == null) {
return null;
}
for (Index idx : t.getIndexes()) {
if (canUseIndex(idx, t, cols, moreColumnOk)) {
return idx;
}
}
return null;
}
// all cols must be in the index key, the order doesn't matter and there
// must be no other fields in the index key
private static boolean canUseUniqueIndex(Index idx, Table table, IndexColumn[] cols) {
if (idx.getTable() != table || !idx.getIndexType().isUnique()) {
return false;
}
Column[] indexCols = idx.getColumns();
HashSet<Column> indexColsSet = new HashSet<>();
Collections.addAll(indexColsSet, indexCols);
HashSet<Column> colsSet = new HashSet<>();
for (IndexColumn c : cols) {
colsSet.add(c.column);
}
return colsSet.equals(indexColsSet);
}
private static boolean canUseIndex(Index existingIndex, Table table,
IndexColumn[] cols, boolean moreColumnsOk) {
if (existingIndex.getTable() != table || existingIndex.getCreateSQL() == null) {
// can't use the scan index or index of another table
return false;
}
Column[] indexCols = existingIndex.getColumns();
if (moreColumnsOk) {
if (indexCols.length < cols.length) {
return false;
}
for (IndexColumn col : cols) {
// all columns of the list must be part of the index,
// but not all columns of the index need to be part of the list
// holes are not allowed (index=a,b,c & list=a,b is ok;
// but list=a,c is not)
int idx = existingIndex.getColumnIndex(col.column);
if (idx < 0 || idx >= cols.length) {
return false;
}
}
} else {
if (indexCols.length != cols.length) {
return false;
}
for (IndexColumn col : cols) {
// all columns of the list must be part of the index
int idx = existingIndex.getColumnIndex(col.column);
if (idx < 0) {
return false;
}
}
}
return true;
}
public void setConstraintName(String constraintName) {
this.constraintName = constraintName;
}
public void setType(int type) {
this.type = type;
}
@Override
public int getType() {
return type;
}
public void setCheckExpression(Expression expression) {
this.checkExpression = expression;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setIndexColumns(IndexColumn[] indexColumns) {
this.indexColumns = indexColumns;
}
public IndexColumn[] getIndexColumns() {
return indexColumns;
}
/**
* Set the referenced table.
*
* @param refSchema the schema
* @param ref the table name
*/
public void setRefTableName(Schema refSchema, String ref) {
this.refSchema = refSchema;
this.refTableName = ref;
}
public void setRefIndexColumns(IndexColumn[] indexColumns) {
this.refIndexColumns = indexColumns;
}
public void setIndex(Index index) {
this.index = index;
}
public void setRefIndex(Index refIndex) {
this.refIndex = refIndex;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setCheckExisting(boolean b) {
this.checkExisting = b;
}
public void setPrimaryKeyHash(boolean b) {
this.primaryKeyHash = b;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableAlterColumn.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.command.ddl;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Parser;
import org.h2.command.Prepared;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintReferential;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.schema.Sequence;
import org.h2.schema.TriggerObject;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableView;
import org.h2.util.New;
/**
* This class represents the statements
* ALTER TABLE ADD,
* ALTER TABLE ADD IF NOT EXISTS,
* ALTER TABLE ALTER COLUMN,
* ALTER TABLE ALTER COLUMN RESTART,
* ALTER TABLE ALTER COLUMN SELECTIVITY,
* ALTER TABLE ALTER COLUMN SET DEFAULT,
* ALTER TABLE ALTER COLUMN SET NOT NULL,
* ALTER TABLE ALTER COLUMN SET NULL,
* ALTER TABLE ALTER COLUMN SET VISIBLE,
* ALTER TABLE ALTER COLUMN SET INVISIBLE,
* ALTER TABLE DROP COLUMN
*/
public class AlterTableAlterColumn extends CommandWithColumns {
private String tableName;
private Column oldColumn;
private Column newColumn;
private int type;
/**
* Default or on update expression.
*/
private Expression defaultExpression;
private Expression newSelectivity;
private boolean addFirst;
private String addBefore;
private String addAfter;
private boolean ifTableExists;
private boolean ifNotExists;
private ArrayList<Column> columnsToAdd;
private ArrayList<Column> columnsToRemove;
private boolean newVisibility;
public AlterTableAlterColumn(Session session, Schema schema) {
super(session, schema);
}
public void setIfTableExists(boolean b) {
ifTableExists = b;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setOldColumn(Column oldColumn) {
this.oldColumn = oldColumn;
}
/**
* Add the column as the first column of the table.
*/
public void setAddFirst() {
addFirst = true;
}
public void setAddBefore(String before) {
this.addBefore = before;
}
public void setAddAfter(String after) {
this.addAfter = after;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
Table table = getSchema().resolveTableOrView(session, tableName);
if (table == null) {
if (ifTableExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
session.getUser().checkRight(table, Right.ALL);
table.checkSupportAlter();
table.lock(session, true, true);
if (newColumn != null) {
checkDefaultReferencesTable(table, newColumn.getDefaultExpression());
checkClustering(newColumn);
}
if (columnsToAdd != null) {
for (Column column : columnsToAdd) {
checkDefaultReferencesTable(table, column.getDefaultExpression());
checkClustering(column);
}
}
switch (type) {
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NOT_NULL: {
if (!oldColumn.isNullable()) {
// no change
break;
}
checkNoNullValues(table);
oldColumn.setNullable(false);
db.updateMeta(session, table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_NULL: {
if (oldColumn.isNullable()) {
// no change
break;
}
checkNullable(table);
oldColumn.setNullable(true);
db.updateMeta(session, table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_DEFAULT: {
Sequence sequence = oldColumn == null ? null : oldColumn.getSequence();
checkDefaultReferencesTable(table, defaultExpression);
oldColumn.setSequence(null);
oldColumn.setDefaultExpression(session, defaultExpression);
removeSequence(table, sequence);
db.updateMeta(session, table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_ON_UPDATE: {
checkDefaultReferencesTable(table, defaultExpression);
oldColumn.setOnUpdateExpression(session, defaultExpression);
db.updateMeta(session, table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE: {
// if the change is only increasing the precision, then we don't
// need to copy the table because the length is only a constraint,
// and does not affect the storage structure.
if (oldColumn.isWideningConversion(newColumn)) {
convertAutoIncrementColumn(table, newColumn);
oldColumn.copy(newColumn);
db.updateMeta(session, table);
} else {
oldColumn.setSequence(null);
oldColumn.setDefaultExpression(session, null);
oldColumn.setConvertNullToDefault(false);
if (oldColumn.isNullable() && !newColumn.isNullable()) {
checkNoNullValues(table);
} else if (!oldColumn.isNullable() && newColumn.isNullable()) {
checkNullable(table);
}
if (oldColumn.getVisible() ^ newColumn.getVisible()) {
oldColumn.setVisible(newColumn.getVisible());
}
convertAutoIncrementColumn(table, newColumn);
copyData(table);
}
table.setModified();
break;
}
case CommandInterface.ALTER_TABLE_ADD_COLUMN: {
// ifNotExists only supported for single column add
if (ifNotExists && columnsToAdd != null && columnsToAdd.size() == 1 &&
table.doesColumnExist(columnsToAdd.get(0).getName())) {
break;
}
ArrayList<Sequence> sequences = generateSequences(columnsToAdd, false);
if (columnsToAdd != null) {
changePrimaryKeysToNotNull(columnsToAdd);
}
copyData(table, sequences, true);
break;
}
case CommandInterface.ALTER_TABLE_DROP_COLUMN: {
if (table.getColumns().length - columnsToRemove.size() < 1) {
throw DbException.get(ErrorCode.CANNOT_DROP_LAST_COLUMN,
columnsToRemove.get(0).getSQL());
}
table.dropMultipleColumnsConstraintsAndIndexes(session, columnsToRemove);
copyData(table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_SELECTIVITY: {
int value = newSelectivity.optimize(session).getValue(session).getInt();
oldColumn.setSelectivity(value);
db.updateMeta(session, table);
break;
}
case CommandInterface.ALTER_TABLE_ALTER_COLUMN_VISIBILITY: {
oldColumn.setVisible(newVisibility);
table.setModified();
db.updateMeta(session, table);
break;
}
default:
DbException.throwInternalError("type=" + type);
}
return 0;
}
private static void checkDefaultReferencesTable(Table table, Expression defaultExpression) {
if (defaultExpression == null) {
return;
}
HashSet<DbObject> dependencies = new HashSet<>();
ExpressionVisitor visitor = ExpressionVisitor
.getDependenciesVisitor(dependencies);
defaultExpression.isEverything(visitor);
if (dependencies.contains(table)) {
throw DbException.get(ErrorCode.COLUMN_IS_REFERENCED_1,
defaultExpression.getSQL());
}
}
private void checkClustering(Column c) {
if (!Constants.CLUSTERING_DISABLED
.equals(session.getDatabase().getCluster())
&& c.isAutoIncrement()) {
throw DbException.getUnsupportedException(
"CLUSTERING && auto-increment columns");
}
}
private void convertAutoIncrementColumn(Table table, Column c) {
if (c.isAutoIncrement()) {
if (c.isPrimaryKey()) {
c.setOriginalSQL("IDENTITY");
} else {
int objId = getObjectId();
c.convertAutoIncrementToSequence(session, getSchema(), objId,
table.isTemporary());
}
}
}
private void removeSequence(Table table, Sequence sequence) {
if (sequence != null) {
table.removeSequence(sequence);
sequence.setBelongsToTable(false);
Database db = session.getDatabase();
db.removeSchemaObject(session, sequence);
}
}
private void copyData(Table table) {
copyData(table, null, false);
}
private void copyData(Table table, ArrayList<Sequence> sequences, boolean createConstraints) {
if (table.isTemporary()) {
throw DbException.getUnsupportedException("TEMP TABLE");
}
Database db = session.getDatabase();
String baseName = table.getName();
String tempName = db.getTempTableName(baseName, session);
Column[] columns = table.getColumns();
ArrayList<Column> newColumns = New.arrayList();
Table newTable = cloneTableStructure(table, columns, db, tempName, newColumns);
if (sequences != null) {
for (Sequence sequence : sequences) {
table.addSequence(sequence);
}
}
try {
// check if a view would become invalid
// (because the column to drop is referenced or so)
checkViews(table, newTable);
} catch (DbException e) {
execute("DROP TABLE " + newTable.getName(), true);
throw DbException.get(ErrorCode.VIEW_IS_INVALID_2, e, getSQL(), e.getMessage());
}
String tableName = table.getName();
ArrayList<TableView> dependentViews = new ArrayList<>(table.getDependentViews());
for (TableView view : dependentViews) {
table.removeDependentView(view);
}
execute("DROP TABLE " + table.getSQL() + " IGNORE", true);
db.renameSchemaObject(session, newTable, tableName);
for (DbObject child : newTable.getChildren()) {
if (child instanceof Sequence) {
continue;
}
String name = child.getName();
if (name == null || child.getCreateSQL() == null) {
continue;
}
if (name.startsWith(tempName + "_")) {
name = name.substring(tempName.length() + 1);
SchemaObject so = (SchemaObject) child;
if (so instanceof Constraint) {
if (so.getSchema().findConstraint(session, name) != null) {
name = so.getSchema().getUniqueConstraintName(session, newTable);
}
} else if (so instanceof Index) {
if (so.getSchema().findIndex(session, name) != null) {
name = so.getSchema().getUniqueIndexName(session, newTable, name);
}
}
db.renameSchemaObject(session, so, name);
}
}
if (createConstraints) {
createConstraints();
}
for (TableView view : dependentViews) {
String sql = view.getCreateSQL(true, true);
execute(sql, true);
}
}
private Table cloneTableStructure(Table table, Column[] columns, Database db,
String tempName, ArrayList<Column> newColumns) {
for (Column col : columns) {
newColumns.add(col.getClone());
}
if (type == CommandInterface.ALTER_TABLE_DROP_COLUMN) {
for (Column removeCol : columnsToRemove) {
Column foundCol = null;
for (Column newCol : newColumns) {
if (newCol.getName().equals(removeCol.getName())) {
foundCol = newCol;
break;
}
}
if (foundCol == null) {
throw DbException.throwInternalError(removeCol.getCreateSQL());
}
newColumns.remove(foundCol);
}
} else if (type == CommandInterface.ALTER_TABLE_ADD_COLUMN) {
int position;
if (addFirst) {
position = 0;
} else if (addBefore != null) {
position = table.getColumn(addBefore).getColumnId();
} else if (addAfter != null) {
position = table.getColumn(addAfter).getColumnId() + 1;
} else {
position = columns.length;
}
if (columnsToAdd != null) {
for (Column column : columnsToAdd) {
newColumns.add(position++, column);
}
}
} else if (type == CommandInterface.ALTER_TABLE_ALTER_COLUMN_CHANGE_TYPE) {
int position = oldColumn.getColumnId();
newColumns.set(position, newColumn);
}
// create a table object in order to get the SQL statement
// can't just use this table, because most column objects are 'shared'
// with the old table
// still need a new id because using 0 would mean: the new table tries
// to use the rows of the table 0 (the meta table)
int id = db.allocateObjectId();
CreateTableData data = new CreateTableData();
data.tableName = tempName;
data.id = id;
data.columns = newColumns;
data.temporary = table.isTemporary();
data.persistData = table.isPersistData();
data.persistIndexes = table.isPersistIndexes();
data.isHidden = table.isHidden();
data.create = true;
data.session = session;
Table newTable = getSchema().createTable(data);
newTable.setComment(table.getComment());
StringBuilder buff = new StringBuilder();
buff.append(newTable.getCreateSQL());
StringBuilder columnList = new StringBuilder();
for (Column nc : newColumns) {
if (columnList.length() > 0) {
columnList.append(", ");
}
if (type == CommandInterface.ALTER_TABLE_ADD_COLUMN &&
columnsToAdd != null && columnsToAdd.contains(nc)) {
Expression def = nc.getDefaultExpression();
columnList.append(def == null ? "NULL" : def.getSQL());
} else {
columnList.append(nc.getSQL());
}
}
buff.append(" AS SELECT ");
if (columnList.length() == 0) {
// special case: insert into test select * from
buff.append('*');
} else {
buff.append(columnList);
}
buff.append(" FROM ").append(table.getSQL());
String newTableSQL = buff.toString();
String newTableName = newTable.getName();
Schema newTableSchema = newTable.getSchema();
newTable.removeChildrenAndResources(session);
execute(newTableSQL, true);
newTable = newTableSchema.getTableOrView(session, newTableName);
ArrayList<String> triggers = New.arrayList();
for (DbObject child : table.getChildren()) {
if (child instanceof Sequence) {
continue;
} else if (child instanceof Index) {
Index idx = (Index) child;
if (idx.getIndexType().getBelongsToConstraint()) {
continue;
}
}
String createSQL = child.getCreateSQL();
if (createSQL == null) {
continue;
}
if (child instanceof TableView) {
continue;
} else if (child.getType() == DbObject.TABLE_OR_VIEW) {
DbException.throwInternalError();
}
String quotedName = Parser.quoteIdentifier(tempName + "_" + child.getName());
String sql = null;
if (child instanceof ConstraintReferential) {
ConstraintReferential r = (ConstraintReferential) child;
if (r.getTable() != table) {
sql = r.getCreateSQLForCopy(r.getTable(), newTable, quotedName, false);
}
}
if (sql == null) {
sql = child.getCreateSQLForCopy(newTable, quotedName);
}
if (sql != null) {
if (child instanceof TriggerObject) {
triggers.add(sql);
} else {
execute(sql, true);
}
}
}
table.setModified();
// remove the sequences from the columns (except dropped columns)
// otherwise the sequence is dropped if the table is dropped
for (Column col : newColumns) {
Sequence seq = col.getSequence();
if (seq != null) {
table.removeSequence(seq);
col.setSequence(null);
}
}
for (String sql : triggers) {
execute(sql, true);
}
return newTable;
}
/**
* Check that all views and other dependent objects.
*/
private void checkViews(SchemaObject sourceTable, SchemaObject newTable) {
String sourceTableName = sourceTable.getName();
String newTableName = newTable.getName();
Database db = sourceTable.getDatabase();
// save the real table under a temporary name
String temp = db.getTempTableName(sourceTableName, session);
db.renameSchemaObject(session, sourceTable, temp);
try {
// have our new table impersonate the target table
db.renameSchemaObject(session, newTable, sourceTableName);
checkViewsAreValid(sourceTable);
} finally {
// always put the source tables back with their proper names
try {
db.renameSchemaObject(session, newTable, newTableName);
} finally {
db.renameSchemaObject(session, sourceTable, sourceTableName);
}
}
}
/**
* Check that a table or view is still valid.
*
* @param tableOrView the table or view to check
*/
private void checkViewsAreValid(DbObject tableOrView) {
for (DbObject view : tableOrView.getChildren()) {
if (view instanceof TableView) {
String sql = ((TableView) view).getQuery();
// check if the query is still valid
// do not execute, not even with limit 1, because that could
// have side effects or take a very long time
session.prepare(sql);
checkViewsAreValid(view);
}
}
}
private void execute(String sql, boolean ddl) {
Prepared command = session.prepare(sql);
command.update();
if (ddl) {
session.commit(true);
}
}
private void checkNullable(Table table) {
for (Index index : table.getIndexes()) {
if (index.getColumnIndex(oldColumn) < 0) {
continue;
}
IndexType indexType = index.getIndexType();
if (indexType.isPrimaryKey() || indexType.isHash()) {
throw DbException.get(
ErrorCode.COLUMN_IS_PART_OF_INDEX_1, index.getSQL());
}
}
}
private void checkNoNullValues(Table table) {
String sql = "SELECT COUNT(*) FROM " +
table.getSQL() + " WHERE " +
oldColumn.getSQL() + " IS NULL";
Prepared command = session.prepare(sql);
ResultInterface result = command.query(0);
result.next();
if (result.currentRow()[0].getInt() > 0) {
throw DbException.get(
ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1,
oldColumn.getSQL());
}
}
public void setType(int type) {
this.type = type;
}
public void setSelectivity(Expression selectivity) {
newSelectivity = selectivity;
}
/**
* Set default or on update expression.
*
* @param defaultExpression default or on update expression
*/
public void setDefaultExpression(Expression defaultExpression) {
this.defaultExpression = defaultExpression;
}
public void setNewColumn(Column newColumn) {
this.newColumn = newColumn;
}
@Override
public int getType() {
return type;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public void addColumn(Column column) {
if (columnsToAdd == null) {
columnsToAdd = New.arrayList();
}
columnsToAdd.add(column);
}
public void setColumnsToRemove(ArrayList<Column> columnsToRemove) {
this.columnsToRemove = columnsToRemove;
}
public void setVisible(boolean visible) {
this.newVisibility = visible;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableDropConstraint.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.Constraint;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* ALTER TABLE DROP CONSTRAINT
*/
public class AlterTableDropConstraint extends SchemaCommand {
private String constraintName;
private final boolean ifExists;
public AlterTableDropConstraint(Session session, Schema schema,
boolean ifExists) {
super(session, schema);
this.ifExists = ifExists;
}
public void setConstraintName(String string) {
constraintName = string;
}
@Override
public int update() {
session.commit(true);
Constraint constraint = getSchema().findConstraint(session, constraintName);
if (constraint == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, constraintName);
}
} else {
session.getUser().checkRight(constraint.getTable(), Right.ALL);
session.getUser().checkRight(constraint.getRefTable(), Right.ALL);
session.getDatabase().removeSchemaObject(session, constraint);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_TABLE_DROP_CONSTRAINT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableRename.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
/**
* This class represents the statement
* ALTER TABLE RENAME
*/
public class AlterTableRename extends SchemaCommand {
private boolean ifTableExists;
private String oldTableName;
private String newTableName;
private boolean hidden;
public AlterTableRename(Session session, Schema schema) {
super(session, schema);
}
public void setIfTableExists(boolean b) {
ifTableExists = b;
}
public void setOldTableName(String name) {
oldTableName = name;
}
public void setNewTableName(String name) {
newTableName = name;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
Table oldTable = getSchema().findTableOrView(session, oldTableName);
if (oldTable == null) {
if (ifTableExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, oldTableName);
}
session.getUser().checkRight(oldTable, Right.ALL);
Table t = getSchema().findTableOrView(session, newTableName);
if (t != null && hidden && newTableName.equals(oldTable.getName())) {
if (!t.isHidden()) {
t.setHidden(hidden);
oldTable.setHidden(true);
db.updateMeta(session, oldTable);
}
return 0;
}
if (t != null || newTableName.equals(oldTable.getName())) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, newTableName);
}
if (oldTable.isTemporary()) {
throw DbException.getUnsupportedException("temp table");
}
db.renameSchemaObject(session, oldTable, newTableName);
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_TABLE_RENAME;
}
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableRenameColumn.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.Table;
/**
* This class represents the statement
* ALTER TABLE ALTER COLUMN RENAME
*/
public class AlterTableRenameColumn extends SchemaCommand {
private boolean ifTableExists;
private String tableName;
private String oldName;
private String newName;
public AlterTableRenameColumn(Session session, Schema schema) {
super(session, schema);
}
public void setIfTableExists(boolean b) {
this.ifTableExists = b;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setOldColumnName(String oldName) {
this.oldName = oldName;
}
public void setNewColumnName(String newName) {
this.newName = newName;
}
@Override
public int update() {
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);
}
Column column = table.getColumn(oldName);
session.getUser().checkRight(table, Right.ALL);
table.checkSupportAlter();
// we need to update CHECK constraint
// since it might reference the name of the column
Expression newCheckExpr = column.getCheckConstraint(session, newName);
table.renameColumn(column, newName);
column.removeCheckConstraint();
column.addCheckConstraint(session, newCheckExpr);
table.setModified();
db.updateMeta(session, table);
for (DbObject child : table.getChildren()) {
if (child.getCreateSQL() != null) {
db.updateMeta(session, child);
}
}
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_TABLE_ALTER_COLUMN_RENAME;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterTableRenameConstraint.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.Constraint;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* ALTER TABLE RENAME CONSTRAINT
*/
public class AlterTableRenameConstraint extends SchemaCommand {
private String constraintName;
private String newConstraintName;
public AlterTableRenameConstraint(Session session, Schema schema) {
super(session, schema);
}
public void setConstraintName(String string) {
constraintName = string;
}
public void setNewConstraintName(String newName) {
this.newConstraintName = newName;
}
@Override
public int update() {
session.commit(true);
Constraint constraint = getSchema().findConstraint(session, constraintName);
if (constraint == null) {
throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, constraintName);
}
if (getSchema().findConstraint(session, newConstraintName) != null ||
newConstraintName.equals(constraintName)) {
throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1,
newConstraintName);
}
session.getUser().checkRight(constraint.getTable(), Right.ALL);
session.getUser().checkRight(constraint.getRefTable(), Right.ALL);
session.getDatabase().renameSchemaObject(session, constraint, newConstraintName);
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_TABLE_RENAME_CONSTRAINT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterUser.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.expression.Expression;
import org.h2.message.DbException;
/**
* This class represents the statements
* ALTER USER ADMIN,
* ALTER USER RENAME,
* ALTER USER SET PASSWORD
*/
public class AlterUser extends DefineCommand {
private int type;
private User user;
private String newName;
private Expression password;
private Expression salt;
private Expression hash;
private boolean admin;
public AlterUser(Session session) {
super(session);
}
public void setType(int type) {
this.type = type;
}
public void setNewName(String newName) {
this.newName = newName;
}
public void setUser(User user) {
this.user = user;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public void setSalt(Expression e) {
salt = e;
}
public void setHash(Expression e) {
hash = e;
}
public void setPassword(Expression password) {
this.password = password;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
switch (type) {
case CommandInterface.ALTER_USER_SET_PASSWORD:
if (user != session.getUser()) {
session.getUser().checkAdmin();
}
if (hash != null && salt != null) {
CreateUser.setSaltAndHash(user, session, salt, hash);
} else {
CreateUser.setPassword(user, session, password);
}
break;
case CommandInterface.ALTER_USER_RENAME:
session.getUser().checkAdmin();
if (db.findUser(newName) != null || newName.equals(user.getName())) {
throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, newName);
}
db.renameDatabaseObject(session, user, newName);
break;
case CommandInterface.ALTER_USER_ADMIN:
session.getUser().checkAdmin();
if (!admin) {
user.checkOwnsNoSchemas();
}
user.setAdmin(admin);
break;
default:
DbException.throwInternalError("type=" + type);
}
db.updateMeta(session, user);
return 0;
}
@Override
public int getType() {
return type;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/AlterView.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.command.ddl;
import org.h2.command.CommandInterface;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.TableView;
/**
* This class represents the statement
* ALTER VIEW
*/
public class AlterView extends DefineCommand {
private boolean ifExists;
private TableView view;
public AlterView(Session session) {
super(session);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setView(TableView view) {
this.view = view;
}
@Override
public int update() {
session.commit(true);
if (view == null && ifExists) {
return 0;
}
session.getUser().checkRight(view, Right.ALL);
DbException e = view.recompile(session, false, true);
if (e != null) {
throw e;
}
return 0;
}
@Override
public int getType() {
return CommandInterface.ALTER_VIEW;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/Analyze.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.command.ddl;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Parameter;
import org.h2.result.ResultInterface;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueNull;
/**
* This class represents the statements
* ANALYZE and ANALYZE TABLE
*/
public class Analyze extends DefineCommand {
/**
* The sample size.
*/
private int sampleRows;
/**
* used in ANALYZE TABLE...
*/
private Table table;
public Analyze(Session session) {
super(session);
sampleRows = session.getDatabase().getSettings().analyzeSample;
}
public void setTable(Table table) {
this.table = table;
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
Database db = session.getDatabase();
if (table != null) {
analyzeTable(session, table, sampleRows, true);
} else {
for (Table table : db.getAllTablesAndViews(false)) {
analyzeTable(session, table, sampleRows, true);
}
}
return 0;
}
/**
* Analyze this table.
*
* @param session the session
* @param table the table
* @param sample the number of sample rows
* @param manual whether the command was called by the user
*/
public static void analyzeTable(Session session, Table table, int sample,
boolean manual) {
if (table.getTableType() != TableType.TABLE ||
table.isHidden() || session == null) {
return;
}
if (!manual) {
if (session.getDatabase().isSysTableLocked()) {
return;
}
if (table.hasSelectTrigger()) {
return;
}
}
if (table.isTemporary() && !table.isGlobalTemporary()
&& session.findLocalTempTable(table.getName()) == null) {
return;
}
if (table.isLockedExclusively() && !table.isLockedExclusivelyBy(session)) {
return;
}
if (!session.getUser().hasRight(table, Right.SELECT)) {
return;
}
if (session.getCancel() != 0) {
// if the connection is closed and there is something to undo
return;
}
Column[] columns = table.getColumns();
if (columns.length == 0) {
return;
}
Database db = session.getDatabase();
StatementBuilder buff = new StatementBuilder("SELECT ");
for (Column col : columns) {
buff.appendExceptFirst(", ");
int type = col.getType();
if (type == Value.BLOB || type == Value.CLOB) {
// can not index LOB columns, so calculating
// the selectivity is not required
buff.append("MAX(NULL)");
} else {
buff.append("SELECTIVITY(").append(col.getSQL()).append(')');
}
}
buff.append(" FROM ").append(table.getSQL());
if (sample > 0) {
buff.append(" LIMIT ? SAMPLE_SIZE ? ");
}
String sql = buff.toString();
Prepared command = session.prepare(sql);
if (sample > 0) {
ArrayList<Parameter> params = command.getParameters();
params.get(0).setValue(ValueInt.get(1));
params.get(1).setValue(ValueInt.get(sample));
}
ResultInterface result = command.query(0);
result.next();
for (int j = 0; j < columns.length; j++) {
Value v = result.currentRow()[j];
if (v != ValueNull.INSTANCE) {
int selectivity = v.getInt();
columns[j].setSelectivity(selectivity);
}
}
db.updateMeta(session, table);
}
public void setTop(int top) {
this.sampleRows = top;
}
@Override
public int getType() {
return CommandInterface.ANALYZE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CommandWithColumns.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Constants;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
import org.h2.table.Column;
import org.h2.table.IndexColumn;
import org.h2.util.New;
public abstract class CommandWithColumns extends SchemaCommand {
private ArrayList<DefineCommand> constraintCommands;
private IndexColumn[] pkColumns;
protected CommandWithColumns(Session session, Schema schema) {
super(session, schema);
}
/**
* Add a column to this table.
*
* @param column
* the column to add
*/
public abstract void addColumn(Column column);
/**
* Add a constraint statement to this statement. The primary key definition is
* one possible constraint statement.
*
* @param command
* the statement to add
*/
public void addConstraintCommand(DefineCommand command) {
if (command instanceof CreateIndex) {
getConstraintCommands().add(command);
} else {
AlterTableAddConstraint con = (AlterTableAddConstraint) command;
boolean alreadySet;
if (con.getType() == CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY) {
alreadySet = setPrimaryKeyColumns(con.getIndexColumns());
} else {
alreadySet = false;
}
if (!alreadySet) {
getConstraintCommands().add(command);
}
}
}
/**
* For the given list of columns, disable "nullable" for those columns that
* are primary key columns.
*
* @param columns the list of columns
*/
protected void changePrimaryKeysToNotNull(ArrayList<Column> columns) {
if (pkColumns != null) {
for (Column c : columns) {
for (IndexColumn idxCol : pkColumns) {
if (c.getName().equals(idxCol.columnName)) {
c.setNullable(false);
}
}
}
}
}
/**
* Create the constraints.
*/
protected void createConstraints() {
if (constraintCommands != null) {
for (DefineCommand command : constraintCommands) {
command.setTransactional(transactional);
command.update();
}
}
}
/**
* For the given list of columns, create sequences for auto-increment
* columns (if needed), and then get the list of all sequences of the
* columns.
*
* @param columns the columns
* @param temporary whether generated sequences should be temporary
* @return the list of sequences (may be empty)
*/
protected ArrayList<Sequence> generateSequences(ArrayList<Column> columns, boolean temporary) {
ArrayList<Sequence> sequences = New.arrayList();
if (columns != null) {
for (Column c : columns) {
if (c.isAutoIncrement()) {
int objId = getObjectId();
c.convertAutoIncrementToSequence(session, getSchema(), objId, temporary);
if (!Constants.CLUSTERING_DISABLED.equals(session.getDatabase().getCluster())) {
throw DbException.getUnsupportedException("CLUSTERING && auto-increment columns");
}
}
Sequence seq = c.getSequence();
if (seq != null) {
sequences.add(seq);
}
}
}
return sequences;
}
private ArrayList<DefineCommand> getConstraintCommands() {
if (constraintCommands == null) {
constraintCommands = New.arrayList();
}
return constraintCommands;
}
/**
* Sets the primary key columns, but also check if a primary key with different
* columns is already defined.
*
* @param columns
* the primary key columns
* @return true if the same primary key columns where already set
*/
private boolean setPrimaryKeyColumns(IndexColumn[] columns) {
if (pkColumns != null) {
int len = columns.length;
if (len != pkColumns.length) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
for (int i = 0; i < len; i++) {
if (!columns[i].columnName.equals(pkColumns[i].columnName)) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
}
return true;
}
this.pkColumns = columns;
return false;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateAggregate.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.UserAggregate;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* CREATE AGGREGATE
*/
public class CreateAggregate extends DefineCommand {
private Schema schema;
private String name;
private String javaClassMethod;
private boolean ifNotExists;
private boolean force;
public CreateAggregate(Session session) {
super(session);
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
Database db = session.getDatabase();
if (db.findAggregate(name) != null || schema.findFunction(name) != null) {
if (!ifNotExists) {
throw DbException.get(
ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1, name);
}
} else {
int id = getObjectId();
UserAggregate aggregate = new UserAggregate(
db, id, name, javaClassMethod, force);
db.addDatabaseObject(session, aggregate);
}
return 0;
}
public void setSchema(Schema schema) {
this.schema = schema;
}
public void setName(String name) {
this.name = name;
}
public void setJavaClassMethod(String string) {
this.javaClassMethod = string;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setForce(boolean force) {
this.force = force;
}
@Override
public int getType() {
return CommandInterface.CREATE_AGGREGATE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateConstant.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.schema.Constant;
import org.h2.schema.Schema;
import org.h2.value.Value;
/**
* This class represents the statement
* CREATE CONSTANT
*/
public class CreateConstant extends SchemaCommand {
private String constantName;
private Expression expression;
private boolean ifNotExists;
public CreateConstant(Session session, Schema schema) {
super(session, schema);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
Database db = session.getDatabase();
if (getSchema().findConstant(constantName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.CONSTANT_ALREADY_EXISTS_1, constantName);
}
int id = getObjectId();
Constant constant = new Constant(getSchema(), id, constantName);
expression = expression.optimize(session);
Value value = expression.getValue(session);
constant.setValue(value);
db.addSchemaObject(session, constant);
return 0;
}
public void setConstantName(String constantName) {
this.constantName = constantName;
}
public void setExpression(Expression expr) {
this.expression = expr;
}
@Override
public int getType() {
return CommandInterface.CREATE_CONSTANT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateFunctionAlias.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.FunctionAlias;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.util.StringUtils;
/**
* This class represents the statement
* CREATE ALIAS
*/
public class CreateFunctionAlias extends SchemaCommand {
private String aliasName;
private String javaClassMethod;
private boolean deterministic;
private boolean ifNotExists;
private boolean force;
private String source;
private boolean bufferResultSetToLocalTemp = true;
public CreateFunctionAlias(Session session, Schema schema) {
super(session, schema);
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
Database db = session.getDatabase();
if (getSchema().findFunction(aliasName) != null) {
if (!ifNotExists) {
throw DbException.get(
ErrorCode.FUNCTION_ALIAS_ALREADY_EXISTS_1, aliasName);
}
} else {
int id = getObjectId();
FunctionAlias functionAlias;
if (javaClassMethod != null) {
functionAlias = FunctionAlias.newInstance(getSchema(), id,
aliasName, javaClassMethod, force,
bufferResultSetToLocalTemp);
} else {
functionAlias = FunctionAlias.newInstanceFromSource(
getSchema(), id, aliasName, source, force,
bufferResultSetToLocalTemp);
}
functionAlias.setDeterministic(deterministic);
db.addSchemaObject(session, functionAlias);
}
return 0;
}
public void setAliasName(String name) {
this.aliasName = name;
}
/**
* Set the qualified method name after removing whitespace.
*
* @param method the qualified method name
*/
public void setJavaClassMethod(String method) {
this.javaClassMethod = StringUtils.replaceAll(method, " ", "");
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setForce(boolean force) {
this.force = force;
}
public void setDeterministic(boolean deterministic) {
this.deterministic = deterministic;
}
/**
* Should the return value ResultSet be buffered in a local temporary file?
*
* @param b the new value
*/
public void setBufferResultSetToLocalTemp(boolean b) {
this.bufferResultSetToLocalTemp = b;
}
public void setSource(String source) {
this.source = source;
}
@Override
public int getType() {
return CommandInterface.CREATE_ALIAS;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateIndex.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.IndexColumn;
import org.h2.table.Table;
/**
* This class represents the statement
* CREATE INDEX
*/
public class CreateIndex extends SchemaCommand {
private String tableName;
private String indexName;
private IndexColumn[] indexColumns;
private boolean primaryKey, unique, hash, spatial, affinity;
private boolean ifTableExists;
private boolean ifNotExists;
private String comment;
public CreateIndex(Session session, Schema schema) {
super(session, schema);
}
public void setIfTableExists(boolean b) {
this.ifTableExists = b;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setIndexColumns(IndexColumn[] columns) {
this.indexColumns = columns;
}
@Override
public int update() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
boolean persistent = db.isPersistent();
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().findIndex(session, indexName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.INDEX_ALREADY_EXISTS_1, indexName);
}
session.getUser().checkRight(table, Right.ALL);
table.lock(session, true, true);
if (!table.isPersistIndexes()) {
persistent = false;
}
int id = getObjectId();
if (indexName == null) {
if (primaryKey) {
indexName = table.getSchema().getUniqueIndexName(session,
table, Constants.PREFIX_PRIMARY_KEY);
} else {
indexName = table.getSchema().getUniqueIndexName(session,
table, Constants.PREFIX_INDEX);
}
}
IndexType indexType;
if (primaryKey) {
if (table.findPrimaryKey() != null) {
throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
}
indexType = IndexType.createPrimaryKey(persistent, hash);
} else if (unique) {
indexType = IndexType.createUnique(persistent, hash);
} else if (affinity) {
indexType = IndexType.createAffinity();
} else {
indexType = IndexType.createNonUnique(persistent, hash, spatial);
}
IndexColumn.mapColumns(indexColumns, table);
table.addIndex(session, indexName, id, indexColumns, indexType, create,
comment);
return 0;
}
public void setPrimaryKey(boolean b) {
this.primaryKey = b;
}
public void setUnique(boolean b) {
this.unique = b;
}
public void setHash(boolean b) {
this.hash = b;
}
public void setSpatial(boolean b) {
this.spatial = b;
}
public void setAffinity(boolean b) {
this.affinity = b;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public int getType() {
return CommandInterface.CREATE_INDEX;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateLinkedTable.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.TableLink;
/**
* This class represents the statement
* CREATE LINKED TABLE
*/
public class CreateLinkedTable extends SchemaCommand {
private String tableName;
private String driver, url, user, password, originalSchema, originalTable;
private boolean ifNotExists;
private String comment;
private boolean emitUpdates;
private boolean force;
private boolean temporary;
private boolean globalTemporary;
private boolean readOnly;
public CreateLinkedTable(Session session, Schema schema) {
super(session, schema);
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setDriver(String driver) {
this.driver = driver;
}
public void setOriginalTable(String originalTable) {
this.originalTable = originalTable;
}
public void setPassword(String password) {
this.password = password;
}
public void setUrl(String url) {
this.url = url;
}
public void setUser(String user) {
this.user = user;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
session.getUser().checkAdmin();
if (getSchema().resolveTableOrView(session, tableName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1,
tableName);
}
int id = getObjectId();
TableLink table = getSchema().createTableLink(id, tableName, driver, url,
user, password, originalSchema, originalTable, emitUpdates, force);
table.setTemporary(temporary);
table.setGlobalTemporary(globalTemporary);
table.setComment(comment);
table.setReadOnly(readOnly);
if (temporary && !globalTemporary) {
session.addLocalTempTable(table);
} else {
db.addSchemaObject(session, table);
}
return 0;
}
public void setEmitUpdates(boolean emitUpdates) {
this.emitUpdates = emitUpdates;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setForce(boolean force) {
this.force = force;
}
public void setTemporary(boolean temp) {
this.temporary = temp;
}
public void setGlobalTemporary(boolean globalTemp) {
this.globalTemporary = globalTemp;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
public void setOriginalSchema(String originalSchema) {
this.originalSchema = originalSchema;
}
@Override
public int getType() {
return CommandInterface.CREATE_LINKED_TABLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateRole.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Role;
import org.h2.engine.Session;
import org.h2.message.DbException;
/**
* This class represents the statement
* CREATE ROLE
*/
public class CreateRole extends DefineCommand {
private String roleName;
private boolean ifNotExists;
public CreateRole(Session session) {
super(session);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setRoleName(String name) {
this.roleName = name;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
if (db.findUser(roleName) != null) {
throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, roleName);
}
if (db.findRole(roleName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.ROLE_ALREADY_EXISTS_1, roleName);
}
int id = getObjectId();
Role role = new Role(db, id, roleName, false);
db.addDatabaseObject(session, role);
return 0;
}
@Override
public int getType() {
return CommandInterface.CREATE_ROLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateSchema.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* CREATE SCHEMA
*/
public class CreateSchema extends DefineCommand {
private String schemaName;
private String authorization;
private boolean ifNotExists;
private ArrayList<String> tableEngineParams;
public CreateSchema(Session session) {
super(session);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
session.getUser().checkSchemaAdmin();
session.commit(true);
Database db = session.getDatabase();
User user = db.getUser(authorization);
// during DB startup, the Right/Role records have not yet been loaded
if (!db.isStarting()) {
user.checkSchemaAdmin();
}
if (db.findSchema(schemaName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.SCHEMA_ALREADY_EXISTS_1, schemaName);
}
int id = getObjectId();
Schema schema = new Schema(db, id, schemaName, user, false);
schema.setTableEngineParams(tableEngineParams);
db.addDatabaseObject(session, schema);
return 0;
}
public void setSchemaName(String name) {
this.schemaName = name;
}
public void setAuthorization(String userName) {
this.authorization = userName;
}
public void setTableEngineParams(ArrayList<String> tableEngineParams) {
this.tableEngineParams = tableEngineParams;
}
@Override
public int getType() {
return CommandInterface.CREATE_SCHEMA;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateSequence.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
/**
* This class represents the statement
* CREATE SEQUENCE
*/
public class CreateSequence extends SchemaCommand {
private String sequenceName;
private boolean ifNotExists;
private boolean cycle;
private Expression minValue;
private Expression maxValue;
private Expression start;
private Expression increment;
private Expression cacheSize;
private boolean belongsToTable;
public CreateSequence(Session session, Schema schema) {
super(session, schema);
}
public void setSequenceName(String sequenceName) {
this.sequenceName = sequenceName;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setCycle(boolean cycle) {
this.cycle = cycle;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
if (getSchema().findSequence(sequenceName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.SEQUENCE_ALREADY_EXISTS_1, sequenceName);
}
int id = getObjectId();
Long startValue = getLong(start);
Long inc = getLong(increment);
Long cache = getLong(cacheSize);
Long min = getLong(minValue);
Long max = getLong(maxValue);
Sequence sequence = new Sequence(getSchema(), id, sequenceName, startValue, inc,
cache, min, max, cycle, belongsToTable);
db.addSchemaObject(session, sequence);
return 0;
}
private Long getLong(Expression expr) {
if (expr == null) {
return null;
}
return expr.optimize(session).getValue(session).getLong();
}
public void setStartWith(Expression start) {
this.start = start;
}
public void setIncrement(Expression increment) {
this.increment = increment;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
public void setBelongsToTable(boolean belongsToTable) {
this.belongsToTable = belongsToTable;
}
public void setCacheSize(Expression cacheSize) {
this.cacheSize = cacheSize;
}
@Override
public int getType() {
return CommandInterface.CREATE_SEQUENCE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateSynonym.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.TableSynonym;
/**
* This class represents the statement
* CREATE SYNONYM
*/
public class CreateSynonym extends SchemaCommand {
private final CreateSynonymData data = new CreateSynonymData();
private boolean ifNotExists;
private boolean orReplace;
private String comment;
public CreateSynonym(Session session, Schema schema) {
super(session, schema);
}
public void setName(String name) {
data.synonymName = name;
}
public void setSynonymFor(String tableName) {
data.synonymFor = tableName;
}
public void setSynonymForSchema(Schema synonymForSchema) {
data.synonymForSchema = synonymForSchema;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setOrReplace(boolean orReplace) { this.orReplace = orReplace; }
@Override
public int update() {
if (!transactional) {
session.commit(true);
}
session.getUser().checkAdmin();
Database db = session.getDatabase();
data.session = session;
db.lockMeta(session);
if (data.synonymForSchema.findTableOrView(session, data.synonymName) != null) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.synonymName);
}
if (data.synonymForSchema.findTableOrView(session, data.synonymFor) != null) {
return createTableSynonym(db);
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1,
data.synonymForSchema.getName() + "." + data.synonymFor);
}
private int createTableSynonym(Database db) {
TableSynonym old = getSchema().getSynonym(data.synonymName);
if (old != null) {
if (orReplace) {
// ok, we replacing the existing synonym
} else if (ifNotExists) {
return 0;
} else {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.synonymName);
}
}
TableSynonym table;
if (old != null) {
table = old;
data.schema = table.getSchema();
table.updateData(data);
table.setComment(comment);
table.setModified();
db.updateMeta(session, table);
} else {
data.id = getObjectId();
table = getSchema().createSynonym(data);
table.setComment(comment);
db.addSchemaObject(session, table);
}
table.updateSynonymFor();
return 0;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public int getType() {
return CommandInterface.CREATE_SYNONYM;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateSynonymData.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.command.ddl;
import org.h2.engine.Session;
import org.h2.schema.Schema;
/**
* The data required to create a synonym.
*/
public class CreateSynonymData {
/**
* The schema.
*/
public Schema schema;
/**
* The synonyms name.
*/
public String synonymName;
/**
* The name of the table the synonym is created for.
*/
public String synonymFor;
/** Schema synonymFor is located in. */
public Schema synonymForSchema;
/**
* The object id.
*/
public int id;
/**
* The session.
*/
public Session session;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateTable.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.command.ddl;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.dml.Insert;
import org.h2.command.dml.Query;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.util.ColumnNamer;
import org.h2.value.DataType;
import org.h2.value.Value;
/**
* This class represents the statement
* CREATE TABLE
*/
public class CreateTable extends CommandWithColumns {
private final CreateTableData data = new CreateTableData();
private boolean ifNotExists;
private boolean onCommitDrop;
private boolean onCommitTruncate;
private Query asQuery;
private String comment;
private boolean sortedInsertMode;
public CreateTable(Session session, Schema schema) {
super(session, schema);
data.persistIndexes = true;
data.persistData = true;
}
public void setQuery(Query query) {
this.asQuery = query;
}
public void setTemporary(boolean temporary) {
data.temporary = temporary;
}
public void setTableName(String tableName) {
data.tableName = tableName;
}
@Override
public void addColumn(Column column) {
data.columns.add(column);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
if (!transactional) {
session.commit(true);
}
Database db = session.getDatabase();
if (!db.isPersistent()) {
data.persistIndexes = false;
}
boolean isSessionTemporary = data.temporary && !data.globalTemporary;
if (!isSessionTemporary) {
db.lockMeta(session);
}
if (getSchema().resolveTableOrView(session, data.tableName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.tableName);
}
if (asQuery != null) {
asQuery.prepare();
if (data.columns.isEmpty()) {
generateColumnsFromQuery();
} else if (data.columns.size() != asQuery.getColumnCount()) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
changePrimaryKeysToNotNull(data.columns);
data.id = getObjectId();
data.create = create;
data.session = session;
Table table = getSchema().createTable(data);
ArrayList<Sequence> sequences = generateSequences(data.columns, data.temporary);
table.setComment(comment);
if (isSessionTemporary) {
if (onCommitDrop) {
table.setOnCommitDrop(true);
}
if (onCommitTruncate) {
table.setOnCommitTruncate(true);
}
session.addLocalTempTable(table);
} else {
db.lockMeta(session);
db.addSchemaObject(session, table);
}
try {
for (Column c : data.columns) {
c.prepareExpression(session);
}
for (Sequence sequence : sequences) {
table.addSequence(sequence);
}
createConstraints();
if (asQuery != null) {
boolean old = session.isUndoLogEnabled();
try {
session.setUndoLogEnabled(false);
session.startStatementWithinTransaction();
Insert insert = new Insert(session);
insert.setSortedInsertMode(sortedInsertMode);
insert.setQuery(asQuery);
insert.setTable(table);
insert.setInsertFromSelect(true);
insert.prepare();
insert.update();
} finally {
session.setUndoLogEnabled(old);
}
}
HashSet<DbObject> set = new HashSet<>();
set.clear();
table.addDependencies(set);
for (DbObject obj : set) {
if (obj == table) {
continue;
}
if (obj.getType() == DbObject.TABLE_OR_VIEW) {
if (obj instanceof Table) {
Table t = (Table) obj;
if (t.getId() > table.getId()) {
throw DbException.get(
ErrorCode.FEATURE_NOT_SUPPORTED_1,
"Table depends on another table " +
"with a higher ID: " + t +
", this is currently not supported, " +
"as it would prevent the database from " +
"being re-opened");
}
}
}
}
} catch (DbException e) {
db.checkPowerOff();
db.removeSchemaObject(session, table);
if (!transactional) {
session.commit(true);
}
throw e;
}
return 0;
}
private void generateColumnsFromQuery() {
int columnCount = asQuery.getColumnCount();
ArrayList<Expression> expressions = asQuery.getExpressions();
ColumnNamer columnNamer= new ColumnNamer(session);
for (int i = 0; i < columnCount; i++) {
Expression expr = expressions.get(i);
int type = expr.getType();
String name = columnNamer.getColumnName(expr,i,expr.getAlias());
long precision = expr.getPrecision();
int displaySize = expr.getDisplaySize();
DataType dt = DataType.getDataType(type);
if (precision > 0 && (dt.defaultPrecision == 0 ||
(dt.defaultPrecision > precision && dt.defaultPrecision < Byte.MAX_VALUE))) {
// dont' set precision to MAX_VALUE if this is the default
precision = dt.defaultPrecision;
}
int scale = expr.getScale();
if (scale > 0 && (dt.defaultScale == 0 ||
(dt.defaultScale > scale && dt.defaultScale < precision))) {
scale = dt.defaultScale;
}
if (scale > precision) {
precision = scale;
}
String[] enumerators = null;
if (dt.type == Value.ENUM) {
/**
* Only columns of tables may be enumerated.
*/
if(!(expr instanceof ExpressionColumn)) {
throw DbException.get(ErrorCode.GENERAL_ERROR_1,
"Unable to resolve enumerators of expression");
}
enumerators = ((ExpressionColumn)expr).getColumn().getEnumerators();
}
Column col = new Column(name, type, precision, scale, displaySize, enumerators);
addColumn(col);
}
}
public void setPersistIndexes(boolean persistIndexes) {
data.persistIndexes = persistIndexes;
}
public void setGlobalTemporary(boolean globalTemporary) {
data.globalTemporary = globalTemporary;
}
/**
* This temporary table is dropped on commit.
*/
public void setOnCommitDrop() {
this.onCommitDrop = true;
}
/**
* This temporary table is truncated on commit.
*/
public void setOnCommitTruncate() {
this.onCommitTruncate = true;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setPersistData(boolean persistData) {
data.persistData = persistData;
if (!persistData) {
data.persistIndexes = false;
}
}
public void setSortedInsertMode(boolean sortedInsertMode) {
this.sortedInsertMode = sortedInsertMode;
}
public void setTableEngine(String tableEngine) {
data.tableEngine = tableEngine;
}
public void setTableEngineParams(ArrayList<String> tableEngineParams) {
data.tableEngineParams = tableEngineParams;
}
public void setHidden(boolean isHidden) {
data.isHidden = isHidden;
}
@Override
public int getType() {
return CommandInterface.CREATE_TABLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateTableData.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.command.ddl;
import java.util.ArrayList;
import org.h2.engine.Session;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.util.New;
/**
* The data required to create a table.
*/
public class CreateTableData {
/**
* The schema.
*/
public Schema schema;
/**
* The table name.
*/
public String tableName;
/**
* The object id.
*/
public int id;
/**
* The column list.
*/
public ArrayList<Column> columns = New.arrayList();
/**
* Whether this is a temporary table.
*/
public boolean temporary;
/**
* Whether the table is global temporary.
*/
public boolean globalTemporary;
/**
* Whether the indexes should be persisted.
*/
public boolean persistIndexes;
/**
* Whether the data should be persisted.
*/
public boolean persistData;
/**
* Whether to create a new table.
*/
public boolean create;
/**
* The session.
*/
public Session session;
/**
* The table engine to use for creating the table.
*/
public String tableEngine;
/**
* The table engine params to use for creating the table.
*/
public ArrayList<String> tableEngineParams;
/**
* The table is hidden.
*/
public boolean isHidden;
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateTrigger.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.TriggerObject;
import org.h2.table.Table;
/**
* This class represents the statement
* CREATE TRIGGER
*/
public class CreateTrigger extends SchemaCommand {
private String triggerName;
private boolean ifNotExists;
private boolean insteadOf;
private boolean before;
private int typeMask;
private boolean rowBased;
private int queueSize = TriggerObject.DEFAULT_QUEUE_SIZE;
private boolean noWait;
private String tableName;
private String triggerClassName;
private String triggerSource;
private boolean force;
private boolean onRollback;
public CreateTrigger(Session session, Schema schema) {
super(session, schema);
}
public void setInsteadOf(boolean insteadOf) {
this.insteadOf = insteadOf;
}
public void setBefore(boolean before) {
this.before = before;
}
public void setTriggerClassName(String triggerClassName) {
this.triggerClassName = triggerClassName;
}
public void setTriggerSource(String triggerSource) {
this.triggerSource = triggerSource;
}
public void setTypeMask(int typeMask) {
this.typeMask = typeMask;
}
public void setRowBased(boolean rowBased) {
this.rowBased = rowBased;
}
public void setQueueSize(int size) {
this.queueSize = size;
}
public void setNoWait(boolean noWait) {
this.noWait = noWait;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public void setTriggerName(String name) {
this.triggerName = name;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
if (getSchema().findTrigger(triggerName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(
ErrorCode.TRIGGER_ALREADY_EXISTS_1,
triggerName);
}
if ((typeMask & Trigger.SELECT) == Trigger.SELECT && rowBased) {
throw DbException.get(
ErrorCode.TRIGGER_SELECT_AND_ROW_BASED_NOT_SUPPORTED,
triggerName);
}
int id = getObjectId();
Table table = getSchema().getTableOrView(session, tableName);
TriggerObject trigger = new TriggerObject(getSchema(), id, triggerName, table);
trigger.setInsteadOf(insteadOf);
trigger.setBefore(before);
trigger.setNoWait(noWait);
trigger.setQueueSize(queueSize);
trigger.setRowBased(rowBased);
trigger.setTypeMask(typeMask);
trigger.setOnRollback(onRollback);
if (this.triggerClassName != null) {
trigger.setTriggerClassName(triggerClassName, force);
} else {
trigger.setTriggerSource(triggerSource, force);
}
db.addSchemaObject(session, trigger);
table.addTrigger(trigger);
return 0;
}
public void setForce(boolean force) {
this.force = force;
}
public void setOnRollback(boolean onRollback) {
this.onRollback = onRollback;
}
@Override
public int getType() {
return CommandInterface.CREATE_TRIGGER;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateUser.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.security.SHA256;
import org.h2.util.StringUtils;
/**
* This class represents the statement
* CREATE USER
*/
public class CreateUser extends DefineCommand {
private String userName;
private boolean admin;
private Expression password;
private Expression salt;
private Expression hash;
private boolean ifNotExists;
private String comment;
public CreateUser(Session session) {
super(session);
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setUserName(String userName) {
this.userName = userName;
}
public void setPassword(Expression password) {
this.password = password;
}
/**
* Set the salt and hash for the given user.
*
* @param user the user
* @param session the session
* @param salt the salt
* @param hash the hash
*/
static void setSaltAndHash(User user, Session session, Expression salt, Expression hash) {
user.setSaltAndHash(getByteArray(session, salt), getByteArray(session, hash));
}
private static byte[] getByteArray(Session session, Expression e) {
String s = e.optimize(session).getValue(session).getString();
return s == null ? new byte[0] : StringUtils.convertHexToBytes(s);
}
/**
* Set the password for the given user.
*
* @param user the user
* @param session the session
* @param password the password
*/
static void setPassword(User user, Session session, Expression password) {
String pwd = password.optimize(session).getValue(session).getString();
char[] passwordChars = pwd == null ? new char[0] : pwd.toCharArray();
byte[] userPasswordHash;
String userName = user.getName();
if (userName.length() == 0 && passwordChars.length == 0) {
userPasswordHash = new byte[0];
} else {
userPasswordHash = SHA256.getKeyPasswordHash(userName, passwordChars);
}
user.setUserPasswordHash(userPasswordHash);
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
if (db.findRole(userName) != null) {
throw DbException.get(ErrorCode.ROLE_ALREADY_EXISTS_1, userName);
}
if (db.findUser(userName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(ErrorCode.USER_ALREADY_EXISTS_1, userName);
}
int id = getObjectId();
User user = new User(db, id, userName, false);
user.setAdmin(admin);
user.setComment(comment);
if (hash != null && salt != null) {
setSaltAndHash(user, session, salt, hash);
} else if (password != null) {
setPassword(user, session, password);
} else {
throw DbException.throwInternalError();
}
db.addDatabaseObject(session, user);
return 0;
}
public void setSalt(Expression e) {
salt = e;
}
public void setHash(Expression e) {
hash = e;
}
public void setAdmin(boolean b) {
admin = b;
}
public void setComment(String comment) {
this.comment = comment;
}
@Override
public int getType() {
return CommandInterface.CREATE_USER;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateUserDataType.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.UserDataType;
import org.h2.message.DbException;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.value.DataType;
/**
* This class represents the statement
* CREATE DOMAIN
*/
public class CreateUserDataType extends DefineCommand {
private String typeName;
private Column column;
private boolean ifNotExists;
public CreateUserDataType(Session session) {
super(session);
}
public void setTypeName(String name) {
this.typeName = name;
}
public void setColumn(Column column) {
this.column = column;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
session.getUser().checkAdmin();
if (db.findUserDataType(typeName) != null) {
if (ifNotExists) {
return 0;
}
throw DbException.get(
ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1,
typeName);
}
DataType builtIn = DataType.getTypeByName(typeName, session.getDatabase().getMode());
if (builtIn != null) {
if (!builtIn.hidden) {
throw DbException.get(
ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1,
typeName);
}
Table table = session.getDatabase().getFirstUserTable();
if (table != null) {
throw DbException.get(
ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1,
typeName + " (" + table.getSQL() + ")");
}
}
int id = getObjectId();
UserDataType type = new UserDataType(db, id, typeName);
type.setColumn(column);
db.addDatabaseObject(session, type);
return 0;
}
@Override
public int getType() {
return CommandInterface.CREATE_DOMAIN;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/CreateView.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.dml.Query;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Parameter;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.table.TableView;
import org.h2.value.Value;
/**
* This class represents the statement
* CREATE VIEW
*/
public class CreateView extends SchemaCommand {
private Query select;
private String viewName;
private boolean ifNotExists;
private String selectSQL;
private String[] columnNames;
private String comment;
private boolean orReplace;
private boolean force;
private boolean isTableExpression;
public CreateView(Session session, Schema schema) {
super(session, schema);
}
public void setViewName(String name) {
viewName = name;
}
public void setSelect(Query select) {
this.select = select;
}
public void setIfNotExists(boolean ifNotExists) {
this.ifNotExists = ifNotExists;
}
public void setSelectSQL(String selectSQL) {
this.selectSQL = selectSQL;
}
public void setColumnNames(String[] cols) {
this.columnNames = cols;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setOrReplace(boolean orReplace) {
this.orReplace = orReplace;
}
public void setForce(boolean force) {
this.force = force;
}
public void setTableExpression(boolean isTableExpression) {
this.isTableExpression = isTableExpression;
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
Database db = session.getDatabase();
TableView view = null;
Table old = getSchema().findTableOrView(session, viewName);
if (old != null) {
if (ifNotExists) {
return 0;
}
if (!orReplace || TableType.VIEW != old.getTableType()) {
throw DbException.get(ErrorCode.VIEW_ALREADY_EXISTS_1, viewName);
}
view = (TableView) old;
}
int id = getObjectId();
String querySQL;
if (select == null) {
querySQL = selectSQL;
} else {
ArrayList<Parameter> params = select.getParameters();
if (params != null && !params.isEmpty()) {
throw DbException.getUnsupportedException("parameters in views");
}
querySQL = select.getPlanSQL();
}
Column[] columnTemplatesAsUnknowns = null;
Column[] columnTemplatesAsStrings = null;
if (columnNames != null) {
columnTemplatesAsUnknowns = new Column[columnNames.length];
columnTemplatesAsStrings = new Column[columnNames.length];
for (int i = 0; i < columnNames.length; ++i) {
// non table expressions are fine to use unknown column type
columnTemplatesAsUnknowns[i] = new Column(columnNames[i], Value.UNKNOWN);
// table expressions can't have unknown types - so we use string instead
columnTemplatesAsStrings[i] = new Column(columnNames[i], Value.STRING);
}
}
if (view == null) {
if (isTableExpression) {
view = TableView.createTableViewMaybeRecursive(getSchema(), id, viewName, querySQL, null,
columnTemplatesAsStrings, session, false /* literalsChecked */, isTableExpression,
true /* isPersistent */, db);
} else {
view = new TableView(getSchema(), id, viewName, querySQL, null, columnTemplatesAsUnknowns, session,
false/* allow recursive */, false/* literalsChecked */, isTableExpression, true);
}
} else {
// TODO support isTableExpression in replace function...
view.replace(querySQL, columnTemplatesAsUnknowns, session, false, force, false);
view.setModified();
}
if (comment != null) {
view.setComment(comment);
}
if (old == null) {
db.addSchemaObject(session, view);
db.unlockMeta(session);
} else {
db.updateMeta(session, view);
}
// TODO: if we added any table expressions that aren't used by this view, detect them
// and drop them - otherwise they will leak and never get cleaned up.
return 0;
}
@Override
public int getType() {
return CommandInterface.CREATE_VIEW;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DeallocateProcedure.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.command.ddl;
import org.h2.command.CommandInterface;
import org.h2.engine.Session;
/**
* This class represents the statement
* DEALLOCATE
*/
public class DeallocateProcedure extends DefineCommand {
private String procedureName;
public DeallocateProcedure(Session session) {
super(session);
}
@Override
public int update() {
session.removeProcedure(procedureName);
return 0;
}
public void setProcedureName(String name) {
this.procedureName = name;
}
@Override
public int getType() {
return CommandInterface.DEALLOCATE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DefineCommand.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.command.ddl;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.result.ResultInterface;
/**
* This class represents a non-transaction statement, for example a CREATE or
* DROP.
*/
public abstract class DefineCommand extends Prepared {
/**
* The transactional behavior. The default is disabled, meaning the command
* commits an open transaction.
*/
protected boolean transactional;
/**
* Create a new command for the given session.
*
* @param session the session
*/
DefineCommand(Session session) {
super(session);
}
@Override
public boolean isReadOnly() {
return false;
}
@Override
public ResultInterface queryMeta() {
return null;
}
public void setTransactional(boolean transactional) {
this.transactional = transactional;
}
@Override
public boolean isTransactional() {
return transactional;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropAggregate.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.UserAggregate;
import org.h2.message.DbException;
/**
* This class represents the statement
* DROP AGGREGATE
*/
public class DropAggregate extends DefineCommand {
private String name;
private boolean ifExists;
public DropAggregate(Session session) {
super(session);
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
UserAggregate aggregate = db.findAggregate(name);
if (aggregate == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.AGGREGATE_NOT_FOUND_1, name);
}
} else {
db.removeDatabaseObject(session, aggregate);
}
return 0;
}
public void setName(String name) {
this.name = name;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int getType() {
return CommandInterface.DROP_AGGREGATE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropConstant.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Constant;
import org.h2.schema.Schema;
/**
* This class represents the statement
* DROP CONSTANT
*/
public class DropConstant extends SchemaCommand {
private String constantName;
private boolean ifExists;
public DropConstant(Session session, Schema schema) {
super(session, schema);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setConstantName(String constantName) {
this.constantName = constantName;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
Constant constant = getSchema().findConstant(constantName);
if (constant == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.CONSTANT_NOT_FOUND_1, constantName);
}
} else {
db.removeSchemaObject(session, constant);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.DROP_CONSTANT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropDatabase.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.command.ddl;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Role;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.schema.Sequence;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.util.New;
/**
* This class represents the statement
* DROP ALL OBJECTS
*/
public class DropDatabase extends DefineCommand {
private boolean dropAllObjects;
private boolean deleteFiles;
public DropDatabase(Session session) {
super(session);
}
@Override
public int update() {
if (dropAllObjects) {
dropAllObjects();
}
if (deleteFiles) {
session.getDatabase().setDeleteFilesOnDisconnect(true);
}
return 0;
}
private void dropAllObjects() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
db.lockMeta(session);
// There can be dependencies between tables e.g. using computed columns,
// so we might need to loop over them multiple times.
boolean runLoopAgain;
do {
ArrayList<Table> tables = db.getAllTablesAndViews(false);
ArrayList<Table> toRemove = New.arrayList();
for (Table t : tables) {
if (t.getName() != null &&
TableType.VIEW == t.getTableType()) {
toRemove.add(t);
}
}
for (Table t : tables) {
if (t.getName() != null &&
TableType.TABLE_LINK == t.getTableType()) {
toRemove.add(t);
}
}
for (Table t : tables) {
if (t.getName() != null &&
TableType.TABLE == t.getTableType() &&
!t.isHidden()) {
toRemove.add(t);
}
}
for (Table t : tables) {
if (t.getName() != null &&
TableType.EXTERNAL_TABLE_ENGINE == t.getTableType() &&
!t.isHidden()) {
toRemove.add(t);
}
}
runLoopAgain = false;
for (Table t : toRemove) {
if (t.getName() == null) {
// ignore, already dead
} else if (db.getDependentTable(t, t) == null) {
db.removeSchemaObject(session, t);
} else {
runLoopAgain = true;
}
}
} while (runLoopAgain);
// TODO session-local temp tables are not removed
for (Schema schema : db.getAllSchemas()) {
if (schema.canDrop()) {
db.removeDatabaseObject(session, schema);
}
}
ArrayList<SchemaObject> list = New.arrayList();
for (SchemaObject obj : db.getAllSchemaObjects(DbObject.SEQUENCE)) {
// ignore these. the ones we want to drop will get dropped when we
// drop their associated tables, and we will ignore the problematic
// ones that belong to session-local temp tables.
if (!((Sequence) obj).getBelongsToTable()) {
list.add(obj);
}
}
// maybe constraints and triggers on system tables will be allowed in
// the future
list.addAll(db.getAllSchemaObjects(DbObject.CONSTRAINT));
list.addAll(db.getAllSchemaObjects(DbObject.TRIGGER));
list.addAll(db.getAllSchemaObjects(DbObject.CONSTANT));
list.addAll(db.getAllSchemaObjects(DbObject.FUNCTION_ALIAS));
for (SchemaObject obj : list) {
if (obj.isHidden()) {
continue;
}
db.removeSchemaObject(session, obj);
}
for (User user : db.getAllUsers()) {
if (user != session.getUser()) {
db.removeDatabaseObject(session, user);
}
}
for (Role role : db.getAllRoles()) {
String sql = role.getCreateSQL();
// the role PUBLIC must not be dropped
if (sql != null) {
db.removeDatabaseObject(session, role);
}
}
ArrayList<DbObject> dbObjects = New.arrayList();
dbObjects.addAll(db.getAllRights());
dbObjects.addAll(db.getAllAggregates());
dbObjects.addAll(db.getAllUserDataTypes());
for (DbObject obj : dbObjects) {
String sql = obj.getCreateSQL();
// the role PUBLIC must not be dropped
if (sql != null) {
db.removeDatabaseObject(session, obj);
}
}
}
public void setDropAllObjects(boolean b) {
this.dropAllObjects = b;
}
public void setDeleteFiles(boolean b) {
this.deleteFiles = b;
}
@Override
public int getType() {
return CommandInterface.DROP_ALL_OBJECTS;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropFunctionAlias.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.FunctionAlias;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
/**
* This class represents the statement
* DROP ALIAS
*/
public class DropFunctionAlias extends SchemaCommand {
private String aliasName;
private boolean ifExists;
public DropFunctionAlias(Session session, Schema schema) {
super(session, schema);
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
FunctionAlias functionAlias = getSchema().findFunction(aliasName);
if (functionAlias == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.FUNCTION_ALIAS_NOT_FOUND_1, aliasName);
}
} else {
db.removeSchemaObject(session, functionAlias);
}
return 0;
}
public void setAliasName(String name) {
this.aliasName = name;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int getType() {
return CommandInterface.DROP_ALIAS;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropIndex.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.Constraint;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
/**
* This class represents the statement
* DROP INDEX
*/
public class DropIndex extends SchemaCommand {
private String indexName;
private boolean ifExists;
public DropIndex(Session session, Schema schema) {
super(session, schema);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
Index index = getSchema().findIndex(session, indexName);
if (index == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName);
}
} else {
Table table = index.getTable();
session.getUser().checkRight(index.getTable(), Right.ALL);
Constraint pkConstraint = null;
ArrayList<Constraint> constraints = table.getConstraints();
for (int i = 0; constraints != null && i < constraints.size(); i++) {
Constraint cons = constraints.get(i);
if (cons.usesIndex(index)) {
// can drop primary key index (for compatibility)
if (Constraint.Type.PRIMARY_KEY == cons.getConstraintType()) {
pkConstraint = cons;
} else {
throw DbException.get(
ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2,
indexName, cons.getName());
}
}
}
index.getTable().setModified();
if (pkConstraint != null) {
db.removeSchemaObject(session, pkConstraint);
} else {
db.removeSchemaObject(session, index);
}
}
return 0;
}
@Override
public int getType() {
return CommandInterface.DROP_INDEX;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropRole.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Role;
import org.h2.engine.Session;
import org.h2.message.DbException;
/**
* This class represents the statement
* DROP ROLE
*/
public class DropRole extends DefineCommand {
private String roleName;
private boolean ifExists;
public DropRole(Session session) {
super(session);
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
if (roleName.equals(Constants.PUBLIC_ROLE_NAME)) {
throw DbException.get(ErrorCode.ROLE_CAN_NOT_BE_DROPPED_1, roleName);
}
Role role = db.findRole(roleName);
if (role == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.ROLE_NOT_FOUND_1, roleName);
}
} else {
db.removeDatabaseObject(session, role);
}
return 0;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int getType() {
return CommandInterface.DROP_ROLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropSchema.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.ConstraintActionType;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.util.StatementBuilder;
/**
* This class represents the statement
* DROP SCHEMA
*/
public class DropSchema extends DefineCommand {
private String schemaName;
private boolean ifExists;
private ConstraintActionType dropAction;
public DropSchema(Session session) {
super(session);
dropAction = session.getDatabase().getSettings().dropRestrict ?
ConstraintActionType.RESTRICT : ConstraintActionType.CASCADE;
}
public void setSchemaName(String name) {
this.schemaName = name;
}
@Override
public int update() {
session.getUser().checkSchemaAdmin();
session.commit(true);
Database db = session.getDatabase();
Schema schema = db.findSchema(schemaName);
if (schema == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1, schemaName);
}
} else {
if (!schema.canDrop()) {
throw DbException.get(ErrorCode.SCHEMA_CAN_NOT_BE_DROPPED_1, schemaName);
}
if (dropAction == ConstraintActionType.RESTRICT && !schema.isEmpty()) {
StatementBuilder buff = new StatementBuilder();
for (SchemaObject object : schema.getAll()) {
buff.appendExceptFirst(", ");
buff.append(object.getName());
}
if (buff.length() > 0) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, schemaName, buff.toString());
}
}
db.removeDatabaseObject(session, schema);
}
return 0;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
public void setDropAction(ConstraintActionType dropAction) {
this.dropAction = dropAction;
}
@Override
public int getType() {
return CommandInterface.DROP_SCHEMA;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropSequence.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
/**
* This class represents the statement
* DROP SEQUENCE
*/
public class DropSequence extends SchemaCommand {
private String sequenceName;
private boolean ifExists;
public DropSequence(Session session, Schema schema) {
super(session, schema);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setSequenceName(String sequenceName) {
this.sequenceName = sequenceName;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
Sequence sequence = getSchema().findSequence(sequenceName);
if (sequence == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, sequenceName);
}
} else {
if (sequence.getBelongsToTable()) {
throw DbException.get(ErrorCode.SEQUENCE_BELONGS_TO_A_TABLE_1, sequenceName);
}
db.removeSchemaObject(session, sequence);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.DROP_SEQUENCE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropSynonym.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.TableSynonym;
/**
* This class represents the statement
* DROP SYNONYM
*/
public class DropSynonym extends SchemaCommand {
private String synonymName;
private boolean ifExists;
public DropSynonym(Session session, Schema schema) {
super(session, schema);
}
public void setSynonymName(String name) {
this.synonymName = name;
}
@Override
public int update() {
session.commit(true);
session.getUser().checkAdmin();
TableSynonym synonym = getSchema().getSynonym(synonymName);
if (synonym == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, synonymName);
}
} else {
session.getDatabase().removeSchemaObject(session, synonym);
}
return 0;
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int getType() {
return CommandInterface.DROP_SYNONYM;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropTable.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.command.ddl;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.Constraint;
import org.h2.constraint.ConstraintActionType;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
import org.h2.table.TableView;
import org.h2.util.StatementBuilder;
/**
* This class represents the statement
* DROP TABLE
*/
public class DropTable extends SchemaCommand {
private boolean ifExists;
private String tableName;
private Table table;
private DropTable next;
private ConstraintActionType dropAction;
public DropTable(Session session, Schema schema) {
super(session, schema);
dropAction = session.getDatabase().getSettings().dropRestrict ?
ConstraintActionType.RESTRICT :
ConstraintActionType.CASCADE;
}
/**
* Chain another drop table statement to this statement.
*
* @param drop the statement to add
*/
public void addNextDropTable(DropTable drop) {
if (next == null) {
next = drop;
} else {
next.addNextDropTable(drop);
}
}
public void setIfExists(boolean b) {
ifExists = b;
if (next != null) {
next.setIfExists(b);
}
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
private void prepareDrop() {
table = getSchema().findTableOrView(session, tableName);
if (table == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
} else {
session.getUser().checkRight(table, Right.ALL);
if (!table.canDrop()) {
throw DbException.get(ErrorCode.CANNOT_DROP_TABLE_1, tableName);
}
if (dropAction == ConstraintActionType.RESTRICT) {
StatementBuilder buff = new StatementBuilder();
CopyOnWriteArrayList<TableView> dependentViews = table.getDependentViews();
if (dependentViews != null && !dependentViews.isEmpty()) {
for (TableView v : dependentViews) {
buff.appendExceptFirst(", ");
buff.append(v.getName());
}
}
if (session.getDatabase()
.getSettings().standardDropTableRestrict) {
final List<Constraint> constraints = table.getConstraints();
if (constraints != null && !constraints.isEmpty()) {
for (Constraint c : constraints) {
if (c.getTable() != table) {
buff.appendExceptFirst(", ");
buff.append(c.getName());
}
}
}
}
if (buff.length() > 0) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, tableName, buff.toString());
}
}
table.lock(session, true, true);
}
if (next != null) {
next.prepareDrop();
}
}
private void executeDrop() {
// need to get the table again, because it may be dropped already
// meanwhile (dependent object, or same object)
table = getSchema().findTableOrView(session, tableName);
if (table != null) {
table.setModified();
Database db = session.getDatabase();
db.lockMeta(session);
db.removeSchemaObject(session, table);
}
if (next != null) {
next.executeDrop();
}
}
@Override
public int update() {
session.commit(true);
prepareDrop();
executeDrop();
return 0;
}
public void setDropAction(ConstraintActionType dropAction) {
this.dropAction = dropAction;
if (next != null) {
next.setDropAction(dropAction);
}
}
@Override
public int getType() {
return CommandInterface.DROP_TABLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropTrigger.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.TriggerObject;
import org.h2.table.Table;
/**
* This class represents the statement
* DROP TRIGGER
*/
public class DropTrigger extends SchemaCommand {
private String triggerName;
private boolean ifExists;
public DropTrigger(Session session, Schema schema) {
super(session, schema);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setTriggerName(String triggerName) {
this.triggerName = triggerName;
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
TriggerObject trigger = getSchema().findTrigger(triggerName);
if (trigger == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.TRIGGER_NOT_FOUND_1, triggerName);
}
} else {
Table table = trigger.getTable();
session.getUser().checkRight(table, Right.ALL);
db.removeSchemaObject(session, trigger);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.DROP_TRIGGER;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropUser.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.User;
import org.h2.message.DbException;
/**
* This class represents the statement
* DROP USER
*/
public class DropUser extends DefineCommand {
private boolean ifExists;
private String userName;
public DropUser(Session session) {
super(session);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
User user = db.findUser(userName);
if (user == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.USER_NOT_FOUND_1, userName);
}
} else {
if (user == session.getUser()) {
int adminUserCount = 0;
for (User u : db.getAllUsers()) {
if (u.isAdmin()) {
adminUserCount++;
}
}
if (adminUserCount == 1) {
throw DbException.get(ErrorCode.CANNOT_DROP_CURRENT_USER);
}
}
user.checkOwnsNoSchemas();
db.removeDatabaseObject(session, user);
}
return 0;
}
@Override
public boolean isTransactional() {
return false;
}
@Override
public int getType() {
return CommandInterface.DROP_USER;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropUserDataType.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.UserDataType;
import org.h2.message.DbException;
/**
* This class represents the statement
* DROP DOMAIN
*/
public class DropUserDataType extends DefineCommand {
private String typeName;
private boolean ifExists;
public DropUserDataType(Session session) {
super(session);
}
public void setIfExists(boolean ifExists) {
this.ifExists = ifExists;
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
UserDataType type = db.findUserDataType(typeName);
if (type == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.USER_DATA_TYPE_NOT_FOUND_1, typeName);
}
} else {
db.removeDatabaseObject(session, type);
}
return 0;
}
public void setTypeName(String name) {
this.typeName = name;
}
@Override
public int getType() {
return CommandInterface.DROP_DOMAIN;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/DropView.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.constraint.ConstraintActionType;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.table.TableView;
/**
* This class represents the statement
* DROP VIEW
*/
public class DropView extends SchemaCommand {
private String viewName;
private boolean ifExists;
private ConstraintActionType dropAction;
public DropView(Session session, Schema schema) {
super(session, schema);
dropAction = session.getDatabase().getSettings().dropRestrict ?
ConstraintActionType.RESTRICT :
ConstraintActionType.CASCADE;
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setDropAction(ConstraintActionType dropAction) {
this.dropAction = dropAction;
}
public void setViewName(String viewName) {
this.viewName = viewName;
}
@Override
public int update() {
session.commit(true);
Table view = getSchema().findTableOrView(session, viewName);
if (view == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
}
} else {
if (TableType.VIEW != view.getTableType()) {
throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
}
session.getUser().checkRight(view, Right.ALL);
if (dropAction == ConstraintActionType.RESTRICT) {
for (DbObject child : view.getChildren()) {
if (child instanceof TableView) {
throw DbException.get(ErrorCode.CANNOT_DROP_2, viewName, child.getName());
}
}
}
// TODO: Where is the ConstraintReferential.CASCADE style drop processing ? It's
// supported from imported keys - but not for dependent db objects
TableView tableView = (TableView) view;
ArrayList<Table> copyOfDependencies = new ArrayList<>(tableView.getTables());
view.lock(session, true, true);
session.getDatabase().removeSchemaObject(session, view);
// remove dependent table expressions
for (Table childTable: copyOfDependencies) {
if (TableType.VIEW == childTable.getTableType()) {
TableView childTableView = (TableView) childTable;
if (childTableView.isTableExpression() && childTableView.getName() != null) {
session.getDatabase().removeSchemaObject(session, childTableView);
}
}
}
// make sure its all unlocked
session.getDatabase().unlockMeta(session);
}
return 0;
}
@Override
public int getType() {
return CommandInterface.DROP_VIEW;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/GrantRevoke.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.command.ddl;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.RightOwner;
import org.h2.engine.Role;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
import org.h2.util.New;
/**
* This class represents the statements
* GRANT RIGHT,
* GRANT ROLE,
* REVOKE RIGHT,
* REVOKE ROLE
*/
public class GrantRevoke extends DefineCommand {
private ArrayList<String> roleNames;
private int operationType;
private int rightMask;
private final ArrayList<Table> tables = New.arrayList();
private Schema schema;
private RightOwner grantee;
public GrantRevoke(Session session) {
super(session);
}
public void setOperationType(int operationType) {
this.operationType = operationType;
}
/**
* Add the specified right bit to the rights bitmap.
*
* @param right the right bit
*/
public void addRight(int right) {
this.rightMask |= right;
}
/**
* Add the specified role to the list of roles.
*
* @param roleName the role
*/
public void addRoleName(String roleName) {
if (roleNames == null) {
roleNames = New.arrayList();
}
roleNames.add(roleName);
}
public void setGranteeName(String granteeName) {
Database db = session.getDatabase();
grantee = db.findUser(granteeName);
if (grantee == null) {
grantee = db.findRole(granteeName);
if (grantee == null) {
throw DbException.get(ErrorCode.USER_OR_ROLE_NOT_FOUND_1, granteeName);
}
}
}
@Override
public int update() {
session.getUser().checkAdmin();
session.commit(true);
Database db = session.getDatabase();
if (roleNames != null) {
for (String name : roleNames) {
Role grantedRole = db.findRole(name);
if (grantedRole == null) {
throw DbException.get(ErrorCode.ROLE_NOT_FOUND_1, name);
}
if (operationType == CommandInterface.GRANT) {
grantRole(grantedRole);
} else if (operationType == CommandInterface.REVOKE) {
revokeRole(grantedRole);
} else {
DbException.throwInternalError("type=" + operationType);
}
}
} else {
if (operationType == CommandInterface.GRANT) {
grantRight();
} else if (operationType == CommandInterface.REVOKE) {
revokeRight();
} else {
DbException.throwInternalError("type=" + operationType);
}
}
return 0;
}
private void grantRight() {
if (schema != null) {
grantRight(schema);
}
for (Table table : tables) {
grantRight(table);
}
}
private void grantRight(DbObject object) {
Database db = session.getDatabase();
Right right = grantee.getRightForObject(object);
if (right == null) {
int id = getObjectId();
right = new Right(db, id, grantee, rightMask, object);
grantee.grantRight(object, right);
db.addDatabaseObject(session, right);
} else {
right.setRightMask(right.getRightMask() | rightMask);
db.updateMeta(session, right);
}
}
private void grantRole(Role grantedRole) {
if (grantedRole != grantee && grantee.isRoleGranted(grantedRole)) {
return;
}
if (grantee instanceof Role) {
Role granteeRole = (Role) grantee;
if (grantedRole.isRoleGranted(granteeRole)) {
// cyclic role grants are not allowed
throw DbException.get(ErrorCode.ROLE_ALREADY_GRANTED_1, grantedRole.getSQL());
}
}
Database db = session.getDatabase();
int id = getObjectId();
Right right = new Right(db, id, grantee, grantedRole);
db.addDatabaseObject(session, right);
grantee.grantRole(grantedRole, right);
}
private void revokeRight() {
if (schema != null) {
revokeRight(schema);
}
for (Table table : tables) {
revokeRight(table);
}
}
private void revokeRight(DbObject object) {
Right right = grantee.getRightForObject(object);
if (right == null) {
return;
}
int mask = right.getRightMask();
int newRight = mask & ~rightMask;
Database db = session.getDatabase();
if (newRight == 0) {
db.removeDatabaseObject(session, right);
} else {
right.setRightMask(newRight);
db.updateMeta(session, right);
}
}
private void revokeRole(Role grantedRole) {
Right right = grantee.getRightForRole(grantedRole);
if (right == null) {
return;
}
Database db = session.getDatabase();
db.removeDatabaseObject(session, right);
}
@Override
public boolean isTransactional() {
return false;
}
/**
* Add the specified table to the list of tables.
*
* @param table the table
*/
public void addTable(Table table) {
tables.add(table);
}
/**
* Set the specified schema
*
* @param schema the schema
*/
public void setSchema(Schema schema) {
this.schema = schema;
}
@Override
public int getType() {
return operationType;
}
/**
* @return true if this command is using Roles
*/
public boolean isRoleMode() {
return roleNames != null;
}
/**
* @return true if this command is using Rights
*/
public boolean isRightMode() {
return rightMask != 0;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/PrepareProcedure.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.command.ddl;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Procedure;
import org.h2.engine.Session;
import org.h2.expression.Parameter;
import org.h2.util.New;
/**
* This class represents the statement
* PREPARE
*/
public class PrepareProcedure extends DefineCommand {
private String procedureName;
private Prepared prepared;
public PrepareProcedure(Session session) {
super(session);
}
@Override
public void checkParameters() {
// no not check parameters
}
@Override
public int update() {
Procedure proc = new Procedure(procedureName, prepared);
prepared.setParameterList(parameters);
prepared.setPrepareAlways(prepareAlways);
prepared.prepare();
session.addProcedure(proc);
return 0;
}
public void setProcedureName(String name) {
this.procedureName = name;
}
public void setPrepared(Prepared prep) {
this.prepared = prep;
}
@Override
public ArrayList<Parameter> getParameters() {
return New.arrayList();
}
@Override
public int getType() {
return CommandInterface.PREPARE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/SchemaCommand.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.command.ddl;
import org.h2.engine.Session;
import org.h2.schema.Schema;
/**
* This class represents a non-transaction statement that involves a schema.
*/
public abstract class SchemaCommand extends DefineCommand {
private final Schema schema;
/**
* Create a new command.
*
* @param session the session
* @param schema the schema
*/
public SchemaCommand(Session session, Schema schema) {
super(session);
this.schema = schema;
}
/**
* Get the schema
*
* @return the schema
*/
protected Schema getSchema() {
return schema;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/SetComment.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Comment;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.table.Table;
/**
* This class represents the statement
* COMMENT
*/
public class SetComment extends DefineCommand {
private String schemaName;
private String objectName;
private boolean column;
private String columnName;
private int objectType;
private Expression expr;
public SetComment(Session session) {
super(session);
}
@Override
public int update() {
session.commit(true);
Database db = session.getDatabase();
session.getUser().checkAdmin();
DbObject object = null;
int errorCode = ErrorCode.GENERAL_ERROR_1;
if (schemaName == null) {
schemaName = session.getCurrentSchemaName();
}
switch (objectType) {
case DbObject.CONSTANT:
object = db.getSchema(schemaName).getConstant(objectName);
break;
case DbObject.CONSTRAINT:
object = db.getSchema(schemaName).getConstraint(objectName);
break;
case DbObject.FUNCTION_ALIAS:
object = db.getSchema(schemaName).findFunction(objectName);
errorCode = ErrorCode.FUNCTION_ALIAS_NOT_FOUND_1;
break;
case DbObject.INDEX:
object = db.getSchema(schemaName).getIndex(objectName);
break;
case DbObject.ROLE:
schemaName = null;
object = db.findRole(objectName);
errorCode = ErrorCode.ROLE_NOT_FOUND_1;
break;
case DbObject.SCHEMA:
schemaName = null;
object = db.findSchema(objectName);
errorCode = ErrorCode.SCHEMA_NOT_FOUND_1;
break;
case DbObject.SEQUENCE:
object = db.getSchema(schemaName).getSequence(objectName);
break;
case DbObject.TABLE_OR_VIEW:
object = db.getSchema(schemaName).getTableOrView(session, objectName);
break;
case DbObject.TRIGGER:
object = db.getSchema(schemaName).findTrigger(objectName);
errorCode = ErrorCode.TRIGGER_NOT_FOUND_1;
break;
case DbObject.USER:
schemaName = null;
object = db.getUser(objectName);
break;
case DbObject.USER_DATATYPE:
schemaName = null;
object = db.findUserDataType(objectName);
errorCode = ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1;
break;
default:
}
if (object == null) {
throw DbException.get(errorCode, objectName);
}
String text = expr.optimize(session).getValue(session).getString();
if (column) {
Table table = (Table) object;
table.getColumn(columnName).setComment(text);
} else {
object.setComment(text);
}
if (column || objectType == DbObject.TABLE_OR_VIEW ||
objectType == DbObject.USER ||
objectType == DbObject.INDEX ||
objectType == DbObject.CONSTRAINT) {
db.updateMeta(session, object);
} else {
Comment comment = db.findComment(object);
if (comment == null) {
if (text == null) {
// reset a non-existing comment - nothing to do
} else {
int id = getObjectId();
comment = new Comment(db, id, object);
comment.setCommentText(text);
db.addDatabaseObject(session, comment);
}
} else {
if (text == null) {
db.removeDatabaseObject(session, comment);
} else {
comment.setCommentText(text);
db.updateMeta(session, comment);
}
}
}
return 0;
}
public void setCommentExpression(Expression expr) {
this.expr = expr;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
public void setObjectType(int objectType) {
this.objectType = objectType;
}
public void setColumnName(String columnName) {
this.columnName = columnName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public void setColumn(boolean column) {
this.column = column;
}
@Override
public int getType() {
return CommandInterface.COMMENT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/ddl/TruncateTable.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.command.ddl;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.table.Table;
/**
* This class represents the statement
* TRUNCATE TABLE
*/
public class TruncateTable extends DefineCommand {
private Table table;
public TruncateTable(Session session) {
super(session);
}
public void setTable(Table table) {
this.table = table;
}
@Override
public int update() {
session.commit(true);
if (!table.canTruncate()) {
throw DbException.get(ErrorCode.CANNOT_TRUNCATE_1, table.getSQL());
}
session.getUser().checkRight(table, Right.DELETE);
table.lock(session, true, true);
table.truncate(session);
return 0;
}
@Override
public int getType() {
return CommandInterface.TRUNCATE_TABLE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/AlterSequence.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.command.dml;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.ddl.SchemaCommand;
import org.h2.engine.Database;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.schema.Sequence;
import org.h2.table.Column;
import org.h2.table.Table;
/**
* This class represents the statement
* ALTER SEQUENCE
*/
public class AlterSequence extends SchemaCommand {
private boolean ifExists;
private Table table;
private String sequenceName;
private Sequence sequence;
private Expression start;
private Expression increment;
private Boolean cycle;
private Expression minValue;
private Expression maxValue;
private Expression cacheSize;
public AlterSequence(Session session, Schema schema) {
super(session, schema);
}
public void setIfExists(boolean b) {
ifExists = b;
}
public void setSequenceName(String sequenceName) {
this.sequenceName = sequenceName;
}
@Override
public boolean isTransactional() {
return true;
}
public void setColumn(Column column) {
table = column.getTable();
sequence = column.getSequence();
if (sequence == null && !ifExists) {
throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, column.getSQL());
}
}
public void setStartWith(Expression start) {
this.start = start;
}
public void setIncrement(Expression increment) {
this.increment = increment;
}
public void setCycle(Boolean cycle) {
this.cycle = cycle;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
public void setCacheSize(Expression cacheSize) {
this.cacheSize = cacheSize;
}
@Override
public int update() {
Database db = session.getDatabase();
if (sequence == null) {
sequence = getSchema().findSequence(sequenceName);
if (sequence == null) {
if (!ifExists) {
throw DbException.get(ErrorCode.SEQUENCE_NOT_FOUND_1, sequenceName);
}
return 0;
}
}
if (table != null) {
session.getUser().checkRight(table, Right.ALL);
}
if (cycle != null) {
sequence.setCycle(cycle);
}
if (cacheSize != null) {
long size = cacheSize.optimize(session).getValue(session).getLong();
sequence.setCacheSize(size);
}
if (start != null || minValue != null ||
maxValue != null || increment != null) {
Long startValue = getLong(start);
Long min = getLong(minValue);
Long max = getLong(maxValue);
Long inc = getLong(increment);
sequence.modify(startValue, min, max, inc);
}
db.updateMeta(session, sequence);
return 0;
}
private Long getLong(Expression expr) {
if (expr == null) {
return null;
}
return expr.optimize(session).getValue(session).getLong();
}
@Override
public int getType() {
return CommandInterface.ALTER_SEQUENCE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/AlterTableSet.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.command.dml;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.ddl.SchemaCommand;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.schema.Schema;
import org.h2.table.Table;
/**
* This class represents the statement
* ALTER TABLE SET
*/
public class AlterTableSet extends SchemaCommand {
private boolean ifTableExists;
private String tableName;
private final int type;
private final boolean value;
private boolean checkExisting;
public AlterTableSet(Session session, Schema schema, int type, boolean value) {
super(session, schema);
this.type = type;
this.value = value;
}
public void setCheckExisting(boolean b) {
this.checkExisting = b;
}
@Override
public boolean isTransactional() {
return true;
}
public void setIfTableExists(boolean b) {
this.ifTableExists = b;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
@Override
public int update() {
Table table = getSchema().resolveTableOrView(session, tableName);
if (table == null) {
if (ifTableExists) {
return 0;
}
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
}
session.getUser().checkRight(table, Right.ALL);
table.lock(session, true, true);
switch (type) {
case CommandInterface.ALTER_TABLE_SET_REFERENTIAL_INTEGRITY:
table.setCheckForeignKeyConstraints(session, value, value ?
checkExisting : false);
break;
default:
DbException.throwInternalError("type="+type);
}
return 0;
}
@Override
public int getType() {
return type;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/BackupCommand.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.command.dml;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.h2.api.DatabaseEventListener;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.mvstore.MVStore;
import org.h2.mvstore.db.MVTableEngine.Store;
import org.h2.result.ResultInterface;
import org.h2.store.FileLister;
import org.h2.store.PageStore;
import org.h2.store.fs.FileUtils;
import org.h2.util.IOUtils;
/**
* This class represents the statement
* BACKUP
*/
public class BackupCommand extends Prepared {
private Expression fileNameExpr;
public BackupCommand(Session session) {
super(session);
}
public void setFileName(Expression fileName) {
this.fileNameExpr = fileName;
}
@Override
public int update() {
String name = fileNameExpr.getValue(session).getString();
session.getUser().checkAdmin();
backupTo(name);
return 0;
}
private void backupTo(String fileName) {
Database db = session.getDatabase();
if (!db.isPersistent()) {
throw DbException.get(ErrorCode.DATABASE_IS_NOT_PERSISTENT);
}
try {
Store mvStore = db.getMvStore();
if (mvStore != null) {
mvStore.flush();
}
String name = db.getName();
name = FileUtils.getName(name);
try (OutputStream zip = FileUtils.newOutputStream(fileName, false)) {
ZipOutputStream out = new ZipOutputStream(zip);
db.flush();
if (db.getPageStore() != null) {
String fn = db.getName() + Constants.SUFFIX_PAGE_FILE;
backupPageStore(out, fn, db.getPageStore());
}
// synchronize on the database, to avoid concurrent temp file
// creation / deletion / backup
String base = FileUtils.getParent(db.getName());
synchronized (db.getLobSyncObject()) {
String prefix = db.getDatabasePath();
String dir = FileUtils.getParent(prefix);
dir = FileLister.getDir(dir);
ArrayList<String> fileList = FileLister.getDatabaseFiles(dir, name, true);
for (String n : fileList) {
if (n.endsWith(Constants.SUFFIX_LOB_FILE)) {
backupFile(out, base, n);
}
if (n.endsWith(Constants.SUFFIX_MV_FILE) && mvStore != null) {
MVStore s = mvStore.getStore();
boolean before = s.getReuseSpace();
s.setReuseSpace(false);
try {
InputStream in = mvStore.getInputStream();
backupFile(out, base, n, in);
} finally {
s.setReuseSpace(before);
}
}
}
}
out.close();
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
}
private void backupPageStore(ZipOutputStream out, String fileName,
PageStore store) throws IOException {
Database db = session.getDatabase();
fileName = FileUtils.getName(fileName);
out.putNextEntry(new ZipEntry(fileName));
int pos = 0;
try {
store.setBackup(true);
while (true) {
pos = store.copyDirect(pos, out);
if (pos < 0) {
break;
}
int max = store.getPageCount();
db.setProgress(DatabaseEventListener.STATE_BACKUP_FILE, fileName, pos, max);
}
} finally {
store.setBackup(false);
}
out.closeEntry();
}
private static void backupFile(ZipOutputStream out, String base, String fn)
throws IOException {
InputStream in = FileUtils.newInputStream(fn);
backupFile(out, base, fn, in);
}
private static void backupFile(ZipOutputStream out, String base, String fn,
InputStream in) throws IOException {
String f = FileUtils.toRealPath(fn);
base = FileUtils.toRealPath(base);
if (!f.startsWith(base)) {
DbException.throwInternalError(f + " does not start with " + base);
}
f = f.substring(base.length());
f = correctFileName(f);
out.putNextEntry(new ZipEntry(f));
IOUtils.copyAndCloseInput(in, out);
out.closeEntry();
}
@Override
public boolean isTransactional() {
return true;
}
/**
* Fix the file name, replacing backslash with slash.
*
* @param f the file name
* @return the corrected file name
*/
public static String correctFileName(String f) {
f = f.replace('\\', '/');
if (f.startsWith("/")) {
f = f.substring(1);
}
return f;
}
@Override
public boolean needRecompile() {
return false;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.BACKUP;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Call.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.command.dml;
import java.sql.ResultSet;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.result.LocalResult;
import org.h2.result.ResultInterface;
import org.h2.value.Value;
/**
* This class represents the statement
* CALL.
*/
public class Call extends Prepared {
private boolean isResultSet;
private Expression expression;
private Expression[] expressions;
public Call(Session session) {
super(session);
}
@Override
public ResultInterface queryMeta() {
LocalResult result;
if (isResultSet) {
Expression[] expr = expression.getExpressionColumns(session);
result = new LocalResult(session, expr, expr.length);
} else {
result = new LocalResult(session, expressions, 1);
}
result.done();
return result;
}
@Override
public int update() {
Value v = expression.getValue(session);
int type = v.getType();
switch (type) {
case Value.RESULT_SET:
// this will throw an exception
// methods returning a result set may not be called like this.
return super.update();
case Value.UNKNOWN:
case Value.NULL:
return 0;
default:
return v.getInt();
}
}
@Override
public ResultInterface query(int maxrows) {
setCurrentRowNumber(1);
Value v = expression.getValue(session);
if (isResultSet) {
v = v.convertTo(Value.RESULT_SET);
ResultSet rs = v.getResultSet();
return LocalResult.read(session, rs, maxrows);
}
LocalResult result = new LocalResult(session, expressions, 1);
Value[] row = { v };
result.addRow(row);
result.done();
return result;
}
@Override
public void prepare() {
expression = expression.optimize(session);
expressions = new Expression[] { expression };
isResultSet = expression.getType() == Value.RESULT_SET;
if (isResultSet) {
prepareAlways = true;
}
}
public void setExpression(Expression expression) {
this.expression = expression;
}
@Override
public boolean isQuery() {
return true;
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public boolean isReadOnly() {
return expression.isEverything(ExpressionVisitor.READONLY_VISITOR);
}
@Override
public int getType() {
return CommandInterface.CALL;
}
@Override
public boolean isCacheable() {
return !isResultSet;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Delete.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.command.dml;
import org.h2.api.Trigger;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.RowList;
import org.h2.table.PlanItem;
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;
/**
* This class represents the statement
* DELETE
*/
public class Delete extends Prepared {
private Expression condition;
private TableFilter targetTableFilter;
/**
* The limit expression as specified in the LIMIT or TOP clause.
*/
private Expression limitExpr;
/**
* This table filter is for MERGE..USING support - not used in stand-alone DML
*/
private TableFilter sourceTableFilter;
public Delete(Session session) {
super(session);
}
public void setTableFilter(TableFilter tableFilter) {
this.targetTableFilter = tableFilter;
}
public void setCondition(Expression condition) {
this.condition = condition;
}
public Expression getCondition() {
return this.condition;
}
@Override
public int update() {
targetTableFilter.startQuery(session);
targetTableFilter.reset();
Table table = targetTableFilter.getTable();
session.getUser().checkRight(table, Right.DELETE);
table.fire(session, Trigger.DELETE, true);
table.lock(session, true, false);
RowList rows = new RowList(session);
int limitRows = -1;
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
limitRows = v.getInt();
}
}
try {
setCurrentRowNumber(0);
int count = 0;
while (limitRows != 0 && targetTableFilter.next()) {
setCurrentRowNumber(rows.size() + 1);
if (condition == null || condition.getBooleanValue(session)) {
Row row = targetTableFilter.get();
boolean done = false;
if (table.fireRow()) {
done = table.fireBeforeRow(session, row, null);
}
if (!done) {
rows.add(row);
}
count++;
if (limitRows >= 0 && count >= limitRows) {
break;
}
}
}
int rowScanCount = 0;
for (rows.reset(); rows.hasNext();) {
if ((++rowScanCount & 127) == 0) {
checkCanceled();
}
Row row = rows.next();
table.removeRow(session, row);
session.log(table, UndoLogRecord.DELETE, row);
}
if (table.fireRow()) {
for (rows.reset(); rows.hasNext();) {
Row row = rows.next();
table.fireAfterRow(session, row, null, false);
}
}
table.fire(session, Trigger.DELETE, false);
return count;
} finally {
rows.close();
}
}
@Override
public String getPlanSQL() {
StringBuilder buff = new StringBuilder();
buff.append("DELETE ");
buff.append("FROM ").append(targetTableFilter.getPlanSQL(false));
if (condition != null) {
buff.append("\nWHERE ").append(StringUtils.unEnclose(
condition.getSQL()));
}
if (limitExpr != null) {
buff.append("\nLIMIT (").append(StringUtils.unEnclose(
limitExpr.getSQL())).append(')');
}
return buff.toString();
}
@Override
public void prepare() {
if (condition != null) {
condition.mapColumns(targetTableFilter, 0);
if (sourceTableFilter != null) {
condition.mapColumns(sourceTableFilter, 0);
}
condition = condition.optimize(session);
condition.createIndexConditions(session, targetTableFilter);
}
TableFilter[] filters;
if (sourceTableFilter == null) {
filters = new TableFilter[] { targetTableFilter };
} else {
filters = new TableFilter[] { targetTableFilter, sourceTableFilter };
}
PlanItem item = targetTableFilter.getBestPlanItem(session, filters, 0,
ExpressionVisitor.allColumnsForTableFilters(filters));
targetTableFilter.setPlanItem(item);
targetTableFilter.prepare();
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.DELETE;
}
public void setLimit(Expression limit) {
this.limitExpr = limit;
}
@Override
public boolean isCacheable() {
return true;
}
public void setSourceTableFilter(TableFilter sourceTableFilter) {
this.sourceTableFilter = sourceTableFilter;
}
public TableFilter getTableFilter() {
return targetTableFilter;
}
public TableFilter getSourceTableFilter() {
return sourceTableFilter;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/ExecuteProcedure.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.command.dml;
import java.util.ArrayList;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Procedure;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.Parameter;
import org.h2.result.ResultInterface;
import org.h2.util.New;
/**
* This class represents the statement
* EXECUTE
*/
public class ExecuteProcedure extends Prepared {
private final ArrayList<Expression> expressions = New.arrayList();
private Procedure procedure;
public ExecuteProcedure(Session session) {
super(session);
}
public void setProcedure(Procedure procedure) {
this.procedure = procedure;
}
/**
* Set the expression at the given index.
*
* @param index the index (0 based)
* @param expr the expression
*/
public void setExpression(int index, Expression expr) {
expressions.add(index, expr);
}
private void setParameters() {
Prepared prepared = procedure.getPrepared();
ArrayList<Parameter> params = prepared.getParameters();
for (int i = 0; params != null && i < params.size() &&
i < expressions.size(); i++) {
Expression expr = expressions.get(i);
Parameter p = params.get(i);
p.setValue(expr.getValue(session));
}
}
@Override
public boolean isQuery() {
Prepared prepared = procedure.getPrepared();
return prepared.isQuery();
}
@Override
public int update() {
setParameters();
Prepared prepared = procedure.getPrepared();
return prepared.update();
}
@Override
public ResultInterface query(int limit) {
setParameters();
Prepared prepared = procedure.getPrepared();
return prepared.query(limit);
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
Prepared prepared = procedure.getPrepared();
return prepared.queryMeta();
}
@Override
public int getType() {
return CommandInterface.EXECUTE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Explain.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.command.dml;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.mvstore.db.MVTableEngine.Store;
import org.h2.result.LocalResult;
import org.h2.result.ResultInterface;
import org.h2.store.PageStore;
import org.h2.table.Column;
import org.h2.value.Value;
import org.h2.value.ValueString;
/**
* This class represents the statement
* EXPLAIN
*/
public class Explain extends Prepared {
private Prepared command;
private LocalResult result;
private boolean executeCommand;
public Explain(Session session) {
super(session);
}
public void setCommand(Prepared command) {
this.command = command;
}
public Prepared getCommand() {
return command;
}
@Override
public void prepare() {
command.prepare();
}
public void setExecuteCommand(boolean executeCommand) {
this.executeCommand = executeCommand;
}
@Override
public ResultInterface queryMeta() {
return query(-1);
}
@Override
protected void checkParameters() {
// Check params only in case of EXPLAIN ANALYZE
if (executeCommand) {
super.checkParameters();
}
}
@Override
public ResultInterface query(int maxrows) {
Column column = new Column("PLAN", Value.STRING);
Database db = session.getDatabase();
ExpressionColumn expr = new ExpressionColumn(db, column);
Expression[] expressions = { expr };
result = new LocalResult(session, expressions, 1);
if (maxrows >= 0) {
String plan;
if (executeCommand) {
PageStore store = null;
Store mvStore = null;
if (db.isPersistent()) {
store = db.getPageStore();
if (store != null) {
store.statisticsStart();
}
mvStore = db.getMvStore();
if (mvStore != null) {
mvStore.statisticsStart();
}
}
if (command.isQuery()) {
command.query(maxrows);
} else {
command.update();
}
plan = command.getPlanSQL();
Map<String, Integer> statistics = null;
if (store != null) {
statistics = store.statisticsEnd();
} else if (mvStore != null) {
statistics = mvStore.statisticsEnd();
}
if (statistics != null) {
int total = 0;
for (Entry<String, Integer> e : statistics.entrySet()) {
total += e.getValue();
}
if (total > 0) {
statistics = new TreeMap<>(statistics);
StringBuilder buff = new StringBuilder();
if (statistics.size() > 1) {
buff.append("total: ").append(total).append('\n');
}
for (Entry<String, Integer> e : statistics.entrySet()) {
int value = e.getValue();
int percent = (int) (100L * value / total);
buff.append(e.getKey()).append(": ").append(value);
if (statistics.size() > 1) {
buff.append(" (").append(percent).append("%)");
}
buff.append('\n');
}
plan += "\n/*\n" + buff.toString() + "*/";
}
}
} else {
plan = command.getPlanSQL();
}
add(plan);
}
result.done();
return result;
}
private void add(String text) {
Value[] row = { ValueString.get(text) };
result.addRow(row);
}
@Override
public boolean isQuery() {
return true;
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public boolean isReadOnly() {
return command.isReadOnly();
}
@Override
public int getType() {
return executeCommand ? CommandInterface.EXPLAIN_ANALYZE : CommandInterface.EXPLAIN;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Insert.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.command.dml;
import java.util.ArrayList;
import java.util.HashMap;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.Command;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.GeneratedKeys;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Comparison;
import org.h2.expression.ConditionAndOr;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.Parameter;
import org.h2.expression.SequenceValue;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.mvstore.db.MVPrimaryIndex;
import org.h2.result.ResultInterface;
import org.h2.result.ResultTarget;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* This class represents the statement
* INSERT
*/
public class Insert extends Prepared implements ResultTarget {
private Table table;
private Column[] columns;
private final ArrayList<Expression[]> list = New.arrayList();
private Query query;
private boolean sortedInsertMode;
private int rowNumber;
private boolean insertFromSelect;
/**
* This table filter is for MERGE..USING support - not used in stand-alone DML
*/
private TableFilter sourceTableFilter;
/**
* For MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ....
*/
private HashMap<Column, Expression> duplicateKeyAssignmentMap;
/**
* For MySQL-style INSERT IGNORE
*/
private boolean ignore;
public Insert(Session session) {
super(session);
}
@Override
public void setCommand(Command command) {
super.setCommand(command);
if (query != null) {
query.setCommand(command);
}
}
public void setTable(Table table) {
this.table = table;
}
public void setColumns(Column[] columns) {
this.columns = columns;
}
/**
* Sets MySQL-style INSERT IGNORE mode
* @param ignore ignore errors
*/
public void setIgnore(boolean ignore) {
this.ignore = ignore;
}
public void setQuery(Query query) {
this.query = query;
}
/**
* Keep a collection of the columns to pass to update if a duplicate key
* happens, for MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ....
*
* @param column the column
* @param expression the expression
*/
public void addAssignmentForDuplicate(Column column, Expression expression) {
if (duplicateKeyAssignmentMap == null) {
duplicateKeyAssignmentMap = new HashMap<>();
}
if (duplicateKeyAssignmentMap.containsKey(column)) {
throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1,
column.getName());
}
duplicateKeyAssignmentMap.put(column, expression);
}
/**
* Add a row to this merge statement.
*
* @param expr the list of values
*/
public void addRow(Expression[] expr) {
list.add(expr);
}
@Override
public int update() {
Index index = null;
if (sortedInsertMode) {
index = table.getScanIndex(session);
index.setSortedInsertMode(true);
}
try {
return insertRows();
} finally {
if (index != null) {
index.setSortedInsertMode(false);
}
}
}
private int insertRows() {
session.getUser().checkRight(table, Right.INSERT);
setCurrentRowNumber(0);
table.fire(session, Trigger.INSERT, true);
rowNumber = 0;
GeneratedKeys generatedKeys = session.getGeneratedKeys();
generatedKeys.initialize(table);
int listSize = list.size();
if (listSize > 0) {
int columnLen = columns.length;
for (int x = 0; x < listSize; x++) {
session.startStatementWithinTransaction();
generatedKeys.nextRow();
Row newRow = table.getTemplateRow();
Expression[] expr = list.get(x);
setCurrentRowNumber(x + 1);
for (int i = 0; i < columnLen; i++) {
Column c = columns[i];
int index = c.getColumnId();
Expression e = expr[i];
if (e != null) {
// e can be null (DEFAULT)
e = e.optimize(session);
try {
Value v = c.convert(e.getValue(session), session.getDatabase().getMode());
newRow.setValue(index, v);
if (e instanceof SequenceValue) {
generatedKeys.add(c);
}
} catch (DbException ex) {
throw setRow(ex, x, getSQL(expr));
}
}
}
rowNumber++;
table.validateConvertUpdateSequence(session, newRow);
boolean done = table.fireBeforeRow(session, null, newRow);
if (!done) {
table.lock(session, true, false);
try {
table.addRow(session, newRow);
} catch (DbException de) {
if (!handleOnDuplicate(de)) {
// INSERT IGNORE case
rowNumber--;
continue;
}
}
generatedKeys.confirmRow(newRow);
session.log(table, UndoLogRecord.INSERT, newRow);
table.fireAfterRow(session, null, newRow, false);
}
}
} else {
table.lock(session, true, false);
if (insertFromSelect) {
query.query(0, this);
} else {
ResultInterface rows = query.query(0);
while (rows.next()) {
generatedKeys.nextRow();
Value[] r = rows.currentRow();
Row newRow = addRowImpl(r);
if (newRow != null) {
generatedKeys.confirmRow(newRow);
}
}
rows.close();
}
}
table.fire(session, Trigger.INSERT, false);
return rowNumber;
}
@Override
public void addRow(Value[] values) {
addRowImpl(values);
}
private Row addRowImpl(Value[] values) {
Row newRow = table.getTemplateRow();
setCurrentRowNumber(++rowNumber);
for (int j = 0, len = columns.length; j < len; j++) {
Column c = columns[j];
int index = c.getColumnId();
try {
Value v = c.convert(values[j], session.getDatabase().getMode());
newRow.setValue(index, v);
} catch (DbException ex) {
throw setRow(ex, rowNumber, getSQL(values));
}
}
table.validateConvertUpdateSequence(session, newRow);
boolean done = table.fireBeforeRow(session, null, newRow);
if (!done) {
table.addRow(session, newRow);
session.log(table, UndoLogRecord.INSERT, newRow);
table.fireAfterRow(session, null, newRow, false);
return newRow;
}
return null;
}
@Override
public int getRowCount() {
return rowNumber;
}
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("INSERT INTO ");
buff.append(table.getSQL()).append('(');
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(")\n");
if (insertFromSelect) {
buff.append("DIRECT ");
}
if (sortedInsertMode) {
buff.append("SORTED ");
}
if (!list.isEmpty()) {
buff.append("VALUES ");
int row = 0;
if (list.size() > 1) {
buff.append('\n');
}
for (Expression[] expr : list) {
if (row++ > 0) {
buff.append(",\n");
}
buff.append('(');
buff.resetCount();
for (Expression e : expr) {
buff.appendExceptFirst(", ");
if (e == null) {
buff.append("DEFAULT");
} else {
buff.append(e.getSQL());
}
}
buff.append(')');
}
} else {
buff.append(query.getPlanSQL());
}
return buff.toString();
}
@Override
public void prepare() {
if (columns == null) {
if (!list.isEmpty() && list.get(0).length == 0) {
// special case where table is used as a sequence
columns = new Column[0];
} else {
columns = table.getColumns();
}
}
if (!list.isEmpty()) {
for (Expression[] expr : list) {
if (expr.length != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
for (int i = 0, len = expr.length; i < len; i++) {
Expression e = expr[i];
if (e != null) {
if(sourceTableFilter!=null){
e.mapColumns(sourceTableFilter, 0);
}
e = e.optimize(session);
if (e instanceof Parameter) {
Parameter p = (Parameter) e;
p.setColumn(columns[i]);
}
expr[i] = e;
}
}
}
} else {
query.prepare();
if (query.getColumnCount() != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
public void setSortedInsertMode(boolean sortedInsertMode) {
this.sortedInsertMode = sortedInsertMode;
}
@Override
public int getType() {
return CommandInterface.INSERT;
}
public void setInsertFromSelect(boolean value) {
this.insertFromSelect = value;
}
@Override
public boolean isCacheable() {
return duplicateKeyAssignmentMap == null ||
duplicateKeyAssignmentMap.isEmpty();
}
/**
* @param de duplicate key exception
* @return {@code true} if row was updated, {@code false} if row was ignored
*/
private boolean handleOnDuplicate(DbException de) {
if (de.getErrorCode() != ErrorCode.DUPLICATE_KEY_1) {
throw de;
}
if (duplicateKeyAssignmentMap == null ||
duplicateKeyAssignmentMap.isEmpty()) {
if (ignore) {
return false;
}
throw de;
}
ArrayList<String> variableNames = new ArrayList<>(
duplicateKeyAssignmentMap.size());
Expression[] row = list.get(getCurrentRowNumber() - 1);
for (int i = 0; i < columns.length; i++) {
String key = table.getSchema().getName() + "." +
table.getName() + "." + columns[i].getName();
variableNames.add(key);
session.setVariable(key,
row[i].getValue(session));
}
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(table.getSQL()).append(" SET ");
for (Column column : duplicateKeyAssignmentMap.keySet()) {
buff.appendExceptFirst(", ");
Expression ex = duplicateKeyAssignmentMap.get(column);
buff.append(column.getSQL()).append("=").append(ex.getSQL());
}
buff.append(" WHERE ");
Index foundIndex = (Index) de.getSource();
if (foundIndex == null) {
throw DbException.getUnsupportedException(
"Unable to apply ON DUPLICATE KEY UPDATE, no index found!");
}
buff.append(prepareUpdateCondition(foundIndex).getSQL());
String sql = buff.toString();
Prepared command = session.prepare(sql);
for (Parameter param : command.getParameters()) {
Parameter insertParam = parameters.get(param.getIndex());
param.setValue(insertParam.getValue(session));
}
command.update();
for (String variableName : variableNames) {
session.setVariable(variableName, ValueNull.INSTANCE);
}
return true;
}
private Expression prepareUpdateCondition(Index foundIndex) {
// MVPrimaryIndex is playing fast and loose with it's implementation of
// the Index interface.
// It returns all of the columns in the table when we call
// getIndexColumns() or getColumns().
// Don't have time right now to fix that, so just special-case it.
final Column[] indexedColumns;
if (foundIndex instanceof MVPrimaryIndex) {
MVPrimaryIndex foundMV = (MVPrimaryIndex) foundIndex;
indexedColumns = new Column[] { foundMV.getIndexColumns()[foundMV
.getMainIndexColumn()].column };
} else {
indexedColumns = foundIndex.getColumns();
}
Expression[] row = list.get(getCurrentRowNumber() - 1);
Expression condition = null;
for (Column column : indexedColumns) {
ExpressionColumn expr = new ExpressionColumn(session.getDatabase(),
table.getSchema().getName(), table.getName(),
column.getName());
for (int i = 0; i < columns.length; i++) {
if (expr.getColumnName().equals(columns[i].getName())) {
if (condition == null) {
condition = new Comparison(session, Comparison.EQUAL, expr, row[i]);
} else {
condition = new ConditionAndOr(ConditionAndOr.AND, condition,
new Comparison(session, Comparison.EQUAL, expr, row[i]));
}
break;
}
}
}
return condition;
}
public void setSourceTableFilter(TableFilter sourceTableFilter) {
this.sourceTableFilter = sourceTableFilter;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Merge.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.command.dml;
import java.util.ArrayList;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.Command;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.GeneratedKeys;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Expression;
import org.h2.expression.Parameter;
import org.h2.expression.SequenceValue;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
/**
* This class represents the statement
* MERGE
*/
public class Merge extends Prepared {
private Table targetTable;
private TableFilter targetTableFilter;
private Column[] columns;
private Column[] keys;
private final ArrayList<Expression[]> valuesExpressionList = New.arrayList();
private Query query;
private Prepared update;
public Merge(Session session) {
super(session);
}
@Override
public void setCommand(Command command) {
super.setCommand(command);
if (query != null) {
query.setCommand(command);
}
}
public void setTargetTable(Table targetTable) {
this.targetTable = targetTable;
}
public void setColumns(Column[] columns) {
this.columns = columns;
}
public void setKeys(Column[] keys) {
this.keys = keys;
}
public void setQuery(Query query) {
this.query = query;
}
/**
* Add a row to this merge statement.
*
* @param expr the list of values
*/
public void addRow(Expression[] expr) {
valuesExpressionList.add(expr);
}
@Override
public int update() {
int count;
session.getUser().checkRight(targetTable, Right.INSERT);
session.getUser().checkRight(targetTable, Right.UPDATE);
setCurrentRowNumber(0);
GeneratedKeys generatedKeys = session.getGeneratedKeys();
if (!valuesExpressionList.isEmpty()) {
// process values in list
count = 0;
generatedKeys.initialize(targetTable);
for (int x = 0, size = valuesExpressionList.size(); x < size; x++) {
setCurrentRowNumber(x + 1);
generatedKeys.nextRow();
Expression[] expr = valuesExpressionList.get(x);
Row newRow = targetTable.getTemplateRow();
for (int i = 0, len = columns.length; i < len; i++) {
Column c = columns[i];
int index = c.getColumnId();
Expression e = expr[i];
if (e != null) {
// e can be null (DEFAULT)
try {
Value v = c.convert(e.getValue(session));
newRow.setValue(index, v);
if (e instanceof SequenceValue) {
generatedKeys.add(c);
}
} catch (DbException ex) {
throw setRow(ex, count, getSQL(expr));
}
}
}
merge(newRow);
count++;
}
} else {
// process select data for list
query.setNeverLazy(true);
ResultInterface rows = query.query(0);
count = 0;
targetTable.fire(session, Trigger.UPDATE | Trigger.INSERT, true);
targetTable.lock(session, true, false);
while (rows.next()) {
count++;
generatedKeys.nextRow();
Value[] r = rows.currentRow();
Row newRow = targetTable.getTemplateRow();
setCurrentRowNumber(count);
for (int j = 0; j < columns.length; j++) {
Column c = columns[j];
int index = c.getColumnId();
try {
Value v = c.convert(r[j]);
newRow.setValue(index, v);
} catch (DbException ex) {
throw setRow(ex, count, getSQL(r));
}
}
merge(newRow);
}
rows.close();
targetTable.fire(session, Trigger.UPDATE | Trigger.INSERT, false);
}
return count;
}
/**
* Merge the given row.
*
* @param row the row
*/
protected void merge(Row row) {
ArrayList<Parameter> k = update.getParameters();
for (int i = 0; i < columns.length; i++) {
Column col = columns[i];
Value v = row.getValue(col.getColumnId());
Parameter p = k.get(i);
p.setValue(v);
}
for (int i = 0; i < keys.length; i++) {
Column col = keys[i];
Value v = row.getValue(col.getColumnId());
if (v == null) {
throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getSQL());
}
Parameter p = k.get(columns.length + i);
p.setValue(v);
}
// try and update
int count = update.update();
// if update fails try an insert
if (count == 0) {
try {
targetTable.validateConvertUpdateSequence(session, row);
boolean done = targetTable.fireBeforeRow(session, null, row);
if (!done) {
targetTable.lock(session, true, false);
targetTable.addRow(session, row);
session.getGeneratedKeys().confirmRow(row);
session.log(targetTable, UndoLogRecord.INSERT, row);
targetTable.fireAfterRow(session, null, row, false);
}
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
// possibly a concurrent merge or insert
Index index = (Index) e.getSource();
if (index != null) {
// verify the index columns match the key
Column[] indexColumns = index.getColumns();
boolean indexMatchesKeys = true;
if (indexColumns.length <= keys.length) {
for (int i = 0; i < indexColumns.length; i++) {
if (indexColumns[i] != keys[i]) {
indexMatchesKeys = false;
break;
}
}
}
if (indexMatchesKeys) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, targetTable.getName());
}
}
}
throw e;
}
} else if (count != 1) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1, targetTable.getSQL());
}
}
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("MERGE INTO ");
buff.append(targetTable.getSQL()).append('(');
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
if (keys != null) {
buff.append(" KEY(");
buff.resetCount();
for (Column c : keys) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
}
buff.append('\n');
if (!valuesExpressionList.isEmpty()) {
buff.append("VALUES ");
int row = 0;
for (Expression[] expr : valuesExpressionList) {
if (row++ > 0) {
buff.append(", ");
}
buff.append('(');
buff.resetCount();
for (Expression e : expr) {
buff.appendExceptFirst(", ");
if (e == null) {
buff.append("DEFAULT");
} else {
buff.append(e.getSQL());
}
}
buff.append(')');
}
} else {
buff.append(query.getPlanSQL());
}
return buff.toString();
}
@Override
public void prepare() {
if (columns == null) {
if (!valuesExpressionList.isEmpty() && valuesExpressionList.get(0).length == 0) {
// special case where table is used as a sequence
columns = new Column[0];
} else {
columns = targetTable.getColumns();
}
}
if (!valuesExpressionList.isEmpty()) {
for (Expression[] expr : valuesExpressionList) {
if (expr.length != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
for (int i = 0; i < expr.length; i++) {
Expression e = expr[i];
if (e != null) {
expr[i] = e.optimize(session);
}
}
}
} else {
query.prepare();
if (query.getColumnCount() != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
if (keys == null) {
Index idx = targetTable.getPrimaryKey();
if (idx == null) {
throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, "PRIMARY KEY");
}
keys = idx.getColumns();
}
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(targetTable.getSQL()).append(" SET ");
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL()).append("=?");
}
buff.append(" WHERE ");
buff.resetCount();
for (Column c : keys) {
buff.appendExceptFirst(" AND ");
buff.append(c.getSQL()).append("=?");
}
String sql = buff.toString();
update = session.prepare(sql);
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.MERGE;
}
@Override
public boolean isCacheable() {
return true;
}
public Table getTargetTable() {
return targetTable;
}
public TableFilter getTargetTableFilter() {
return targetTableFilter;
}
public void setTargetTableFilter(TableFilter targetTableFilter) {
this.targetTableFilter = targetTableFilter;
setTargetTable(targetTableFilter.getTable());
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/MergeUsing.java
|
/*
* Copyright 2004-2017 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.command.dml;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Right;
import org.h2.expression.ConditionAndOr;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.RowImpl;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
/**
* This class represents the statement syntax
* MERGE table alias USING...
*
* It does not replace the existing MERGE INTO... KEYS... form.
*
* It supports the SQL 2003/2008 standard MERGE statement:
* http://en.wikipedia.org/wiki/Merge_%28SQL%29
*
* Database management systems Oracle Database, DB2, Teradata, EXASOL, Firebird, CUBRID, HSQLDB,
* MS SQL, Vectorwise and Apache Derby & Postgres support the standard syntax of the
* SQL 2003/2008 MERGE command:
*
* MERGE INTO targetTable AS T USING sourceTable AS S ON (T.ID = S.ID)
* WHEN MATCHED THEN
* UPDATE SET column1 = value1 [, column2 = value2 ...] WHERE column1=valueUpdate
* DELETE WHERE column1=valueDelete
* WHEN NOT MATCHED THEN
* INSERT (column1 [, column2 ...]) VALUES (value1 [, value2 ...]);
*
* Only Oracle support the additional optional DELETE clause.
*
* Implementation notes:
*
* 1) The ON clause must specify 1 or more columns from the TARGET table because they are
* used in the plan SQL WHERE statement. Otherwise an exception is raised.
*
* 2) The ON clause must specify 1 or more columns from the SOURCE table/query because they
* are used to track the join key values for every source table row - to prevent any
* TARGET rows from being updated twice per MERGE USING statement.
*
* This is to implement a requirement from the MERGE INTO specification
* requiring each row from being updated more than once per MERGE USING statement.
* The source columns are used to gather the effective "key" values which have been
* updated, in order to implement this requirement.
* If the no SOURCE table/query columns are found in the ON clause, then an exception is
* raised.
*
* The update row counts of the embedded UPDATE and DELETE statements are also tracked to
* ensure no more than 1 row is ever updated. (Note One special case of this is that
* the DELETE is allowed to affect the same row which was updated by UPDATE - this is an
* Oracle only extension.)
*
* 3) UPDATE and DELETE statements are allowed to specify extra conditional criteria
* (in the WHERE clause) to allow fine-grained control of actions when a record is found.
* The ON clause conditions are always prepended to the WHERE clause of these embedded
* statements, so they will never update more than the ON join condition.
*
* 4) Previously if neither UPDATE or DELETE clause is supplied, but INSERT is supplied - the INSERT
* action is always triggered. This is because the embedded UPDATE and DELETE statement's
* returned update row count is used to detect a matching join.
* If neither of the two the statements are provided, no matching join is NEVER detected.
*
* A fix for this is now implemented as described below:
* We now generate a "matchSelect" query and use that to always detect
* a match join - rather than relying on UPDATE or DELETE statements.
*
* This is an improvement, especially in the case that if either of the
* UPDATE or DELETE statements had their own fine-grained WHERE conditions, making
* them completely different conditions than the plain ON condition clause which
* the SQL author would be specifying/expecting.
*
* An additional benefit of this solution is that this "matchSelect" query
* is used to return the ROWID of the found (or inserted) query - for more accurate
* enforcing of the only-update-each-target-row-once rule.
*/
public class MergeUsing extends Prepared {
// Merge fields
private Table targetTable;
private TableFilter targetTableFilter;
private Column[] columns;
private Column[] keys;
private final ArrayList<Expression[]> valuesExpressionList = New
.arrayList();
private Query query;
// MergeUsing fields
private TableFilter sourceTableFilter;
private Expression onCondition;
private Update updateCommand;
private Delete deleteCommand;
private Insert insertCommand;
private String queryAlias;
private int countUpdatedRows;
private Column[] sourceKeys;
private Select targetMatchQuery;
private final HashMap<Value, Integer> targetRowidsRemembered = new HashMap<>();
private int sourceQueryRowNumber;
public MergeUsing(Merge merge) {
super(merge.getSession());
// bring across only the already parsed data from Merge...
this.targetTable = merge.getTargetTable();
this.targetTableFilter = merge.getTargetTableFilter();
}
@Override
public int update() {
// clear list of source table keys & rowids we have processed already
targetRowidsRemembered.clear();
if (targetTableFilter != null) {
targetTableFilter.startQuery(session);
targetTableFilter.reset();
}
if (sourceTableFilter != null) {
sourceTableFilter.startQuery(session);
sourceTableFilter.reset();
}
sourceQueryRowNumber = 0;
checkRights();
setCurrentRowNumber(0);
// process source select query data for row creation
ResultInterface rows = query.query(0);
targetTable.fire(session, evaluateTriggerMasks(), true);
targetTable.lock(session, true, false);
while (rows.next()) {
sourceQueryRowNumber++;
Value[] sourceRowValues = rows.currentRow();
Row sourceRow = new RowImpl(sourceRowValues, 0);
setCurrentRowNumber(sourceQueryRowNumber);
merge(sourceRow);
}
rows.close();
targetTable.fire(session, evaluateTriggerMasks(), false);
return countUpdatedRows;
}
private int evaluateTriggerMasks() {
int masks = 0;
if (insertCommand != null) {
masks |= Trigger.INSERT;
}
if (updateCommand != null) {
masks |= Trigger.UPDATE;
}
if (deleteCommand != null) {
masks |= Trigger.DELETE;
}
return masks;
}
private void checkRights() {
if (insertCommand != null) {
session.getUser().checkRight(targetTable, Right.INSERT);
}
if (updateCommand != null) {
session.getUser().checkRight(targetTable, Right.UPDATE);
}
if (deleteCommand != null) {
session.getUser().checkRight(targetTable, Right.DELETE);
}
// check the underlying tables
session.getUser().checkRight(targetTable, Right.SELECT);
session.getUser().checkRight(sourceTableFilter.getTable(),
Right.SELECT);
}
/**
* Merge the given row.
*
* @param sourceRow the row
*/
protected void merge(Row sourceRow) {
// put the column values into the table filter
sourceTableFilter.set(sourceRow);
// Is the target row there already ?
boolean rowFound = isTargetRowFound();
// try and perform an update
int rowUpdateCount = 0;
if (rowFound) {
if (updateCommand != null) {
rowUpdateCount += updateCommand.update();
}
if (deleteCommand != null) {
int deleteRowUpdateCount = deleteCommand.update();
// under oracle rules these updates & delete combinations are
// allowed together
if (rowUpdateCount == 1 && deleteRowUpdateCount == 1) {
countUpdatedRows += deleteRowUpdateCount;
deleteRowUpdateCount = 0;
} else {
rowUpdateCount += deleteRowUpdateCount;
}
}
} else {
// if either updates do nothing, try an insert
if (rowUpdateCount == 0) {
rowUpdateCount += addRowByCommandInsert(sourceRow);
} else if (rowUpdateCount != 1) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1,
"Duplicate key inserted " + rowUpdateCount
+ " rows at once, only 1 expected:"
+ targetTable.getSQL());
}
}
countUpdatedRows += rowUpdateCount;
}
private boolean isTargetRowFound() {
ResultInterface rows = targetMatchQuery.query(0);
int countTargetRowsFound = 0;
Value[] targetRowIdValue = null;
while (rows.next()) {
countTargetRowsFound++;
targetRowIdValue = rows.currentRow();
// throw and exception if we have processed this _ROWID_ before...
if (targetRowidsRemembered.containsKey(targetRowIdValue[0])) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1,
"Merge using ON column expression, " +
"duplicate _ROWID_ target record already updated, deleted or inserted:_ROWID_="
+ targetRowIdValue[0].toString() + ":in:"
+ targetTableFilter.getTable()
+ ":conflicting source row number:"
+ targetRowidsRemembered
.get(targetRowIdValue[0]));
} else {
// remember the source column values we have used before (they
// are the effective ON clause keys
// and should not be repeated
targetRowidsRemembered.put(targetRowIdValue[0],
sourceQueryRowNumber);
}
}
rows.close();
if (countTargetRowsFound > 1) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1,
"Duplicate key updated " + countTargetRowsFound
+ " rows at once, only 1 expected:_ROWID_="
+ targetRowIdValue[0].toString() + ":in:"
+ targetTableFilter.getTable()
+ ":conflicting source row number:"
+ targetRowidsRemembered.get(targetRowIdValue[0]));
}
return countTargetRowsFound > 0;
}
private int addRowByCommandInsert(Row sourceRow) {
int localCount = 0;
if (insertCommand != null) {
localCount += insertCommand.update();
if (!isTargetRowFound()) {
throw DbException.get(ErrorCode.GENERAL_ERROR_1,
"Expected to find key after row inserted, but none found. Insert does not match ON condition.:"
+ targetTable.getSQL() + ":source row="
+ Arrays.asList(sourceRow.getValueList()));
}
}
return localCount;
}
// Use the regular merge syntax as our plan SQL
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("MERGE INTO ");
buff.append(targetTable.getSQL()).append('(');
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
if (keys != null) {
buff.append(" KEY(");
buff.resetCount();
for (Column c : keys) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
}
buff.append('\n');
if (!valuesExpressionList.isEmpty()) {
buff.append("VALUES ");
int row = 0;
for (Expression[] expr : valuesExpressionList) {
if (row++ > 0) {
buff.append(", ");
}
buff.append('(');
buff.resetCount();
for (Expression e : expr) {
buff.appendExceptFirst(", ");
if (e == null) {
buff.append("DEFAULT");
} else {
buff.append(e.getSQL());
}
}
buff.append(')');
}
} else {
buff.append(query.getPlanSQL());
}
return buff.toString();
}
@Override
public void prepare() {
onCondition.addFilterConditions(sourceTableFilter, true);
onCondition.addFilterConditions(targetTableFilter, true);
onCondition.mapColumns(sourceTableFilter, 2);
onCondition.mapColumns(targetTableFilter, 1);
if (keys == null) {
HashSet<Column> targetColumns = buildColumnListFromOnCondition(
targetTableFilter);
keys = targetColumns.toArray(new Column[0]);
}
if (keys.length == 0) {
throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1,
"No references to target columns found in ON clause:"
+ targetTableFilter.toString());
}
if (sourceKeys == null) {
HashSet<Column> sourceColumns = buildColumnListFromOnCondition(
sourceTableFilter);
sourceKeys = sourceColumns.toArray(new Column[0]);
}
if (sourceKeys.length == 0) {
throw DbException.get(ErrorCode.COLUMN_NOT_FOUND_1,
"No references to source columns found in ON clause:"
+ sourceTableFilter.toString());
}
// only do the optimize now - before we have already gathered the
// unoptimized column data
onCondition = onCondition.optimize(session);
onCondition.createIndexConditions(session, sourceTableFilter);
onCondition.createIndexConditions(session, targetTableFilter);
if (columns == null) {
if (!valuesExpressionList.isEmpty()
&& valuesExpressionList.get(0).length == 0) {
// special case where table is used as a sequence
columns = new Column[0];
} else {
columns = targetTable.getColumns();
}
}
if (!valuesExpressionList.isEmpty()) {
for (Expression[] expr : valuesExpressionList) {
if (expr.length != columns.length) {
throw DbException
.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
for (int i = 0; i < expr.length; i++) {
Expression e = expr[i];
if (e != null) {
expr[i] = e.optimize(session);
}
}
}
} else {
query.prepare();
if (query.getColumnCount() != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
int embeddedStatementsCount = 0;
// Prepare each of the sub-commands ready to aid in the MERGE
// collaboration
if (updateCommand != null) {
updateCommand.setSourceTableFilter(sourceTableFilter);
updateCommand.setCondition(appendOnCondition(updateCommand));
updateCommand.prepare();
embeddedStatementsCount++;
}
if (deleteCommand != null) {
deleteCommand.setSourceTableFilter(sourceTableFilter);
deleteCommand.setCondition(appendOnCondition(deleteCommand));
deleteCommand.prepare();
embeddedStatementsCount++;
}
if (insertCommand != null) {
insertCommand.setSourceTableFilter(sourceTableFilter);
insertCommand.prepare();
embeddedStatementsCount++;
}
if (embeddedStatementsCount == 0) {
throw DbException.get(ErrorCode.SYNTAX_ERROR_1,
"At least UPDATE, DELETE or INSERT embedded statement must be supplied.");
}
// setup the targetMatchQuery - for detecting if the target row exists
Expression targetMatchCondition = targetMatchQuery.getCondition();
targetMatchCondition.addFilterConditions(sourceTableFilter, true);
targetMatchCondition.mapColumns(sourceTableFilter, 2);
targetMatchCondition = targetMatchCondition.optimize(session);
targetMatchCondition.createIndexConditions(session, sourceTableFilter);
targetMatchQuery.prepare();
}
private HashSet<Column> buildColumnListFromOnCondition(
TableFilter anyTableFilter) {
HashSet<Column> filteredColumns = new HashSet<>();
HashSet<Column> columns = new HashSet<>();
ExpressionVisitor visitor = ExpressionVisitor
.getColumnsVisitor(columns);
onCondition.isEverything(visitor);
for (Column c : columns) {
if (c != null && c.getTable() == anyTableFilter.getTable()) {
filteredColumns.add(c);
}
}
return filteredColumns;
}
private Expression appendOnCondition(Update updateCommand) {
if (updateCommand.getCondition() == null) {
return onCondition;
}
return new ConditionAndOr(ConditionAndOr.AND,
updateCommand.getCondition(), onCondition);
}
private Expression appendOnCondition(Delete deleteCommand) {
if (deleteCommand.getCondition() == null) {
return onCondition;
}
return new ConditionAndOr(ConditionAndOr.AND,
deleteCommand.getCondition(), onCondition);
}
public void setSourceTableFilter(TableFilter sourceTableFilter) {
this.sourceTableFilter = sourceTableFilter;
}
public TableFilter getSourceTableFilter() {
return sourceTableFilter;
}
public void setOnCondition(Expression condition) {
this.onCondition = condition;
}
public Expression getOnCondition() {
return onCondition;
}
public Prepared getUpdateCommand() {
return updateCommand;
}
public void setUpdateCommand(Update updateCommand) {
this.updateCommand = updateCommand;
}
public Prepared getDeleteCommand() {
return deleteCommand;
}
public void setDeleteCommand(Delete deleteCommand) {
this.deleteCommand = deleteCommand;
}
public Insert getInsertCommand() {
return insertCommand;
}
public void setInsertCommand(Insert insertCommand) {
this.insertCommand = insertCommand;
}
public void setQueryAlias(String alias) {
this.queryAlias = alias;
}
public String getQueryAlias() {
return this.queryAlias;
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
public void setTargetTableFilter(TableFilter targetTableFilter) {
this.targetTableFilter = targetTableFilter;
}
public TableFilter getTargetTableFilter() {
return targetTableFilter;
}
public Table getTargetTable() {
return targetTable;
}
public void setTargetTable(Table targetTable) {
this.targetTable = targetTable;
}
public Select getTargetMatchQuery() {
return targetMatchQuery;
}
public void setTargetMatchQuery(Select targetMatchQuery) {
this.targetMatchQuery = targetMatchQuery;
}
// Prepared interface implementations
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.MERGE;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/NoOperation.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.command.dml;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.result.ResultInterface;
/**
* Represents an empty statement or a statement that has no effect.
*/
public class NoOperation extends Prepared {
public NoOperation(Session session) {
super(session);
}
@Override
public int update() {
return 0;
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public boolean needRecompile() {
return false;
}
@Override
public boolean isReadOnly() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.NO_OPERATION;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Optimizer.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.command.dml;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.table.Plan;
import org.h2.table.PlanItem;
import org.h2.table.TableFilter;
import org.h2.util.BitField;
import org.h2.util.Permutations;
/**
* The optimizer is responsible to find the best execution plan
* for a given query.
*/
class Optimizer {
private static final int MAX_BRUTE_FORCE_FILTERS = 7;
private static final int MAX_BRUTE_FORCE = 2000;
private static final int MAX_GENETIC = 500;
private long startNs;
private BitField switched;
// possible plans for filters, if using brute force:
// 1 filter 1 plan
// 2 filters 2 plans
// 3 filters 6 plans
// 4 filters 24 plans
// 5 filters 120 plans
// 6 filters 720 plans
// 7 filters 5040 plans
// 8 filters 40320 plan
// 9 filters 362880 plans
// 10 filters 3628800 filters
private final TableFilter[] filters;
private final Expression condition;
private final Session session;
private Plan bestPlan;
private TableFilter topFilter;
private double cost;
private Random random;
Optimizer(TableFilter[] filters, Expression condition, Session session) {
this.filters = filters;
this.condition = condition;
this.session = session;
}
/**
* How many filter to calculate using brute force. The remaining filters are
* selected using a greedy algorithm which has a runtime of (1 + 2 + ... +
* n) = (n * (n-1) / 2) for n filters. The brute force algorithm has a
* runtime of n * (n-1) * ... * (n-m) when calculating m brute force of n
* total. The combined runtime is (brute force) * (greedy).
*
* @param filterCount the number of filters total
* @return the number of filters to calculate using brute force
*/
private static int getMaxBruteForceFilters(int filterCount) {
int i = 0, j = filterCount, total = filterCount;
while (j > 0 && total * (j * (j - 1) / 2) < MAX_BRUTE_FORCE) {
j--;
total *= j;
i++;
}
return i;
}
private void calculateBestPlan() {
cost = -1;
if (filters.length == 1 || session.isForceJoinOrder()) {
testPlan(filters);
} else {
startNs = System.nanoTime();
if (filters.length <= MAX_BRUTE_FORCE_FILTERS) {
calculateBruteForceAll();
} else {
calculateBruteForceSome();
random = new Random(0);
calculateGenetic();
}
}
}
private void calculateFakePlan() {
cost = -1;
bestPlan = new Plan(filters, filters.length, condition);
}
private boolean canStop(int x) {
return (x & 127) == 0
&& cost >= 0 // don't calculate for simple queries (no rows or so)
&& 10 * (System.nanoTime() - startNs) > cost * TimeUnit.MILLISECONDS.toNanos(1);
}
private void calculateBruteForceAll() {
TableFilter[] list = new TableFilter[filters.length];
Permutations<TableFilter> p = Permutations.create(filters, list);
for (int x = 0; !canStop(x) && p.next(); x++) {
testPlan(list);
}
}
private void calculateBruteForceSome() {
int bruteForce = getMaxBruteForceFilters(filters.length);
TableFilter[] list = new TableFilter[filters.length];
Permutations<TableFilter> p = Permutations.create(filters, list, bruteForce);
for (int x = 0; !canStop(x) && p.next(); x++) {
// find out what filters are not used yet
for (TableFilter f : filters) {
f.setUsed(false);
}
for (int i = 0; i < bruteForce; i++) {
list[i].setUsed(true);
}
// fill the remaining elements with the unused elements (greedy)
for (int i = bruteForce; i < filters.length; i++) {
double costPart = -1.0;
int bestPart = -1;
for (int j = 0; j < filters.length; j++) {
if (!filters[j].isUsed()) {
if (i == filters.length - 1) {
bestPart = j;
break;
}
list[i] = filters[j];
Plan part = new Plan(list, i+1, condition);
double costNow = part.calculateCost(session);
if (costPart < 0 || costNow < costPart) {
costPart = costNow;
bestPart = j;
}
}
}
filters[bestPart].setUsed(true);
list[i] = filters[bestPart];
}
testPlan(list);
}
}
private void calculateGenetic() {
TableFilter[] best = new TableFilter[filters.length];
TableFilter[] list = new TableFilter[filters.length];
for (int x = 0; x < MAX_GENETIC; x++) {
if (canStop(x)) {
break;
}
boolean generateRandom = (x & 127) == 0;
if (!generateRandom) {
System.arraycopy(best, 0, list, 0, filters.length);
if (!shuffleTwo(list)) {
generateRandom = true;
}
}
if (generateRandom) {
switched = new BitField();
System.arraycopy(filters, 0, best, 0, filters.length);
shuffleAll(best);
System.arraycopy(best, 0, list, 0, filters.length);
}
if (testPlan(list)) {
switched = new BitField();
System.arraycopy(list, 0, best, 0, filters.length);
}
}
}
private boolean testPlan(TableFilter[] list) {
Plan p = new Plan(list, list.length, condition);
double costNow = p.calculateCost(session);
if (cost < 0 || costNow < cost) {
cost = costNow;
bestPlan = p;
return true;
}
return false;
}
private void shuffleAll(TableFilter[] f) {
for (int i = 0; i < f.length - 1; i++) {
int j = i + random.nextInt(f.length - i);
if (j != i) {
TableFilter temp = f[i];
f[i] = f[j];
f[j] = temp;
}
}
}
private boolean shuffleTwo(TableFilter[] f) {
int a = 0, b = 0, i = 0;
for (; i < 20; i++) {
a = random.nextInt(f.length);
b = random.nextInt(f.length);
if (a == b) {
continue;
}
if (a < b) {
int temp = a;
a = b;
b = temp;
}
int s = a * f.length + b;
if (switched.get(s)) {
continue;
}
switched.set(s);
break;
}
if (i == 20) {
return false;
}
TableFilter temp = f[a];
f[a] = f[b];
f[b] = temp;
return true;
}
/**
* Calculate the best query plan to use.
*
* @param parse If we do not need to really get the best plan because it is
* a view parsing stage.
*/
void optimize(boolean parse) {
if (parse) {
calculateFakePlan();
} else {
calculateBestPlan();
bestPlan.removeUnusableIndexConditions();
}
TableFilter[] f2 = bestPlan.getFilters();
topFilter = f2[0];
for (int i = 0; i < f2.length - 1; i++) {
f2[i].addJoin(f2[i + 1], false, null);
}
if (parse) {
return;
}
for (TableFilter f : f2) {
PlanItem item = bestPlan.getItem(f);
f.setPlanItem(item);
}
}
public TableFilter getTopFilter() {
return topFilter;
}
double getCost() {
return cost;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Query.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.command.dml;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.Prepared;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.expression.Alias;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionVisitor;
import org.h2.expression.Parameter;
import org.h2.expression.ValueExpression;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.ResultTarget;
import org.h2.result.SortOrder;
import org.h2.table.ColumnResolver;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueNull;
/**
* Represents a SELECT statement (simple, or union).
*/
public abstract class Query extends Prepared {
/**
* The limit expression as specified in the LIMIT or TOP clause.
*/
protected Expression limitExpr;
/**
* The offset expression as specified in the LIMIT .. OFFSET clause.
*/
protected Expression offsetExpr;
/**
* The sample size expression as specified in the SAMPLE_SIZE clause.
*/
protected Expression sampleSizeExpr;
/**
* Whether the result must only contain distinct rows.
*/
protected boolean distinct;
/**
* Whether the result needs to support random access.
*/
protected boolean randomAccessResult;
private boolean noCache;
private int lastLimit;
private long lastEvaluated;
private ResultInterface lastResult;
private Value[] lastParameters;
private boolean cacheableChecked;
private boolean neverLazy;
Query(Session session) {
super(session);
}
public void setNeverLazy(boolean b) {
this.neverLazy = b;
}
public boolean isNeverLazy() {
return neverLazy;
}
/**
* Check if this is a UNION query.
*
* @return {@code true} if this is a UNION query
*/
public abstract boolean isUnion();
/**
* Prepare join batching.
*/
public abstract void prepareJoinBatch();
/**
* Execute the query without checking the cache. If a target is specified,
* the results are written to it, and the method returns null. If no target
* is specified, a new LocalResult is created and returned.
*
* @param limit the limit as specified in the JDBC method call
* @param target the target to write results to
* @return the result
*/
protected abstract ResultInterface queryWithoutCache(int limit,
ResultTarget target);
private ResultInterface queryWithoutCacheLazyCheck(int limit,
ResultTarget target) {
boolean disableLazy = neverLazy && session.isLazyQueryExecution();
if (disableLazy) {
session.setLazyQueryExecution(false);
}
try {
return queryWithoutCache(limit, target);
} finally {
if (disableLazy) {
session.setLazyQueryExecution(true);
}
}
}
/**
* Initialize the query.
*/
public abstract void init();
/**
* The the list of select expressions.
* This may include invisible expressions such as order by expressions.
*
* @return the list of expressions
*/
public abstract ArrayList<Expression> getExpressions();
/**
* Calculate the cost to execute this query.
*
* @return the cost
*/
public abstract double getCost();
/**
* Calculate the cost when used as a subquery.
* This method returns a value between 10 and 1000000,
* to ensure adding other values can't result in an integer overflow.
*
* @return the estimated cost as an integer
*/
public int getCostAsExpression() {
// ensure the cost is not larger than 1 million,
// so that adding other values can't overflow
return (int) Math.min(1_000_000d, 10d + 10d * getCost());
}
/**
* Get all tables that are involved in this query.
*
* @return the set of tables
*/
public abstract HashSet<Table> getTables();
/**
* Set the order by list.
*
* @param order the order by list
*/
public abstract void setOrder(ArrayList<SelectOrderBy> order);
/**
* Whether the query has an order.
*
* @return true if it has
*/
public abstract boolean hasOrder();
/**
* Set the 'for update' flag.
*
* @param forUpdate the new setting
*/
public abstract void setForUpdate(boolean forUpdate);
/**
* Get the column count of this query.
*
* @return the column count
*/
public abstract int getColumnCount();
/**
* Map the columns to the given column resolver.
*
* @param resolver
* the resolver
* @param level
* the subquery level (0 is the top level query, 1 is the first
* subquery level)
*/
public abstract void mapColumns(ColumnResolver resolver, int level);
/**
* Change the evaluatable flag. This is used when building the execution
* plan.
*
* @param tableFilter the table filter
* @param b the new value
*/
public abstract void setEvaluatable(TableFilter tableFilter, boolean b);
/**
* Add a condition to the query. This is used for views.
*
* @param param the parameter
* @param columnId the column index (0 meaning the first column)
* @param comparisonType the comparison type
*/
public abstract void addGlobalCondition(Parameter param, int columnId,
int comparisonType);
/**
* Check whether adding condition to the query is allowed. This is not
* allowed for views that have an order by and a limit, as it would affect
* the returned results.
*
* @return true if adding global conditions is allowed
*/
public abstract boolean allowGlobalConditions();
/**
* 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);
/**
* Update all aggregate function values.
*
* @param s the session
*/
public abstract void updateAggregate(Session s);
/**
* Call the before triggers on all tables.
*/
public abstract void fireBeforeSelectTriggers();
/**
* Set the distinct flag.
*
* @param b the new value
*/
public void setDistinct(boolean b) {
distinct = b;
}
public boolean isDistinct() {
return distinct;
}
/**
* Whether results need to support random access.
*
* @param b the new value
*/
public void setRandomAccessResult(boolean b) {
randomAccessResult = b;
}
@Override
public boolean isQuery() {
return true;
}
@Override
public boolean isTransactional() {
return true;
}
/**
* Disable caching of result sets.
*/
public void disableCache() {
this.noCache = true;
}
private boolean sameResultAsLast(Session s, Value[] params,
Value[] lastParams, long lastEval) {
if (!cacheableChecked) {
long max = getMaxDataModificationId();
noCache = max == Long.MAX_VALUE;
cacheableChecked = true;
}
if (noCache) {
return false;
}
Database db = s.getDatabase();
for (int i = 0; i < params.length; i++) {
Value a = lastParams[i], b = params[i];
if (a.getType() != b.getType() || !db.areEqual(a, b)) {
return false;
}
}
if (!isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR) ||
!isEverything(ExpressionVisitor.INDEPENDENT_VISITOR)) {
return false;
}
if (db.getModificationDataId() > lastEval &&
getMaxDataModificationId() > lastEval) {
return false;
}
return true;
}
public final Value[] getParameterValues() {
ArrayList<Parameter> list = getParameters();
if (list == null) {
list = New.arrayList();
}
int size = list.size();
Value[] params = new Value[size];
for (int i = 0; i < size; i++) {
Value v = list.get(i).getParamValue();
params[i] = v;
}
return params;
}
@Override
public final ResultInterface query(int maxrows) {
return query(maxrows, null);
}
/**
* Execute the query, writing the result to the target result.
*
* @param limit the maximum number of rows to return
* @param target the target result (null will return the result)
* @return the result set (if the target is not set).
*/
public final ResultInterface query(int limit, ResultTarget target) {
if (isUnion()) {
// union doesn't always know the parameter list of the left and
// right queries
return queryWithoutCacheLazyCheck(limit, target);
}
fireBeforeSelectTriggers();
if (noCache || !session.getDatabase().getOptimizeReuseResults() ||
session.isLazyQueryExecution()) {
return queryWithoutCacheLazyCheck(limit, target);
}
Value[] params = getParameterValues();
long now = session.getDatabase().getModificationDataId();
if (isEverything(ExpressionVisitor.DETERMINISTIC_VISITOR)) {
if (lastResult != null && !lastResult.isClosed() &&
limit == lastLimit) {
if (sameResultAsLast(session, params, lastParameters,
lastEvaluated)) {
lastResult = lastResult.createShallowCopy(session);
if (lastResult != null) {
lastResult.reset();
return lastResult;
}
}
}
}
lastParameters = params;
closeLastResult();
ResultInterface r = queryWithoutCacheLazyCheck(limit, target);
lastResult = r;
this.lastEvaluated = now;
lastLimit = limit;
return r;
}
private void closeLastResult() {
if (lastResult != null) {
lastResult.close();
}
}
/**
* Initialize the order by list. This call may extend the expressions list.
*
* @param session the session
* @param expressions the select list expressions
* @param expressionSQL the select list SQL snippets
* @param orderList the order by list
* @param visible the number of visible columns in the select list
* @param mustBeInResult all order by expressions must be in the select list
* @param filters the table filters
*/
static void initOrder(Session session,
ArrayList<Expression> expressions,
ArrayList<String> expressionSQL,
ArrayList<SelectOrderBy> orderList,
int visible,
boolean mustBeInResult,
ArrayList<TableFilter> filters) {
Database db = session.getDatabase();
for (SelectOrderBy o : orderList) {
Expression e = o.expression;
if (e == null) {
continue;
}
// special case: SELECT 1 AS A FROM DUAL ORDER BY A
// (oracle supports it, but only in order by, not in group by and
// not in having):
// SELECT 1 AS A FROM DUAL ORDER BY -A
boolean isAlias = false;
int idx = expressions.size();
if (e instanceof ExpressionColumn) {
// order by expression
ExpressionColumn exprCol = (ExpressionColumn) e;
String tableAlias = exprCol.getOriginalTableAliasName();
String col = exprCol.getOriginalColumnName();
for (int j = 0; j < visible; j++) {
boolean found = false;
Expression ec = expressions.get(j);
if (ec instanceof ExpressionColumn) {
// select expression
ExpressionColumn c = (ExpressionColumn) ec;
found = db.equalsIdentifiers(col, c.getColumnName());
if (found && tableAlias != null) {
String ca = c.getOriginalTableAliasName();
if (ca == null) {
found = false;
if (filters != null) {
// select id from test order by test.id
for (TableFilter f : filters) {
if (db.equalsIdentifiers(f.getTableAlias(), tableAlias)) {
found = true;
break;
}
}
}
} else {
found = db.equalsIdentifiers(ca, tableAlias);
}
}
} else if (!(ec instanceof Alias)) {
continue;
} else if (tableAlias == null && db.equalsIdentifiers(col, ec.getAlias())) {
found = true;
} else {
Expression ec2 = ec.getNonAliasExpression();
if (ec2 instanceof ExpressionColumn) {
ExpressionColumn c2 = (ExpressionColumn) ec2;
String ta = exprCol.getSQL();
String tb = c2.getSQL();
String s2 = c2.getColumnName();
found = db.equalsIdentifiers(col, s2);
if (!db.equalsIdentifiers(ta, tb)) {
found = false;
}
}
}
if (found) {
idx = j;
isAlias = true;
break;
}
}
} else {
String s = e.getSQL();
if (expressionSQL != null) {
for (int j = 0, size = expressionSQL.size(); j < size; j++) {
String s2 = expressionSQL.get(j);
if (db.equalsIdentifiers(s2, s)) {
idx = j;
isAlias = true;
break;
}
}
}
}
if (!isAlias) {
if (mustBeInResult) {
throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT,
e.getSQL());
}
expressions.add(e);
String sql = e.getSQL();
expressionSQL.add(sql);
}
o.columnIndexExpr = ValueExpression.get(ValueInt.get(idx + 1));
o.expression = expressions.get(idx).getNonAliasExpression();
}
}
/**
* Create a {@link SortOrder} object given the list of {@link SelectOrderBy}
* objects. The expression list is extended if necessary.
*
* @param orderList a list of {@link SelectOrderBy} elements
* @param expressionCount the number of columns in the query
* @return the {@link SortOrder} object
*/
public SortOrder prepareOrder(ArrayList<SelectOrderBy> orderList,
int expressionCount) {
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);
int idx;
boolean reverse = false;
Expression expr = o.columnIndexExpr;
Value v = expr.getValue(null);
if (v == ValueNull.INSTANCE) {
// parameter not yet set - order by first column
idx = 0;
} else {
idx = v.getInt();
if (idx < 0) {
reverse = true;
idx = -idx;
}
idx -= 1;
if (idx < 0 || idx >= expressionCount) {
throw DbException.get(ErrorCode.ORDER_BY_NOT_IN_RESULT, "" + (idx + 1));
}
}
index[i] = idx;
boolean desc = o.descending;
if (reverse) {
desc = !desc;
}
int type = desc ? SortOrder.DESCENDING : SortOrder.ASCENDING;
if (o.nullsFirst) {
type += SortOrder.NULLS_FIRST;
} else if (o.nullsLast) {
type += SortOrder.NULLS_LAST;
}
sortType[i] = type;
}
return new SortOrder(session.getDatabase(), index, sortType, orderList);
}
public void setOffset(Expression offset) {
this.offsetExpr = offset;
}
public Expression getOffset() {
return offsetExpr;
}
public void setLimit(Expression limit) {
this.limitExpr = limit;
}
public Expression getLimit() {
return limitExpr;
}
/**
* Add a parameter to the parameter list.
*
* @param param the parameter to add
*/
void addParameter(Parameter param) {
if (parameters == null) {
parameters = New.arrayList();
}
parameters.add(param);
}
public void setSampleSize(Expression sampleSize) {
this.sampleSizeExpr = sampleSize;
}
/**
* Get the sample size, if set.
*
* @param session the session
* @return the sample size
*/
int getSampleSizeValue(Session session) {
if (sampleSizeExpr == null) {
return 0;
}
Value v = sampleSizeExpr.optimize(session).getValue(session);
if (v == ValueNull.INSTANCE) {
return 0;
}
return v.getInt();
}
public final long getMaxDataModificationId() {
ExpressionVisitor visitor = ExpressionVisitor.getMaxModificationIdVisitor();
isEverything(visitor);
return visitor.getMaxDataModificationId();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Replace.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.command.dml;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.Command;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.engine.UndoLogRecord;
import org.h2.expression.Expression;
import org.h2.expression.Parameter;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.table.Column;
import org.h2.table.Table;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.value.Value;
import java.util.ArrayList;
/**
* This class represents the MySQL-compatibility REPLACE statement
*/
public class Replace extends Prepared {
private Table table;
private Column[] columns;
private Column[] keys;
private final ArrayList<Expression[]> list = New.arrayList();
private Query query;
private Prepared update;
public Replace(Session session) {
super(session);
}
@Override
public void setCommand(Command command) {
super.setCommand(command);
if (query != null) {
query.setCommand(command);
}
}
public void setTable(Table table) {
this.table = table;
}
public void setColumns(Column[] columns) {
this.columns = columns;
}
public void setKeys(Column[] keys) {
this.keys = keys;
}
public void setQuery(Query query) {
this.query = query;
}
/**
* Add a row to this replace statement.
*
* @param expr the list of values
*/
public void addRow(Expression[] expr) {
list.add(expr);
}
@Override
public int update() {
int count;
session.getUser().checkRight(table, Right.INSERT);
session.getUser().checkRight(table, Right.UPDATE);
setCurrentRowNumber(0);
if (!list.isEmpty()) {
count = 0;
for (int x = 0, size = list.size(); x < size; x++) {
setCurrentRowNumber(x + 1);
Expression[] expr = list.get(x);
Row newRow = table.getTemplateRow();
for (int i = 0, len = columns.length; i < len; i++) {
Column c = columns[i];
int index = c.getColumnId();
Expression e = expr[i];
if (e != null) {
// e can be null (DEFAULT)
try {
Value v = c.convert(e.getValue(session));
newRow.setValue(index, v);
} catch (DbException ex) {
throw setRow(ex, count, getSQL(expr));
}
}
}
replace(newRow);
count++;
}
} else {
ResultInterface rows = query.query(0);
count = 0;
table.fire(session, Trigger.UPDATE | Trigger.INSERT, true);
table.lock(session, true, false);
while (rows.next()) {
count++;
Value[] r = rows.currentRow();
Row newRow = table.getTemplateRow();
setCurrentRowNumber(count);
for (int j = 0; j < columns.length; j++) {
Column c = columns[j];
int index = c.getColumnId();
try {
Value v = c.convert(r[j]);
newRow.setValue(index, v);
} catch (DbException ex) {
throw setRow(ex, count, getSQL(r));
}
}
replace(newRow);
}
rows.close();
table.fire(session, Trigger.UPDATE | Trigger.INSERT, false);
}
return count;
}
private void replace(Row row) {
int count = update(row);
if (count == 0) {
try {
table.validateConvertUpdateSequence(session, row);
boolean done = table.fireBeforeRow(session, null, row);
if (!done) {
table.lock(session, true, false);
table.addRow(session, row);
session.log(table, UndoLogRecord.INSERT, row);
table.fireAfterRow(session, null, row, false);
}
} catch (DbException e) {
if (e.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) {
// possibly a concurrent replace or insert
Index index = (Index) e.getSource();
if (index != null) {
// verify the index columns match the key
Column[] indexColumns = index.getColumns();
boolean indexMatchesKeys = false;
if (indexColumns.length <= keys.length) {
for (int i = 0; i < indexColumns.length; i++) {
if (indexColumns[i] != keys[i]) {
indexMatchesKeys = false;
break;
}
}
}
if (indexMatchesKeys) {
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, table.getName());
}
}
}
throw e;
}
} else if (count != 1) {
throw DbException.get(ErrorCode.DUPLICATE_KEY_1, table.getSQL());
}
}
private int update(Row row) {
// if there is no valid primary key,
// the statement degenerates to an INSERT
if (update == null) {
return 0;
}
ArrayList<Parameter> k = update.getParameters();
for (int i = 0; i < columns.length; i++) {
Column col = columns[i];
Value v = row.getValue(col.getColumnId());
Parameter p = k.get(i);
p.setValue(v);
}
for (int i = 0; i < keys.length; i++) {
Column col = keys[i];
Value v = row.getValue(col.getColumnId());
if (v == null) {
throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getSQL());
}
Parameter p = k.get(columns.length + i);
p.setValue(v);
}
return update.update();
}
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("REPLACE INTO ");
buff.append(table.getSQL()).append('(');
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL());
}
buff.append(')');
buff.append('\n');
if (!list.isEmpty()) {
buff.append("VALUES ");
int row = 0;
for (Expression[] expr : list) {
if (row++ > 0) {
buff.append(", ");
}
buff.append('(');
buff.resetCount();
for (Expression e : expr) {
buff.appendExceptFirst(", ");
if (e == null) {
buff.append("DEFAULT");
} else {
buff.append(e.getSQL());
}
}
buff.append(')');
}
} else {
buff.append(query.getPlanSQL());
}
return buff.toString();
}
@Override
public void prepare() {
if (columns == null) {
if (!list.isEmpty() && list.get(0).length == 0) {
// special case where table is used as a sequence
columns = new Column[0];
} else {
columns = table.getColumns();
}
}
if (!list.isEmpty()) {
for (Expression[] expr : list) {
if (expr.length != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
for (int i = 0; i < expr.length; i++) {
Expression e = expr[i];
if (e != null) {
expr[i] = e.optimize(session);
}
}
}
} else {
query.prepare();
if (query.getColumnCount() != columns.length) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
}
if (keys == null) {
Index idx = table.getPrimaryKey();
if (idx == null) {
throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, "PRIMARY KEY");
}
keys = idx.getColumns();
}
// if there is no valid primary key, the statement degenerates to an
// INSERT
for (Column key : keys) {
boolean found = false;
for (Column column : columns) {
if (column.getColumnId() == key.getColumnId()) {
found = true;
break;
}
}
if (!found) {
return;
}
}
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(table.getSQL()).append(" SET ");
for (Column c : columns) {
buff.appendExceptFirst(", ");
buff.append(c.getSQL()).append("=?");
}
buff.append(" WHERE ");
buff.resetCount();
for (Column c : keys) {
buff.appendExceptFirst(" AND ");
buff.append(c.getSQL()).append("=?");
}
String sql = buff.toString();
update = session.prepare(sql);
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.REPLACE;
}
@Override
public boolean isCacheable() {
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/RunScriptCommand.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.command.dml;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.util.ScriptReader;
/**
* This class represents the statement
* RUNSCRIPT
*/
public class RunScriptCommand extends ScriptBase {
/**
* The byte order mark.
* 0xfeff because this is the Unicode char
* represented by the UTF-8 byte order mark (EF BB BF).
*/
private static final char UTF8_BOM = '\uFEFF';
private Charset charset = StandardCharsets.UTF_8;
public RunScriptCommand(Session session) {
super(session);
}
@Override
public int update() {
session.getUser().checkAdmin();
int count = 0;
try {
openInput();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset));
// if necessary, strip the BOM from the front of the file
reader.mark(1);
if (reader.read() != UTF8_BOM) {
reader.reset();
}
ScriptReader r = new ScriptReader(reader);
while (true) {
String sql = r.readStatement();
if (sql == null) {
break;
}
execute(sql);
count++;
if ((count & 127) == 0) {
checkCanceled();
}
}
r.close();
} catch (IOException e) {
throw DbException.convertIOException(e, null);
} finally {
closeIO();
}
return count;
}
private void execute(String sql) {
try {
Prepared command = session.prepare(sql);
if (command.isQuery()) {
command.query(0);
} else {
command.update();
}
if (session.getAutoCommit()) {
session.commit(false);
}
} catch (DbException e) {
throw e.addSQL(sql);
}
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.RUNSCRIPT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/ScriptBase.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.command.dml;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.h2.api.ErrorCode;
import org.h2.api.JavaObjectSerializer;
import org.h2.command.Prepared;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.expression.Expression;
import org.h2.message.DbException;
import org.h2.security.SHA256;
import org.h2.store.DataHandler;
import org.h2.store.FileStore;
import org.h2.store.FileStoreInputStream;
import org.h2.store.FileStoreOutputStream;
import org.h2.store.LobStorageBackend;
import org.h2.store.fs.FileUtils;
import org.h2.tools.CompressTool;
import org.h2.util.IOUtils;
import org.h2.util.SmallLRUCache;
import org.h2.util.TempFileDeleter;
import org.h2.value.CompareMode;
/**
* This class is the base for RunScriptCommand and ScriptCommand.
*/
abstract class ScriptBase extends Prepared implements DataHandler {
/**
* The default name of the script file if .zip compression is used.
*/
private static final String SCRIPT_SQL = "script.sql";
/**
* The output stream.
*/
protected OutputStream out;
/**
* The input stream.
*/
protected InputStream in;
/**
* The file name (if set).
*/
private Expression fileNameExpr;
private Expression password;
private String fileName;
private String cipher;
private FileStore store;
private String compressionAlgorithm;
ScriptBase(Session session) {
super(session);
}
public void setCipher(String c) {
cipher = c;
}
private boolean isEncrypted() {
return cipher != null;
}
public void setPassword(Expression password) {
this.password = password;
}
public void setFileNameExpr(Expression file) {
this.fileNameExpr = file;
}
protected String getFileName() {
if (fileNameExpr != null && fileName == null) {
fileName = fileNameExpr.optimize(session).getValue(session).getString();
if (fileName == null || fileName.trim().length() == 0) {
fileName = "script.sql";
}
fileName = SysProperties.getScriptDirectory() + fileName;
}
return fileName;
}
@Override
public boolean isTransactional() {
return false;
}
/**
* Delete the target file.
*/
void deleteStore() {
String file = getFileName();
if (file != null) {
FileUtils.delete(file);
}
}
private void initStore() {
Database db = session.getDatabase();
byte[] key = null;
if (cipher != null && password != null) {
char[] pass = password.optimize(session).
getValue(session).getString().toCharArray();
key = SHA256.getKeyPasswordHash("script", pass);
}
String file = getFileName();
store = FileStore.open(db, file, "rw", cipher, key);
store.setCheckedWriting(false);
store.init();
}
/**
* Open the output stream.
*/
void openOutput() {
String file = getFileName();
if (file == null) {
return;
}
if (isEncrypted()) {
initStore();
out = new FileStoreOutputStream(store, this, compressionAlgorithm);
// always use a big buffer, otherwise end-of-block is written a lot
out = new BufferedOutputStream(out, Constants.IO_BUFFER_SIZE_COMPRESS);
} else {
OutputStream o;
try {
o = FileUtils.newOutputStream(file, false);
} catch (IOException e) {
throw DbException.convertIOException(e, null);
}
out = new BufferedOutputStream(o, Constants.IO_BUFFER_SIZE);
out = CompressTool.wrapOutputStream(out, compressionAlgorithm, SCRIPT_SQL);
}
}
/**
* Open the input stream.
*/
void openInput() {
String file = getFileName();
if (file == null) {
return;
}
if (isEncrypted()) {
initStore();
in = new FileStoreInputStream(store, this, compressionAlgorithm != null, false);
} else {
InputStream inStream;
try {
inStream = FileUtils.newInputStream(file);
} catch (IOException e) {
throw DbException.convertIOException(e, file);
}
in = new BufferedInputStream(inStream, Constants.IO_BUFFER_SIZE);
in = CompressTool.wrapInputStream(in, compressionAlgorithm, SCRIPT_SQL);
if (in == null) {
throw DbException.get(ErrorCode.FILE_NOT_FOUND_1, SCRIPT_SQL + " in " + file);
}
}
}
/**
* Close input and output streams.
*/
void closeIO() {
IOUtils.closeSilently(out);
out = null;
IOUtils.closeSilently(in);
in = null;
if (store != null) {
store.closeSilently();
store = null;
}
}
@Override
public boolean needRecompile() {
return false;
}
@Override
public String getDatabasePath() {
return null;
}
@Override
public FileStore openFile(String name, String mode, boolean mustExist) {
return null;
}
@Override
public void checkPowerOff() {
session.getDatabase().checkPowerOff();
}
@Override
public void checkWritingAllowed() {
session.getDatabase().checkWritingAllowed();
}
@Override
public int getMaxLengthInplaceLob() {
return session.getDatabase().getMaxLengthInplaceLob();
}
@Override
public TempFileDeleter getTempFileDeleter() {
return session.getDatabase().getTempFileDeleter();
}
@Override
public String getLobCompressionAlgorithm(int type) {
return session.getDatabase().getLobCompressionAlgorithm(type);
}
public void setCompressionAlgorithm(String algorithm) {
this.compressionAlgorithm = algorithm;
}
@Override
public Object getLobSyncObject() {
return this;
}
@Override
public SmallLRUCache<String, String[]> getLobFileListCache() {
return null;
}
@Override
public LobStorageBackend getLobStorage() {
return null;
}
@Override
public int readLob(long lobId, byte[] hmac, long offset, byte[] buff,
int off, int length) {
throw DbException.throwInternalError();
}
@Override
public JavaObjectSerializer getJavaObjectSerializer() {
return session.getDataHandler().getJavaObjectSerializer();
}
@Override
public CompareMode getCompareMode() {
return session.getDataHandler().getCompareMode();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/ScriptCommand.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.command.dml;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Parser;
import org.h2.constraint.Constraint;
import org.h2.engine.Comment;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.DbObject;
import org.h2.engine.Right;
import org.h2.engine.Role;
import org.h2.engine.Session;
import org.h2.engine.Setting;
import org.h2.engine.SysProperties;
import org.h2.engine.User;
import org.h2.engine.UserAggregate;
import org.h2.engine.UserDataType;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.message.DbException;
import org.h2.result.LocalResult;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.schema.Constant;
import org.h2.schema.Schema;
import org.h2.schema.SchemaObject;
import org.h2.schema.Sequence;
import org.h2.schema.TriggerObject;
import org.h2.table.Column;
import org.h2.table.PlanItem;
import org.h2.table.Table;
import org.h2.table.TableType;
import org.h2.util.IOUtils;
import org.h2.util.MathUtils;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.util.Utils;
import org.h2.value.Value;
import org.h2.value.ValueString;
/**
* This class represents the statement
* SCRIPT
*/
public class ScriptCommand extends ScriptBase {
private Charset charset = StandardCharsets.UTF_8;
private Set<String> schemaNames;
private Collection<Table> tables;
private boolean passwords;
// true if we're generating the INSERT..VALUES statements for row values
private boolean data;
private boolean settings;
// true if we're generating the DROP statements
private boolean drop;
private boolean simple;
private LocalResult result;
private String lineSeparatorString;
private byte[] lineSeparator;
private byte[] buffer;
private boolean tempLobTableCreated;
private int nextLobId;
private int lobBlockSize = Constants.IO_BUFFER_SIZE;
public ScriptCommand(Session session) {
super(session);
}
@Override
public boolean isQuery() {
return true;
}
// TODO lock all tables for 'script' command
public void setSchemaNames(Set<String> schemaNames) {
this.schemaNames = schemaNames;
}
public void setTables(Collection<Table> tables) {
this.tables = tables;
}
public void setData(boolean data) {
this.data = data;
}
public void setPasswords(boolean passwords) {
this.passwords = passwords;
}
public void setSettings(boolean settings) {
this.settings = settings;
}
public void setLobBlockSize(long blockSize) {
this.lobBlockSize = MathUtils.convertLongToInt(blockSize);
}
public void setDrop(boolean drop) {
this.drop = drop;
}
@Override
public ResultInterface queryMeta() {
LocalResult r = createResult();
r.done();
return r;
}
private LocalResult createResult() {
Expression[] expressions = { new ExpressionColumn(
session.getDatabase(), new Column("SCRIPT", Value.STRING)) };
return new LocalResult(session, expressions, 1);
}
@Override
public ResultInterface query(int maxrows) {
session.getUser().checkAdmin();
reset();
Database db = session.getDatabase();
if (schemaNames != null) {
for (String schemaName : schemaNames) {
Schema schema = db.findSchema(schemaName);
if (schema == null) {
throw DbException.get(ErrorCode.SCHEMA_NOT_FOUND_1,
schemaName);
}
}
}
try {
result = createResult();
deleteStore();
openOutput();
if (out != null) {
buffer = new byte[Constants.IO_BUFFER_SIZE];
}
if (settings) {
for (Setting setting : db.getAllSettings()) {
if (setting.getName().equals(SetTypes.getTypeName(
SetTypes.CREATE_BUILD))) {
// don't add CREATE_BUILD to the script
// (it is only set when creating the database)
continue;
}
add(setting.getCreateSQL(), false);
}
}
if (out != null) {
add("", true);
}
for (User user : db.getAllUsers()) {
add(user.getCreateSQL(passwords), false);
}
for (Role role : db.getAllRoles()) {
add(role.getCreateSQL(true), false);
}
for (Schema schema : db.getAllSchemas()) {
if (excludeSchema(schema)) {
continue;
}
add(schema.getCreateSQL(), false);
}
for (UserDataType datatype : db.getAllUserDataTypes()) {
if (drop) {
add(datatype.getDropSQL(), false);
}
add(datatype.getCreateSQL(), false);
}
for (SchemaObject obj : db.getAllSchemaObjects(
DbObject.CONSTANT)) {
if (excludeSchema(obj.getSchema())) {
continue;
}
Constant constant = (Constant) obj;
add(constant.getCreateSQL(), false);
}
final ArrayList<Table> tables = db.getAllTablesAndViews(false);
// sort by id, so that views are after tables and views on views
// after the base views
Collections.sort(tables, new Comparator<Table>() {
@Override
public int compare(Table t1, Table t2) {
return t1.getId() - t2.getId();
}
});
// Generate the DROP XXX ... IF EXISTS
for (Table table : tables) {
if (excludeSchema(table.getSchema())) {
continue;
}
if (excludeTable(table)) {
continue;
}
if (table.isHidden()) {
continue;
}
table.lock(session, false, false);
String sql = table.getCreateSQL();
if (sql == null) {
// null for metadata tables
continue;
}
if (drop) {
add(table.getDropSQL(), false);
}
}
for (SchemaObject obj : db.getAllSchemaObjects(
DbObject.FUNCTION_ALIAS)) {
if (excludeSchema(obj.getSchema())) {
continue;
}
if (drop) {
add(obj.getDropSQL(), false);
}
add(obj.getCreateSQL(), false);
}
for (UserAggregate agg : db.getAllAggregates()) {
if (drop) {
add(agg.getDropSQL(), false);
}
add(agg.getCreateSQL(), false);
}
for (SchemaObject obj : db.getAllSchemaObjects(
DbObject.SEQUENCE)) {
if (excludeSchema(obj.getSchema())) {
continue;
}
Sequence sequence = (Sequence) obj;
if (drop) {
add(sequence.getDropSQL(), false);
}
add(sequence.getCreateSQL(), false);
}
// Generate CREATE TABLE and INSERT...VALUES
int count = 0;
for (Table table : tables) {
if (excludeSchema(table.getSchema())) {
continue;
}
if (excludeTable(table)) {
continue;
}
if (table.isHidden()) {
continue;
}
table.lock(session, false, false);
String createTableSql = table.getCreateSQL();
if (createTableSql == null) {
// null for metadata tables
continue;
}
final TableType tableType = table.getTableType();
add(createTableSql, false);
final ArrayList<Constraint> constraints = table.getConstraints();
if (constraints != null) {
for (Constraint constraint : constraints) {
if (Constraint.Type.PRIMARY_KEY == constraint.getConstraintType()) {
add(constraint.getCreateSQLWithoutIndexes(), false);
}
}
}
if (TableType.TABLE == tableType) {
if (table.canGetRowCount()) {
String rowcount = "-- " +
table.getRowCountApproximation() +
" +/- SELECT COUNT(*) FROM " + table.getSQL();
add(rowcount, false);
}
if (data) {
count = generateInsertValues(count, table);
}
}
final ArrayList<Index> indexes = table.getIndexes();
for (int j = 0; indexes != null && j < indexes.size(); j++) {
Index index = indexes.get(j);
if (!index.getIndexType().getBelongsToConstraint()) {
add(index.getCreateSQL(), false);
}
}
}
if (tempLobTableCreated) {
add("DROP TABLE IF EXISTS SYSTEM_LOB_STREAM", true);
add("CALL SYSTEM_COMBINE_BLOB(-1)", true);
add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_CLOB", true);
add("DROP ALIAS IF EXISTS SYSTEM_COMBINE_BLOB", true);
tempLobTableCreated = false;
}
// Generate CREATE CONSTRAINT ...
final ArrayList<SchemaObject> constraints = db.getAllSchemaObjects(
DbObject.CONSTRAINT);
Collections.sort(constraints, new Comparator<SchemaObject>() {
@Override
public int compare(SchemaObject c1, SchemaObject c2) {
return ((Constraint) c1).compareTo((Constraint) c2);
}
});
for (SchemaObject obj : constraints) {
if (excludeSchema(obj.getSchema())) {
continue;
}
Constraint constraint = (Constraint) obj;
if (excludeTable(constraint.getTable())) {
continue;
}
if (constraint.getTable().isHidden()) {
continue;
}
if (Constraint.Type.PRIMARY_KEY != constraint.getConstraintType()) {
add(constraint.getCreateSQLWithoutIndexes(), false);
}
}
// Generate CREATE TRIGGER ...
for (SchemaObject obj : db.getAllSchemaObjects(DbObject.TRIGGER)) {
if (excludeSchema(obj.getSchema())) {
continue;
}
TriggerObject trigger = (TriggerObject) obj;
if (excludeTable(trigger.getTable())) {
continue;
}
add(trigger.getCreateSQL(), false);
}
// Generate GRANT ...
for (Right right : db.getAllRights()) {
DbObject object = right.getGrantedObject();
if (object != null) {
if (object instanceof Schema) {
if (excludeSchema((Schema) object)) {
continue;
}
} else if (object instanceof Table) {
Table table = (Table) object;
if (excludeSchema(table.getSchema())) {
continue;
}
if (excludeTable(table)) {
continue;
}
}
}
add(right.getCreateSQL(), false);
}
// Generate COMMENT ON ...
for (Comment comment : db.getAllComments()) {
add(comment.getCreateSQL(), false);
}
if (out != null) {
out.close();
}
} catch (IOException e) {
throw DbException.convertIOException(e, getFileName());
} finally {
closeIO();
}
result.done();
LocalResult r = result;
reset();
return r;
}
private int generateInsertValues(int count, Table table) throws IOException {
PlanItem plan = table.getBestPlanItem(session, null, null, -1, null, null);
Index index = plan.getIndex();
Cursor cursor = index.find(session, null, null);
Column[] columns = table.getColumns();
StatementBuilder buff = new StatementBuilder("INSERT INTO ");
buff.append(table.getSQL()).append('(');
for (Column col : columns) {
buff.appendExceptFirst(", ");
buff.append(Parser.quoteIdentifier(col.getName()));
}
buff.append(") VALUES");
if (!simple) {
buff.append('\n');
}
buff.append('(');
String ins = buff.toString();
buff = null;
while (cursor.next()) {
Row row = cursor.get();
if (buff == null) {
buff = new StatementBuilder(ins);
} else {
buff.append(",\n(");
}
for (int j = 0; j < row.getColumnCount(); j++) {
if (j > 0) {
buff.append(", ");
}
Value v = row.getValue(j);
if (v.getPrecision() > lobBlockSize) {
int id;
if (v.getType() == Value.CLOB) {
id = writeLobStream(v);
buff.append("SYSTEM_COMBINE_CLOB(").append(id).append(')');
} else if (v.getType() == Value.BLOB) {
id = writeLobStream(v);
buff.append("SYSTEM_COMBINE_BLOB(").append(id).append(')');
} else {
buff.append(v.getSQL());
}
} else {
buff.append(v.getSQL());
}
}
buff.append(')');
count++;
if ((count & 127) == 0) {
checkCanceled();
}
if (simple || buff.length() > Constants.IO_BUFFER_SIZE) {
add(buff.toString(), true);
buff = null;
}
}
if (buff != null) {
add(buff.toString(), true);
}
return count;
}
private int writeLobStream(Value v) throws IOException {
if (!tempLobTableCreated) {
add("CREATE TABLE IF NOT EXISTS SYSTEM_LOB_STREAM" +
"(ID INT NOT NULL, PART INT NOT NULL, " +
"CDATA VARCHAR, BDATA BINARY)",
true);
add("CREATE PRIMARY KEY SYSTEM_LOB_STREAM_PRIMARY_KEY " +
"ON SYSTEM_LOB_STREAM(ID, PART)", true);
add("CREATE ALIAS IF NOT EXISTS " + "SYSTEM_COMBINE_CLOB FOR \"" +
this.getClass().getName() + ".combineClob\"", true);
add("CREATE ALIAS IF NOT EXISTS " + "SYSTEM_COMBINE_BLOB FOR \"" +
this.getClass().getName() + ".combineBlob\"", true);
tempLobTableCreated = true;
}
int id = nextLobId++;
switch (v.getType()) {
case Value.BLOB: {
byte[] bytes = new byte[lobBlockSize];
try (InputStream input = v.getInputStream()) {
for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(").append(id)
.append(", ").append(i).append(", NULL, '");
int len = IOUtils.readFully(input, bytes, lobBlockSize);
if (len <= 0) {
break;
}
buff.append(StringUtils.convertBytesToHex(bytes, len)).append("')");
String sql = buff.toString();
add(sql, true);
}
}
break;
}
case Value.CLOB: {
char[] chars = new char[lobBlockSize];
try (Reader reader = v.getReader()) {
for (int i = 0;; i++) {
StringBuilder buff = new StringBuilder(lobBlockSize * 2);
buff.append("INSERT INTO SYSTEM_LOB_STREAM VALUES(").append(id).append(", ").append(i)
.append(", ");
int len = IOUtils.readFully(reader, chars, lobBlockSize);
if (len == 0) {
break;
}
buff.append(StringUtils.quoteStringSQL(new String(chars, 0, len))).
append(", NULL)");
String sql = buff.toString();
add(sql, true);
}
}
break;
}
default:
DbException.throwInternalError("type:" + v.getType());
}
return id;
}
/**
* Combine a BLOB.
* This method is called from the script.
* When calling with id -1, the file is deleted.
*
* @param conn a connection
* @param id the lob id
* @return a stream for the combined data
*/
public static InputStream combineBlob(Connection conn, int id)
throws SQLException {
if (id < 0) {
return null;
}
final ResultSet rs = getLobStream(conn, "BDATA", id);
return new InputStream() {
private InputStream current;
private boolean closed;
@Override
public int read() throws IOException {
while (true) {
try {
if (current == null) {
if (closed) {
return -1;
}
if (!rs.next()) {
close();
return -1;
}
current = rs.getBinaryStream(1);
current = new BufferedInputStream(current);
}
int x = current.read();
if (x >= 0) {
return x;
}
current = null;
} catch (SQLException e) {
throw DbException.convertToIOException(e);
}
}
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
rs.close();
} catch (SQLException e) {
throw DbException.convertToIOException(e);
}
}
};
}
/**
* Combine a CLOB.
* This method is called from the script.
*
* @param conn a connection
* @param id the lob id
* @return a reader for the combined data
*/
public static Reader combineClob(Connection conn, int id) throws SQLException {
if (id < 0) {
return null;
}
final ResultSet rs = getLobStream(conn, "CDATA", id);
return new Reader() {
private Reader current;
private boolean closed;
@Override
public int read() throws IOException {
while (true) {
try {
if (current == null) {
if (closed) {
return -1;
}
if (!rs.next()) {
close();
return -1;
}
current = rs.getCharacterStream(1);
current = new BufferedReader(current);
}
int x = current.read();
if (x >= 0) {
return x;
}
current = null;
} catch (SQLException e) {
throw DbException.convertToIOException(e);
}
}
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
rs.close();
} catch (SQLException e) {
throw DbException.convertToIOException(e);
}
}
@Override
public int read(char[] buffer, int off, int len) throws IOException {
if (len == 0) {
return 0;
}
int c = read();
if (c == -1) {
return -1;
}
buffer[off] = (char) c;
int i = 1;
for (; i < len; i++) {
c = read();
if (c == -1) {
break;
}
buffer[off + i] = (char) c;
}
return i;
}
};
}
private static ResultSet getLobStream(Connection conn, String column, int id)
throws SQLException {
PreparedStatement prep = conn.prepareStatement("SELECT " + column +
" FROM SYSTEM_LOB_STREAM WHERE ID=? ORDER BY PART");
prep.setInt(1, id);
return prep.executeQuery();
}
private void reset() {
result = null;
buffer = null;
lineSeparatorString = SysProperties.LINE_SEPARATOR;
lineSeparator = lineSeparatorString.getBytes(charset);
}
private boolean excludeSchema(Schema schema) {
if (schemaNames != null && !schemaNames.contains(schema.getName())) {
return true;
}
if (tables != null) {
// if filtering on specific tables, only include those schemas
for (Table table : schema.getAllTablesAndViews()) {
if (tables.contains(table)) {
return false;
}
}
return true;
}
return false;
}
private boolean excludeTable(Table table) {
return tables != null && !tables.contains(table);
}
private void add(String s, boolean insert) throws IOException {
if (s == null) {
return;
}
if (lineSeparator.length > 1 || lineSeparator[0] != '\n') {
s = StringUtils.replaceAll(s, "\n", lineSeparatorString);
}
s += ";";
if (out != null) {
byte[] buff = s.getBytes(charset);
int len = MathUtils.roundUpInt(buff.length +
lineSeparator.length, Constants.FILE_BLOCK_SIZE);
buffer = Utils.copy(buff, buffer);
if (len > buffer.length) {
buffer = new byte[len];
}
System.arraycopy(buff, 0, buffer, 0, buff.length);
for (int i = buff.length; i < len - lineSeparator.length; i++) {
buffer[i] = ' ';
}
for (int j = 0, i = len - lineSeparator.length; i < len; i++, j++) {
buffer[i] = lineSeparator[j];
}
out.write(buffer, 0, len);
if (!insert) {
Value[] row = { ValueString.get(s) };
result.addRow(row);
}
} else {
Value[] row = { ValueString.get(s) };
result.addRow(row);
}
}
public void setSimple(boolean simple) {
this.simple = simple;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
@Override
public int getType() {
return CommandInterface.SCRIPT;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Select.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.command.dml;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.CommandInterface;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.expression.*;
import org.h2.index.Cursor;
import org.h2.index.Index;
import org.h2.index.IndexType;
import org.h2.message.DbException;
import org.h2.result.*;
import org.h2.table.*;
import org.h2.util.*;
import org.h2.value.Value;
import org.h2.value.ValueArray;
import org.h2.value.ValueNull;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
/**
* This class represents a simple SELECT statement.
*
* For each select statement,
* visibleColumnCount <= distinctColumnCount <= expressionCount.
* The expression list count could include ORDER BY and GROUP BY expressions
* that are not in the select list.
*
* The call sequence is init(), mapColumns() if it's a subquery, prepare().
*
* @author Thomas Mueller
* @author Joel Turkel (Group sorted query)
*/
public class Select extends Query {
/**
* The main (top) table filter.
*/
TableFilter topTableFilter;
private final ArrayList<TableFilter> filters = New.arrayList();
private final ArrayList<TableFilter> topFilters = New.arrayList();
/**
* The column list, including synthetic columns (columns not shown in the
* result).
*/
ArrayList<Expression> expressions;
private Expression[] expressionArray;
private Expression having;
private Expression condition;
/**
* The visible columns (the ones required in the result).
*/
int visibleColumnCount;
private int distinctColumnCount;
private ArrayList<SelectOrderBy> orderList;
private ArrayList<Expression> group;
/**
* The indexes of the group-by columns.
*/
int[] groupIndex;
/**
* Whether a column in the expression list is part of a group-by.
*/
boolean[] groupByExpression;
/**
* The current group-by values.
*/
HashMap<Expression, Object> currentGroup;
private int havingIndex;
private boolean isGroupQuery, isGroupSortedQuery;
private boolean isForUpdate, isForUpdateMvcc;
private double cost;
private boolean isQuickAggregateQuery, isDistinctQuery;
private boolean isPrepared, checkInit;
private boolean sortUsingIndex;
private SortOrder sort;
/**
* The id of the current group.
*/
int currentGroupRowId;
public Select(Session session) {
super(session);
}
@Override
public boolean isUnion() {
return false;
}
/**
* Add a table to the query.
*
* @param filter the table to add
* @param isTop if the table can be the first table in the query plan
*/
public void addTableFilter(TableFilter filter, boolean isTop) {
// Oracle doesn't check on duplicate aliases
// String alias = filter.getAlias();
// if (filterNames.contains(alias)) {
// throw Message.getSQLException(
// ErrorCode.DUPLICATE_TABLE_ALIAS, alias);
// }
// filterNames.add(alias);
filters.add(filter);
if (isTop) {
topFilters.add(filter);
}
}
public ArrayList<TableFilter> getTopFilters() {
return topFilters;
}
public void setExpressions(ArrayList<Expression> expressions) {
this.expressions = expressions;
}
/**
* Called if this query contains aggregate functions.
*/
public void setGroupQuery() {
isGroupQuery = true;
}
public void setGroupBy(ArrayList<Expression> group) {
this.group = group;
}
public ArrayList<Expression> getGroupBy() {
return group;
}
public HashMap<Expression, Object> getCurrentGroup() {
return currentGroup;
}
public int getCurrentGroupRowId() {
return currentGroupRowId;
}
@Override
public void setOrder(ArrayList<SelectOrderBy> order) {
orderList = order;
}
@Override
public boolean hasOrder() {
return orderList != null || sort != null;
}
/**
* Add a condition to the list of conditions.
*
* @param cond the condition to add
*/
public void addCondition(Expression cond) {
if (condition == null) {
condition = cond;
} else {
condition = new ConditionAndOr(ConditionAndOr.AND, cond, condition);
}
}
public Expression getCondition() {
return condition;
}
private LazyResult queryGroupSorted(int columnCount, ResultTarget result) {
LazyResultGroupSorted lazyResult = new LazyResultGroupSorted(expressionArray, columnCount);
if (result == null) {
return lazyResult;
}
while (lazyResult.next()) {
result.addRow(lazyResult.currentRow());
}
return null;
}
/**
* Create a row with the current values, for queries with group-sort.
*
* @param keyValues the key values
* @param columnCount the number of columns
* @return the row
*/
Value[] createGroupSortedRow(Value[] keyValues, int columnCount) {
Value[] row = new Value[columnCount];
for (int j = 0; groupIndex != null && j < groupIndex.length; j++) {
row[groupIndex[j]] = keyValues[j];
}
for (int j = 0; j < columnCount; j++) {
if (groupByExpression != null && groupByExpression[j]) {
continue;
}
Expression expr = expressions.get(j);
row[j] = expr.getValue(session);
}
if (isHavingNullOrFalse(row)) {
return null;
}
row = keepOnlyDistinct(row, columnCount);
return row;
}
private Value[] keepOnlyDistinct(Value[] row, int columnCount) {
if (columnCount == distinctColumnCount) {
return row;
}
// remove columns so that 'distinct' can filter duplicate rows
return Arrays.copyOf(row, distinctColumnCount);
}
private boolean isHavingNullOrFalse(Value[] row) {
return havingIndex >= 0 && !row[havingIndex].getBoolean();
}
private Index getGroupSortedIndex() {
if (groupIndex == null || groupByExpression == null) {
return null;
}
ArrayList<Index> indexes = topTableFilter.getTable().getIndexes();
if (indexes != null) {
for (Index index : indexes) {
if (index.getIndexType().isScan()) {
continue;
}
if (index.getIndexType().isHash()) {
// does not allow scanning entries
continue;
}
if (isGroupSortedIndex(topTableFilter, index)) {
return index;
}
}
}
return null;
}
private boolean isGroupSortedIndex(TableFilter tableFilter, Index index) {
// check that all the GROUP BY expressions are part of the index
Column[] indexColumns = index.getColumns();
// also check that the first columns in the index are grouped
boolean[] grouped = new boolean[indexColumns.length];
outerLoop:
for (int i = 0, size = expressions.size(); i < size; i++) {
if (!groupByExpression[i]) {
continue;
}
Expression expr = expressions.get(i).getNonAliasExpression();
if (!(expr instanceof ExpressionColumn)) {
return false;
}
ExpressionColumn exprCol = (ExpressionColumn) expr;
for (int j = 0; j < indexColumns.length; ++j) {
if (tableFilter == exprCol.getTableFilter()) {
if (indexColumns[j].equals(exprCol.getColumn())) {
grouped[j] = true;
continue outerLoop;
}
}
}
// We didn't find a matching index column
// for one group by expression
return false;
}
// check that the first columns in the index are grouped
// good: index(a, b, c); group by b, a
// bad: index(a, b, c); group by a, c
for (int i = 1; i < grouped.length; i++) {
if (!grouped[i - 1] && grouped[i]) {
return false;
}
}
return true;
}
private int getGroupByExpressionCount() {
if (groupByExpression == null) {
return 0;
}
int count = 0;
for (boolean b : groupByExpression) {
if (b) {
++count;
}
}
return count;
}
boolean isConditionMet() {
return condition == null || condition.getBooleanValue(session);
}
private void queryGroup(int columnCount, LocalResult result) {
ValueHashMap<HashMap<Expression, Object>> groups =
ValueHashMap.newInstance();
int rowNumber = 0;
setCurrentRowNumber(0);
currentGroup = null;
ValueArray defaultGroup = ValueArray.get(new Value[0]);
int sampleSize = getSampleSizeValue(session);
while (topTableFilter.next()) {
setCurrentRowNumber(rowNumber + 1);
if (isConditionMet()) {
Value key;
rowNumber++;
if (groupIndex == null) {
key = defaultGroup;
} else {
Value[] keyValues = new Value[groupIndex.length];
// update group
for (int i = 0; i < groupIndex.length; i++) {
int idx = groupIndex[i];
Expression expr = expressions.get(idx);
keyValues[i] = expr.getValue(session);
}
key = ValueArray.get(keyValues);
}
HashMap<Expression, Object> values = groups.get(key);
if (values == null) {
values = new HashMap<>();
groups.put(key, values);
}
currentGroup = values;
currentGroupRowId++;
for (int i = 0; i < columnCount; i++) {
if (groupByExpression == null || !groupByExpression[i]) {
Expression expr = expressions.get(i);
expr.updateAggregate(session);
}
}
if (sampleSize > 0 && rowNumber >= sampleSize) {
break;
}
}
}
if (groupIndex == null && groups.size() == 0) {
groups.put(defaultGroup, new HashMap<Expression, Object>());
}
ArrayList<Value> keys = groups.keys();
for (Value v : keys) {
ValueArray key = (ValueArray) v;
currentGroup = groups.get(key);
Value[] keyValues = key.getList();
Value[] row = new Value[columnCount];
for (int j = 0; groupIndex != null && j < groupIndex.length; j++) {
row[groupIndex[j]] = keyValues[j];
}
for (int j = 0; j < columnCount; j++) {
if (groupByExpression != null && groupByExpression[j]) {
continue;
}
Expression expr = expressions.get(j);
row[j] = expr.getValue(session);
}
if (isHavingNullOrFalse(row)) {
continue;
}
row = keepOnlyDistinct(row, columnCount);
result.addRow(row);
}
}
/**
* Get the index that matches the ORDER BY list, if one exists. This is to
* avoid running a separate ORDER BY if an index can be used. This is
* specially important for large result sets, if only the first few rows are
* important (LIMIT is used)
*
* @return the index if one is found
*/
private Index getSortIndex() {
if (sort == null) {
return null;
}
ArrayList<Column> sortColumns = New.arrayList();
for (int idx : sort.getQueryColumnIndexes()) {
if (idx < 0 || idx >= expressions.size()) {
throw DbException.getInvalidValueException("ORDER BY", idx + 1);
}
Expression expr = expressions.get(idx);
expr = expr.getNonAliasExpression();
if (expr.isConstant()) {
continue;
}
if (!(expr instanceof ExpressionColumn)) {
return null;
}
ExpressionColumn exprCol = (ExpressionColumn) expr;
if (exprCol.getTableFilter() != topTableFilter) {
return null;
}
sortColumns.add(exprCol.getColumn());
}
Column[] sortCols = sortColumns.toArray(new Column[0]);
if (sortCols.length == 0) {
// sort just on constants - can use scan index
return topTableFilter.getTable().getScanIndex(session);
}
ArrayList<Index> list = topTableFilter.getTable().getIndexes();
if (list != null) {
int[] sortTypes = sort.getSortTypesWithNullPosition();
for (Index index : list) {
if (index.getCreateSQL() == null) {
// can't use the scan index
continue;
}
if (index.getIndexType().isHash()) {
continue;
}
IndexColumn[] indexCols = index.getIndexColumns();
if (indexCols.length < sortCols.length) {
continue;
}
boolean ok = true;
for (int j = 0; j < sortCols.length; j++) {
// the index and the sort order must start
// with the exact same columns
IndexColumn idxCol = indexCols[j];
Column sortCol = sortCols[j];
if (idxCol.column != sortCol) {
ok = false;
break;
}
if (SortOrder.addExplicitNullPosition(idxCol.sortType) != sortTypes[j]) {
ok = false;
break;
}
}
if (ok) {
return index;
}
}
}
if (sortCols.length == 1 && sortCols[0].getColumnId() == -1) {
// special case: order by _ROWID_
Index index = topTableFilter.getTable().getScanIndex(session);
if (index.isRowIdIndex()) {
return index;
}
}
return null;
}
private void queryDistinct(ResultTarget result, long limitRows) {
// limitRows must be long, otherwise we get an int overflow
// if limitRows is at or near Integer.MAX_VALUE
// limitRows is never 0 here
if (limitRows > 0 && offsetExpr != null) {
int offset = offsetExpr.getValue(session).getInt();
if (offset > 0) {
limitRows += offset;
}
}
int rowNumber = 0;
setCurrentRowNumber(0);
Index index = topTableFilter.getIndex();
SearchRow first = null;
int columnIndex = index.getColumns()[0].getColumnId();
int sampleSize = getSampleSizeValue(session);
while (true) {
setCurrentRowNumber(rowNumber + 1);
Cursor cursor = index.findNext(session, first, null);
if (!cursor.next()) {
break;
}
SearchRow found = cursor.getSearchRow();
Value value = found.getValue(columnIndex);
if (first == null) {
first = topTableFilter.getTable().getTemplateSimpleRow(true);
}
first.setValue(columnIndex, value);
Value[] row = { value };
result.addRow(row);
rowNumber++;
if ((sort == null || sortUsingIndex) && limitRows > 0 &&
rowNumber >= limitRows) {
break;
}
if (sampleSize > 0 && rowNumber >= sampleSize) {
break;
}
}
}
private LazyResult queryFlat(int columnCount, ResultTarget result, long limitRows) {
// limitRows must be long, otherwise we get an int overflow
// if limitRows is at or near Integer.MAX_VALUE
// limitRows is never 0 here
if (limitRows > 0 && offsetExpr != null) {
int offset = offsetExpr.getValue(session).getInt();
if (offset > 0) {
limitRows += offset;
}
}
ArrayList<Row> forUpdateRows = null;
if (isForUpdateMvcc) {
forUpdateRows = New.arrayList();
}
int sampleSize = getSampleSizeValue(session);
LazyResultQueryFlat lazyResult = new LazyResultQueryFlat(expressionArray,
sampleSize, columnCount);
if (result == null) {
return lazyResult;
}
while (lazyResult.next()) {
if (isForUpdateMvcc) {
topTableFilter.lockRowAdd(forUpdateRows);
}
result.addRow(lazyResult.currentRow());
if ((sort == null || sortUsingIndex) && limitRows > 0 &&
result.getRowCount() >= limitRows) {
break;
}
}
if (isForUpdateMvcc) {
topTableFilter.lockRows(forUpdateRows);
}
return null;
}
private void queryQuick(int columnCount, ResultTarget result) {
Value[] row = new Value[columnCount];
for (int i = 0; i < columnCount; i++) {
Expression expr = expressions.get(i);
row[i] = expr.getValue(session);
}
result.addRow(row);
}
@Override
public ResultInterface queryMeta() {
LocalResult result = new LocalResult(session, expressionArray,
visibleColumnCount);
result.done();
return result;
}
@Override
protected ResultInterface queryWithoutCache(int maxRows, ResultTarget target) {
int limitRows = maxRows == 0 ? -1 : maxRows;
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
int l = v == ValueNull.INSTANCE ? -1 : v.getInt();
if (limitRows < 0) {
limitRows = l;
} else if (l >= 0) {
limitRows = Math.min(l, limitRows);
}
}
boolean lazy = session.isLazyQueryExecution() &&
target == null && !isForUpdate && !isQuickAggregateQuery &&
limitRows != 0 && offsetExpr == null && isReadOnly();
int columnCount = expressions.size();
LocalResult result = null;
if (!lazy && (target == null ||
!session.getDatabase().getSettings().optimizeInsertFromSelect)) {
result = createLocalResult(result);
}
if (sort != null && (!sortUsingIndex || distinct)) {
result = createLocalResult(result);
result.setSortOrder(sort);
}
if (distinct && !isDistinctQuery) {
result = createLocalResult(result);
result.setDistinct();
}
if (randomAccessResult) {
result = createLocalResult(result);
}
if (isGroupQuery && !isGroupSortedQuery) {
result = createLocalResult(result);
}
if (!lazy && (limitRows >= 0 || offsetExpr != null)) {
result = createLocalResult(result);
}
topTableFilter.startQuery(session);
topTableFilter.reset();
boolean exclusive = isForUpdate && !isForUpdateMvcc;
if (isForUpdateMvcc) {
if (isGroupQuery) {
throw DbException.getUnsupportedException(
"MVCC=TRUE && FOR UPDATE && GROUP");
} else if (distinct) {
throw DbException.getUnsupportedException(
"MVCC=TRUE && FOR UPDATE && DISTINCT");
} else if (isQuickAggregateQuery) {
throw DbException.getUnsupportedException(
"MVCC=TRUE && FOR UPDATE && AGGREGATE");
} else if (topTableFilter.getJoin() != null) {
throw DbException.getUnsupportedException(
"MVCC=TRUE && FOR UPDATE && JOIN");
}
}
topTableFilter.lock(session, exclusive, exclusive);
ResultTarget to = result != null ? result : target;
lazy &= to == null;
LazyResult lazyResult = null;
if (limitRows != 0) {
try {
if (isQuickAggregateQuery) {
queryQuick(columnCount, to);
} else if (isGroupQuery) {
if (isGroupSortedQuery) {
lazyResult = queryGroupSorted(columnCount, to);
} else {
queryGroup(columnCount, result);
}
} else if (isDistinctQuery) {
queryDistinct(to, limitRows);
} else {
lazyResult = queryFlat(columnCount, to, limitRows);
}
} finally {
if (!lazy) {
resetJoinBatchAfterQuery();
}
}
}
assert lazy == (lazyResult != null): lazy;
if (lazyResult != null) {
if (limitRows > 0) {
lazyResult.setLimit(limitRows);
}
return lazyResult;
}
if (offsetExpr != null) {
result.setOffset(offsetExpr.getValue(session).getInt());
}
if (limitRows >= 0) {
result.setLimit(limitRows);
}
if (result != null) {
result.done();
if (target != null) {
while (result.next()) {
target.addRow(result.currentRow());
}
result.close();
return null;
}
return result;
}
return null;
}
/**
* Reset the batch-join after the query result is closed.
*/
void resetJoinBatchAfterQuery() {
JoinBatch jb = getJoinBatch();
if (jb != null) {
jb.reset(false);
}
}
private LocalResult createLocalResult(LocalResult old) {
return old != null ? old : new LocalResult(session, expressionArray,
visibleColumnCount);
}
private void expandColumnList() {
Database db = session.getDatabase();
// the expressions may change within the loop
for (int i = 0; i < expressions.size(); i++) {
Expression expr = expressions.get(i);
if (!expr.isWildcard()) {
continue;
}
String schemaName = expr.getSchemaName();
String tableAlias = expr.getTableAlias();
if (tableAlias == null) {
expressions.remove(i);
for (TableFilter filter : filters) {
i = expandColumnList(filter, i);
}
i--;
} else {
TableFilter filter = null;
for (TableFilter f : filters) {
if (db.equalsIdentifiers(tableAlias, f.getTableAlias())) {
if (schemaName == null ||
db.equalsIdentifiers(schemaName,
f.getSchemaName())) {
filter = f;
break;
}
}
}
if (filter == null) {
throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1,
tableAlias);
}
expressions.remove(i);
i = expandColumnList(filter, i);
i--;
}
}
}
private int expandColumnList(TableFilter filter, int index) {
Table t = filter.getTable();
String alias = filter.getTableAlias();
Column[] columns = t.getColumns();
for (Column c : columns) {
if (!c.getVisible()) {
continue;
}
if (filter.isNaturalJoinColumn(c)) {
continue;
}
String name = filter.getDerivedColumnName(c);
ExpressionColumn ec = new ExpressionColumn(
session.getDatabase(), null, alias, name != null ? name : c.getName());
expressions.add(index++, ec);
}
return index;
}
@Override
public void init() {
if (SysProperties.CHECK && checkInit) {
DbException.throwInternalError();
}
expandColumnList();
visibleColumnCount = expressions.size();
ArrayList<String> expressionSQL;
if (orderList != null || group != null) {
expressionSQL = New.arrayList();
for (int i = 0; i < visibleColumnCount; i++) {
Expression expr = expressions.get(i);
expr = expr.getNonAliasExpression();
String sql = expr.getSQL();
expressionSQL.add(sql);
}
} else {
expressionSQL = null;
}
if (orderList != null) {
initOrder(session, expressions, expressionSQL, orderList,
visibleColumnCount, distinct, filters);
}
distinctColumnCount = expressions.size();
if (having != null) {
expressions.add(having);
havingIndex = expressions.size() - 1;
having = null;
} else {
havingIndex = -1;
}
Database db = session.getDatabase();
// first the select list (visible columns),
// then 'ORDER BY' expressions,
// then 'HAVING' expressions,
// and 'GROUP BY' expressions at the end
if (group != null) {
int size = group.size();
int expSize = expressionSQL.size();
groupIndex = new int[size];
for (int i = 0; i < size; i++) {
Expression expr = group.get(i);
String sql = expr.getSQL();
int found = -1;
for (int j = 0; j < expSize; j++) {
String s2 = expressionSQL.get(j);
if (db.equalsIdentifiers(s2, sql)) {
found = j;
break;
}
}
if (found < 0) {
// special case: GROUP BY a column alias
for (int j = 0; j < expSize; j++) {
Expression e = expressions.get(j);
if (db.equalsIdentifiers(sql, e.getAlias())) {
found = j;
break;
}
sql = expr.getAlias();
if (db.equalsIdentifiers(sql, e.getAlias())) {
found = j;
break;
}
}
}
if (found < 0) {
int index = expressions.size();
groupIndex[i] = index;
expressions.add(expr);
} else {
groupIndex[i] = found;
}
}
groupByExpression = new boolean[expressions.size()];
for (int gi : groupIndex) {
groupByExpression[gi] = true;
}
group = null;
}
// map columns in select list and condition
for (TableFilter f : filters) {
mapColumns(f, 0);
}
if (havingIndex >= 0) {
Expression expr = expressions.get(havingIndex);
SelectListColumnResolver res = new SelectListColumnResolver(this);
expr.mapColumns(res, 0);
}
checkInit = true;
}
@Override
public void prepare() {
if (isPrepared) {
// sometimes a subquery is prepared twice (CREATE TABLE AS SELECT)
return;
}
if (SysProperties.CHECK && !checkInit) {
DbException.throwInternalError("not initialized");
}
if (orderList != null) {
sort = prepareOrder(orderList, expressions.size());
orderList = null;
}
ColumnNamer columnNamer = new ColumnNamer(session);
for (int i = 0; i < expressions.size(); i++) {
Expression e = expressions.get(i);
String proposedColumnName = e.getAlias();
String columnName = columnNamer.getColumnName(e, i, proposedColumnName);
// if the name changed, create an alias
if (!columnName.equals(proposedColumnName)) {
e = new Alias(e, columnName, true);
}
expressions.set(i, e.optimize(session));
}
if (condition != null) {
condition = condition.optimize(session);
for (TableFilter f : filters) {
// outer joins: must not add index conditions such as
// "c is null" - example:
// create table parent(p int primary key) as select 1;
// create table child(c int primary key, pc int);
// insert into child values(2, 1);
// select p, c from parent
// left outer join child on p = pc where c is null;
if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
condition.createIndexConditions(session, f);
}
}
}
if (isGroupQuery && groupIndex == null &&
havingIndex < 0 && filters.size() == 1) {
if (condition == null) {
Table t = filters.get(0).getTable();
ExpressionVisitor optimizable = ExpressionVisitor.
getOptimizableVisitor(t);
isQuickAggregateQuery = isEverything(optimizable);
}
}
cost = preparePlan(session.isParsingCreateView());
if (distinct && session.getDatabase().getSettings().optimizeDistinct &&
!isGroupQuery && filters.size() == 1 &&
expressions.size() == 1 && condition == null) {
Expression expr = expressions.get(0);
expr = expr.getNonAliasExpression();
if (expr instanceof ExpressionColumn) {
Column column = ((ExpressionColumn) expr).getColumn();
int selectivity = column.getSelectivity();
Index columnIndex = topTableFilter.getTable().
getIndexForColumn(column, false, true);
if (columnIndex != null &&
selectivity != Constants.SELECTIVITY_DEFAULT &&
selectivity < 20) {
// the first column must be ascending
boolean ascending = columnIndex.
getIndexColumns()[0].sortType == SortOrder.ASCENDING;
Index current = topTableFilter.getIndex();
// if another index is faster
if (columnIndex.canFindNext() && ascending &&
(current == null ||
current.getIndexType().isScan() ||
columnIndex == current)) {
IndexType type = columnIndex.getIndexType();
// hash indexes don't work, and unique single column
// indexes don't work
if (!type.isHash() && (!type.isUnique() ||
columnIndex.getColumns().length > 1)) {
topTableFilter.setIndex(columnIndex);
isDistinctQuery = true;
}
}
}
}
}
if (sort != null && !isQuickAggregateQuery && !isGroupQuery) {
Index index = getSortIndex();
Index current = topTableFilter.getIndex();
if (index != null && current != null) {
if (current.getIndexType().isScan() || current == index) {
topTableFilter.setIndex(index);
if (!topTableFilter.hasInComparisons()) {
// in(select ...) and in(1,2,3) may return the key in
// another order
sortUsingIndex = true;
}
} else if (index.getIndexColumns() != null
&& index.getIndexColumns().length >= current
.getIndexColumns().length) {
IndexColumn[] sortColumns = index.getIndexColumns();
IndexColumn[] currentColumns = current.getIndexColumns();
boolean swapIndex = false;
for (int i = 0; i < currentColumns.length; i++) {
if (sortColumns[i].column != currentColumns[i].column) {
swapIndex = false;
break;
}
if (sortColumns[i].sortType != currentColumns[i].sortType) {
swapIndex = true;
}
}
if (swapIndex) {
topTableFilter.setIndex(index);
sortUsingIndex = true;
}
}
}
}
if (!isQuickAggregateQuery && isGroupQuery &&
getGroupByExpressionCount() > 0) {
Index index = getGroupSortedIndex();
Index current = topTableFilter.getIndex();
if (index != null && current != null && (current.getIndexType().isScan() ||
current == index)) {
topTableFilter.setIndex(index);
isGroupSortedQuery = true;
}
}
expressionArray = expressions.toArray(new Expression[0]);
isPrepared = true;
}
@Override
public void prepareJoinBatch() {
ArrayList<TableFilter> list = New.arrayList();
TableFilter f = getTopTableFilter();
do {
if (f.getNestedJoin() != null) {
// we do not support batching with nested joins
return;
}
list.add(f);
f = f.getJoin();
} while (f != null);
TableFilter[] fs = list.toArray(new TableFilter[0]);
// prepare join batch
JoinBatch jb = null;
for (int i = fs.length - 1; i >= 0; i--) {
jb = fs[i].prepareJoinBatch(jb, fs, i);
}
}
public JoinBatch getJoinBatch() {
return getTopTableFilter().getJoinBatch();
}
@Override
public double getCost() {
return cost;
}
@Override
public HashSet<Table> getTables() {
HashSet<Table> set = new HashSet<>();
for (TableFilter filter : filters) {
set.add(filter.getTable());
}
return set;
}
@Override
public void fireBeforeSelectTriggers() {
for (TableFilter filter : filters) {
filter.getTable().fire(session, Trigger.SELECT, true);
}
}
private double preparePlan(boolean parse) {
TableFilter[] topArray = topFilters.toArray(new TableFilter[0]);
for (TableFilter t : topArray) {
t.setFullCondition(condition);
}
Optimizer optimizer = new Optimizer(topArray, condition, session);
optimizer.optimize(parse);
topTableFilter = optimizer.getTopFilter();
double planCost = optimizer.getCost();
setEvaluatableRecursive(topTableFilter);
if (!parse) {
topTableFilter.prepare();
}
return planCost;
}
private void setEvaluatableRecursive(TableFilter f) {
for (; f != null; f = f.getJoin()) {
f.setEvaluatable(f, true);
if (condition != null) {
condition.setEvaluatable(f, true);
}
TableFilter n = f.getNestedJoin();
if (n != null) {
setEvaluatableRecursive(n);
}
Expression on = f.getJoinCondition();
if (on != null) {
if (!on.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
// need to check that all added are bound to a table
on = on.optimize(session);
if (!f.isJoinOuter() && !f.isJoinOuterIndirect()) {
f.removeJoinCondition();
addCondition(on);
}
}
}
on = f.getFilterCondition();
if (on != null) {
if (!on.isEverything(ExpressionVisitor.EVALUATABLE_VISITOR)) {
f.removeFilterCondition();
addCondition(on);
}
}
// this is only important for subqueries, so they know
// the result columns are evaluatable
for (Expression e : expressions) {
e.setEvaluatable(f, true);
}
}
}
@Override
public String getPlanSQL() {
// can not use the field sqlStatement because the parameter
// indexes may be incorrect: ? may be in fact ?2 for a subquery
// but indexes may be set manually as well
Expression[] exprList = expressions.toArray(new Expression[0]);
StatementBuilder buff = new StatementBuilder();
for (TableFilter f : topFilters) {
Table t = f.getTable();
TableView tableView = t.isView() ? (TableView) t : null;
if (tableView != null && tableView.isRecursive() && tableView.isTableExpression()) {
if (tableView.isPersistent()) {
// skip the generation of plan SQL for this already recursive persistent CTEs,
// since using a with statement will re-create the common table expression
// views.
} else {
buff.append("WITH RECURSIVE ").append(t.getName()).append('(');
buff.resetCount();
for (Column c : t.getColumns()) {
buff.appendExceptFirst(",");
buff.append(c.getName());
}
buff.append(") AS ").append(t.getSQL()).append("\n");
}
}
}
buff.resetCount();
buff.append("SELECT");
if (distinct) {
buff.append(" DISTINCT");
}
for (int i = 0; i < visibleColumnCount; i++) {
buff.appendExceptFirst(",");
buff.append('\n');
buff.append(StringUtils.indent(exprList[i].getSQL(), 4, false));
}
buff.append("\nFROM ");
TableFilter filter = topTableFilter;
if (filter != null) {
buff.resetCount();
int i = 0;
do {
buff.appendExceptFirst("\n");
buff.append(filter.getPlanSQL(i++ > 0));
filter = filter.getJoin();
} while (filter != null);
} else {
buff.resetCount();
int i = 0;
for (TableFilter f : topFilters) {
do {
buff.appendExceptFirst("\n");
buff.append(f.getPlanSQL(i++ > 0));
f = f.getJoin();
} while (f != null);
}
}
if (condition != null) {
buff.append("\nWHERE ").append(
StringUtils.unEnclose(condition.getSQL()));
}
if (groupIndex != null) {
buff.append("\nGROUP BY ");
buff.resetCount();
for (int gi : groupIndex) {
Expression g = exprList[gi];
g = g.getNonAliasExpression();
buff.appendExceptFirst(", ");
buff.append(StringUtils.unEnclose(g.getSQL()));
}
}
if (group != null) {
buff.append("\nGROUP BY ");
buff.resetCount();
for (Expression g : group) {
buff.appendExceptFirst(", ");
buff.append(StringUtils.unEnclose(g.getSQL()));
}
}
if (having != null) {
// could be set in addGlobalCondition
// in this case the query is not run directly, just getPlanSQL is
// called
Expression h = having;
buff.append("\nHAVING ").append(
StringUtils.unEnclose(h.getSQL()));
} else if (havingIndex >= 0) {
Expression h = exprList[havingIndex];
buff.append("\nHAVING ").append(
StringUtils.unEnclose(h.getSQL()));
}
if (sort != null) {
buff.append("\nORDER BY ").append(
sort.getSQL(exprList, visibleColumnCount));
}
if (orderList != null) {
buff.append("\nORDER BY ");
buff.resetCount();
for (SelectOrderBy o : orderList) {
buff.appendExceptFirst(", ");
buff.append(StringUtils.unEnclose(o.getSQL()));
}
}
if (limitExpr != null) {
buff.append("\nLIMIT ").append(
StringUtils.unEnclose(limitExpr.getSQL()));
if (offsetExpr != null) {
buff.append(" OFFSET ").append(
StringUtils.unEnclose(offsetExpr.getSQL()));
}
}
if (sampleSizeExpr != null) {
buff.append("\nSAMPLE_SIZE ").append(
StringUtils.unEnclose(sampleSizeExpr.getSQL()));
}
if (isForUpdate) {
buff.append("\nFOR UPDATE");
}
if (isQuickAggregateQuery) {
buff.append("\n/* direct lookup */");
}
if (isDistinctQuery) {
buff.append("\n/* distinct */");
}
if (sortUsingIndex) {
buff.append("\n/* index sorted */");
}
if (isGroupQuery) {
if (isGroupSortedQuery) {
buff.append("\n/* group sorted */");
}
}
// buff.append("\n/* cost: " + cost + " */");
return buff.toString();
}
public void setHaving(Expression having) {
this.having = having;
}
public Expression getHaving() {
return having;
}
@Override
public int getColumnCount() {
return visibleColumnCount;
}
public TableFilter getTopTableFilter() {
return topTableFilter;
}
@Override
public ArrayList<Expression> getExpressions() {
return expressions;
}
@Override
public void setForUpdate(boolean b) {
this.isForUpdate = b;
if (session.getDatabase().getSettings().selectForUpdateMvcc &&
session.getDatabase().isMultiVersion()) {
isForUpdateMvcc = b;
}
}
@Override
public void mapColumns(ColumnResolver resolver, int level) {
for (Expression e : expressions) {
e.mapColumns(resolver, level);
}
if (condition != null) {
condition.mapColumns(resolver, level);
}
}
@Override
public void setEvaluatable(TableFilter tableFilter, boolean b) {
for (Expression e : expressions) {
e.setEvaluatable(tableFilter, b);
}
if (condition != null) {
condition.setEvaluatable(tableFilter, b);
}
}
/**
* Check if this is an aggregate query with direct lookup, for example a
* query of the type SELECT COUNT(*) FROM TEST or
* SELECT MAX(ID) FROM TEST.
*
* @return true if a direct lookup is possible
*/
public boolean isQuickAggregateQuery() {
return isQuickAggregateQuery;
}
@Override
public void addGlobalCondition(Parameter param, int columnId,
int comparisonType) {
addParameter(param);
Expression comp;
Expression col = expressions.get(columnId);
col = col.getNonAliasExpression();
if (col.isEverything(ExpressionVisitor.QUERY_COMPARABLE_VISITOR)) {
comp = new Comparison(session, comparisonType, col, param);
} else {
// this condition will always evaluate to true, but need to
// add the parameter, so it can be set later
comp = new Comparison(session, Comparison.EQUAL_NULL_SAFE, param, param);
}
comp = comp.optimize(session);
boolean addToCondition = true;
if (isGroupQuery) {
addToCondition = false;
for (int i = 0; groupIndex != null && i < groupIndex.length; i++) {
if (groupIndex[i] == columnId) {
addToCondition = true;
break;
}
}
if (!addToCondition) {
if (havingIndex >= 0) {
having = expressions.get(havingIndex);
}
if (having == null) {
having = comp;
} else {
having = new ConditionAndOr(ConditionAndOr.AND, having, comp);
}
}
}
if (addToCondition) {
if (condition == null) {
condition = comp;
} else {
condition = new ConditionAndOr(ConditionAndOr.AND, condition, comp);
}
}
}
@Override
public void updateAggregate(Session s) {
for (Expression e : expressions) {
e.updateAggregate(s);
}
if (condition != null) {
condition.updateAggregate(s);
}
if (having != null) {
having.updateAggregate(s);
}
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
switch (visitor.getType()) {
case ExpressionVisitor.DETERMINISTIC: {
if (isForUpdate) {
return false;
}
for (TableFilter f : filters) {
if (!f.getTable().isDeterministic()) {
return false;
}
}
break;
}
case ExpressionVisitor.SET_MAX_DATA_MODIFICATION_ID: {
for (TableFilter f : filters) {
long m = f.getTable().getMaxDataModificationId();
visitor.addDataModificationId(m);
}
break;
}
case ExpressionVisitor.EVALUATABLE: {
if (!session.getDatabase().getSettings().optimizeEvaluatableSubqueries) {
return false;
}
break;
}
case ExpressionVisitor.GET_DEPENDENCIES: {
for (TableFilter f : filters) {
Table table = f.getTable();
visitor.addDependency(table);
table.addDependencies(visitor.getDependencies());
}
break;
}
default:
}
ExpressionVisitor v2 = visitor.incrementQueryLevel(1);
boolean result = true;
for (Expression e : expressions) {
if (!e.isEverything(v2)) {
result = false;
break;
}
}
if (result && condition != null && !condition.isEverything(v2)) {
result = false;
}
if (result && having != null && !having.isEverything(v2)) {
result = false;
}
return result;
}
@Override
public boolean isReadOnly() {
return isEverything(ExpressionVisitor.READONLY_VISITOR);
}
@Override
public boolean isCacheable() {
return !isForUpdate;
}
@Override
public int getType() {
return CommandInterface.SELECT;
}
@Override
public boolean allowGlobalConditions() {
return offsetExpr == null && (limitExpr == null || sort == null);
}
public SortOrder getSortOrder() {
return sort;
}
/**
* Lazy execution for this select.
*/
private abstract class LazyResultSelect extends LazyResult {
int rowNumber;
int columnCount;
LazyResultSelect(Expression[] expressions, int columnCount) {
super(expressions);
this.columnCount = columnCount;
setCurrentRowNumber(0);
}
@Override
public final int getVisibleColumnCount() {
return visibleColumnCount;
}
@Override
public void close() {
if (!isClosed()) {
super.close();
resetJoinBatchAfterQuery();
}
}
@Override
public void reset() {
super.reset();
resetJoinBatchAfterQuery();
topTableFilter.reset();
setCurrentRowNumber(0);
rowNumber = 0;
}
}
/**
* Lazy execution for a flat query.
*/
private final class LazyResultQueryFlat extends LazyResultSelect {
int sampleSize;
LazyResultQueryFlat(Expression[] expressions, int sampleSize, int columnCount) {
super(expressions, columnCount);
this.sampleSize = sampleSize;
}
@Override
protected Value[] fetchNextRow() {
while ((sampleSize <= 0 || rowNumber < sampleSize) &&
topTableFilter.next()) {
setCurrentRowNumber(rowNumber + 1);
if (isConditionMet()) {
++rowNumber;
Value[] row = new Value[columnCount];
for (int i = 0; i < columnCount; i++) {
Expression expr = expressions.get(i);
row[i] = expr.getValue(getSession());
}
return row;
}
}
return null;
}
}
/**
* Lazy execution for a group sorted query.
*/
private final class LazyResultGroupSorted extends LazyResultSelect {
Value[] previousKeyValues;
LazyResultGroupSorted(Expression[] expressions, int columnCount) {
super(expressions, columnCount);
currentGroup = null;
}
@Override
public void reset() {
super.reset();
currentGroup = null;
}
@Override
protected Value[] fetchNextRow() {
while (topTableFilter.next()) {
setCurrentRowNumber(rowNumber + 1);
if (isConditionMet()) {
rowNumber++;
Value[] keyValues = new Value[groupIndex.length];
// update group
for (int i = 0; i < groupIndex.length; i++) {
int idx = groupIndex[i];
Expression expr = expressions.get(idx);
keyValues[i] = expr.getValue(getSession());
}
Value[] row = null;
if (previousKeyValues == null) {
previousKeyValues = keyValues;
currentGroup = new HashMap<>();
} else if (!Arrays.equals(previousKeyValues, keyValues)) {
row = createGroupSortedRow(previousKeyValues, columnCount);
previousKeyValues = keyValues;
currentGroup = new HashMap<>();
}
currentGroupRowId++;
for (int i = 0; i < columnCount; i++) {
if (groupByExpression == null || !groupByExpression[i]) {
Expression expr = expressions.get(i);
expr.updateAggregate(getSession());
}
}
if (row != null) {
return row;
}
}
}
Value[] row = null;
if (previousKeyValues != null) {
row = createGroupSortedRow(previousKeyValues, columnCount);
previousKeyValues = null;
}
return row;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/SelectListColumnResolver.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.command.dml;
import java.util.ArrayList;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.table.Column;
import org.h2.table.ColumnResolver;
import org.h2.table.TableFilter;
import org.h2.util.ColumnNamer;
import org.h2.value.Value;
/**
* This class represents a column resolver for the column list of a SELECT
* statement. It is used to resolve select column aliases in the HAVING clause.
* Example:
* <p>
* SELECT X/3 AS A, COUNT(*) FROM SYSTEM_RANGE(1, 10) GROUP BY A HAVING A>2;
* </p>
*
* @author Thomas Mueller
*/
public class SelectListColumnResolver implements ColumnResolver {
private final Select select;
private final Expression[] expressions;
private final Column[] columns;
SelectListColumnResolver(Select select) {
this.select = select;
int columnCount = select.getColumnCount();
columns = new Column[columnCount];
expressions = new Expression[columnCount];
ArrayList<Expression> columnList = select.getExpressions();
ColumnNamer columnNamer= new ColumnNamer(select.getSession());
for (int i = 0; i < columnCount; i++) {
Expression expr = columnList.get(i);
String columnName = columnNamer.getColumnName(expr, i, expr.getAlias());
Column column = new Column(columnName, Value.NULL);
column.setTable(null, i);
columns[i] = column;
expressions[i] = expr.getNonAliasExpression();
}
}
@Override
public Column[] getColumns() {
return columns;
}
@Override
public String getDerivedColumnName(Column column) {
return null;
}
@Override
public String getSchemaName() {
return null;
}
@Override
public Select getSelect() {
return select;
}
@Override
public Column[] getSystemColumns() {
return null;
}
@Override
public Column getRowIdColumn() {
return null;
}
@Override
public String getTableAlias() {
return null;
}
@Override
public TableFilter getTableFilter() {
return null;
}
@Override
public Value getValue(Column column) {
return null;
}
@Override
public Expression optimize(ExpressionColumn expressionColumn, Column column) {
return expressions[column.getColumnId()];
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/SelectOrderBy.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.command.dml;
import org.h2.expression.Expression;
/**
* Describes one element of the ORDER BY clause of a query.
*/
public class SelectOrderBy {
/**
* The order by expression.
*/
public Expression expression;
/**
* The column index expression. This can be a column index number (1 meaning
* the first column of the select list) or a parameter (the parameter is a
* number representing the column index number).
*/
public Expression columnIndexExpr;
/**
* If the column should be sorted descending.
*/
public boolean descending;
/**
* If NULL should be appear first.
*/
public boolean nullsFirst;
/**
* If NULL should be appear at the end.
*/
public boolean nullsLast;
public String getSQL() {
StringBuilder buff = new StringBuilder();
if (expression != null) {
buff.append('=').append(expression.getSQL());
} else {
buff.append(columnIndexExpr.getSQL());
}
if (descending) {
buff.append(" DESC");
}
if (nullsFirst) {
buff.append(" NULLS FIRST");
} else if (nullsLast) {
buff.append(" NULLS LAST");
}
return buff.toString();
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/SelectUnion.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.command.dml;
import java.util.ArrayList;
import java.util.HashSet;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.engine.Session;
import org.h2.engine.SysProperties;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionColumn;
import org.h2.expression.ExpressionVisitor;
import org.h2.expression.Parameter;
import org.h2.expression.ValueExpression;
import org.h2.message.DbException;
import org.h2.result.LazyResult;
import org.h2.result.LocalResult;
import org.h2.result.ResultInterface;
import org.h2.result.ResultTarget;
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.ColumnNamer;
import org.h2.util.New;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueInt;
import org.h2.value.ValueNull;
/**
* Represents a union SELECT statement.
*/
public class SelectUnion extends Query {
public enum UnionType {
/**
* The type of a UNION statement.
*/
UNION,
/**
* The type of a UNION ALL statement.
*/
UNION_ALL,
/**
* The type of an EXCEPT statement.
*/
EXCEPT,
/**
* The type of an INTERSECT statement.
*/
INTERSECT
}
private UnionType unionType;
/**
* The left hand side of the union (the first subquery).
*/
final Query left;
/**
* The right hand side of the union (the second subquery).
*/
Query right;
private ArrayList<Expression> expressions;
private Expression[] expressionArray;
private ArrayList<SelectOrderBy> orderList;
private SortOrder sort;
private boolean isPrepared, checkInit;
private boolean isForUpdate;
public SelectUnion(Session session, Query query) {
super(session);
this.left = query;
}
@Override
public boolean isUnion() {
return true;
}
@Override
public void prepareJoinBatch() {
left.prepareJoinBatch();
right.prepareJoinBatch();
}
public void setUnionType(UnionType type) {
this.unionType = type;
}
public UnionType getUnionType() {
return unionType;
}
public void setRight(Query select) {
right = select;
}
public Query getLeft() {
return left;
}
public Query getRight() {
return right;
}
@Override
public void setSQL(String sql) {
this.sqlStatement = sql;
}
@Override
public void setOrder(ArrayList<SelectOrderBy> order) {
orderList = order;
}
@Override
public boolean hasOrder() {
return orderList != null || sort != null;
}
private Value[] convert(Value[] values, int columnCount) {
Value[] newValues;
if (columnCount == values.length) {
// re-use the array if possible
newValues = values;
} else {
// create a new array if needed,
// for the value hash set
newValues = new Value[columnCount];
}
for (int i = 0; i < columnCount; i++) {
Expression e = expressions.get(i);
newValues[i] = values[i].convertTo(e.getType());
}
return newValues;
}
@Override
public ResultInterface queryMeta() {
int columnCount = left.getColumnCount();
LocalResult result = new LocalResult(session, expressionArray, columnCount);
result.done();
return result;
}
public LocalResult getEmptyResult() {
int columnCount = left.getColumnCount();
return new LocalResult(session, expressionArray, columnCount);
}
@Override
protected ResultInterface queryWithoutCache(int maxRows, ResultTarget target) {
if (maxRows != 0) {
// maxRows is set (maxRows 0 means no limit)
int l;
if (limitExpr == null) {
l = -1;
} else {
Value v = limitExpr.getValue(session);
l = v == ValueNull.INSTANCE ? -1 : v.getInt();
}
if (l < 0) {
// for limitExpr, 0 means no rows, and -1 means no limit
l = maxRows;
} else {
l = Math.min(l, maxRows);
}
limitExpr = ValueExpression.get(ValueInt.get(l));
}
if (session.getDatabase().getSettings().optimizeInsertFromSelect) {
if (unionType == UnionType.UNION_ALL && target != null) {
if (sort == null && !distinct && maxRows == 0 &&
offsetExpr == null && limitExpr == null) {
left.query(0, target);
right.query(0, target);
return null;
}
}
}
int columnCount = left.getColumnCount();
if (session.isLazyQueryExecution() && unionType == UnionType.UNION_ALL && !distinct &&
sort == null && !randomAccessResult && !isForUpdate &&
offsetExpr == null && isReadOnly()) {
int limit = -1;
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
limit = v.getInt();
}
}
// limit 0 means no rows
if (limit != 0) {
LazyResultUnion lazyResult = new LazyResultUnion(expressionArray, columnCount);
if (limit > 0) {
lazyResult.setLimit(limit);
}
return lazyResult;
}
}
LocalResult result = new LocalResult(session, expressionArray, columnCount);
if (sort != null) {
result.setSortOrder(sort);
}
if (distinct) {
left.setDistinct(true);
right.setDistinct(true);
result.setDistinct();
}
if (randomAccessResult) {
result.setRandomAccess();
}
switch (unionType) {
case UNION:
case EXCEPT:
left.setDistinct(true);
right.setDistinct(true);
result.setDistinct();
break;
case UNION_ALL:
break;
case INTERSECT:
left.setDistinct(true);
right.setDistinct(true);
break;
default:
DbException.throwInternalError("type=" + unionType);
}
ResultInterface l = left.query(0);
ResultInterface r = right.query(0);
l.reset();
r.reset();
switch (unionType) {
case UNION_ALL:
case UNION: {
while (l.next()) {
result.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
result.addRow(convert(r.currentRow(), columnCount));
}
break;
}
case EXCEPT: {
while (l.next()) {
result.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
result.removeDistinct(convert(r.currentRow(), columnCount));
}
break;
}
case INTERSECT: {
LocalResult temp = new LocalResult(session, expressionArray, columnCount);
temp.setDistinct();
temp.setRandomAccess();
while (l.next()) {
temp.addRow(convert(l.currentRow(), columnCount));
}
while (r.next()) {
Value[] values = convert(r.currentRow(), columnCount);
if (temp.containsDistinct(values)) {
result.addRow(values);
}
}
temp.close();
break;
}
default:
DbException.throwInternalError("type=" + unionType);
}
if (offsetExpr != null) {
result.setOffset(offsetExpr.getValue(session).getInt());
}
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
result.setLimit(v.getInt());
}
}
l.close();
r.close();
result.done();
if (target != null) {
while (result.next()) {
target.addRow(result.currentRow());
}
result.close();
return null;
}
return result;
}
@Override
public void init() {
if (SysProperties.CHECK && checkInit) {
DbException.throwInternalError();
}
checkInit = true;
left.init();
right.init();
int len = left.getColumnCount();
if (len != right.getColumnCount()) {
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
}
ArrayList<Expression> le = left.getExpressions();
// set the expressions to get the right column count and names,
// but can't validate at this time
expressions = New.arrayList();
for (int i = 0; i < len; i++) {
Expression l = le.get(i);
expressions.add(l);
}
}
@Override
public void prepare() {
if (isPrepared) {
// sometimes a subquery is prepared twice (CREATE TABLE AS SELECT)
return;
}
if (SysProperties.CHECK && !checkInit) {
DbException.throwInternalError("not initialized");
}
isPrepared = true;
left.prepare();
right.prepare();
int len = left.getColumnCount();
// set the correct expressions now
expressions = New.arrayList();
ArrayList<Expression> le = left.getExpressions();
ArrayList<Expression> re = right.getExpressions();
ColumnNamer columnNamer= new ColumnNamer(session);
for (int i = 0; i < len; i++) {
Expression l = le.get(i);
Expression r = re.get(i);
int type = Value.getHigherOrder(l.getType(), r.getType());
long prec = Math.max(l.getPrecision(), r.getPrecision());
int scale = Math.max(l.getScale(), r.getScale());
int displaySize = Math.max(l.getDisplaySize(), r.getDisplaySize());
String columnName = columnNamer.getColumnName(l,i,l.getAlias());
Column col = new Column(columnName, type, prec, scale, displaySize);
Expression e = new ExpressionColumn(session.getDatabase(), col);
expressions.add(e);
}
if (orderList != null) {
initOrder(session, expressions, null, orderList, getColumnCount(), true, null);
sort = prepareOrder(orderList, expressions.size());
orderList = null;
}
expressionArray = expressions.toArray(new Expression[0]);
}
@Override
public double getCost() {
return left.getCost() + right.getCost();
}
@Override
public HashSet<Table> getTables() {
HashSet<Table> set = left.getTables();
set.addAll(right.getTables());
return set;
}
@Override
public ArrayList<Expression> getExpressions() {
return expressions;
}
@Override
public void setForUpdate(boolean forUpdate) {
left.setForUpdate(forUpdate);
right.setForUpdate(forUpdate);
isForUpdate = forUpdate;
}
@Override
public int getColumnCount() {
return left.getColumnCount();
}
@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 addGlobalCondition(Parameter param, int columnId,
int comparisonType) {
addParameter(param);
switch (unionType) {
case UNION_ALL:
case UNION:
case INTERSECT: {
left.addGlobalCondition(param, columnId, comparisonType);
right.addGlobalCondition(param, columnId, comparisonType);
break;
}
case EXCEPT: {
left.addGlobalCondition(param, columnId, comparisonType);
break;
}
default:
DbException.throwInternalError("type=" + unionType);
}
}
@Override
public String getPlanSQL() {
StringBuilder buff = new StringBuilder();
buff.append('(').append(left.getPlanSQL()).append(')');
switch (unionType) {
case UNION_ALL:
buff.append("\nUNION ALL\n");
break;
case UNION:
buff.append("\nUNION\n");
break;
case INTERSECT:
buff.append("\nINTERSECT\n");
break;
case EXCEPT:
buff.append("\nEXCEPT\n");
break;
default:
DbException.throwInternalError("type=" + unionType);
}
buff.append('(').append(right.getPlanSQL()).append(')');
Expression[] exprList = expressions.toArray(new Expression[0]);
if (sort != null) {
buff.append("\nORDER BY ").append(sort.getSQL(exprList, exprList.length));
}
if (limitExpr != null) {
buff.append("\nLIMIT ").append(
StringUtils.unEnclose(limitExpr.getSQL()));
if (offsetExpr != null) {
buff.append("\nOFFSET ").append(
StringUtils.unEnclose(offsetExpr.getSQL()));
}
}
if (sampleSizeExpr != null) {
buff.append("\nSAMPLE_SIZE ").append(
StringUtils.unEnclose(sampleSizeExpr.getSQL()));
}
if (isForUpdate) {
buff.append("\nFOR UPDATE");
}
return buff.toString();
}
@Override
public boolean isEverything(ExpressionVisitor visitor) {
return left.isEverything(visitor) && right.isEverything(visitor);
}
@Override
public boolean isReadOnly() {
return left.isReadOnly() && right.isReadOnly();
}
@Override
public void updateAggregate(Session s) {
left.updateAggregate(s);
right.updateAggregate(s);
}
@Override
public void fireBeforeSelectTriggers() {
left.fireBeforeSelectTriggers();
right.fireBeforeSelectTriggers();
}
@Override
public int getType() {
return CommandInterface.SELECT;
}
@Override
public boolean allowGlobalConditions() {
return left.allowGlobalConditions() && right.allowGlobalConditions();
}
/**
* Lazy execution for this union.
*/
private final class LazyResultUnion extends LazyResult {
int columnCount;
ResultInterface l;
ResultInterface r;
boolean leftDone;
boolean rightDone;
LazyResultUnion(Expression[] expressions, int columnCount) {
super(expressions);
this.columnCount = columnCount;
}
@Override
public int getVisibleColumnCount() {
return columnCount;
}
@Override
protected Value[] fetchNextRow() {
if (rightDone) {
return null;
}
if (!leftDone) {
if (l == null) {
l = left.query(0);
l.reset();
}
if (l.next()) {
return l.currentRow();
}
leftDone = true;
}
if (r == null) {
r = right.query(0);
r.reset();
}
if (r.next()) {
return r.currentRow();
}
rightDone = true;
return null;
}
@Override
public void close() {
super.close();
if (l != null) {
l.close();
}
if (r != null) {
r.close();
}
}
@Override
public void reset() {
super.reset();
if (l != null) {
l.reset();
}
if (r != null) {
r.reset();
}
leftDone = false;
rightDone = false;
}
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Set.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.command.dml;
import java.text.Collator;
import org.h2.api.ErrorCode;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.compress.Compressor;
import org.h2.engine.Constants;
import org.h2.engine.Database;
import org.h2.engine.Mode;
import org.h2.engine.Session;
import org.h2.engine.Setting;
import org.h2.expression.Expression;
import org.h2.expression.ValueExpression;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.RowFactory;
import org.h2.schema.Schema;
import org.h2.table.Table;
import org.h2.tools.CompressTool;
import org.h2.util.JdbcUtils;
import org.h2.util.StringUtils;
import org.h2.value.CompareMode;
import org.h2.value.ValueInt;
/**
* This class represents the statement
* SET
*/
public class Set extends Prepared {
private final int type;
private Expression expression;
private String stringValue;
private String[] stringValueList;
public Set(Session session, int type) {
super(session);
this.type = type;
}
public void setString(String v) {
this.stringValue = v;
}
@Override
public boolean isTransactional() {
switch (type) {
case SetTypes.CLUSTER:
case SetTypes.VARIABLE:
case SetTypes.QUERY_TIMEOUT:
case SetTypes.LOCK_TIMEOUT:
case SetTypes.TRACE_LEVEL_SYSTEM_OUT:
case SetTypes.TRACE_LEVEL_FILE:
case SetTypes.THROTTLE:
case SetTypes.SCHEMA:
case SetTypes.SCHEMA_SEARCH_PATH:
case SetTypes.RETENTION_TIME:
return true;
default:
}
return false;
}
@Override
public int update() {
Database database = session.getDatabase();
String name = SetTypes.getTypeName(type);
switch (type) {
case SetTypes.ALLOW_LITERALS: {
session.getUser().checkAdmin();
int value = getIntValue();
if (value < 0 || value > 2) {
throw DbException.getInvalidValueException("ALLOW_LITERALS",
getIntValue());
}
database.setAllowLiterals(value);
addOrUpdateSetting(name, null, value);
break;
}
case SetTypes.CACHE_SIZE:
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("CACHE_SIZE",
getIntValue());
}
session.getUser().checkAdmin();
database.setCacheSize(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.CLUSTER: {
if (Constants.CLUSTERING_ENABLED.equals(stringValue)) {
// this value is used when connecting
// ignore, as the cluster setting is checked later
break;
}
String value = StringUtils.quoteStringSQL(stringValue);
if (!value.equals(database.getCluster())) {
if (!value.equals(Constants.CLUSTERING_DISABLED)) {
// anybody can disable the cluster
// (if he can't access a cluster node)
session.getUser().checkAdmin();
}
database.setCluster(value);
// use the system session so that the current transaction
// (if any) is not committed
Session sysSession = database.getSystemSession();
synchronized (sysSession) {
synchronized (database) {
addOrUpdateSetting(sysSession, name, value, 0);
sysSession.commit(true);
}
}
}
break;
}
case SetTypes.COLLATION: {
session.getUser().checkAdmin();
final boolean binaryUnsigned = database.
getCompareMode().isBinaryUnsigned();
CompareMode compareMode;
StringBuilder buff = new StringBuilder(stringValue);
if (stringValue.equals(CompareMode.OFF)) {
compareMode = CompareMode.getInstance(null, 0, binaryUnsigned);
} else {
int strength = getIntValue();
buff.append(" STRENGTH ");
if (strength == Collator.IDENTICAL) {
buff.append("IDENTICAL");
} else if (strength == Collator.PRIMARY) {
buff.append("PRIMARY");
} else if (strength == Collator.SECONDARY) {
buff.append("SECONDARY");
} else if (strength == Collator.TERTIARY) {
buff.append("TERTIARY");
}
compareMode = CompareMode.getInstance(stringValue, strength,
binaryUnsigned);
}
CompareMode old = database.getCompareMode();
if (old.equals(compareMode)) {
break;
}
Table table = database.getFirstUserTable();
if (table != null) {
throw DbException.get(
ErrorCode.COLLATION_CHANGE_WITH_DATA_TABLE_1,
table.getSQL());
}
addOrUpdateSetting(name, buff.toString(), 0);
database.setCompareMode(compareMode);
break;
}
case SetTypes.BINARY_COLLATION: {
session.getUser().checkAdmin();
Table table = database.getFirstUserTable();
if (table != null) {
throw DbException.get(
ErrorCode.COLLATION_CHANGE_WITH_DATA_TABLE_1,
table.getSQL());
}
CompareMode currentMode = database.getCompareMode();
CompareMode newMode;
if (stringValue.equals(CompareMode.SIGNED)) {
newMode = CompareMode.getInstance(currentMode.getName(),
currentMode.getStrength(), false);
} else if (stringValue.equals(CompareMode.UNSIGNED)) {
newMode = CompareMode.getInstance(currentMode.getName(),
currentMode.getStrength(), true);
} else {
throw DbException.getInvalidValueException("BINARY_COLLATION",
stringValue);
}
addOrUpdateSetting(name, stringValue, 0);
database.setCompareMode(newMode);
break;
}
case SetTypes.COMPRESS_LOB: {
session.getUser().checkAdmin();
int algo = CompressTool.getCompressAlgorithm(stringValue);
database.setLobCompressionAlgorithm(algo == Compressor.NO ?
null : stringValue);
addOrUpdateSetting(name, stringValue, 0);
break;
}
case SetTypes.CREATE_BUILD: {
session.getUser().checkAdmin();
if (database.isStarting()) {
// just ignore the command if not starting
// this avoids problems when running recovery scripts
int value = getIntValue();
addOrUpdateSetting(name, null, value);
}
break;
}
case SetTypes.DATABASE_EVENT_LISTENER: {
session.getUser().checkAdmin();
database.setEventListenerClass(stringValue);
break;
}
case SetTypes.DB_CLOSE_DELAY: {
int x = getIntValue();
if (x == -1) {
// -1 is a special value for in-memory databases,
// which means "keep the DB alive and use the same
// DB for all connections"
} else if (x < 0) {
throw DbException.getInvalidValueException("DB_CLOSE_DELAY", x);
}
session.getUser().checkAdmin();
database.setCloseDelay(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.DEFAULT_LOCK_TIMEOUT:
if (getIntValue() < 0) {
throw DbException.getInvalidValueException(
"DEFAULT_LOCK_TIMEOUT", getIntValue());
}
session.getUser().checkAdmin();
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.DEFAULT_TABLE_TYPE:
session.getUser().checkAdmin();
database.setDefaultTableType(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.EXCLUSIVE: {
session.getUser().checkAdmin();
int value = getIntValue();
switch (value) {
case 0:
database.setExclusiveSession(null, false);
break;
case 1:
database.setExclusiveSession(session, false);
break;
case 2:
database.setExclusiveSession(session, true);
break;
default:
throw DbException.getInvalidValueException("EXCLUSIVE", value);
}
break;
}
case SetTypes.JAVA_OBJECT_SERIALIZER: {
session.getUser().checkAdmin();
Table table = database.getFirstUserTable();
if (table != null) {
throw DbException.get(ErrorCode.
JAVA_OBJECT_SERIALIZER_CHANGE_WITH_DATA_TABLE,
table.getSQL());
}
database.setJavaObjectSerializerName(stringValue);
addOrUpdateSetting(name, stringValue, 0);
break;
}
case SetTypes.IGNORECASE:
session.getUser().checkAdmin();
database.setIgnoreCase(getIntValue() == 1);
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.LOCK_MODE:
session.getUser().checkAdmin();
database.setLockMode(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.LOCK_TIMEOUT:
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("LOCK_TIMEOUT",
getIntValue());
}
session.setLockTimeout(getIntValue());
break;
case SetTypes.LOG: {
int value = getIntValue();
if (database.isPersistent() && value != database.getLogMode()) {
session.getUser().checkAdmin();
database.setLogMode(value);
}
break;
}
case SetTypes.MAX_LENGTH_INPLACE_LOB: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException(
"MAX_LENGTH_INPLACE_LOB", getIntValue());
}
session.getUser().checkAdmin();
database.setMaxLengthInplaceLob(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.MAX_LOG_SIZE:
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("MAX_LOG_SIZE",
getIntValue());
}
session.getUser().checkAdmin();
database.setMaxLogSize((long) getIntValue() * 1024 * 1024);
addOrUpdateSetting(name, null, getIntValue());
break;
case SetTypes.MAX_MEMORY_ROWS: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("MAX_MEMORY_ROWS",
getIntValue());
}
session.getUser().checkAdmin();
database.setMaxMemoryRows(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.MAX_MEMORY_UNDO: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("MAX_MEMORY_UNDO",
getIntValue());
}
session.getUser().checkAdmin();
database.setMaxMemoryUndo(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.MAX_OPERATION_MEMORY: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException(
"MAX_OPERATION_MEMORY", getIntValue());
}
session.getUser().checkAdmin();
int value = getIntValue();
database.setMaxOperationMemory(value);
break;
}
case SetTypes.MODE:
Mode mode = Mode.getInstance(stringValue);
if (mode == null) {
throw DbException.get(ErrorCode.UNKNOWN_MODE_1, stringValue);
}
if (database.getMode() != mode) {
session.getUser().checkAdmin();
database.setMode(mode);
session.getColumnNamerConfiguration().configure(mode.getEnum());
}
break;
case SetTypes.MULTI_THREADED: {
session.getUser().checkAdmin();
database.setMultiThreaded(getIntValue() == 1);
break;
}
case SetTypes.MVCC: {
if (database.isMultiVersion() != (getIntValue() == 1)) {
throw DbException.get(
ErrorCode.CANNOT_CHANGE_SETTING_WHEN_OPEN_1, "MVCC");
}
break;
}
case SetTypes.OPTIMIZE_REUSE_RESULTS: {
session.getUser().checkAdmin();
database.setOptimizeReuseResults(getIntValue() != 0);
break;
}
case SetTypes.QUERY_TIMEOUT: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("QUERY_TIMEOUT",
getIntValue());
}
int value = getIntValue();
session.setQueryTimeout(value);
break;
}
case SetTypes.REDO_LOG_BINARY: {
int value = getIntValue();
session.setRedoLogBinary(value == 1);
break;
}
case SetTypes.REFERENTIAL_INTEGRITY: {
session.getUser().checkAdmin();
int value = getIntValue();
if (value < 0 || value > 1) {
throw DbException.getInvalidValueException(
"REFERENTIAL_INTEGRITY", getIntValue());
}
database.setReferentialIntegrity(value == 1);
break;
}
case SetTypes.QUERY_STATISTICS: {
session.getUser().checkAdmin();
int value = getIntValue();
if (value < 0 || value > 1) {
throw DbException.getInvalidValueException("QUERY_STATISTICS",
getIntValue());
}
database.setQueryStatistics(value == 1);
break;
}
case SetTypes.QUERY_STATISTICS_MAX_ENTRIES: {
session.getUser().checkAdmin();
int value = getIntValue();
if (value < 1) {
throw DbException.getInvalidValueException("QUERY_STATISTICS_MAX_ENTRIES",
getIntValue());
}
database.setQueryStatisticsMaxEntries(value);
break;
}
case SetTypes.SCHEMA: {
Schema schema = database.getSchema(stringValue);
session.setCurrentSchema(schema);
break;
}
case SetTypes.SCHEMA_SEARCH_PATH: {
session.setSchemaSearchPath(stringValueList);
break;
}
case SetTypes.TRACE_LEVEL_FILE:
session.getUser().checkAdmin();
if (getCurrentObjectId() == 0) {
// don't set the property when opening the database
// this is for compatibility with older versions, because
// this setting was persistent
database.getTraceSystem().setLevelFile(getIntValue());
}
break;
case SetTypes.TRACE_LEVEL_SYSTEM_OUT:
session.getUser().checkAdmin();
if (getCurrentObjectId() == 0) {
// don't set the property when opening the database
// this is for compatibility with older versions, because
// this setting was persistent
database.getTraceSystem().setLevelSystemOut(getIntValue());
}
break;
case SetTypes.TRACE_MAX_FILE_SIZE: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException(
"TRACE_MAX_FILE_SIZE", getIntValue());
}
session.getUser().checkAdmin();
int size = getIntValue() * 1024 * 1024;
database.getTraceSystem().setMaxFileSize(size);
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.THROTTLE: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("THROTTLE",
getIntValue());
}
session.setThrottle(getIntValue());
break;
}
case SetTypes.UNDO_LOG: {
int value = getIntValue();
if (value < 0 || value > 1) {
throw DbException.getInvalidValueException("UNDO_LOG",
getIntValue());
}
session.setUndoLogEnabled(value == 1);
break;
}
case SetTypes.VARIABLE: {
Expression expr = expression.optimize(session);
session.setVariable(stringValue, expr.getValue(session));
break;
}
case SetTypes.WRITE_DELAY: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("WRITE_DELAY",
getIntValue());
}
session.getUser().checkAdmin();
database.setWriteDelay(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.RETENTION_TIME: {
if (getIntValue() < 0) {
throw DbException.getInvalidValueException("RETENTION_TIME",
getIntValue());
}
session.getUser().checkAdmin();
database.setRetentionTime(getIntValue());
addOrUpdateSetting(name, null, getIntValue());
break;
}
case SetTypes.ROW_FACTORY: {
session.getUser().checkAdmin();
String rowFactoryName = expression.getColumnName();
Class<RowFactory> rowFactoryClass = JdbcUtils.loadUserClass(rowFactoryName);
RowFactory rowFactory;
try {
rowFactory = rowFactoryClass.newInstance();
} catch (Exception e) {
throw DbException.convert(e);
}
database.setRowFactory(rowFactory);
break;
}
case SetTypes.BATCH_JOINS: {
int value = getIntValue();
if (value != 0 && value != 1) {
throw DbException.getInvalidValueException("BATCH_JOINS",
getIntValue());
}
session.setJoinBatchEnabled(value == 1);
break;
}
case SetTypes.FORCE_JOIN_ORDER: {
int value = getIntValue();
if (value != 0 && value != 1) {
throw DbException.getInvalidValueException("FORCE_JOIN_ORDER",
value);
}
session.setForceJoinOrder(value == 1);
break;
}
case SetTypes.LAZY_QUERY_EXECUTION: {
int value = getIntValue();
if (value != 0 && value != 1) {
throw DbException.getInvalidValueException("LAZY_QUERY_EXECUTION",
value);
}
session.setLazyQueryExecution(value == 1);
break;
}
case SetTypes.BUILTIN_ALIAS_OVERRIDE: {
session.getUser().checkAdmin();
int value = getIntValue();
if (value != 0 && value != 1) {
throw DbException.getInvalidValueException("BUILTIN_ALIAS_OVERRIDE",
value);
}
database.setAllowBuiltinAliasOverride(value == 1);
break;
}
case SetTypes.COLUMN_NAME_RULES: {
session.getUser().checkAdmin();
session.getColumnNamerConfiguration().configure(expression.getColumnName());
break;
}
default:
DbException.throwInternalError("type="+type);
}
// the meta data information has changed
database.getNextModificationDataId();
// query caches might be affected as well, for example
// when changing the compatibility mode
database.getNextModificationMetaId();
return 0;
}
private int getIntValue() {
expression = expression.optimize(session);
return expression.getValue(session).getInt();
}
public void setInt(int value) {
this.expression = ValueExpression.get(ValueInt.get(value));
}
public void setExpression(Expression expression) {
this.expression = expression;
}
private void addOrUpdateSetting(String name, String s, int v) {
addOrUpdateSetting(session, name, s, v);
}
private void addOrUpdateSetting(Session session, String name, String s,
int v) {
Database database = session.getDatabase();
if (database.isReadOnly()) {
return;
}
Setting setting = database.findSetting(name);
boolean addNew = false;
if (setting == null) {
addNew = true;
int id = getObjectId();
setting = new Setting(database, id, name);
}
if (s != null) {
if (!addNew && setting.getStringValue().equals(s)) {
return;
}
setting.setStringValue(s);
} else {
if (!addNew && setting.getIntValue() == v) {
return;
}
setting.setIntValue(v);
}
if (addNew) {
database.addDatabaseObject(session, setting);
} else {
database.updateMeta(session, setting);
}
}
@Override
public boolean needRecompile() {
return false;
}
@Override
public ResultInterface queryMeta() {
return null;
}
public void setStringArray(String[] list) {
this.stringValueList = list;
}
@Override
public int getType() {
return CommandInterface.SET;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/SetTypes.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.command.dml;
import java.util.ArrayList;
/**
* The list of setting for a SET statement.
*/
public class SetTypes {
/**
* The type of a SET IGNORECASE statement.
*/
public static final int IGNORECASE = 1;
/**
* The type of a SET MAX_LOG_SIZE statement.
*/
public static final int MAX_LOG_SIZE = 2;
/**
* The type of a SET MODE statement.
*/
public static final int MODE = 3;
/**
* The type of a SET READONLY statement.
*/
public static final int READONLY = 4;
/**
* The type of a SET LOCK_TIMEOUT statement.
*/
public static final int LOCK_TIMEOUT = 5;
/**
* The type of a SET DEFAULT_LOCK_TIMEOUT statement.
*/
public static final int DEFAULT_LOCK_TIMEOUT = 6;
/**
* The type of a SET DEFAULT_TABLE_TYPE statement.
*/
public static final int DEFAULT_TABLE_TYPE = 7;
/**
* The type of a SET CACHE_SIZE statement.
*/
public static final int CACHE_SIZE = 8;
/**
* The type of a SET TRACE_LEVEL_SYSTEM_OUT statement.
*/
public static final int TRACE_LEVEL_SYSTEM_OUT = 9;
/**
* The type of a SET TRACE_LEVEL_FILE statement.
*/
public static final int TRACE_LEVEL_FILE = 10;
/**
* The type of a SET TRACE_MAX_FILE_SIZE statement.
*/
public static final int TRACE_MAX_FILE_SIZE = 11;
/**
* The type of a SET COLLATION statement.
*/
public static final int COLLATION = 12;
/**
* The type of a SET CLUSTER statement.
*/
public static final int CLUSTER = 13;
/**
* The type of a SET WRITE_DELAY statement.
*/
public static final int WRITE_DELAY = 14;
/**
* The type of a SET DATABASE_EVENT_LISTENER statement.
*/
public static final int DATABASE_EVENT_LISTENER = 15;
/**
* The type of a SET MAX_MEMORY_ROWS statement.
*/
public static final int MAX_MEMORY_ROWS = 16;
/**
* The type of a SET LOCK_MODE statement.
*/
public static final int LOCK_MODE = 17;
/**
* The type of a SET DB_CLOSE_DELAY statement.
*/
public static final int DB_CLOSE_DELAY = 18;
/**
* The type of a SET LOG statement.
*/
public static final int LOG = 19;
/**
* The type of a SET THROTTLE statement.
*/
public static final int THROTTLE = 20;
/**
* The type of a SET MAX_MEMORY_UNDO statement.
*/
public static final int MAX_MEMORY_UNDO = 21;
/**
* The type of a SET MAX_LENGTH_INPLACE_LOB statement.
*/
public static final int MAX_LENGTH_INPLACE_LOB = 22;
/**
* The type of a SET COMPRESS_LOB statement.
*/
public static final int COMPRESS_LOB = 23;
/**
* The type of a SET ALLOW_LITERALS statement.
*/
public static final int ALLOW_LITERALS = 24;
/**
* The type of a SET MULTI_THREADED statement.
*/
public static final int MULTI_THREADED = 25;
/**
* The type of a SET SCHEMA statement.
*/
public static final int SCHEMA = 26;
/**
* The type of a SET OPTIMIZE_REUSE_RESULTS statement.
*/
public static final int OPTIMIZE_REUSE_RESULTS = 27;
/**
* The type of a SET SCHEMA_SEARCH_PATH statement.
*/
public static final int SCHEMA_SEARCH_PATH = 28;
/**
* The type of a SET UNDO_LOG statement.
*/
public static final int UNDO_LOG = 29;
/**
* The type of a SET REFERENTIAL_INTEGRITY statement.
*/
public static final int REFERENTIAL_INTEGRITY = 30;
/**
* The type of a SET MVCC statement.
*/
public static final int MVCC = 31;
/**
* The type of a SET MAX_OPERATION_MEMORY statement.
*/
public static final int MAX_OPERATION_MEMORY = 32;
/**
* The type of a SET EXCLUSIVE statement.
*/
public static final int EXCLUSIVE = 33;
/**
* The type of a SET CREATE_BUILD statement.
*/
public static final int CREATE_BUILD = 34;
/**
* The type of a SET \@VARIABLE statement.
*/
public static final int VARIABLE = 35;
/**
* The type of a SET QUERY_TIMEOUT statement.
*/
public static final int QUERY_TIMEOUT = 36;
/**
* The type of a SET REDO_LOG_BINARY statement.
*/
public static final int REDO_LOG_BINARY = 37;
/**
* The type of a SET BINARY_COLLATION statement.
*/
public static final int BINARY_COLLATION = 38;
/**
* The type of a SET JAVA_OBJECT_SERIALIZER statement.
*/
public static final int JAVA_OBJECT_SERIALIZER = 39;
/**
* The type of a SET RETENTION_TIME statement.
*/
public static final int RETENTION_TIME = 40;
/**
* The type of a SET QUERY_STATISTICS statement.
*/
public static final int QUERY_STATISTICS = 41;
/**
* The type of a SET QUERY_STATISTICS_MAX_ENTRIES statement.
*/
public static final int QUERY_STATISTICS_MAX_ENTRIES = 42;
/**
* The type of a SET ROW_FACTORY statement.
*/
public static final int ROW_FACTORY = 43;
/**
* The type of SET BATCH_JOINS statement.
*/
public static final int BATCH_JOINS = 44;
/**
* The type of SET FORCE_JOIN_ORDER statement.
*/
public static final int FORCE_JOIN_ORDER = 45;
/**
* The type of SET LAZY_QUERY_EXECUTION statement.
*/
public static final int LAZY_QUERY_EXECUTION = 46;
/**
* The type of SET BUILTIN_ALIAS_OVERRIDE statement.
*/
public static final int BUILTIN_ALIAS_OVERRIDE = 47;
/**
* The type of a SET COLUMN_NAME_RULES statement.
*/
public static final int COLUMN_NAME_RULES = 48;
private static final int COUNT = COLUMN_NAME_RULES + 1;
private static final ArrayList<String> TYPES;
private SetTypes() {
// utility class
}
static {
ArrayList<String> list = new ArrayList<>(COUNT);
list.add(null);
list.add(IGNORECASE, "IGNORECASE");
list.add(MAX_LOG_SIZE, "MAX_LOG_SIZE");
list.add(MODE, "MODE");
list.add(READONLY, "READONLY");
list.add(LOCK_TIMEOUT, "LOCK_TIMEOUT");
list.add(DEFAULT_LOCK_TIMEOUT, "DEFAULT_LOCK_TIMEOUT");
list.add(DEFAULT_TABLE_TYPE, "DEFAULT_TABLE_TYPE");
list.add(CACHE_SIZE, "CACHE_SIZE");
list.add(TRACE_LEVEL_SYSTEM_OUT, "TRACE_LEVEL_SYSTEM_OUT");
list.add(TRACE_LEVEL_FILE, "TRACE_LEVEL_FILE");
list.add(TRACE_MAX_FILE_SIZE, "TRACE_MAX_FILE_SIZE");
list.add(COLLATION, "COLLATION");
list.add(CLUSTER, "CLUSTER");
list.add(WRITE_DELAY, "WRITE_DELAY");
list.add(DATABASE_EVENT_LISTENER, "DATABASE_EVENT_LISTENER");
list.add(MAX_MEMORY_ROWS, "MAX_MEMORY_ROWS");
list.add(LOCK_MODE, "LOCK_MODE");
list.add(DB_CLOSE_DELAY, "DB_CLOSE_DELAY");
list.add(LOG, "LOG");
list.add(THROTTLE, "THROTTLE");
list.add(MAX_MEMORY_UNDO, "MAX_MEMORY_UNDO");
list.add(MAX_LENGTH_INPLACE_LOB, "MAX_LENGTH_INPLACE_LOB");
list.add(COMPRESS_LOB, "COMPRESS_LOB");
list.add(ALLOW_LITERALS, "ALLOW_LITERALS");
list.add(MULTI_THREADED, "MULTI_THREADED");
list.add(SCHEMA, "SCHEMA");
list.add(OPTIMIZE_REUSE_RESULTS, "OPTIMIZE_REUSE_RESULTS");
list.add(SCHEMA_SEARCH_PATH, "SCHEMA_SEARCH_PATH");
list.add(UNDO_LOG, "UNDO_LOG");
list.add(REFERENTIAL_INTEGRITY, "REFERENTIAL_INTEGRITY");
list.add(MVCC, "MVCC");
list.add(MAX_OPERATION_MEMORY, "MAX_OPERATION_MEMORY");
list.add(EXCLUSIVE, "EXCLUSIVE");
list.add(CREATE_BUILD, "CREATE_BUILD");
list.add(VARIABLE, "@");
list.add(QUERY_TIMEOUT, "QUERY_TIMEOUT");
list.add(REDO_LOG_BINARY, "REDO_LOG_BINARY");
list.add(BINARY_COLLATION, "BINARY_COLLATION");
list.add(JAVA_OBJECT_SERIALIZER, "JAVA_OBJECT_SERIALIZER");
list.add(RETENTION_TIME, "RETENTION_TIME");
list.add(QUERY_STATISTICS, "QUERY_STATISTICS");
list.add(QUERY_STATISTICS_MAX_ENTRIES, "QUERY_STATISTICS_MAX_ENTRIES");
list.add(ROW_FACTORY, "ROW_FACTORY");
list.add(BATCH_JOINS, "BATCH_JOINS");
list.add(FORCE_JOIN_ORDER, "FORCE_JOIN_ORDER");
list.add(LAZY_QUERY_EXECUTION, "LAZY_QUERY_EXECUTION");
list.add(BUILTIN_ALIAS_OVERRIDE, "BUILTIN_ALIAS_OVERRIDE");
list.add(COLUMN_NAME_RULES, "COLUMN_NAME_RULES");
TYPES = list;
}
/**
* Get the set type number.
*
* @param name the set type name
* @return the number
*/
public static int getType(String name) {
return TYPES.indexOf(name);
}
public static ArrayList<String> getTypes() {
return TYPES;
}
/**
* Get the set type name.
*
* @param type the type number
* @return the name
*/
public static String getTypeName(int type) {
return TYPES.get(type);
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/TransactionCommand.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.command.dml;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Database;
import org.h2.engine.Session;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
/**
* Represents a transactional statement.
*/
public class TransactionCommand extends Prepared {
private final int type;
private String savepointName;
private String transactionName;
public TransactionCommand(Session session, int type) {
super(session);
this.type = type;
}
public void setSavepointName(String name) {
this.savepointName = name;
}
@Override
public int update() {
switch (type) {
case CommandInterface.SET_AUTOCOMMIT_TRUE:
session.setAutoCommit(true);
break;
case CommandInterface.SET_AUTOCOMMIT_FALSE:
session.setAutoCommit(false);
break;
case CommandInterface.BEGIN:
session.begin();
break;
case CommandInterface.COMMIT:
session.commit(false);
break;
case CommandInterface.ROLLBACK:
session.rollback();
break;
case CommandInterface.CHECKPOINT:
session.getUser().checkAdmin();
session.getDatabase().checkpoint();
break;
case CommandInterface.SAVEPOINT:
session.addSavepoint(savepointName);
break;
case CommandInterface.ROLLBACK_TO_SAVEPOINT:
session.rollbackToSavepoint(savepointName);
break;
case CommandInterface.CHECKPOINT_SYNC:
session.getUser().checkAdmin();
session.getDatabase().sync();
break;
case CommandInterface.PREPARE_COMMIT:
session.prepareCommit(transactionName);
break;
case CommandInterface.COMMIT_TRANSACTION:
session.getUser().checkAdmin();
session.setPreparedTransaction(transactionName, true);
break;
case CommandInterface.ROLLBACK_TRANSACTION:
session.getUser().checkAdmin();
session.setPreparedTransaction(transactionName, false);
break;
case CommandInterface.SHUTDOWN_IMMEDIATELY:
session.getUser().checkAdmin();
session.getDatabase().shutdownImmediately();
break;
case CommandInterface.SHUTDOWN:
case CommandInterface.SHUTDOWN_COMPACT:
case CommandInterface.SHUTDOWN_DEFRAG: {
session.getUser().checkAdmin();
session.commit(false);
if (type == CommandInterface.SHUTDOWN_COMPACT ||
type == CommandInterface.SHUTDOWN_DEFRAG) {
session.getDatabase().setCompactMode(type);
}
// close the database, but don't update the persistent setting
session.getDatabase().setCloseDelay(0);
Database db = session.getDatabase();
// throttle, to allow testing concurrent
// execution of shutdown and query
session.throttle();
for (Session s : db.getSessions(false)) {
if (db.isMultiThreaded()) {
synchronized (s) {
s.rollback();
}
} else {
// if not multi-threaded, the session could already own
// the lock, which would result in a deadlock
// the other session can not concurrently do anything
// because the current session has locked the database
s.rollback();
}
if (s != session) {
s.close();
}
}
session.close();
break;
}
default:
DbException.throwInternalError("type=" + type);
}
return 0;
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public boolean needRecompile() {
return false;
}
public void setTransactionName(String string) {
this.transactionName = string;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return type;
}
@Override
public boolean isCacheable() {
return true;
}
}
|
0
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command
|
java-sources/ai/platon/pulsar/pulsar-h2/1.4.196/org/h2/command/dml/Update.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.command.dml;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import org.h2.api.ErrorCode;
import org.h2.api.Trigger;
import org.h2.command.CommandInterface;
import org.h2.command.Prepared;
import org.h2.engine.Right;
import org.h2.engine.Session;
import org.h2.expression.Expression;
import org.h2.expression.ExpressionVisitor;
import org.h2.expression.Parameter;
import org.h2.expression.ValueExpression;
import org.h2.message.DbException;
import org.h2.result.ResultInterface;
import org.h2.result.Row;
import org.h2.result.RowList;
import org.h2.table.Column;
import org.h2.table.PlanItem;
import org.h2.table.Table;
import org.h2.table.TableFilter;
import org.h2.util.New;
import org.h2.util.StatementBuilder;
import org.h2.util.StringUtils;
import org.h2.value.Value;
import org.h2.value.ValueNull;
/**
* This class represents the statement
* UPDATE
*/
public class Update extends Prepared {
private Expression condition;
private TableFilter targetTableFilter;// target of update
/**
* This table filter is for MERGE..USING support - not used in stand-alone DML
*/
private TableFilter sourceTableFilter;
/** The limit expression as specified in the LIMIT clause. */
private Expression limitExpr;
private final ArrayList<Column> columns = New.arrayList();
private final HashMap<Column, Expression> expressionMap = new HashMap<>();
public Update(Session session) {
super(session);
}
public void setTableFilter(TableFilter tableFilter) {
this.targetTableFilter = tableFilter;
}
public void setCondition(Expression condition) {
this.condition = condition;
}
public Expression getCondition( ) {
return this.condition;
}
/**
* Add an assignment of the form column = expression.
*
* @param column the column
* @param expression the expression
*/
public void setAssignment(Column column, Expression expression) {
if (expressionMap.containsKey(column)) {
throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1, column
.getName());
}
columns.add(column);
expressionMap.put(column, expression);
if (expression instanceof Parameter) {
Parameter p = (Parameter) expression;
p.setColumn(column);
}
}
@Override
public int update() {
targetTableFilter.startQuery(session);
targetTableFilter.reset();
RowList rows = new RowList(session);
try {
Table table = targetTableFilter.getTable();
session.getUser().checkRight(table, Right.UPDATE);
table.fire(session, Trigger.UPDATE, true);
table.lock(session, true, false);
int columnCount = table.getColumns().length;
// get the old rows, compute the new rows
setCurrentRowNumber(0);
int count = 0;
Column[] columns = table.getColumns();
int limitRows = -1;
if (limitExpr != null) {
Value v = limitExpr.getValue(session);
if (v != ValueNull.INSTANCE) {
limitRows = v.getInt();
}
}
while (targetTableFilter.next()) {
setCurrentRowNumber(count+1);
if (limitRows >= 0 && count >= limitRows) {
break;
}
if (condition == null || condition.getBooleanValue(session)) {
Row oldRow = targetTableFilter.get();
Row newRow = table.getTemplateRow();
boolean setOnUpdate = false;
for (int i = 0; i < columnCount; i++) {
Expression newExpr = expressionMap.get(columns[i]);
Column column = table.getColumn(i);
Value newValue;
if (newExpr == null) {
if (column.getOnUpdateExpression() != null) {
setOnUpdate = true;
}
newValue = oldRow.getValue(i);
} else if (newExpr == ValueExpression.getDefault()) {
newValue = table.getDefaultValue(session, column);
} else {
newValue = column.convert(newExpr.getValue(session));
}
newRow.setValue(i, newValue);
}
if (setOnUpdate) {
setOnUpdate = false;
for (int i = 0; i < columnCount; i++) {
// Use equals here to detect changes from numeric 0 to 0.0 and similar
if (!Objects.equals(oldRow.getValue(i), newRow.getValue(i))) {
setOnUpdate = true;
break;
}
}
if (setOnUpdate) {
for (int i = 0; i < columnCount; i++) {
if (expressionMap.get(columns[i]) == null) {
Column column = table.getColumn(i);
if (column.getOnUpdateExpression() != null) {
newRow.setValue(i, table.getOnUpdateValue(session, column));
}
}
}
}
}
table.validateConvertUpdateSequence(session, newRow);
boolean done = false;
if (table.fireRow()) {
done = table.fireBeforeRow(session, oldRow, newRow);
}
if (!done) {
rows.add(oldRow);
rows.add(newRow);
}
count++;
}
}
// TODO self referencing referential integrity constraints
// don't work if update is multi-row and 'inversed' the condition!
// probably need multi-row triggers with 'deleted' and 'inserted'
// at the same time. anyway good for sql compatibility
// TODO update in-place (but if the key changes,
// we need to update all indexes) before row triggers
// the cached row is already updated - we need the old values
table.updateRows(this, session, rows);
if (table.fireRow()) {
rows.invalidateCache();
for (rows.reset(); rows.hasNext();) {
Row o = rows.next();
Row n = rows.next();
table.fireAfterRow(session, o, n, false);
}
}
table.fire(session, Trigger.UPDATE, false);
return count;
} finally {
rows.close();
}
}
@Override
public String getPlanSQL() {
StatementBuilder buff = new StatementBuilder("UPDATE ");
buff.append(targetTableFilter.getPlanSQL(false)).append("\nSET\n ");
for (Column c : columns) {
Expression e = expressionMap.get(c);
buff.appendExceptFirst(",\n ");
buff.append(c.getName()).append(" = ").append(e.getSQL());
}
if (condition != null) {
buff.append("\nWHERE ").append(StringUtils.unEnclose(condition.getSQL()));
}
if (limitExpr != null) {
buff.append("\nLIMIT ").append(
StringUtils.unEnclose(limitExpr.getSQL()));
}
return buff.toString();
}
@Override
public void prepare() {
if (condition != null) {
condition.mapColumns(targetTableFilter, 0);
condition = condition.optimize(session);
condition.createIndexConditions(session, targetTableFilter);
}
for (Column c : columns) {
Expression e = expressionMap.get(c);
e.mapColumns(targetTableFilter, 0);
if (sourceTableFilter!=null){
e.mapColumns(sourceTableFilter, 0);
}
expressionMap.put(c, e.optimize(session));
}
TableFilter[] filters;
if(sourceTableFilter==null){
filters = new TableFilter[] { targetTableFilter };
}
else{
filters = new TableFilter[] { targetTableFilter, sourceTableFilter };
}
PlanItem item = targetTableFilter.getBestPlanItem(session, filters, 0,
ExpressionVisitor.allColumnsForTableFilters(filters));
targetTableFilter.setPlanItem(item);
targetTableFilter.prepare();
}
@Override
public boolean isTransactional() {
return true;
}
@Override
public ResultInterface queryMeta() {
return null;
}
@Override
public int getType() {
return CommandInterface.UPDATE;
}
public void setLimit(Expression limit) {
this.limitExpr = limit;
}
@Override
public boolean isCacheable() {
return true;
}
public TableFilter getSourceTableFilter() {
return sourceTableFilter;
}
public void setSourceTableFilter(TableFilter sourceTableFilter) {
this.sourceTableFilter = sourceTableFilter;
}
}
|
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/CompressDeflate.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.util.StringTokenizer;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
import org.h2.api.ErrorCode;
import org.h2.message.DbException;
/**
* This is a wrapper class for the Deflater class.
* This algorithm supports the following options:
* <ul>
* <li>l or level: -1 (default), 0 (no compression),
* 1 (best speed), ..., 9 (best compression)
* </li><li>s or strategy: 0 (default),
* 1 (filtered), 2 (huffman only)
* </li></ul>
* See also java.util.zip.Deflater for details.
*/
public class CompressDeflate implements Compressor {
private int level = Deflater.DEFAULT_COMPRESSION;
private int strategy = Deflater.DEFAULT_STRATEGY;
@Override
public void setOptions(String options) {
if (options == null) {
return;
}
try {
StringTokenizer tokenizer = new StringTokenizer(options);
while (tokenizer.hasMoreElements()) {
String option = tokenizer.nextToken();
if ("level".equals(option) || "l".equals(option)) {
level = Integer.parseInt(tokenizer.nextToken());
} else if ("strategy".equals(option) || "s".equals(option)) {
strategy = Integer.parseInt(tokenizer.nextToken());
}
Deflater deflater = new Deflater(level);
deflater.setStrategy(strategy);
}
} catch (Exception e) {
throw DbException.get(ErrorCode.UNSUPPORTED_COMPRESSION_OPTIONS_1, options);
}
}
@Override
public int compress(byte[] in, int inLen, byte[] out, int outPos) {
Deflater deflater = new Deflater(level);
deflater.setStrategy(strategy);
deflater.setInput(in, 0, inLen);
deflater.finish();
int compressed = deflater.deflate(out, outPos, out.length - outPos);
while (compressed == 0) {
// the compressed length is 0, meaning compression didn't work
// (sounds like a JDK bug)
// try again, using the default strategy and compression level
strategy = Deflater.DEFAULT_STRATEGY;
level = Deflater.DEFAULT_COMPRESSION;
return compress(in, inLen, out, outPos);
}
deflater.end();
return outPos + compressed;
}
@Override
public int getAlgorithm() {
return Compressor.DEFLATE;
}
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos,
int outLen) {
Inflater decompresser = new Inflater();
decompresser.setInput(in, inPos, inLen);
decompresser.finished();
try {
int len = decompresser.inflate(out, outPos, outLen);
if (len != outLen) {
throw new DataFormatException(len + " " + outLen);
}
} catch (DataFormatException e) {
throw DbException.get(ErrorCode.COMPRESSION_ERROR, e);
}
decompresser.end();
}
}
|
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/CompressLZF.java
|
/*
* Copyright 2004-2018 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
*
* This code is based on the LZF algorithm from Marc Lehmann. It is a
* re-implementation of the C code:
* http://cvs.schmorp.de/liblzf/lzf_c.c?view=markup
* http://cvs.schmorp.de/liblzf/lzf_d.c?view=markup
*
* According to a mail from Marc Lehmann, it's OK to use his algorithm:
* Date: 2010-07-15 15:57
* Subject: Re: Question about LZF licensing
* ...
* The algorithm is not copyrighted (and cannot be copyrighted afaik) - as long
* as you wrote everything yourself, without copying my code, that's just fine
* (looking is of course fine too).
* ...
*
* Still I would like to keep his copyright info:
*
* Copyright (c) 2000-2005 Marc Alexander Lehmann <schmorp@schmorp.de>
* Copyright (c) 2005 Oren J. Maurice <oymaurice@hazorea.org.il>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.h2.compress;
import java.nio.ByteBuffer;
/**
* <p>
* This class implements the LZF lossless data compression algorithm. LZF is a
* Lempel-Ziv variant with byte-aligned output, and optimized for speed.
* </p>
* <p>
* Safety/Use Notes:
* </p>
* <ul>
* <li>Each instance should be used by a single thread only.</li>
* <li>The data buffers should be smaller than 1 GB.</li>
* <li>For performance reasons, safety checks on expansion are omitted.</li>
* <li>Invalid compressed data can cause an ArrayIndexOutOfBoundsException.</li>
* </ul>
* <p>
* The LZF compressed format knows literal runs and back-references:
* </p>
* <ul>
* <li>Literal run: directly copy bytes from input to output.</li>
* <li>Back-reference: copy previous data to output stream, with specified
* offset from location and length. The length is at least 3 bytes.</li>
* </ul>
*<p>
* The first byte of the compressed stream is the control byte. For literal
* runs, the highest three bits of the control byte are not set, the the lower
* bits are the literal run length, and the next bytes are data to copy directly
* into the output. For back-references, the highest three bits of the control
* byte are the back-reference length. If all three bits are set, then the
* back-reference length is stored in the next byte. The lower bits of the
* control byte combined with the next byte form the offset for the
* back-reference.
* </p>
*/
public final class CompressLZF implements Compressor {
/**
* The number of entries in the hash table. The size is a trade-off between
* hash collisions (reduced compression) and speed (amount that fits in CPU
* cache).
*/
private static final int HASH_SIZE = 1 << 14;
/**
* The maximum number of literals in a chunk (32).
*/
private static final int MAX_LITERAL = 1 << 5;
/**
* The maximum offset allowed for a back-reference (8192).
*/
private static final int MAX_OFF = 1 << 13;
/**
* The maximum back-reference length (264).
*/
private static final int MAX_REF = (1 << 8) + (1 << 3);
/**
* Hash table for matching byte sequences (reused for performance).
*/
private int[] cachedHashTable;
@Override
public void setOptions(String options) {
// nothing to do
}
/**
* Return the integer with the first two bytes 0, then the bytes at the
* index, then at index+1.
*/
private static int first(byte[] in, int inPos) {
return (in[inPos] << 8) | (in[inPos + 1] & 255);
}
/**
* Return the integer with the first two bytes 0, then the bytes at the
* index, then at index+1.
*/
private static int first(ByteBuffer in, int inPos) {
return (in.get(inPos) << 8) | (in.get(inPos + 1) & 255);
}
/**
* Shift the value 1 byte left, and add the byte at index inPos+2.
*/
private static int next(int v, byte[] in, int inPos) {
return (v << 8) | (in[inPos + 2] & 255);
}
/**
* Shift the value 1 byte left, and add the byte at index inPos+2.
*/
private static int next(int v, ByteBuffer in, int inPos) {
return (v << 8) | (in.get(inPos + 2) & 255);
}
/**
* Compute the address in the hash table.
*/
private static int hash(int h) {
return ((h * 2777) >> 9) & (HASH_SIZE - 1);
}
@Override
public int compress(byte[] in, int inLen, byte[] out, int outPos) {
int inPos = 0;
if (cachedHashTable == null) {
cachedHashTable = new int[HASH_SIZE];
}
int[] hashTab = cachedHashTable;
int literals = 0;
outPos++;
int future = first(in, 0);
while (inPos < inLen - 4) {
byte p2 = in[inPos + 2];
// next
future = (future << 8) + (p2 & 255);
int off = hash(future);
int ref = hashTab[off];
hashTab[off] = inPos;
// if (ref < inPos
// && ref > 0
// && (off = inPos - ref - 1) < MAX_OFF
// && in[ref + 2] == p2
// && (((in[ref] & 255) << 8) | (in[ref + 1] & 255)) ==
// ((future >> 8) & 0xffff)) {
if (ref < inPos
&& ref > 0
&& (off = inPos - ref - 1) < MAX_OFF
&& in[ref + 2] == p2
&& in[ref + 1] == (byte) (future >> 8)
&& in[ref] == (byte) (future >> 16)) {
// match
int maxLen = inLen - inPos - 2;
if (maxLen > MAX_REF) {
maxLen = MAX_REF;
}
if (literals == 0) {
// multiple back-references,
// so there is no literal run control byte
outPos--;
} else {
// set the control byte at the start of the literal run
// to store the number of literals
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
}
int len = 3;
while (len < maxLen && in[ref + len] == in[inPos + len]) {
len++;
}
len -= 2;
if (len < 7) {
out[outPos++] = (byte) ((off >> 8) + (len << 5));
} else {
out[outPos++] = (byte) ((off >> 8) + (7 << 5));
out[outPos++] = (byte) (len - 7);
}
out[outPos++] = (byte) off;
// move one byte forward to allow for a literal run control byte
outPos++;
inPos += len;
// rebuild the future, and store the last bytes to the
// hashtable. Storing hashes of the last bytes in back-reference
// improves the compression ratio and only reduces speed
// slightly.
future = first(in, inPos);
future = next(future, in, inPos);
hashTab[hash(future)] = inPos++;
future = next(future, in, inPos);
hashTab[hash(future)] = inPos++;
} else {
// copy one byte from input to output as part of literal
out[outPos++] = in[inPos++];
literals++;
// at the end of this literal chunk, write the length
// to the control byte and start a new chunk
if (literals == MAX_LITERAL) {
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
// move ahead one byte to allow for the
// literal run control byte
outPos++;
}
}
}
// write the remaining few bytes as literals
while (inPos < inLen) {
out[outPos++] = in[inPos++];
literals++;
if (literals == MAX_LITERAL) {
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
outPos++;
}
}
// writes the final literal run length to the control byte
out[outPos - literals - 1] = (byte) (literals - 1);
if (literals == 0) {
outPos--;
}
return outPos;
}
/**
* Compress a number of bytes.
*
* @param in the input data
* @param inPos the offset at the input buffer
* @param out the output area
* @param outPos the offset at the output array
* @return the end position
*/
public int compress(ByteBuffer in, int inPos, byte[] out, int outPos) {
int inLen = in.capacity() - inPos;
if (cachedHashTable == null) {
cachedHashTable = new int[HASH_SIZE];
}
int[] hashTab = cachedHashTable;
int literals = 0;
outPos++;
int future = first(in, 0);
while (inPos < inLen - 4) {
byte p2 = in.get(inPos + 2);
// next
future = (future << 8) + (p2 & 255);
int off = hash(future);
int ref = hashTab[off];
hashTab[off] = inPos;
// if (ref < inPos
// && ref > 0
// && (off = inPos - ref - 1) < MAX_OFF
// && in[ref + 2] == p2
// && (((in[ref] & 255) << 8) | (in[ref + 1] & 255)) ==
// ((future >> 8) & 0xffff)) {
if (ref < inPos
&& ref > 0
&& (off = inPos - ref - 1) < MAX_OFF
&& in.get(ref + 2) == p2
&& in.get(ref + 1) == (byte) (future >> 8)
&& in.get(ref) == (byte) (future >> 16)) {
// match
int maxLen = inLen - inPos - 2;
if (maxLen > MAX_REF) {
maxLen = MAX_REF;
}
if (literals == 0) {
// multiple back-references,
// so there is no literal run control byte
outPos--;
} else {
// set the control byte at the start of the literal run
// to store the number of literals
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
}
int len = 3;
while (len < maxLen && in.get(ref + len) == in.get(inPos + len)) {
len++;
}
len -= 2;
if (len < 7) {
out[outPos++] = (byte) ((off >> 8) + (len << 5));
} else {
out[outPos++] = (byte) ((off >> 8) + (7 << 5));
out[outPos++] = (byte) (len - 7);
}
out[outPos++] = (byte) off;
// move one byte forward to allow for a literal run control byte
outPos++;
inPos += len;
// rebuild the future, and store the last bytes to the
// hashtable. Storing hashes of the last bytes in back-reference
// improves the compression ratio and only reduces speed
// slightly.
future = first(in, inPos);
future = next(future, in, inPos);
hashTab[hash(future)] = inPos++;
future = next(future, in, inPos);
hashTab[hash(future)] = inPos++;
} else {
// copy one byte from input to output as part of literal
out[outPos++] = in.get(inPos++);
literals++;
// at the end of this literal chunk, write the length
// to the control byte and start a new chunk
if (literals == MAX_LITERAL) {
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
// move ahead one byte to allow for the
// literal run control byte
outPos++;
}
}
}
// write the remaining few bytes as literals
while (inPos < inLen) {
out[outPos++] = in.get(inPos++);
literals++;
if (literals == MAX_LITERAL) {
out[outPos - literals - 1] = (byte) (literals - 1);
literals = 0;
outPos++;
}
}
// writes the final literal run length to the control byte
out[outPos - literals - 1] = (byte) (literals - 1);
if (literals == 0) {
outPos--;
}
return outPos;
}
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos,
int outLen) {
// if ((inPos | outPos | outLen) < 0) {
if (inPos < 0 || outPos < 0 || outLen < 0) {
throw new IllegalArgumentException();
}
do {
int ctrl = in[inPos++] & 255;
if (ctrl < MAX_LITERAL) {
// literal run of length = ctrl + 1,
ctrl++;
// copy to output and move forward this many bytes
// while (ctrl-- > 0) {
// out[outPos++] = in[inPos++];
// }
System.arraycopy(in, inPos, out, outPos, ctrl);
outPos += ctrl;
inPos += ctrl;
} else {
// back reference
// the highest 3 bits are the match length
int len = ctrl >> 5;
// if the length is maxed, add the next byte to the length
if (len == 7) {
len += in[inPos++] & 255;
}
// minimum back-reference is 3 bytes,
// so 2 was subtracted before storing size
len += 2;
// ctrl is now the offset for a back-reference...
// the logical AND operation removes the length bits
ctrl = -((ctrl & 0x1f) << 8) - 1;
// the next byte augments/increases the offset
ctrl -= in[inPos++] & 255;
// copy the back-reference bytes from the given
// location in output to current position
ctrl += outPos;
if (outPos + len >= out.length) {
// reduce array bounds checking
throw new ArrayIndexOutOfBoundsException();
}
for (int i = 0; i < len; i++) {
out[outPos++] = out[ctrl++];
}
}
} while (outPos < outLen);
}
/**
* Expand a number of compressed bytes.
*
* @param in the compressed data
* @param out the output area
*/
public static void expand(ByteBuffer in, ByteBuffer out) {
do {
int ctrl = in.get() & 255;
if (ctrl < MAX_LITERAL) {
// literal run of length = ctrl + 1,
ctrl++;
// copy to output and move forward this many bytes
// (maybe slice would be faster)
for (int i = 0; i < ctrl; i++) {
out.put(in.get());
}
} else {
// back reference
// the highest 3 bits are the match length
int len = ctrl >> 5;
// if the length is maxed, add the next byte to the length
if (len == 7) {
len += in.get() & 255;
}
// minimum back-reference is 3 bytes,
// so 2 was subtracted before storing size
len += 2;
// ctrl is now the offset for a back-reference...
// the logical AND operation removes the length bits
ctrl = -((ctrl & 0x1f) << 8) - 1;
// the next byte augments/increases the offset
ctrl -= in.get() & 255;
// copy the back-reference bytes from the given
// location in output to current position
// (maybe slice would be faster)
ctrl += out.position();
for (int i = 0; i < len; i++) {
out.put(out.get(ctrl++));
}
}
} while (out.position() < out.capacity());
}
@Override
public int getAlgorithm() {
return Compressor.LZF;
}
}
|
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/CompressNo.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;
/**
* This class implements a data compression algorithm that does in fact not
* compress. This is useful if the data can not be compressed because it is
* encrypted, already compressed, or random.
*/
public class CompressNo implements Compressor {
@Override
public int getAlgorithm() {
return Compressor.NO;
}
@Override
public void setOptions(String options) {
// nothing to do
}
@Override
public int compress(byte[] in, int inLen, byte[] out, int outPos) {
System.arraycopy(in, 0, out, outPos, inLen);
return outPos + inLen;
}
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos,
int outLen) {
System.arraycopy(in, inPos, out, outPos, outLen);
}
}
|
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/Compressor.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;
/**
* Each data compression algorithm must implement this interface.
*/
public interface Compressor {
/**
* No compression is used.
*/
int NO = 0;
/**
* The LZF compression algorithm is used
*/
int LZF = 1;
/**
* The DEFLATE compression algorithm is used.
*/
int DEFLATE = 2;
/**
* Get the compression algorithm type.
*
* @return the type
*/
int getAlgorithm();
/**
* Compress a number of bytes.
*
* @param in the input data
* @param inLen the number of bytes to compress
* @param out the output area
* @param outPos the offset at the output array
* @return the end position
*/
int compress(byte[] in, int inLen, byte[] out, int outPos);
/**
* Expand a number of compressed bytes.
*
* @param in the compressed data
* @param inPos the offset at the input array
* @param inLen the number of bytes to read
* @param out the output area
* @param outPos the offset at the output array
* @param outLen the size of the uncompressed data
*/
void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos,
int outLen);
/**
* Set the compression options. This may include settings for
* higher performance but less compression.
*
* @param options the options
*/
void setOptions(String options);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.