use of org.h2.schema.Sequence in project h2database by h2database.
the class Function method getValueWithArgs.
private Value getValueWithArgs(Session session, Expression[] args) {
Value[] values = new Value[args.length];
if (info.nullIfParameterIsNull) {
for (int i = 0; i < args.length; i++) {
Expression e = args[i];
Value v = e.getValue(session);
if (v == ValueNull.INSTANCE) {
return ValueNull.INSTANCE;
}
values[i] = v;
}
}
Value v0 = getNullOrValue(session, args, values, 0);
Value resultSimple = getSimpleValue(session, v0, args, values);
if (resultSimple != null) {
return resultSimple;
}
Value v1 = getNullOrValue(session, args, values, 1);
Value v2 = getNullOrValue(session, args, values, 2);
Value v3 = getNullOrValue(session, args, values, 3);
Value v4 = getNullOrValue(session, args, values, 4);
Value v5 = getNullOrValue(session, args, values, 5);
Value result;
switch(info.type) {
case ATAN2:
result = ValueDouble.get(Math.atan2(v0.getDouble(), v1.getDouble()));
break;
case BITAND:
result = ValueLong.get(v0.getLong() & v1.getLong());
break;
case BITGET:
result = ValueBoolean.get((v0.getLong() & (1L << v1.getInt())) != 0);
break;
case BITOR:
result = ValueLong.get(v0.getLong() | v1.getLong());
break;
case BITXOR:
result = ValueLong.get(v0.getLong() ^ v1.getLong());
break;
case MOD:
{
long x = v1.getLong();
if (x == 0) {
throw DbException.get(ErrorCode.DIVISION_BY_ZERO_1, getSQL());
}
result = ValueLong.get(v0.getLong() % x);
break;
}
case POWER:
result = ValueDouble.get(Math.pow(v0.getDouble(), v1.getDouble()));
break;
case ROUND:
{
double f = v1 == null ? 1. : Math.pow(10., v1.getDouble());
double middleResult = v0.getDouble() * f;
int oneWithSymbol = middleResult > 0 ? 1 : -1;
result = ValueDouble.get(Math.round(Math.abs(middleResult)) / f * oneWithSymbol);
break;
}
case TRUNCATE:
{
if (v0.getType() == Value.TIMESTAMP) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueTimestamp) v0).getDateValue(), 0);
} else if (v0.getType() == Value.DATE) {
result = ValueTimestamp.fromDateValueAndNanos(((ValueDate) v0).getDateValue(), 0);
} else if (v0.getType() == Value.TIMESTAMP_TZ) {
ValueTimestampTimeZone ts = (ValueTimestampTimeZone) v0;
result = ValueTimestampTimeZone.fromDateValueAndNanos(ts.getDateValue(), 0, ts.getTimeZoneOffsetMins());
} else if (v0.getType() == Value.STRING) {
ValueTimestamp ts = ValueTimestamp.parse(v0.getString(), session.getDatabase().getMode());
result = ValueTimestamp.fromDateValueAndNanos(ts.getDateValue(), 0);
} else {
double d = v0.getDouble();
int p = v1 == null ? 0 : v1.getInt();
double f = Math.pow(10., p);
double g = d * f;
result = ValueDouble.get(((d < 0) ? Math.ceil(g) : Math.floor(g)) / f);
}
break;
}
case HASH:
result = ValueBytes.getNoCopy(getHash(v0.getString(), v1.getBytesNoCopy(), v2.getInt()));
break;
case ENCRYPT:
result = ValueBytes.getNoCopy(encrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case DECRYPT:
result = ValueBytes.getNoCopy(decrypt(v0.getString(), v1.getBytesNoCopy(), v2.getBytesNoCopy()));
break;
case COMPRESS:
{
String algorithm = null;
if (v1 != null) {
algorithm = v1.getString();
}
result = ValueBytes.getNoCopy(CompressTool.getInstance().compress(v0.getBytesNoCopy(), algorithm));
break;
}
case DIFFERENCE:
result = ValueInt.get(getDifference(v0.getString(), v1.getString()));
break;
case INSERT:
{
if (v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE) {
result = v1;
} else {
result = ValueString.get(insert(v0.getString(), v1.getInt(), v2.getInt(), v3.getString()), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case LEFT:
result = ValueString.get(left(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
break;
case LOCATE:
{
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v0.getString(), v1.getString(), start));
break;
}
case INSTR:
{
int start = v2 == null ? 0 : v2.getInt();
result = ValueInt.get(locate(v1.getString(), v0.getString(), start));
break;
}
case REPEAT:
{
int count = Math.max(0, v1.getInt());
result = ValueString.get(repeat(v0.getString(), count), database.getMode().treatEmptyStringsAsNull);
break;
}
case REPLACE:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE || v2 == ValueNull.INSTANCE && database.getMode().getEnum() != Mode.ModeEnum.Oracle) {
result = ValueNull.INSTANCE;
} else {
String s0 = v0.getString();
String s1 = v1.getString();
String s2 = (v2 == null) ? "" : v2.getString();
if (s2 == null) {
s2 = "";
}
result = ValueString.get(StringUtils.replaceAll(s0, s1, s2), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case RIGHT:
result = ValueString.get(right(v0.getString(), v1.getInt()), database.getMode().treatEmptyStringsAsNull);
break;
case LTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), true, false, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case TRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), true, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case RTRIM:
result = ValueString.get(StringUtils.trim(v0.getString(), false, true, v1 == null ? " " : v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case SUBSTR:
case SUBSTRING:
{
String s = v0.getString();
int offset = v1.getInt();
if (offset < 0) {
offset = s.length() + offset + 1;
}
int length = v2 == null ? s.length() : v2.getInt();
result = ValueString.get(substring(s, offset, length), database.getMode().treatEmptyStringsAsNull);
break;
}
case POSITION:
result = ValueInt.get(locate(v0.getString(), v1.getString(), 0));
break;
case XMLATTR:
result = ValueString.get(StringUtils.xmlAttr(v0.getString(), v1.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case XMLNODE:
{
String attr = v1 == null ? null : v1 == ValueNull.INSTANCE ? null : v1.getString();
String content = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
boolean indent = v3 == null ? true : v3.getBoolean();
result = ValueString.get(StringUtils.xmlNode(v0.getString(), attr, content, indent), database.getMode().treatEmptyStringsAsNull);
break;
}
case REGEXP_REPLACE:
{
String regexp = v1.getString();
String replacement = v2.getString();
if (database.getMode().regexpReplaceBackslashReferences) {
if ((replacement.indexOf('\\') >= 0) || (replacement.indexOf('$') >= 0)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < replacement.length(); i++) {
char c = replacement.charAt(i);
if (c == '$') {
sb.append('\\');
} else if (c == '\\' && ++i < replacement.length()) {
c = replacement.charAt(i);
sb.append(c >= '0' && c <= '9' ? '$' : '\\');
}
sb.append(c);
}
replacement = sb.toString();
}
}
String regexpMode = v3 == null || v3.getString() == null ? "" : v3.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueString.get(Pattern.compile(regexp, flags).matcher(v0.getString()).replaceAll(replacement), database.getMode().treatEmptyStringsAsNull);
} catch (StringIndexOutOfBoundsException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
} catch (IllegalArgumentException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, replacement);
}
break;
}
case RPAD:
result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), true), database.getMode().treatEmptyStringsAsNull);
break;
case LPAD:
result = ValueString.get(StringUtils.pad(v0.getString(), v1.getInt(), v2 == null ? null : v2.getString(), false), database.getMode().treatEmptyStringsAsNull);
break;
case ORA_HASH:
result = ValueLong.get(oraHash(v0.getString(), v1 == null ? null : v1.getInt(), v2 == null ? null : v2.getInt()));
break;
case TO_CHAR:
switch(v0.getType()) {
case Value.TIME:
case Value.DATE:
case Value.TIMESTAMP:
case Value.TIMESTAMP_TZ:
result = ValueString.get(ToChar.toCharDateTime(v0, v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
break;
case Value.SHORT:
case Value.INT:
case Value.LONG:
case Value.DECIMAL:
case Value.DOUBLE:
case Value.FLOAT:
result = ValueString.get(ToChar.toChar(v0.getBigDecimal(), v1 == null ? null : v1.getString(), v2 == null ? null : v2.getString()), database.getMode().treatEmptyStringsAsNull);
break;
default:
result = ValueString.get(v0.getString(), database.getMode().treatEmptyStringsAsNull);
}
break;
case TO_DATE:
result = ToDateParser.toDate(v0.getString(), v1 == null ? null : v1.getString());
break;
case TO_TIMESTAMP:
result = ToDateParser.toTimestamp(v0.getString(), v1 == null ? null : v1.getString());
break;
case ADD_MONTHS:
result = DateTimeFunctions.dateadd("MONTH", v1.getInt(), v0);
break;
case TO_TIMESTAMP_TZ:
result = ToDateParser.toTimestampTz(v0.getString(), v1 == null ? null : v1.getString());
break;
case TRANSLATE:
{
String matching = v1.getString();
String replacement = v2.getString();
result = ValueString.get(translate(v0.getString(), matching, replacement), database.getMode().treatEmptyStringsAsNull);
break;
}
case H2VERSION:
result = ValueString.get(Constants.getVersion(), database.getMode().treatEmptyStringsAsNull);
break;
case DATE_ADD:
result = DateTimeFunctions.dateadd(v0.getString(), v1.getLong(), v2);
break;
case DATE_DIFF:
result = ValueLong.get(DateTimeFunctions.datediff(v0.getString(), v1, v2));
break;
case DATE_TRUNC:
result = DateTimeFunctions.truncateDate(v0.getString(), v1);
break;
case EXTRACT:
result = DateTimeFunctions.extract(v0.getString(), v1);
break;
case FORMATDATETIME:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
if (v0 instanceof ValueTimestampTimeZone) {
tz = DateTimeUtils.timeZoneNameFromOffsetMins(((ValueTimestampTimeZone) v0).getTimeZoneOffsetMins());
}
result = ValueString.get(DateTimeFunctions.formatDateTime(v0.getTimestamp(), v1.getString(), locale, tz), database.getMode().treatEmptyStringsAsNull);
}
break;
}
case PARSEDATETIME:
{
if (v0 == ValueNull.INSTANCE || v1 == ValueNull.INSTANCE) {
result = ValueNull.INSTANCE;
} else {
String locale = v2 == null ? null : v2 == ValueNull.INSTANCE ? null : v2.getString();
String tz = v3 == null ? null : v3 == ValueNull.INSTANCE ? null : v3.getString();
java.util.Date d = DateTimeFunctions.parseDateTime(v0.getString(), v1.getString(), locale, tz);
result = ValueTimestamp.fromMillis(d.getTime());
}
break;
}
case NULLIF:
result = database.areEqual(v0, v1) ? ValueNull.INSTANCE : v0;
break;
// system
case NEXTVAL:
{
Sequence sequence = getSequence(session, v0, v1);
SequenceValue value = new SequenceValue(sequence);
result = value.getValue(session);
break;
}
case CURRVAL:
{
Sequence sequence = getSequence(session, v0, v1);
result = ValueLong.get(sequence.getCurrentValue());
break;
}
case CSVREAD:
{
String fileName = v0.getString();
String columnList = v1 == null ? null : v1.getString();
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorRead = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
setCsvDelimiterEscape(csv, fieldSeparatorRead, fieldDelimiter, escapeCharacter);
csv.setNullString(nullString);
}
char fieldSeparator = csv.getFieldSeparatorRead();
String[] columns = StringUtils.arraySplit(columnList, fieldSeparator, true);
try {
result = ValueResultSet.get(csv.read(fileName, columns, charset));
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case LINK_SCHEMA:
{
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
ResultSet rs = LinkSchema.linkSchema(conn, v0.getString(), v1.getString(), v2.getString(), v3.getString(), v4.getString(), v5.getString());
result = ValueResultSet.get(rs);
break;
}
case CSVWRITE:
{
session.getUser().checkAdmin();
Connection conn = session.createConnection(false);
Csv csv = new Csv();
String options = v2 == null ? null : v2.getString();
String charset = null;
if (options != null && options.indexOf('=') >= 0) {
charset = csv.setOptions(options);
} else {
charset = options;
String fieldSeparatorWrite = v3 == null ? null : v3.getString();
String fieldDelimiter = v4 == null ? null : v4.getString();
String escapeCharacter = v5 == null ? null : v5.getString();
Value v6 = getNullOrValue(session, args, values, 6);
String nullString = v6 == null ? null : v6.getString();
Value v7 = getNullOrValue(session, args, values, 7);
String lineSeparator = v7 == null ? null : v7.getString();
setCsvDelimiterEscape(csv, fieldSeparatorWrite, fieldDelimiter, escapeCharacter);
csv.setNullString(nullString);
if (lineSeparator != null) {
csv.setLineSeparator(lineSeparator);
}
}
try {
int rows = csv.write(conn, v0.getString(), v1.getString(), charset);
result = ValueInt.get(rows);
} catch (SQLException e) {
throw DbException.convert(e);
}
break;
}
case SET:
{
Variable var = (Variable) args[0];
session.setVariable(var.getName(), v1);
result = v1;
break;
}
case FILE_READ:
{
session.getUser().checkAdmin();
String fileName = v0.getString();
boolean blob = args.length == 1;
try {
long fileLength = FileUtils.size(fileName);
final InputStream in = FileUtils.newInputStream(fileName);
try {
if (blob) {
result = database.getLobStorage().createBlob(in, fileLength);
} else {
Reader reader;
if (v1 == ValueNull.INSTANCE) {
reader = new InputStreamReader(in);
} else {
reader = new InputStreamReader(in, v1.getString());
}
result = database.getLobStorage().createClob(reader, fileLength);
}
} finally {
IOUtils.closeSilently(in);
}
session.addTemporaryLob(result);
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case FILE_WRITE:
{
session.getUser().checkAdmin();
result = ValueNull.INSTANCE;
String fileName = v1.getString();
try {
FileOutputStream fileOutputStream = new FileOutputStream(fileName);
try (InputStream in = v0.getInputStream()) {
result = ValueLong.get(IOUtils.copyAndClose(in, fileOutputStream));
}
} catch (IOException e) {
throw DbException.convertIOException(e, fileName);
}
break;
}
case TRUNCATE_VALUE:
{
result = v0.convertPrecision(v1.getLong(), v2.getBoolean());
break;
}
case XMLTEXT:
if (v1 == null) {
result = ValueString.get(StringUtils.xmlText(v0.getString()), database.getMode().treatEmptyStringsAsNull);
} else {
result = ValueString.get(StringUtils.xmlText(v0.getString(), v1.getBoolean()), database.getMode().treatEmptyStringsAsNull);
}
break;
case REGEXP_LIKE:
{
String regexp = v1.getString();
String regexpMode = v2 == null || v2.getString() == null ? "" : v2.getString();
int flags = makeRegexpFlags(regexpMode);
try {
result = ValueBoolean.get(Pattern.compile(regexp, flags).matcher(v0.getString()).find());
} catch (PatternSyntaxException e) {
throw DbException.get(ErrorCode.LIKE_ESCAPE_ERROR_1, e, regexp);
}
break;
}
case VALUES:
result = session.getVariable(args[0].getSchemaName() + "." + args[0].getTableName() + "." + args[0].getColumnName());
break;
case SIGNAL:
{
String sqlState = v0.getString();
if (sqlState.startsWith("00") || !SIGNAL_PATTERN.matcher(sqlState).matches()) {
throw DbException.getInvalidValueException("SQLSTATE", sqlState);
}
String msgText = v1.getString();
throw DbException.fromUser(sqlState, msgText);
}
default:
throw DbException.throwInternalError("type=" + info.type);
}
return result;
}
use of org.h2.schema.Sequence in project h2database by h2database.
the class WebApp method tables.
private String tables() {
DbContents contents = session.getContents();
boolean isH2 = false;
try {
String url = (String) session.get("url");
Connection conn = session.getConnection();
contents.readContents(url, conn);
session.loadBnf();
isH2 = contents.isH2();
StringBuilder buff = new StringBuilder().append("setNode(0, 0, 0, 'database', '").append(PageParser.escapeJavaScript(url)).append("', null);\n");
int treeIndex = 1;
DbSchema defaultSchema = contents.getDefaultSchema();
treeIndex = addTablesAndViews(defaultSchema, true, buff, treeIndex);
DbSchema[] schemas = contents.getSchemas();
for (DbSchema schema : schemas) {
if (schema == defaultSchema || schema == null) {
continue;
}
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'folder', '").append(PageParser.escapeJavaScript(schema.name)).append("', null);\n");
treeIndex++;
treeIndex = addTablesAndViews(schema, false, buff, treeIndex);
}
if (isH2) {
try (Statement stat = conn.createStatement()) {
ResultSet rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.SEQUENCES ORDER BY SEQUENCE_NAME");
for (int i = 0; rs.next(); i++) {
if (i == 0) {
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'sequences', '${text.tree.sequences}', null);\n");
treeIndex++;
}
String name = rs.getString("SEQUENCE_NAME");
String current = rs.getString("CURRENT_VALUE");
String increment = rs.getString("INCREMENT");
buff.append("setNode(").append(treeIndex).append(", 1, 1, 'sequence', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
treeIndex++;
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.current}: ").append(PageParser.escapeJavaScript(current)).append("', null);\n");
treeIndex++;
if (!"1".equals(increment)) {
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.increment}: ").append(PageParser.escapeJavaScript(increment)).append("', null);\n");
treeIndex++;
}
}
rs.close();
rs = stat.executeQuery("SELECT * FROM " + "INFORMATION_SCHEMA.USERS ORDER BY NAME");
for (int i = 0; rs.next(); i++) {
if (i == 0) {
buff.append("setNode(").append(treeIndex).append(", 0, 1, 'users', '${text.tree.users}', null);\n");
treeIndex++;
}
String name = rs.getString("NAME");
String admin = rs.getString("ADMIN");
buff.append("setNode(").append(treeIndex).append(", 1, 1, 'user', '").append(PageParser.escapeJavaScript(name)).append("', null);\n");
treeIndex++;
if (admin.equalsIgnoreCase("TRUE")) {
buff.append("setNode(").append(treeIndex).append(", 2, 2, 'type', '${text.tree.admin}', null);\n");
treeIndex++;
}
}
rs.close();
}
}
DatabaseMetaData meta = session.getMetaData();
String version = meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion();
buff.append("setNode(").append(treeIndex).append(", 0, 0, 'info', '").append(PageParser.escapeJavaScript(version)).append("', null);\n").append("refreshQueryTables();");
session.put("tree", buff.toString());
} catch (Exception e) {
session.put("tree", "");
session.put("error", getStackTrace(0, e, isH2));
}
return "tables.jsp";
}
use of org.h2.schema.Sequence in project h2database by h2database.
the class MetaTable method generateRows.
/**
* Generate the data for the given metadata table using the given first and
* last row filters.
*
* @param session the session
* @param first the first row to return
* @param last the last row to return
* @return the generated rows
*/
public ArrayList<Row> generateRows(Session session, SearchRow first, SearchRow last) {
Value indexFrom = null, indexTo = null;
if (indexColumn >= 0) {
if (first != null) {
indexFrom = first.getValue(indexColumn);
}
if (last != null) {
indexTo = last.getValue(indexColumn);
}
}
ArrayList<Row> rows = New.arrayList();
String catalog = identifier(database.getShortName());
boolean admin = session.getUser().isAdmin();
switch(type) {
case TABLES:
{
for (Table table : getAllTables(session)) {
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
if (hideTable(table, session)) {
continue;
}
String storageType;
if (table.isTemporary()) {
if (table.isGlobalTemporary()) {
storageType = "GLOBAL TEMPORARY";
} else {
storageType = "LOCAL TEMPORARY";
}
} else {
storageType = table.isPersistIndexes() ? "CACHED" : "MEMORY";
}
String sql = table.getCreateSQL();
if (!admin) {
if (sql != null && sql.contains(JdbcSQLException.HIDE_SQL)) {
// hide the password of linked tables
sql = "-";
}
}
add(rows, // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // TABLE_TYPE
table.getTableType().toString(), // STORAGE_TYPE
storageType, // SQL
sql, // REMARKS
replaceNullWithEmpty(table.getComment()), // LAST_MODIFICATION
"" + table.getMaxDataModificationId(), // ID
"" + table.getId(), // TYPE_NAME
null, // TABLE_CLASS
table.getClass().getName(), // ROW_COUNT_ESTIMATE
"" + table.getRowCountApproximation());
}
break;
}
case COLUMNS:
{
// reduce the number of tables to scan - makes some metadata queries
// 10x faster
final ArrayList<Table> tablesToList;
if (indexFrom != null && indexFrom.equals(indexTo)) {
String tableName = identifier(indexFrom.getString());
tablesToList = getTablesByName(session, tableName);
} else {
tablesToList = getAllTables(session);
}
for (Table table : tablesToList) {
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
if (hideTable(table, session)) {
continue;
}
Column[] cols = table.getColumns();
String collation = database.getCompareMode().getName();
for (int j = 0; j < cols.length; j++) {
Column c = cols[j];
Sequence sequence = c.getSequence();
add(rows, // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // COLUMN_NAME
identifier(c.getName()), // ORDINAL_POSITION
String.valueOf(j + 1), // COLUMN_DEFAULT
c.getDefaultSQL(), // IS_NULLABLE
c.isNullable() ? "YES" : "NO", // DATA_TYPE
"" + DataType.convertTypeToSQLType(c.getType()), // CHARACTER_MAXIMUM_LENGTH
"" + c.getPrecisionAsInt(), // CHARACTER_OCTET_LENGTH
"" + c.getPrecisionAsInt(), // NUMERIC_PRECISION
"" + c.getPrecisionAsInt(), // NUMERIC_PRECISION_RADIX
"10", // NUMERIC_SCALE
"" + c.getScale(), // CHARACTER_SET_NAME
CHARACTER_SET_NAME, // COLLATION_NAME
collation, // TYPE_NAME
identifier(DataType.getDataType(c.getType()).name), // NULLABLE
"" + (c.isNullable() ? DatabaseMetaData.columnNullable : DatabaseMetaData.columnNoNulls), // IS_COMPUTED
"" + (c.getComputed() ? "TRUE" : "FALSE"), // SELECTIVITY
"" + (c.getSelectivity()), // CHECK_CONSTRAINT
c.getCheckConstraintSQL(session, c.getName()), // SEQUENCE_NAME
sequence == null ? null : sequence.getName(), // REMARKS
replaceNullWithEmpty(c.getComment()), // SOURCE_DATA_TYPE
null, // COLUMN_TYPE
c.getCreateSQLWithoutName(), // COLUMN_ON_UPDATE
c.getOnUpdateSQL());
}
}
break;
}
case INDEXES:
{
// reduce the number of tables to scan - makes some metadata queries
// 10x faster
final ArrayList<Table> tablesToList;
if (indexFrom != null && indexFrom.equals(indexTo)) {
String tableName = identifier(indexFrom.getString());
tablesToList = getTablesByName(session, tableName);
} else {
tablesToList = getAllTables(session);
}
for (Table table : tablesToList) {
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
if (hideTable(table, session)) {
continue;
}
ArrayList<Index> indexes = table.getIndexes();
ArrayList<Constraint> constraints = table.getConstraints();
for (int j = 0; indexes != null && j < indexes.size(); j++) {
Index index = indexes.get(j);
if (index.getCreateSQL() == null) {
continue;
}
String constraintName = null;
for (int k = 0; constraints != null && k < constraints.size(); k++) {
Constraint constraint = constraints.get(k);
if (constraint.usesIndex(index)) {
if (index.getIndexType().isPrimaryKey()) {
if (constraint.getConstraintType() == Constraint.Type.PRIMARY_KEY) {
constraintName = constraint.getName();
}
} else {
constraintName = constraint.getName();
}
}
}
IndexColumn[] cols = index.getIndexColumns();
String indexClass;
if (index instanceof MultiVersionIndex) {
indexClass = ((MultiVersionIndex) index).getBaseIndex().getClass().getName();
} else {
indexClass = index.getClass().getName();
}
for (int k = 0; k < cols.length; k++) {
IndexColumn idxCol = cols[k];
Column column = idxCol.column;
add(rows, // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // NON_UNIQUE
index.getIndexType().isUnique() ? "FALSE" : "TRUE", // INDEX_NAME
identifier(index.getName()), // ORDINAL_POSITION
"" + (k + 1), // COLUMN_NAME
identifier(column.getName()), // CARDINALITY
"0", // PRIMARY_KEY
index.getIndexType().isPrimaryKey() ? "TRUE" : "FALSE", // INDEX_TYPE_NAME
index.getIndexType().getSQL(), // IS_GENERATED
index.getIndexType().getBelongsToConstraint() ? "TRUE" : "FALSE", // INDEX_TYPE
"" + DatabaseMetaData.tableIndexOther, // ASC_OR_DESC
(idxCol.sortType & SortOrder.DESCENDING) != 0 ? "D" : "A", // PAGES
"0", // FILTER_CONDITION
"", // REMARKS
replaceNullWithEmpty(index.getComment()), // SQL
index.getCreateSQL(), // ID
"" + index.getId(), // SORT_TYPE
"" + idxCol.sortType, // CONSTRAINT_NAME
constraintName, // INDEX_CLASS
indexClass, // AFFINITY
index.getIndexType().isAffinity() ? "TRUE" : "FALSE");
}
}
}
break;
}
case TABLE_TYPES:
{
add(rows, TableType.TABLE.toString());
add(rows, TableType.TABLE_LINK.toString());
add(rows, TableType.SYSTEM_TABLE.toString());
add(rows, TableType.VIEW.toString());
add(rows, TableType.EXTERNAL_TABLE_ENGINE.toString());
break;
}
case CATALOGS:
{
add(rows, catalog);
break;
}
case SETTINGS:
{
for (Setting s : database.getAllSettings()) {
String value = s.getStringValue();
if (value == null) {
value = "" + s.getIntValue();
}
add(rows, identifier(s.getName()), value);
}
add(rows, "info.BUILD_ID", "" + Constants.BUILD_ID);
add(rows, "info.VERSION_MAJOR", "" + Constants.VERSION_MAJOR);
add(rows, "info.VERSION_MINOR", "" + Constants.VERSION_MINOR);
add(rows, "info.VERSION", "" + Constants.getFullVersion());
if (admin) {
String[] settings = { "java.runtime.version", "java.vm.name", "java.vendor", "os.name", "os.arch", "os.version", "sun.os.patch.level", "file.separator", "path.separator", "line.separator", "user.country", "user.language", "user.variant", "file.encoding" };
for (String s : settings) {
add(rows, "property." + s, Utils.getProperty(s, ""));
}
}
add(rows, "EXCLUSIVE", database.getExclusiveSession() == null ? "FALSE" : "TRUE");
add(rows, "MODE", database.getMode().getName());
add(rows, "MULTI_THREADED", database.isMultiThreaded() ? "1" : "0");
add(rows, "MVCC", database.isMultiVersion() ? "TRUE" : "FALSE");
add(rows, "QUERY_TIMEOUT", "" + session.getQueryTimeout());
add(rows, "RETENTION_TIME", "" + database.getRetentionTime());
add(rows, "LOG", "" + database.getLogMode());
// database settings
ArrayList<String> settingNames = New.arrayList();
HashMap<String, String> s = database.getSettings().getSettings();
settingNames.addAll(s.keySet());
Collections.sort(settingNames);
for (String k : settingNames) {
add(rows, k, s.get(k));
}
if (database.isPersistent()) {
PageStore store = database.getPageStore();
if (store != null) {
add(rows, "info.FILE_WRITE_TOTAL", "" + store.getWriteCountTotal());
add(rows, "info.FILE_WRITE", "" + store.getWriteCount());
add(rows, "info.FILE_READ", "" + store.getReadCount());
add(rows, "info.PAGE_COUNT", "" + store.getPageCount());
add(rows, "info.PAGE_SIZE", "" + store.getPageSize());
add(rows, "info.CACHE_MAX_SIZE", "" + store.getCache().getMaxMemory());
add(rows, "info.CACHE_SIZE", "" + store.getCache().getMemory());
}
Store mvStore = database.getMvStore();
if (mvStore != null) {
FileStore fs = mvStore.getStore().getFileStore();
add(rows, "info.FILE_WRITE", "" + fs.getWriteCount());
add(rows, "info.FILE_READ", "" + fs.getReadCount());
long size;
try {
size = fs.getFile().size();
} catch (IOException e) {
throw DbException.convertIOException(e, "Can not get size");
}
int pageSize = 4 * 1024;
long pageCount = size / pageSize;
add(rows, "info.PAGE_COUNT", "" + pageCount);
add(rows, "info.PAGE_SIZE", "" + pageSize);
add(rows, "info.CACHE_MAX_SIZE", "" + mvStore.getStore().getCacheSize());
add(rows, "info.CACHE_SIZE", "" + mvStore.getStore().getCacheSizeUsed());
}
}
break;
}
case TYPE_INFO:
{
for (DataType t : DataType.getTypes()) {
if (t.hidden || t.sqlType == Value.NULL) {
continue;
}
add(rows, // TYPE_NAME
t.name, // DATA_TYPE
String.valueOf(t.sqlType), // PRECISION
String.valueOf(MathUtils.convertLongToInt(t.maxPrecision)), // PREFIX
t.prefix, // SUFFIX
t.suffix, // PARAMS
t.params, // AUTO_INCREMENT
String.valueOf(t.autoIncrement), // MINIMUM_SCALE
String.valueOf(t.minScale), // MAXIMUM_SCALE
String.valueOf(t.maxScale), // RADIX
t.decimal ? "10" : null, // POS
String.valueOf(t.sqlTypePos), // CASE_SENSITIVE
String.valueOf(t.caseSensitive), // NULLABLE
"" + DatabaseMetaData.typeNullable, // SEARCHABLE
"" + DatabaseMetaData.typeSearchable);
}
break;
}
case HELP:
{
String resource = "/org/h2/res/help.csv";
try {
byte[] data = Utils.getResource(resource);
Reader reader = new InputStreamReader(new ByteArrayInputStream(data));
Csv csv = new Csv();
csv.setLineCommentCharacter('#');
ResultSet rs = csv.read(reader, null);
for (int i = 0; rs.next(); i++) {
add(rows, // ID
String.valueOf(i), // SECTION
rs.getString(1).trim(), // TOPIC
rs.getString(2).trim(), // SYNTAX
rs.getString(3).trim(), // TEXT
rs.getString(4).trim());
}
} catch (Exception e) {
throw DbException.convert(e);
}
break;
}
case SEQUENCES:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.SEQUENCE)) {
Sequence s = (Sequence) obj;
add(rows, // SEQUENCE_CATALOG
catalog, // SEQUENCE_SCHEMA
identifier(s.getSchema().getName()), // SEQUENCE_NAME
identifier(s.getName()), // CURRENT_VALUE
String.valueOf(s.getCurrentValue()), // INCREMENT
String.valueOf(s.getIncrement()), // IS_GENERATED
s.getBelongsToTable() ? "TRUE" : "FALSE", // REMARKS
replaceNullWithEmpty(s.getComment()), // CACHE
String.valueOf(s.getCacheSize()), // MIN_VALUE
String.valueOf(s.getMinValue()), // MAX_VALUE
String.valueOf(s.getMaxValue()), // IS_CYCLE
s.getCycle() ? "TRUE" : "FALSE", // ID
"" + s.getId());
}
break;
}
case USERS:
{
for (User u : database.getAllUsers()) {
if (admin || session.getUser() == u) {
add(rows, // NAME
identifier(u.getName()), // ADMIN
String.valueOf(u.isAdmin()), // REMARKS
replaceNullWithEmpty(u.getComment()), // ID
"" + u.getId());
}
}
break;
}
case ROLES:
{
for (Role r : database.getAllRoles()) {
if (admin || session.getUser().isRoleGranted(r)) {
add(rows, // NAME
identifier(r.getName()), // REMARKS
replaceNullWithEmpty(r.getComment()), // ID
"" + r.getId());
}
}
break;
}
case RIGHTS:
{
if (admin) {
for (Right r : database.getAllRights()) {
Role role = r.getGrantedRole();
DbObject grantee = r.getGrantee();
String rightType = grantee.getType() == DbObject.USER ? "USER" : "ROLE";
if (role == null) {
DbObject object = r.getGrantedObject();
Schema schema = null;
Table table = null;
if (object != null) {
if (object instanceof Schema) {
schema = (Schema) object;
} else if (object instanceof Table) {
table = (Table) object;
schema = table.getSchema();
}
}
String tableName = (table != null) ? identifier(table.getName()) : "";
String schemaName = (schema != null) ? identifier(schema.getName()) : "";
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
add(rows, // GRANTEE
identifier(grantee.getName()), // GRANTEETYPE
rightType, // GRANTEDROLE
"", // RIGHTS
r.getRights(), // TABLE_SCHEMA
schemaName, // TABLE_NAME
tableName, // ID
"" + r.getId());
} else {
add(rows, // GRANTEE
identifier(grantee.getName()), // GRANTEETYPE
rightType, // GRANTEDROLE
identifier(role.getName()), // RIGHTS
"", // TABLE_SCHEMA
"", // TABLE_NAME
"", // ID
"" + r.getId());
}
}
}
break;
}
case FUNCTION_ALIASES:
{
for (SchemaObject aliasAsSchemaObject : database.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
FunctionAlias alias = (FunctionAlias) aliasAsSchemaObject;
JavaMethod[] methods;
try {
methods = alias.getJavaMethods();
} catch (DbException e) {
methods = new JavaMethod[0];
}
for (FunctionAlias.JavaMethod method : methods) {
int returnsResult = method.getDataType() == Value.NULL ? DatabaseMetaData.procedureNoResult : DatabaseMetaData.procedureReturnsResult;
add(rows, // ALIAS_CATALOG
catalog, // ALIAS_SCHEMA
alias.getSchema().getName(), // ALIAS_NAME
identifier(alias.getName()), // JAVA_CLASS
alias.getJavaClassName(), // JAVA_METHOD
alias.getJavaMethodName(), // DATA_TYPE
"" + DataType.convertTypeToSQLType(method.getDataType()), // TYPE_NAME
DataType.getDataType(method.getDataType()).name, // COLUMN_COUNT INT
"" + method.getParameterCount(), // RETURNS_RESULT SMALLINT
"" + returnsResult, // REMARKS
replaceNullWithEmpty(alias.getComment()), // ID
"" + alias.getId(), // SOURCE
alias.getSource());
}
}
for (UserAggregate agg : database.getAllAggregates()) {
int returnsResult = DatabaseMetaData.procedureReturnsResult;
add(rows, // ALIAS_CATALOG
catalog, // ALIAS_SCHEMA
Constants.SCHEMA_MAIN, // ALIAS_NAME
identifier(agg.getName()), // JAVA_CLASS
agg.getJavaClassName(), // JAVA_METHOD
"", // DATA_TYPE
"" + DataType.convertTypeToSQLType(Value.NULL), // TYPE_NAME
DataType.getDataType(Value.NULL).name, // COLUMN_COUNT INT
"1", // RETURNS_RESULT SMALLINT
"" + returnsResult, // REMARKS
replaceNullWithEmpty(agg.getComment()), // ID
"" + agg.getId(), // SOURCE
"");
}
break;
}
case FUNCTION_COLUMNS:
{
for (SchemaObject aliasAsSchemaObject : database.getAllSchemaObjects(DbObject.FUNCTION_ALIAS)) {
FunctionAlias alias = (FunctionAlias) aliasAsSchemaObject;
JavaMethod[] methods;
try {
methods = alias.getJavaMethods();
} catch (DbException e) {
methods = new JavaMethod[0];
}
for (FunctionAlias.JavaMethod method : methods) {
// Add return column index 0
if (method.getDataType() != Value.NULL) {
DataType dt = DataType.getDataType(method.getDataType());
add(rows, // ALIAS_CATALOG
catalog, // ALIAS_SCHEMA
alias.getSchema().getName(), // ALIAS_NAME
identifier(alias.getName()), // JAVA_CLASS
alias.getJavaClassName(), // JAVA_METHOD
alias.getJavaMethodName(), // COLUMN_COUNT
"" + method.getParameterCount(), // POS INT
"0", // COLUMN_NAME
"P0", // DATA_TYPE
"" + DataType.convertTypeToSQLType(method.getDataType()), // TYPE_NAME
dt.name, // PRECISION INT
"" + MathUtils.convertLongToInt(dt.defaultPrecision), // SCALE
"" + dt.defaultScale, // RADIX
"10", // NULLABLE SMALLINT
"" + DatabaseMetaData.columnNullableUnknown, // COLUMN_TYPE
"" + DatabaseMetaData.procedureColumnReturn, // REMARKS
"", // COLUMN_DEFAULT
null);
}
Class<?>[] columnList = method.getColumnClasses();
for (int k = 0; k < columnList.length; k++) {
if (method.hasConnectionParam() && k == 0) {
continue;
}
Class<?> clazz = columnList[k];
int dataType = DataType.getTypeFromClass(clazz);
DataType dt = DataType.getDataType(dataType);
int nullable = clazz.isPrimitive() ? DatabaseMetaData.columnNoNulls : DatabaseMetaData.columnNullable;
add(rows, // ALIAS_CATALOG
catalog, // ALIAS_SCHEMA
alias.getSchema().getName(), // ALIAS_NAME
identifier(alias.getName()), // JAVA_CLASS
alias.getJavaClassName(), // JAVA_METHOD
alias.getJavaMethodName(), // COLUMN_COUNT
"" + method.getParameterCount(), // POS INT
"" + (k + (method.hasConnectionParam() ? 0 : 1)), // COLUMN_NAME
"P" + (k + 1), // DATA_TYPE
"" + DataType.convertTypeToSQLType(dt.type), // TYPE_NAME
dt.name, // PRECISION INT
"" + MathUtils.convertLongToInt(dt.defaultPrecision), // SCALE
"" + dt.defaultScale, // RADIX
"10", // NULLABLE SMALLINT
"" + nullable, // COLUMN_TYPE
"" + DatabaseMetaData.procedureColumnIn, // REMARKS
"", // COLUMN_DEFAULT
null);
}
}
}
break;
}
case SCHEMATA:
{
String collation = database.getCompareMode().getName();
for (Schema schema : database.getAllSchemas()) {
add(rows, // CATALOG_NAME
catalog, // SCHEMA_NAME
identifier(schema.getName()), // SCHEMA_OWNER
identifier(schema.getOwner().getName()), // DEFAULT_CHARACTER_SET_NAME
CHARACTER_SET_NAME, // DEFAULT_COLLATION_NAME
collation, // IS_DEFAULT
Constants.SCHEMA_MAIN.equals(schema.getName()) ? "TRUE" : "FALSE", // REMARKS
replaceNullWithEmpty(schema.getComment()), // ID
"" + schema.getId());
}
break;
}
case TABLE_PRIVILEGES:
{
for (Right r : database.getAllRights()) {
DbObject object = r.getGrantedObject();
if (!(object instanceof Table)) {
continue;
}
Table table = (Table) object;
if (hideTable(table, session)) {
continue;
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
addPrivileges(rows, r.getGrantee(), catalog, table, null, r.getRightMask());
}
break;
}
case COLUMN_PRIVILEGES:
{
for (Right r : database.getAllRights()) {
DbObject object = r.getGrantedObject();
if (!(object instanceof Table)) {
continue;
}
Table table = (Table) object;
if (hideTable(table, session)) {
continue;
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
DbObject grantee = r.getGrantee();
int mask = r.getRightMask();
for (Column column : table.getColumns()) {
addPrivileges(rows, grantee, catalog, table, column.getName(), mask);
}
}
break;
}
case COLLATIONS:
{
for (Locale l : Collator.getAvailableLocales()) {
add(rows, // NAME
CompareMode.getName(l), // KEY
l.toString());
}
break;
}
case VIEWS:
{
for (Table table : getAllTables(session)) {
if (table.getTableType() != TableType.VIEW) {
continue;
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
TableView view = (TableView) table;
add(rows, // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // VIEW_DEFINITION
table.getCreateSQL(), // CHECK_OPTION
"NONE", // IS_UPDATABLE
"NO", // STATUS
view.isInvalid() ? "INVALID" : "VALID", // REMARKS
replaceNullWithEmpty(view.getComment()), // ID
"" + view.getId());
}
break;
}
case IN_DOUBT:
{
ArrayList<InDoubtTransaction> prepared = database.getInDoubtTransactions();
if (prepared != null && admin) {
for (InDoubtTransaction prep : prepared) {
add(rows, // TRANSACTION
prep.getTransactionName(), // STATE
prep.getState());
}
}
break;
}
case CROSS_REFERENCES:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
Constraint constraint = (Constraint) obj;
if (constraint.getConstraintType() != Constraint.Type.REFERENTIAL) {
continue;
}
ConstraintReferential ref = (ConstraintReferential) constraint;
IndexColumn[] cols = ref.getColumns();
IndexColumn[] refCols = ref.getRefColumns();
Table tab = ref.getTable();
Table refTab = ref.getRefTable();
String tableName = identifier(refTab.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
int update = getRefAction(ref.getUpdateAction());
int delete = getRefAction(ref.getDeleteAction());
for (int j = 0; j < cols.length; j++) {
add(rows, // PKTABLE_CATALOG
catalog, // PKTABLE_SCHEMA
identifier(refTab.getSchema().getName()), // PKTABLE_NAME
identifier(refTab.getName()), // PKCOLUMN_NAME
identifier(refCols[j].column.getName()), // FKTABLE_CATALOG
catalog, // FKTABLE_SCHEMA
identifier(tab.getSchema().getName()), // FKTABLE_NAME
identifier(tab.getName()), // FKCOLUMN_NAME
identifier(cols[j].column.getName()), // ORDINAL_POSITION
String.valueOf(j + 1), // UPDATE_RULE SMALLINT
String.valueOf(update), // DELETE_RULE SMALLINT
String.valueOf(delete), // FK_NAME
identifier(ref.getName()), // PK_NAME
identifier(ref.getUniqueIndex().getName()), // DEFERRABILITY
"" + DatabaseMetaData.importedKeyNotDeferrable);
}
}
break;
}
case CONSTRAINTS:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
Constraint constraint = (Constraint) obj;
Constraint.Type constraintType = constraint.getConstraintType();
String checkExpression = null;
IndexColumn[] indexColumns = null;
Table table = constraint.getTable();
if (hideTable(table, session)) {
continue;
}
Index index = constraint.getUniqueIndex();
String uniqueIndexName = null;
if (index != null) {
uniqueIndexName = index.getName();
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
if (constraintType == Constraint.Type.CHECK) {
checkExpression = ((ConstraintCheck) constraint).getExpression().getSQL();
} else if (constraintType == Constraint.Type.UNIQUE || constraintType == Constraint.Type.PRIMARY_KEY) {
indexColumns = ((ConstraintUnique) constraint).getColumns();
} else if (constraintType == Constraint.Type.REFERENTIAL) {
indexColumns = ((ConstraintReferential) constraint).getColumns();
}
String columnList = null;
if (indexColumns != null) {
StatementBuilder buff = new StatementBuilder();
for (IndexColumn col : indexColumns) {
buff.appendExceptFirst(",");
buff.append(col.column.getName());
}
columnList = buff.toString();
}
add(rows, // CONSTRAINT_CATALOG
catalog, // CONSTRAINT_SCHEMA
identifier(constraint.getSchema().getName()), // CONSTRAINT_NAME
identifier(constraint.getName()), // CONSTRAINT_TYPE
constraintType == Constraint.Type.PRIMARY_KEY ? constraintType.getSqlName() : constraintType.name(), // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // UNIQUE_INDEX_NAME
uniqueIndexName, // CHECK_EXPRESSION
checkExpression, // COLUMN_LIST
columnList, // REMARKS
replaceNullWithEmpty(constraint.getComment()), // SQL
constraint.getCreateSQL(), // ID
"" + constraint.getId());
}
break;
}
case CONSTANTS:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTANT)) {
Constant constant = (Constant) obj;
ValueExpression expr = constant.getValue();
add(rows, // CONSTANT_CATALOG
catalog, // CONSTANT_SCHEMA
identifier(constant.getSchema().getName()), // CONSTANT_NAME
identifier(constant.getName()), // CONSTANT_TYPE
"" + DataType.convertTypeToSQLType(expr.getType()), // REMARKS
replaceNullWithEmpty(constant.getComment()), // SQL
expr.getSQL(), // ID
"" + constant.getId());
}
break;
}
case DOMAINS:
{
for (UserDataType dt : database.getAllUserDataTypes()) {
Column col = dt.getColumn();
add(rows, // DOMAIN_CATALOG
catalog, // DOMAIN_SCHEMA
Constants.SCHEMA_MAIN, // DOMAIN_NAME
identifier(dt.getName()), // COLUMN_DEFAULT
col.getDefaultSQL(), // IS_NULLABLE
col.isNullable() ? "YES" : "NO", // DATA_TYPE
"" + col.getDataType().sqlType, // PRECISION INT
"" + col.getPrecisionAsInt(), // SCALE INT
"" + col.getScale(), // TYPE_NAME
col.getDataType().name, // SELECTIVITY INT
"" + col.getSelectivity(), // CHECK_CONSTRAINT
"" + col.getCheckConstraintSQL(session, "VALUE"), // REMARKS
replaceNullWithEmpty(dt.getComment()), // SQL
"" + dt.getCreateSQL(), // ID
"" + dt.getId());
}
break;
}
case TRIGGERS:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.TRIGGER)) {
TriggerObject trigger = (TriggerObject) obj;
Table table = trigger.getTable();
add(rows, // TRIGGER_CATALOG
catalog, // TRIGGER_SCHEMA
identifier(trigger.getSchema().getName()), // TRIGGER_NAME
identifier(trigger.getName()), // TRIGGER_TYPE
trigger.getTypeNameList(), // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
identifier(table.getName()), // BEFORE BIT
"" + trigger.isBefore(), // JAVA_CLASS
trigger.getTriggerClassName(), // QUEUE_SIZE INT
"" + trigger.getQueueSize(), // NO_WAIT BIT
"" + trigger.isNoWait(), // REMARKS
replaceNullWithEmpty(trigger.getComment()), // SQL
trigger.getCreateSQL(), // ID
"" + trigger.getId());
}
break;
}
case SESSIONS:
{
long now = System.currentTimeMillis();
for (Session s : database.getSessions(false)) {
if (admin || s == session) {
Command command = s.getCurrentCommand();
long start = s.getCurrentCommandStart();
if (start == 0) {
start = now;
}
add(rows, // ID
"" + s.getId(), // USER_NAME
s.getUser().getName(), // SESSION_START
new Timestamp(s.getSessionStart()).toString(), // STATEMENT
command == null ? null : command.toString(), // STATEMENT_START
new Timestamp(start).toString(), // CONTAINS_UNCOMMITTED
"" + s.containsUncommitted());
}
}
break;
}
case LOCKS:
{
for (Session s : database.getSessions(false)) {
if (admin || s == session) {
for (Table table : s.getLocks()) {
add(rows, // TABLE_SCHEMA
table.getSchema().getName(), // TABLE_NAME
table.getName(), // SESSION_ID
"" + s.getId(), // LOCK_TYPE
table.isLockedExclusivelyBy(s) ? "WRITE" : "READ");
}
}
}
break;
}
case SESSION_STATE:
{
for (String name : session.getVariableNames()) {
Value v = session.getVariable(name);
add(rows, // KEY
"@" + name, // SQL
"SET @" + name + " " + v.getSQL());
}
for (Table table : session.getLocalTempTables()) {
add(rows, // KEY
"TABLE " + table.getName(), // SQL
table.getCreateSQL());
}
String[] path = session.getSchemaSearchPath();
if (path != null && path.length > 0) {
StatementBuilder buff = new StatementBuilder("SET SCHEMA_SEARCH_PATH ");
for (String p : path) {
buff.appendExceptFirst(", ");
buff.append(StringUtils.quoteIdentifier(p));
}
add(rows, // KEY
"SCHEMA_SEARCH_PATH", // SQL
buff.toString());
}
String schema = session.getCurrentSchemaName();
if (schema != null) {
add(rows, // KEY
"SCHEMA", // SQL
"SET SCHEMA " + StringUtils.quoteIdentifier(schema));
}
break;
}
case QUERY_STATISTICS:
{
QueryStatisticsData control = database.getQueryStatisticsData();
if (control != null) {
for (QueryStatisticsData.QueryEntry entry : control.getQueries()) {
add(rows, // SQL_STATEMENT
entry.sqlStatement, // EXECUTION_COUNT
"" + entry.count, // MIN_EXECUTION_TIME
"" + entry.executionTimeMinNanos / 1000d / 1000, // MAX_EXECUTION_TIME
"" + entry.executionTimeMaxNanos / 1000d / 1000, // CUMULATIVE_EXECUTION_TIME
"" + entry.executionTimeCumulativeNanos / 1000d / 1000, // AVERAGE_EXECUTION_TIME
"" + entry.executionTimeMeanNanos / 1000d / 1000, // STD_DEV_EXECUTION_TIME
"" + entry.getExecutionTimeStandardDeviation() / 1000d / 1000, // MIN_ROW_COUNT
"" + entry.rowCountMin, // MAX_ROW_COUNT
"" + entry.rowCountMax, // CUMULATIVE_ROW_COUNT
"" + entry.rowCountCumulative, // AVERAGE_ROW_COUNT
"" + entry.rowCountMean, // STD_DEV_ROW_COUNT
"" + entry.getRowCountStandardDeviation());
}
}
break;
}
case SYNONYMS:
{
for (TableSynonym synonym : database.getAllSynonyms()) {
add(rows, // SYNONYM_CATALOG
catalog, // SYNONYM_SCHEMA
identifier(synonym.getSchema().getName()), // SYNONYM_NAME
identifier(synonym.getName()), // SYNONYM_FOR
synonym.getSynonymForName(), // SYNONYM_FOR_SCHEMA
synonym.getSynonymForSchema().getName(), // TYPE NAME
"SYNONYM", // STATUS
"VALID", // REMARKS
replaceNullWithEmpty(synonym.getComment()), // ID
"" + synonym.getId());
}
break;
}
case TABLE_CONSTRAINTS:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
Constraint constraint = (Constraint) obj;
Constraint.Type constraintType = constraint.getConstraintType();
Table table = constraint.getTable();
if (hideTable(table, session)) {
continue;
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
add(rows, // CONSTRAINT_CATALOG
catalog, // CONSTRAINT_SCHEMA
identifier(constraint.getSchema().getName()), // CONSTRAINT_NAME
identifier(constraint.getName()), // CONSTRAINT_TYPE
constraintType.getSqlName(), // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // IS_DEFERRABLE
"NO", // INITIALLY_DEFERRED
"NO");
}
break;
}
case KEY_COLUMN_USAGE:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
Constraint constraint = (Constraint) obj;
Constraint.Type constraintType = constraint.getConstraintType();
IndexColumn[] indexColumns = null;
Table table = constraint.getTable();
if (hideTable(table, session)) {
continue;
}
String tableName = identifier(table.getName());
if (!checkIndex(session, tableName, indexFrom, indexTo)) {
continue;
}
if (constraintType == Constraint.Type.UNIQUE || constraintType == Constraint.Type.PRIMARY_KEY) {
indexColumns = ((ConstraintUnique) constraint).getColumns();
} else if (constraintType == Constraint.Type.REFERENTIAL) {
indexColumns = ((ConstraintReferential) constraint).getColumns();
}
if (indexColumns == null) {
continue;
}
ConstraintUnique referenced;
if (constraintType == Constraint.Type.REFERENTIAL) {
referenced = lookupUniqueForReferential((ConstraintReferential) constraint);
} else {
referenced = null;
}
for (int i = 0; i < indexColumns.length; i++) {
IndexColumn indexColumn = indexColumns[i];
String ordinalPosition = Integer.toString(i + 1);
String positionInUniqueConstraint;
if (constraintType == Constraint.Type.REFERENTIAL) {
positionInUniqueConstraint = ordinalPosition;
if (referenced != null) {
Column c = ((ConstraintReferential) constraint).getRefColumns()[i].column;
IndexColumn[] refColumns = referenced.getColumns();
for (int j = 0; j < refColumns.length; j++) {
if (refColumns[j].column.equals(c)) {
positionInUniqueConstraint = Integer.toString(j + 1);
break;
}
}
}
} else {
positionInUniqueConstraint = null;
}
add(rows, // CONSTRAINT_CATALOG
catalog, // CONSTRAINT_SCHEMA
identifier(constraint.getSchema().getName()), // CONSTRAINT_NAME
identifier(constraint.getName()), // TABLE_CATALOG
catalog, // TABLE_SCHEMA
identifier(table.getSchema().getName()), // TABLE_NAME
tableName, // COLUMN_NAME
indexColumn.columnName, // ORDINAL_POSITION
ordinalPosition, // POSITION_IN_UNIQUE_CONSTRAINT
positionInUniqueConstraint);
}
}
break;
}
case REFERENTIAL_CONSTRAINTS:
{
for (SchemaObject obj : database.getAllSchemaObjects(DbObject.CONSTRAINT)) {
if (((Constraint) obj).getConstraintType() != Constraint.Type.REFERENTIAL) {
continue;
}
ConstraintReferential constraint = (ConstraintReferential) obj;
Table table = constraint.getTable();
if (hideTable(table, session)) {
continue;
}
// Should be referenced unique constraint, but H2 uses indexes instead.
// So try to find matching unique constraint first and there is no such
// constraint use index name to return something.
SchemaObject unique = lookupUniqueForReferential(constraint);
if (unique == null) {
unique = constraint.getUniqueIndex();
}
add(rows, // CONSTRAINT_CATALOG
catalog, // CONSTRAINT_SCHEMA
identifier(constraint.getSchema().getName()), // CONSTRAINT_NAME
identifier(constraint.getName()), // UNIQUE_CONSTRAINT_CATALOG
catalog, // UNIQUE_CONSTRAINT_SCHEMA
identifier(unique.getSchema().getName()), // UNIQUE_CONSTRAINT_NAME
unique.getName(), // MATCH_OPTION
"NONE", // UPDATE_RULE
constraint.getUpdateAction().getSqlName(), // DELETE_RULE
constraint.getDeleteAction().getSqlName());
}
break;
}
default:
DbException.throwInternalError("type=" + type);
}
return rows;
}
use of org.h2.schema.Sequence in project h2database by h2database.
the class Table method validateConvertUpdateSequence.
/**
* Validate all values in this row, convert the values if required, and
* update the sequence values if required. This call will also set the
* default values if required and set the computed column if there are any.
*
* @param session the session
* @param row the row
*/
public void validateConvertUpdateSequence(Session session, Row row) {
for (int i = 0; i < columns.length; i++) {
Value value = row.getValue(i);
Column column = columns[i];
Value v2;
if (column.getComputed()) {
// force updating the value
value = null;
v2 = column.computeValue(session, row);
}
v2 = column.validateConvertUpdateSequence(session, value);
if (v2 != value) {
row.setValue(i, v2);
}
}
}
use of org.h2.schema.Sequence in project h2database by h2database.
the class Column method validateConvertUpdateSequence.
/**
* Validate the value, convert it if required, and update the sequence value
* if required. If the value is null, the default value (NULL if no default
* is set) is returned. Check constraints are validated as well.
*
* @param session the session
* @param value the value or null
* @return the new or converted value
*/
public Value validateConvertUpdateSequence(Session session, Value value) {
// take a local copy of defaultExpression to avoid holding the lock
// while calling getValue
final Expression localDefaultExpression;
synchronized (this) {
localDefaultExpression = defaultExpression;
}
Mode mode = session.getDatabase().getMode();
if (value == null) {
if (localDefaultExpression == null) {
value = ValueNull.INSTANCE;
} else {
value = convert(localDefaultExpression.getValue(session), mode);
if (!localDefaultExpression.isConstant()) {
session.getGeneratedKeys().add(this);
}
if (primaryKey) {
session.setLastIdentity(value);
}
}
}
if (value == ValueNull.INSTANCE) {
if (convertNullToDefault) {
value = convert(localDefaultExpression.getValue(session), mode);
if (!localDefaultExpression.isConstant()) {
session.getGeneratedKeys().add(this);
}
}
if (value == ValueNull.INSTANCE && !nullable) {
if (mode.convertInsertNullToZero) {
DataType dt = DataType.getDataType(type);
if (dt.decimal) {
value = ValueInt.get(0).convertTo(type);
} else if (dt.type == Value.TIMESTAMP) {
value = ValueTimestamp.fromMillis(session.getTransactionStart());
} else if (dt.type == Value.TIMESTAMP_TZ) {
long ms = session.getTransactionStart();
value = ValueTimestampTimeZone.fromDateValueAndNanos(DateTimeUtils.dateValueFromDate(ms), DateTimeUtils.nanosFromDate(ms), (short) 0);
} else if (dt.type == Value.TIME) {
value = ValueTime.fromNanos(0);
} else if (dt.type == Value.DATE) {
value = ValueDate.fromMillis(session.getTransactionStart());
} else {
value = ValueString.get("").convertTo(type);
}
} else {
throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, name);
}
}
}
if (checkConstraint != null) {
resolver.setValue(value);
Value v;
synchronized (this) {
v = checkConstraint.getValue(session);
}
// Both TRUE and NULL are ok
if (v != ValueNull.INSTANCE && !v.getBoolean()) {
throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, checkConstraint.getSQL());
}
}
value = value.convertScale(mode.convertOnlyToSmallerScale, scale);
if (precision > 0) {
if (!value.checkPrecision(precision)) {
String s = value.getTraceSQL();
if (s.length() > 127) {
s = s.substring(0, 128) + "...";
}
throw DbException.get(ErrorCode.VALUE_TOO_LONG_2, getCreateSQL(), s + " (" + value.getPrecision() + ")");
}
}
if (isEnumerated() && value != ValueNull.INSTANCE) {
if (!ValueEnum.isValid(enumerators, value)) {
String s = value.getTraceSQL();
if (s.length() > 127) {
s = s.substring(0, 128) + "...";
}
throw DbException.get(ErrorCode.ENUM_VALUE_NOT_PERMITTED, getCreateSQL(), s);
}
value = ValueEnum.get(enumerators, value.getInt());
}
updateSequenceIfRequired(session, value);
return value;
}
Aggregations