Debian Codegraph @

src/main/org/h2/table/InformationSchemaTableLegacy.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.table;
7
8 import java.io.ByteArrayInputStream;
9 import java.io.InputStreamReader;
10 import java.io.Reader;
11 import java.nio.charset.StandardCharsets;
12 import java.sql.DatabaseMetaData;
13 import java.sql.ResultSet;
14 import java.sql.Types;
15 import java.util.ArrayList;
16 import java.util.BitSet;
17 import java.util.HashSet;
18 import java.util.Locale;
19 import java.util.Map;
20
21 import org.h2.command.Command;
22 import org.h2.command.Parser;
23 import org.h2.command.dml.Help;
24 import org.h2.constraint.Constraint;
25 import org.h2.constraint.Constraint.Type;
26 import org.h2.constraint.ConstraintActionType;
27 import org.h2.constraint.ConstraintCheck;
28 import org.h2.constraint.ConstraintDomain;
29 import org.h2.constraint.ConstraintReferential;
30 import org.h2.constraint.ConstraintUnique;
31 import org.h2.engine.Constants;
32 import org.h2.engine.DbObject;
33 import org.h2.engine.QueryStatisticsData;
34 import org.h2.engine.Right;
35 import org.h2.engine.RightOwner;
36 import org.h2.engine.Role;
37 import org.h2.engine.SessionLocal;
38 import org.h2.engine.SessionLocal.State;
39 import org.h2.engine.Setting;
40 import org.h2.engine.User;
41 import org.h2.expression.Expression;
42 import org.h2.expression.ExpressionVisitor;
43 import org.h2.expression.ValueExpression;
44 import org.h2.index.Index;
45 import org.h2.index.MetaIndex;
46 import org.h2.message.DbException;
47 import org.h2.result.Row;
48 import org.h2.result.SearchRow;
49 import org.h2.result.SortOrder;
50 import org.h2.schema.Constant;
51 import org.h2.schema.Domain;
52 import org.h2.schema.FunctionAlias;
53 import org.h2.schema.FunctionAlias.JavaMethod;
54 import org.h2.schema.Schema;
55 import org.h2.schema.SchemaObject;
56 import org.h2.schema.Sequence;
57 import org.h2.schema.TriggerObject;
58 import org.h2.schema.UserDefinedFunction;
59 import org.h2.store.InDoubtTransaction;
60 import org.h2.tools.Csv;
61 import org.h2.util.DateTimeUtils;
62 import org.h2.util.HasSQL;
63 import org.h2.util.MathUtils;
64 import org.h2.util.NetworkConnectionInfo;
65 import org.h2.util.StringUtils;
66 import org.h2.util.TimeZoneProvider;
67 import org.h2.util.Utils;
68 import org.h2.value.CompareMode;
69 import org.h2.value.DataType;
70 import org.h2.value.TypeInfo;
71 import org.h2.value.Value;
72 import org.h2.value.ValueBigint;
73 import org.h2.value.ValueBoolean;
74 import org.h2.value.ValueDouble;
75 import org.h2.value.ValueInteger;
76 import org.h2.value.ValueSmallint;
77 import org.h2.value.ValueToObjectConverter2;
78
79 /**
80 * This class is responsible to build the legacy variant of INFORMATION_SCHEMA
81 * tables.
82 */
83 public final class InformationSchemaTableLegacy extends MetaTable {
84
85 private static final String CHARACTER_SET_NAME = "Unicode";
86
87 private static final int TABLES = 0;
88 private static final int COLUMNS = TABLES + 1;
89 private static final int INDEXES = COLUMNS + 1;
90 private static final int TABLE_TYPES = INDEXES + 1;
91 private static final int TYPE_INFO = TABLE_TYPES + 1;
92 private static final int CATALOGS = TYPE_INFO + 1;
93 private static final int SETTINGS = CATALOGS + 1;
94 private static final int HELP = SETTINGS + 1;
95 private static final int SEQUENCES = HELP + 1;
96 private static final int USERS = SEQUENCES + 1;
97 private static final int ROLES = USERS + 1;
98 private static final int RIGHTS = ROLES + 1;
99 private static final int FUNCTION_ALIASES = RIGHTS + 1;
100 private static final int SCHEMATA = FUNCTION_ALIASES + 1;
101 private static final int TABLE_PRIVILEGES = SCHEMATA + 1;
102 private static final int COLUMN_PRIVILEGES = TABLE_PRIVILEGES + 1;
103 private static final int COLLATIONS = COLUMN_PRIVILEGES + 1;
104 private static final int VIEWS = COLLATIONS + 1;
105 private static final int IN_DOUBT = VIEWS + 1;
106 private static final int CROSS_REFERENCES = IN_DOUBT + 1;
107 private static final int FUNCTION_COLUMNS = CROSS_REFERENCES + 1;
108 private static final int CONSTRAINTS = FUNCTION_COLUMNS + 1;
109 private static final int CONSTANTS = CONSTRAINTS + 1;
110 private static final int DOMAINS = CONSTANTS + 1;
111 private static final int TRIGGERS = DOMAINS + 1;
112 private static final int SESSIONS = TRIGGERS + 1;
113 private static final int LOCKS = SESSIONS + 1;
114 private static final int SESSION_STATE = LOCKS + 1;
115 private static final int QUERY_STATISTICS = SESSION_STATE + 1;
116 private static final int SYNONYMS = QUERY_STATISTICS + 1;
117 private static final int TABLE_CONSTRAINTS = SYNONYMS + 1;
118 private static final int DOMAIN_CONSTRAINTS = TABLE_CONSTRAINTS + 1;
119 private static final int KEY_COLUMN_USAGE = DOMAIN_CONSTRAINTS + 1;
120 private static final int REFERENTIAL_CONSTRAINTS = KEY_COLUMN_USAGE + 1;
121 private static final int CHECK_CONSTRAINTS = REFERENTIAL_CONSTRAINTS + 1;
122 private static final int CONSTRAINT_COLUMN_USAGE = CHECK_CONSTRAINTS + 1;
123
124 /**
125 * The number of meta table types. Supported meta table types are
126 * {@code 0..META_TABLE_TYPE_COUNT - 1}.
127 */
128 public static final int META_TABLE_TYPE_COUNT = CONSTRAINT_COLUMN_USAGE + 1;
129
130 /**
131 * Create a new metadata table.
132 *
133 * @param schema the schema
134 * @param id the object id
135 * @param type the meta table type
136 */
137 public InformationSchemaTableLegacy(Schema schema, int id, int type) {
138 super(schema, id, type);
139 Column[] cols;
140 String indexColumnName = null;
141 switch (type) {
142 case TABLES:
143 setMetaTableName("TABLES");
144 cols = new Column[] {
145 column("TABLE_CATALOG"), //
146 column("TABLE_SCHEMA"), //
147 column("TABLE_NAME"), //
148 column("TABLE_TYPE"), //
149 // extensions
150 column("STORAGE_TYPE"), //
151 column("SQL"), //
152 column("REMARKS"), //
153 column("LAST_MODIFICATION", TypeInfo.TYPE_BIGINT), //
154 column("ID", TypeInfo.TYPE_INTEGER), //
155 column("TYPE_NAME"), //
156 column("TABLE_CLASS"), //
157 column("ROW_COUNT_ESTIMATE", TypeInfo.TYPE_BIGINT), //
158 };
159 indexColumnName = "TABLE_NAME";
160 break;
161 case COLUMNS:
162 setMetaTableName("COLUMNS");
163 cols = new Column[] {
164 column("TABLE_CATALOG"), //
165 column("TABLE_SCHEMA"), //
166 column("TABLE_NAME"), //
167 column("COLUMN_NAME"), //
168 column("ORDINAL_POSITION", TypeInfo.TYPE_INTEGER), //
169 column("COLUMN_DEFAULT"), //
170 column("IS_NULLABLE"), //
171 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
172 column("CHARACTER_MAXIMUM_LENGTH", TypeInfo.TYPE_INTEGER), //
173 column("CHARACTER_OCTET_LENGTH", TypeInfo.TYPE_INTEGER), //
174 column("NUMERIC_PRECISION", TypeInfo.TYPE_INTEGER), //
175 column("NUMERIC_PRECISION_RADIX", TypeInfo.TYPE_INTEGER), //
176 column("NUMERIC_SCALE", TypeInfo.TYPE_INTEGER), //
177 column("DATETIME_PRECISION", TypeInfo.TYPE_INTEGER), //
178 column("INTERVAL_TYPE"), //
179 column("INTERVAL_PRECISION", TypeInfo.TYPE_INTEGER), //
180 column("CHARACTER_SET_NAME"), //
181 column("COLLATION_NAME"), //
182 column("DOMAIN_CATALOG"), //
183 column("DOMAIN_SCHEMA"), //
184 column("DOMAIN_NAME"), //
185 column("IS_GENERATED"), //
186 column("GENERATION_EXPRESSION"), //
187 // extensions
188 column("TYPE_NAME"), //
189 column("NULLABLE", TypeInfo.TYPE_INTEGER), //
190 column("IS_COMPUTED", TypeInfo.TYPE_BOOLEAN), //
191 column("SELECTIVITY", TypeInfo.TYPE_INTEGER), //
192 column("SEQUENCE_NAME"), //
193 column("REMARKS"), //
194 column("SOURCE_DATA_TYPE", TypeInfo.TYPE_SMALLINT), //
195 column("COLUMN_TYPE"), //
196 column("COLUMN_ON_UPDATE"), //
197 column("IS_VISIBLE"), //
198 // compatibility
199 column("CHECK_CONSTRAINT"), //
200 };
201 indexColumnName = "TABLE_NAME";
202 break;
203 case INDEXES:
204 setMetaTableName("INDEXES");
205 cols = new Column[] {
206 column("TABLE_CATALOG"), //
207 column("TABLE_SCHEMA"), //
208 column("TABLE_NAME"), //
209 column("NON_UNIQUE", TypeInfo.TYPE_BOOLEAN), //
210 column("INDEX_NAME"), //
211 column("ORDINAL_POSITION", TypeInfo.TYPE_SMALLINT), //
212 column("COLUMN_NAME"), //
213 column("CARDINALITY", TypeInfo.TYPE_INTEGER), //
214 column("PRIMARY_KEY", TypeInfo.TYPE_BOOLEAN), //
215 column("INDEX_TYPE_NAME"), //
216 column("IS_GENERATED", TypeInfo.TYPE_BOOLEAN), //
217 column("INDEX_TYPE", TypeInfo.TYPE_SMALLINT), //
218 column("ASC_OR_DESC"), //
219 column("PAGES", TypeInfo.TYPE_INTEGER), //
220 column("FILTER_CONDITION"), //
221 column("REMARKS"), //
222 column("SQL"), //
223 column("ID", TypeInfo.TYPE_INTEGER), //
224 column("SORT_TYPE", TypeInfo.TYPE_INTEGER), //
225 column("CONSTRAINT_NAME"), //
226 column("INDEX_CLASS"), //
227 };
228 indexColumnName = "TABLE_NAME";
229 break;
230 case TABLE_TYPES:
231 setMetaTableName("TABLE_TYPES");
232 cols = new Column[] {
233 column("TYPE"), //
234 };
235 break;
236 case TYPE_INFO:
237 setMetaTableName("TYPE_INFO");
238 cols = new Column[] {
239 column("TYPE_NAME"), //
240 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
241 column("PRECISION", TypeInfo.TYPE_INTEGER), //
242 column("PREFIX"), //
243 column("SUFFIX"), //
244 column("PARAMS"), //
245 column("AUTO_INCREMENT", TypeInfo.TYPE_BOOLEAN), //
246 column("MINIMUM_SCALE", TypeInfo.TYPE_SMALLINT), //
247 column("MAXIMUM_SCALE", TypeInfo.TYPE_SMALLINT), //
248 column("RADIX", TypeInfo.TYPE_INTEGER), //
249 column("POS", TypeInfo.TYPE_INTEGER), //
250 column("CASE_SENSITIVE", TypeInfo.TYPE_BOOLEAN), //
251 column("NULLABLE", TypeInfo.TYPE_SMALLINT), //
252 column("SEARCHABLE", TypeInfo.TYPE_SMALLINT), //
253 };
254 break;
255 case CATALOGS:
256 setMetaTableName("CATALOGS");
257 cols = new Column[] {
258 column("CATALOG_NAME"), //
259 };
260 break;
261 case SETTINGS:
262 setMetaTableName("SETTINGS");
263 cols = new Column[] {
264 column("NAME"), //
265 column("VALUE"), //
266 };
267 break;
268 case HELP:
269 setMetaTableName("HELP");
270 cols = new Column[] {
271 column("ID", TypeInfo.TYPE_INTEGER), //
272 column("SECTION"), //
273 column("TOPIC"), //
274 column("SYNTAX"), //
275 column("TEXT"), //
276 };
277 break;
278 case SEQUENCES:
279 setMetaTableName("SEQUENCES");
280 cols = new Column[] {
281 column("SEQUENCE_CATALOG"), //
282 column("SEQUENCE_SCHEMA"), //
283 column("SEQUENCE_NAME"), //
284 column("DATA_TYPE"), //
285 column("NUMERIC_PRECISION", TypeInfo.TYPE_INTEGER), //
286 column("NUMERIC_PRECISION_RADIX", TypeInfo.TYPE_INTEGER), //
287 column("NUMERIC_SCALE", TypeInfo.TYPE_INTEGER), //
288 column("START_VALUE", TypeInfo.TYPE_BIGINT), //
289 column("MINIMUM_VALUE", TypeInfo.TYPE_BIGINT), //
290 column("MAXIMUM_VALUE", TypeInfo.TYPE_BIGINT), //
291 column("INCREMENT", TypeInfo.TYPE_BIGINT), //
292 column("CYCLE_OPTION"), //
293 column("DECLARED_DATA_TYPE"), //
294 column("DECLARED_NUMERIC_PRECISION", TypeInfo.TYPE_INTEGER), //
295 column("DECLARED_NUMERIC_SCALE", TypeInfo.TYPE_INTEGER), //
296 column("CURRENT_VALUE", TypeInfo.TYPE_BIGINT), //
297 column("IS_GENERATED", TypeInfo.TYPE_BOOLEAN), //
298 column("REMARKS"), //
299 column("CACHE", TypeInfo.TYPE_BIGINT), //
300 column("ID", TypeInfo.TYPE_INTEGER), //
301 // compatibility
302 column("MIN_VALUE", TypeInfo.TYPE_BIGINT), //
303 column("MAX_VALUE", TypeInfo.TYPE_BIGINT), //
304 column("IS_CYCLE", TypeInfo.TYPE_BOOLEAN), //
305 };
306 break;
307 case USERS:
308 setMetaTableName("USERS");
309 cols = new Column[] {
310 column("NAME"), //
311 column("ADMIN"), //
312 column("REMARKS"), //
313 column("ID", TypeInfo.TYPE_INTEGER), //
314 };
315 break;
316 case ROLES:
317 setMetaTableName("ROLES");
318 cols = new Column[] {
319 column("NAME"), //
320 column("REMARKS"), //
321 column("ID", TypeInfo.TYPE_INTEGER), //
322 };
323 break;
324 case RIGHTS:
325 setMetaTableName("RIGHTS");
326 cols = new Column[] {
327 column("GRANTEE"), //
328 column("GRANTEETYPE"), //
329 column("GRANTEDROLE"), //
330 column("RIGHTS"), //
331 column("TABLE_SCHEMA"), //
332 column("TABLE_NAME"), //
333 column("ID", TypeInfo.TYPE_INTEGER), //
334 };
335 indexColumnName = "TABLE_NAME";
336 break;
337 case FUNCTION_ALIASES:
338 setMetaTableName("FUNCTION_ALIASES");
339 cols = new Column[] {
340 column("ALIAS_CATALOG"), //
341 column("ALIAS_SCHEMA"), //
342 column("ALIAS_NAME"), //
343 column("JAVA_CLASS"), //
344 column("JAVA_METHOD"), //
345 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
346 column("TYPE_NAME"), //
347 column("COLUMN_COUNT", TypeInfo.TYPE_INTEGER), //
348 column("RETURNS_RESULT", TypeInfo.TYPE_SMALLINT), //
349 column("REMARKS"), //
350 column("ID", TypeInfo.TYPE_INTEGER), //
351 column("SOURCE"), //
352 };
353 break;
354 case FUNCTION_COLUMNS:
355 setMetaTableName("FUNCTION_COLUMNS");
356 cols = new Column[] {
357 column("ALIAS_CATALOG"), //
358 column("ALIAS_SCHEMA"), //
359 column("ALIAS_NAME"), //
360 column("JAVA_CLASS"), //
361 column("JAVA_METHOD"), //
362 column("COLUMN_COUNT", TypeInfo.TYPE_INTEGER), //
363 column("POS", TypeInfo.TYPE_INTEGER), //
364 column("COLUMN_NAME"), //
365 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
366 column("TYPE_NAME"), //
367 column("PRECISION", TypeInfo.TYPE_INTEGER), //
368 column("SCALE", TypeInfo.TYPE_SMALLINT), //
369 column("RADIX", TypeInfo.TYPE_SMALLINT), //
370 column("NULLABLE", TypeInfo.TYPE_SMALLINT), //
371 column("COLUMN_TYPE", TypeInfo.TYPE_SMALLINT), //
372 column("REMARKS"), //
373 column("COLUMN_DEFAULT"), //
374 };
375 break;
376 case SCHEMATA:
377 setMetaTableName("SCHEMATA");
378 cols = new Column[] {
379 column("CATALOG_NAME"), //
380 column("SCHEMA_NAME"), //
381 column("SCHEMA_OWNER"), //
382 column("DEFAULT_CHARACTER_SET_NAME"), //
383 column("DEFAULT_COLLATION_NAME"), //
384 column("IS_DEFAULT", TypeInfo.TYPE_BOOLEAN), //
385 column("REMARKS"), //
386 column("ID", TypeInfo.TYPE_INTEGER), //
387 };
388 break;
389 case TABLE_PRIVILEGES:
390 setMetaTableName("TABLE_PRIVILEGES");
391 cols = new Column[] {
392 column("GRANTOR"), //
393 column("GRANTEE"), //
394 column("TABLE_CATALOG"), //
395 column("TABLE_SCHEMA"), //
396 column("TABLE_NAME"), //
397 column("PRIVILEGE_TYPE"), //
398 column("IS_GRANTABLE"), //
399 };
400 indexColumnName = "TABLE_NAME";
401 break;
402 case COLUMN_PRIVILEGES:
403 setMetaTableName("COLUMN_PRIVILEGES");
404 cols = new Column[] {
405 column("GRANTOR"), //
406 column("GRANTEE"), //
407 column("TABLE_CATALOG"), //
408 column("TABLE_SCHEMA"), //
409 column("TABLE_NAME"), //
410 column("COLUMN_NAME"), //
411 column("PRIVILEGE_TYPE"), //
412 column("IS_GRANTABLE"), //
413 };
414 indexColumnName = "TABLE_NAME";
415 break;
416 case COLLATIONS:
417 setMetaTableName("COLLATIONS");
418 cols = new Column[] {
419 column("NAME"), //
420 column("KEY"), //
421 };
422 break;
423 case VIEWS:
424 setMetaTableName("VIEWS");
425 cols = new Column[] {
426 column("TABLE_CATALOG"), //
427 column("TABLE_SCHEMA"), //
428 column("TABLE_NAME"), //
429 column("VIEW_DEFINITION"), //
430 column("CHECK_OPTION"), //
431 column("IS_UPDATABLE"), //
432 column("STATUS"), //
433 column("REMARKS"), //
434 column("ID", TypeInfo.TYPE_INTEGER), //
435 };
436 indexColumnName = "TABLE_NAME";
437 break;
438 case IN_DOUBT:
439 setMetaTableName("IN_DOUBT");
440 cols = new Column[] {
441 column("TRANSACTION"), //
442 column("STATE"), //
443 };
444 break;
445 case CROSS_REFERENCES:
446 setMetaTableName("CROSS_REFERENCES");
447 cols = new Column[] {
448 column("PKTABLE_CATALOG"), //
449 column("PKTABLE_SCHEMA"), //
450 column("PKTABLE_NAME"), //
451 column("PKCOLUMN_NAME"), //
452 column("FKTABLE_CATALOG"), //
453 column("FKTABLE_SCHEMA"), //
454 column("FKTABLE_NAME"), //
455 column("FKCOLUMN_NAME"), //
456 column("ORDINAL_POSITION", TypeInfo.TYPE_SMALLINT), //
457 column("UPDATE_RULE", TypeInfo.TYPE_SMALLINT), //
458 column("DELETE_RULE", TypeInfo.TYPE_SMALLINT), //
459 column("FK_NAME"), //
460 column("PK_NAME"), //
461 column("DEFERRABILITY", TypeInfo.TYPE_SMALLINT), //
462 };
463 indexColumnName = "PKTABLE_NAME";
464 break;
465 case CONSTRAINTS:
466 setMetaTableName("CONSTRAINTS");
467 cols = new Column[] {
468 column("CONSTRAINT_CATALOG"), //
469 column("CONSTRAINT_SCHEMA"), //
470 column("CONSTRAINT_NAME"), //
471 column("CONSTRAINT_TYPE"), //
472 column("TABLE_CATALOG"), //
473 column("TABLE_SCHEMA"), //
474 column("TABLE_NAME"), //
475 column("UNIQUE_INDEX_NAME"), //
476 column("CHECK_EXPRESSION"), //
477 column("COLUMN_LIST"), //
478 column("REMARKS"), //
479 column("SQL"), //
480 column("ID", TypeInfo.TYPE_INTEGER), //
481 };
482 indexColumnName = "TABLE_NAME";
483 break;
484 case CONSTANTS:
485 setMetaTableName("CONSTANTS");
486 cols = new Column[] {
487 column("CONSTANT_CATALOG"), //
488 column("CONSTANT_SCHEMA"), //
489 column("CONSTANT_NAME"), //
490 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
491 column("REMARKS"), //
492 column("SQL"), //
493 column("ID", TypeInfo.TYPE_INTEGER), //
494 };
495 break;
496 case DOMAINS:
497 setMetaTableName("DOMAINS");
498 cols = new Column[] {
499 column("DOMAIN_CATALOG"), //
500 column("DOMAIN_SCHEMA"), //
501 column("DOMAIN_NAME"), //
502 column("DOMAIN_DEFAULT"), //
503 column("DOMAIN_ON_UPDATE"), //
504 column("DATA_TYPE", TypeInfo.TYPE_INTEGER), //
505 column("PRECISION", TypeInfo.TYPE_INTEGER), //
506 column("SCALE", TypeInfo.TYPE_INTEGER), //
507 column("TYPE_NAME"), //
508 column("PARENT_DOMAIN_CATALOG"), //
509 column("PARENT_DOMAIN_SCHEMA"), //
510 column("PARENT_DOMAIN_NAME"), //
511 column("SELECTIVITY", TypeInfo.TYPE_INTEGER), //
512 column("REMARKS"), //
513 column("SQL"), //
514 column("ID", TypeInfo.TYPE_INTEGER), //
515 // compatibility
516 column("COLUMN_DEFAULT"), //
517 column("IS_NULLABLE"), //
518 column("CHECK_CONSTRAINT"), //
519 };
520 break;
521 case TRIGGERS:
522 setMetaTableName("TRIGGERS");
523 cols = new Column[] {
524 column("TRIGGER_CATALOG"), //
525 column("TRIGGER_SCHEMA"), //
526 column("TRIGGER_NAME"), //
527 column("TRIGGER_TYPE"), //
528 column("TABLE_CATALOG"), //
529 column("TABLE_SCHEMA"), //
530 column("TABLE_NAME"), //
531 column("BEFORE", TypeInfo.TYPE_BOOLEAN), //
532 column("JAVA_CLASS"), //
533 column("QUEUE_SIZE", TypeInfo.TYPE_INTEGER), //
534 column("NO_WAIT", TypeInfo.TYPE_BOOLEAN), //
535 column("REMARKS"), //
536 column("SQL"), //
537 column("ID", TypeInfo.TYPE_INTEGER), //
538 };
539 break;
540 case SESSIONS: {
541 setMetaTableName("SESSIONS");
542 cols = new Column[] {
543 column("ID", TypeInfo.TYPE_INTEGER), //
544 column("USER_NAME"), //
545 column("SERVER"), //
546 column("CLIENT_ADDR"), //
547 column("CLIENT_INFO"), //
548 column("SESSION_START", TypeInfo.TYPE_TIMESTAMP_TZ), //
549 column("ISOLATION_LEVEL"), //
550 column("STATEMENT"), //
551 column("STATEMENT_START", TypeInfo.TYPE_TIMESTAMP_TZ), //
552 column("CONTAINS_UNCOMMITTED", TypeInfo.TYPE_BOOLEAN), //
553 column("STATE"), //
554 column("BLOCKER_ID", TypeInfo.TYPE_INTEGER), //
555 column("SLEEP_SINCE", TypeInfo.TYPE_TIMESTAMP_TZ), //
556 };
557 break;
558 }
559 case LOCKS: {
560 setMetaTableName("LOCKS");
561 cols = new Column[] {
562 column("TABLE_SCHEMA"), //
563 column("TABLE_NAME"), //
564 column("SESSION_ID", TypeInfo.TYPE_INTEGER), //
565 column("LOCK_TYPE"), //
566 };
567 break;
568 }
569 case SESSION_STATE: {
570 setMetaTableName("SESSION_STATE");
571 cols = new Column[] {
572 column("KEY"), //
573 column("SQL"), //
574 };
575 break;
576 }
577 case QUERY_STATISTICS: {
578 setMetaTableName("QUERY_STATISTICS");
579 cols = new Column[] {
580 column("SQL_STATEMENT"), //
581 column("EXECUTION_COUNT", TypeInfo.TYPE_INTEGER), //
582 column("MIN_EXECUTION_TIME", TypeInfo.TYPE_DOUBLE), //
583 column("MAX_EXECUTION_TIME", TypeInfo.TYPE_DOUBLE), //
584 column("CUMULATIVE_EXECUTION_TIME", TypeInfo.TYPE_DOUBLE), //
585 column("AVERAGE_EXECUTION_TIME", TypeInfo.TYPE_DOUBLE), //
586 column("STD_DEV_EXECUTION_TIME", TypeInfo.TYPE_DOUBLE), //
587 column("MIN_ROW_COUNT", TypeInfo.TYPE_BIGINT), //
588 column("MAX_ROW_COUNT", TypeInfo.TYPE_BIGINT), //
589 column("CUMULATIVE_ROW_COUNT", TypeInfo.TYPE_BIGINT), //
590 column("AVERAGE_ROW_COUNT", TypeInfo.TYPE_DOUBLE), //
591 column("STD_DEV_ROW_COUNT", TypeInfo.TYPE_DOUBLE), //
592 };
593 break;
594 }
595 case SYNONYMS: {
596 setMetaTableName("SYNONYMS");
597 cols = new Column[] {
598 column("SYNONYM_CATALOG"), //
599 column("SYNONYM_SCHEMA"), //
600 column("SYNONYM_NAME"), //
601 column("SYNONYM_FOR"), //
602 column("SYNONYM_FOR_SCHEMA"), //
603 column("TYPE_NAME"), //
604 column("STATUS"), //
605 column("REMARKS"), //
606 column("ID", TypeInfo.TYPE_INTEGER), //
607 };
608 indexColumnName = "SYNONYM_NAME";
609 break;
610 }
611 case TABLE_CONSTRAINTS: {
612 setMetaTableName("TABLE_CONSTRAINTS");
613 cols = new Column[] {
614 column("CONSTRAINT_CATALOG"), //
615 column("CONSTRAINT_SCHEMA"), //
616 column("CONSTRAINT_NAME"), //
617 column("CONSTRAINT_TYPE"), //
618 column("TABLE_CATALOG"), //
619 column("TABLE_SCHEMA"), //
620 column("TABLE_NAME"), //
621 column("IS_DEFERRABLE"), //
622 column("INITIALLY_DEFERRED"), //
623 column("REMARKS"), //
624 column("SQL"), //
625 column("ID", TypeInfo.TYPE_INTEGER), //
626 };
627 indexColumnName = "TABLE_NAME";
628 break;
629 }
630 case DOMAIN_CONSTRAINTS: {
631 setMetaTableName("DOMAIN_CONSTRAINTS");
632 cols = new Column[] {
633 column("CONSTRAINT_CATALOG"), //
634 column("CONSTRAINT_SCHEMA"), //
635 column("CONSTRAINT_NAME"), //
636 column("DOMAIN_CATALOG"), //
637 column("DOMAIN_SCHEMA"), //
638 column("DOMAIN_NAME"), //
639 column("IS_DEFERRABLE"), //
640 column("INITIALLY_DEFERRED"), //
641 column("REMARKS"), //
642 column("SQL"), //
643 column("ID", TypeInfo.TYPE_INTEGER), //
644 };
645 break;
646 }
647 case KEY_COLUMN_USAGE: {
648 setMetaTableName("KEY_COLUMN_USAGE");
649 cols = new Column[] {
650 column("CONSTRAINT_CATALOG"), //
651 column("CONSTRAINT_SCHEMA"), //
652 column("CONSTRAINT_NAME"), //
653 column("TABLE_CATALOG"), //
654 column("TABLE_SCHEMA"), //
655 column("TABLE_NAME"), //
656 column("COLUMN_NAME"), //
657 column("ORDINAL_POSITION", TypeInfo.TYPE_INTEGER), //
658 column("POSITION_IN_UNIQUE_CONSTRAINT", TypeInfo.TYPE_INTEGER), //
659 column("INDEX_CATALOG"), //
660 column("INDEX_SCHEMA"), //
661 column("INDEX_NAME"), //
662 };
663 indexColumnName = "TABLE_NAME";
664 break;
665 }
666 case REFERENTIAL_CONSTRAINTS: {
667 setMetaTableName("REFERENTIAL_CONSTRAINTS");
668 cols = new Column[] {
669 column("CONSTRAINT_CATALOG"), //
670 column("CONSTRAINT_SCHEMA"), //
671 column("CONSTRAINT_NAME"), //
672 column("UNIQUE_CONSTRAINT_CATALOG"), //
673 column("UNIQUE_CONSTRAINT_SCHEMA"), //
674 column("UNIQUE_CONSTRAINT_NAME"), //
675 column("MATCH_OPTION"), //
676 column("UPDATE_RULE"), //
677 column("DELETE_RULE"), //
678 };
679 break;
680 }
681 case CHECK_CONSTRAINTS: {
682 setMetaTableName("CHECK_CONSTRAINTS");
683 cols = new Column[] {
684 column("CONSTRAINT_CATALOG"), //
685 column("CONSTRAINT_SCHEMA"), //
686 column("CONSTRAINT_NAME"), //
687 column("CHECK_CLAUSE"), //
688 };
689 break;
690 }
691 case CONSTRAINT_COLUMN_USAGE: {
692 setMetaTableName("CONSTRAINT_COLUMN_USAGE");
693 cols = new Column[] {
694 column("TABLE_CATALOG"), //
695 column("TABLE_SCHEMA"), //
696 column("TABLE_NAME"), //
697 column("COLUMN_NAME"), //
698 column("CONSTRAINT_CATALOG"), //
699 column("CONSTRAINT_SCHEMA"), //
700 column("CONSTRAINT_NAME"), //
701 };
702 indexColumnName = "TABLE_NAME";
703 break;
704 }
705 default:
706 throw DbException.getInternalError("type=" + type);
707 }
708 setColumns(cols);
709
710 if (indexColumnName == null) {
711 indexColumn = -1;
712 metaIndex = null;
713 } else {
714 indexColumn = getColumn(database.sysIdentifier(indexColumnName)).getColumnId();
715 IndexColumn[] indexCols = IndexColumn.wrap(
716 new Column[] { cols[indexColumn] });
717 metaIndex = new MetaIndex(this, indexCols, false);
718 }
719 }
720
721 private static String replaceNullWithEmpty(String s) {
722 return s == null ? "" : s;
723 }
724
725 @Override
726 public ArrayList<Row> generateRows(SessionLocal session, SearchRow first, SearchRow last) {
727 Value indexFrom = null, indexTo = null;
728
729 if (indexColumn >= 0) {
730 if (first != null) {
731 indexFrom = first.getValue(indexColumn);
732 }
733 if (last != null) {
734 indexTo = last.getValue(indexColumn);
735 }
736 }
737
738 ArrayList<Row> rows = Utils.newSmallArrayList();
739 String catalog = database.getShortName();
740 boolean admin = session.getUser().isAdmin();
741 switch (type) {
742 case TABLES: {
743 for (Table table : getAllTables(session)) {
744 String tableName = table.getName();
745 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
746 continue;
747 }
748 if (hideTable(table, session)) {
749 continue;
750 }
751 String storageType;
752 if (table.isTemporary()) {
753 if (table.isGlobalTemporary()) {
754 storageType = "GLOBAL TEMPORARY";
755 } else {
756 storageType = "LOCAL TEMPORARY";
757 }
758 } else {
759 storageType = table.isPersistIndexes() ?
760 "CACHED" : "MEMORY";
761 }
762 String sql = table.getCreateSQL();
763 if (!admin) {
764 if (sql != null && sql.contains(DbException.HIDE_SQL)) {
765 // hide the password of linked tables
766 sql = "-";
767 }
768 }
769 add(session,
770 rows,
771 // TABLE_CATALOG
772 catalog,
773 // TABLE_SCHEMA
774 table.getSchema().getName(),
775 // TABLE_NAME
776 tableName,
777 // TABLE_TYPE
778 table.getTableType().toString(),
779 // STORAGE_TYPE
780 storageType,
781 // SQL
782 sql,
783 // REMARKS
784 replaceNullWithEmpty(table.getComment()),
785 // LAST_MODIFICATION
786 ValueBigint.get(table.getMaxDataModificationId()),
787 // ID
788 ValueInteger.get(table.getId()),
789 // TYPE_NAME
790 null,
791 // TABLE_CLASS
792 table.getClass().getName(),
793 // ROW_COUNT_ESTIMATE
794 ValueBigint.get(table.getRowCountApproximation(session))
795 );
796 }
797 break;
798 }
799 case COLUMNS: {
800 // reduce the number of tables to scan - makes some metadata queries
801 // 10x faster
802 final ArrayList<Table> tablesToList;
803 if (indexFrom != null && indexFrom.equals(indexTo)) {
804 String tableName = indexFrom.getString();
805 if (tableName == null) {
806 break;
807 }
808 tablesToList = getTablesByName(session, tableName);
809 } else {
810 tablesToList = getAllTables(session);
811 }
812 for (Table table : tablesToList) {
813 String tableName = table.getName();
814 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
815 continue;
816 }
817 if (hideTable(table, session)) {
818 continue;
819 }
820 Column[] cols = table.getColumns();
821 String collation = database.getCompareMode().getName();
822 for (int j = 0; j < cols.length; j++) {
823 Column c = cols[j];
824 Domain domain = c.getDomain();
825 TypeInfo typeInfo = c.getType();
826 ValueInteger precision = ValueInteger.get(MathUtils.convertLongToInt(typeInfo.getPrecision()));
827 ValueInteger scale = ValueInteger.get(typeInfo.getScale());
828 Sequence sequence = c.getSequence();
829 boolean hasDateTimePrecision;
830 int type = typeInfo.getValueType();
831 switch (type) {
832 case Value.TIME:
833 case Value.TIME_TZ:
834 case Value.DATE:
835 case Value.TIMESTAMP:
836 case Value.TIMESTAMP_TZ:
837 case Value.INTERVAL_SECOND:
838 case Value.INTERVAL_DAY_TO_SECOND:
839 case Value.INTERVAL_HOUR_TO_SECOND:
840 case Value.INTERVAL_MINUTE_TO_SECOND:
841 hasDateTimePrecision = true;
842 break;
843 default:
844 hasDateTimePrecision = false;
845 }
846 boolean isGenerated = c.isGenerated();
847 boolean isInterval = DataType.isIntervalType(type);
848 String createSQLWithoutName = c.getCreateSQLWithoutName();
849 add(session,
850 rows,
851 // TABLE_CATALOG
852 catalog,
853 // TABLE_SCHEMA
854 table.getSchema().getName(),
855 // TABLE_NAME
856 tableName,
857 // COLUMN_NAME
858 c.getName(),
859 // ORDINAL_POSITION
860 ValueInteger.get(j + 1),
861 // COLUMN_DEFAULT
862 isGenerated ? null : c.getDefaultSQL(),
863 // IS_NULLABLE
864 c.isNullable() ? "YES" : "NO",
865 // DATA_TYPE
866 ValueInteger.get(DataType.convertTypeToSQLType(typeInfo)),
867 // CHARACTER_MAXIMUM_LENGTH
868 precision,
869 // CHARACTER_OCTET_LENGTH
870 precision,
871 // NUMERIC_PRECISION
872 precision,
873 // NUMERIC_PRECISION_RADIX
874 ValueInteger.get(10),
875 // NUMERIC_SCALE
876 scale,
877 // DATETIME_PRECISION
878 hasDateTimePrecision ? scale : null,
879 // INTERVAL_TYPE
880 isInterval ? createSQLWithoutName.substring(9) : null,
881 // INTERVAL_PRECISION
882 isInterval ? precision : null,
883 // CHARACTER_SET_NAME
884 CHARACTER_SET_NAME,
885 // COLLATION_NAME
886 collation,
887 // DOMAIN_CATALOG
888 domain != null ? catalog : null,
889 // DOMAIN_SCHEMA
890 domain != null ? domain.getSchema().getName() : null,
891 // DOMAIN_NAME
892 domain != null ? domain.getName() : null,
893 // IS_GENERATED
894 isGenerated ? "ALWAYS" : "NEVER",
895 // GENERATION_EXPRESSION
896 isGenerated ? c.getDefaultSQL() : null,
897 // TYPE_NAME
898 identifier(isInterval ? "INTERVAL" : typeInfo.getDeclaredTypeName()),
899 // NULLABLE
900 ValueInteger.get(c.isNullable()
901 ? DatabaseMetaData.columnNullable : DatabaseMetaData.columnNoNulls),
902 // IS_COMPUTED
903 ValueBoolean.get(isGenerated),
904 // SELECTIVITY
905 ValueInteger.get(c.getSelectivity()),
906 // SEQUENCE_NAME
907 sequence == null ? null : sequence.getName(),
908 // REMARKS
909 replaceNullWithEmpty(c.getComment()),
910 // SOURCE_DATA_TYPE
911 // SMALLINT
912 null,
913 // COLUMN_TYPE
914 createSQLWithoutName,
915 // COLUMN_ON_UPDATE
916 c.getOnUpdateSQL(),
917 // IS_VISIBLE
918 ValueBoolean.get(c.getVisible()),
919 // CHECK_CONSTRAINT
920 null
921 );
922 }
923 }
924 break;
925 }
926 case INDEXES: {
927 // reduce the number of tables to scan - makes some metadata queries
928 // 10x faster
929 final ArrayList<Table> tablesToList;
930 if (indexFrom != null && indexFrom.equals(indexTo)) {
931 String tableName = indexFrom.getString();
932 if (tableName == null) {
933 break;
934 }
935 tablesToList = getTablesByName(session, tableName);
936 } else {
937 tablesToList = getAllTables(session);
938 }
939 for (Table table : tablesToList) {
940 String tableName = table.getName();
941 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
942 continue;
943 }
944 if (hideTable(table, session)) {
945 continue;
946 }
947 ArrayList<Index> indexes = table.getIndexes();
948 ArrayList<Constraint> constraints = table.getConstraints();
949 for (int j = 0; indexes != null && j < indexes.size(); j++) {
950 Index index = indexes.get(j);
951 if (index.getCreateSQL() == null) {
952 continue;
953 }
954 String constraintName = null;
955 for (int k = 0; constraints != null && k < constraints.size(); k++) {
956 Constraint constraint = constraints.get(k);
957 if (constraint.usesIndex(index)) {
958 if (index.getIndexType().isPrimaryKey()) {
959 if (constraint.getConstraintType() == Constraint.Type.PRIMARY_KEY) {
960 constraintName = constraint.getName();
961 }
962 } else {
963 constraintName = constraint.getName();
964 }
965 }
966 }
967 IndexColumn[] cols = index.getIndexColumns();
968 int uniqueColumnCount = index.getUniqueColumnCount();
969 String indexClass = index.getClass().getName();
970 for (int k = 0; k < cols.length; k++) {
971 IndexColumn idxCol = cols[k];
972 Column column = idxCol.column;
973 add(session,
974 rows,
975 // TABLE_CATALOG
976 catalog,
977 // TABLE_SCHEMA
978 table.getSchema().getName(),
979 // TABLE_NAME
980 tableName,
981 // NON_UNIQUE
982 ValueBoolean.get(k >= uniqueColumnCount),
983 // INDEX_NAME
984 index.getName(),
985 // ORDINAL_POSITION
986 ValueSmallint.get((short) (k + 1)),
987 // COLUMN_NAME
988 column.getName(),
989 // CARDINALITY
990 ValueInteger.get(0),
991 // PRIMARY_KEY
992 ValueBoolean.get(index.getIndexType().isPrimaryKey()),
993 // INDEX_TYPE_NAME
994 index.getIndexType().getSQL(false),
995 // IS_GENERATED
996 ValueBoolean.get(index.getIndexType().getBelongsToConstraint()),
997 // INDEX_TYPE
998 ValueSmallint.get(DatabaseMetaData.tableIndexOther),
999 // ASC_OR_DESC
1000 (idxCol.sortType & SortOrder.DESCENDING) != 0 ? "D" : "A",
1001 // PAGES
1002 ValueInteger.get(0),
1003 // FILTER_CONDITION
1004 "",
1005 // REMARKS
1006 replaceNullWithEmpty(index.getComment()),
1007 // SQL
1008 index.getCreateSQL(),
1009 // ID
1010 ValueInteger.get(index.getId()),
1011 // SORT_TYPE
1012 ValueInteger.get(idxCol.sortType),
1013 // CONSTRAINT_NAME
1014 constraintName,
1015 // INDEX_CLASS
1016 indexClass
1017 );
1018 }
1019 }
1020 }
1021 break;
1022 }
1023 case TABLE_TYPES: {
1024 add(session, rows, TableType.TABLE.toString());
1025 add(session, rows, TableType.TABLE_LINK.toString());
1026 add(session, rows, TableType.SYSTEM_TABLE.toString());
1027 add(session, rows, TableType.VIEW.toString());
1028 add(session, rows, TableType.EXTERNAL_TABLE_ENGINE.toString());
1029 break;
1030 }
1031 case TYPE_INFO: {
1032 for (int i = 1, l = Value.TYPE_COUNT; i < l; i++) {
1033 DataType t = DataType.getDataType(i);
1034 add(session,
1035 rows,
1036 // TYPE_NAME
1037 Value.getTypeName(t.type),
1038 // DATA_TYPE
1039 ValueInteger.get(t.sqlType),
1040 // PRECISION
1041 ValueInteger.get(MathUtils.convertLongToInt(t.maxPrecision)),
1042 // PREFIX
1043 t.prefix,
1044 // SUFFIX
1045 t.suffix,
1046 // PARAMS
1047 t.params,
1048 // AUTO_INCREMENT
1049 ValueBoolean.FALSE,
1050 // MINIMUM_SCALE
1051 ValueSmallint.get(MathUtils.convertIntToShort(t.minScale)),
1052 // MAXIMUM_SCALE
1053 ValueSmallint.get(MathUtils.convertIntToShort(t.maxScale)),
1054 // RADIX
1055 DataType.isNumericType(i) ? ValueInteger.get(10) : null,
1056 // POS
1057 ValueInteger.get(t.type),
1058 // CASE_SENSITIVE
1059 ValueBoolean.get(t.caseSensitive),
1060 // NULLABLE
1061 ValueSmallint.get((short) DatabaseMetaData.typeNullable),
1062 // SEARCHABLE
1063 ValueSmallint.get((short) DatabaseMetaData.typeSearchable)
1064 );
1065 }
1066 break;
1067 }
1068 case CATALOGS: {
1069 add(session, rows, catalog);
1070 break;
1071 }
1072 case SETTINGS: {
1073 for (Setting s : database.getAllSettings()) {
1074 String value = s.getStringValue();
1075 if (value == null) {
1076 value = Integer.toString(s.getIntValue());
1077 }
1078 add(session,
1079 rows,
1080 identifier(s.getName()), value
1081 );
1082 }
1083 add(session, rows, "info.BUILD_ID", "" + Constants.BUILD_ID);
1084 add(session, rows, "info.VERSION_MAJOR", "" + Constants.VERSION_MAJOR);
1085 add(session, rows, "info.VERSION_MINOR", "" + Constants.VERSION_MINOR);
1086 add(session, rows, "info.VERSION", Constants.FULL_VERSION);
1087 if (admin) {
1088 String[] settings = {
1089 "java.runtime.version", "java.vm.name",
1090 "java.vendor", "os.name", "os.arch", "os.version",
1091 "sun.os.patch.level", "file.separator",
1092 "path.separator", "line.separator", "user.country",
1093 "user.language", "user.variant", "file.encoding" };
1094 for (String s : settings) {
1095 add(session, rows, "property." + s, Utils.getProperty(s, ""));
1096 }
1097 }
1098 add(session, rows, "DEFAULT_NULL_ORDERING", database.getDefaultNullOrdering().name());
1099 add(session, rows, "EXCLUSIVE", database.getExclusiveSession() == null ?
1100 "FALSE" : "TRUE");
1101 add(session, rows, "MODE", database.getMode().getName());
1102 add(session, rows, "QUERY_TIMEOUT", Integer.toString(session.getQueryTimeout()));
1103 add(session, rows, "TIME ZONE", session.currentTimeZone().getId());
1104 add(session, rows, "TRUNCATE_LARGE_LENGTH", session.isTruncateLargeLength() ? "TRUE" : "FALSE");
1105 add(session, rows, "VARIABLE_BINARY", session.isVariableBinary() ? "TRUE" : "FALSE");
1106 add(session, rows, "OLD_INFORMATION_SCHEMA", session.isOldInformationSchema() ? "TRUE" : "FALSE");
1107 BitSet nonKeywords = session.getNonKeywords();
1108 if (nonKeywords != null) {
1109 add(session, rows, "NON_KEYWORDS", Parser.formatNonKeywords(nonKeywords));
1110 }
1111 add(session, rows, "RETENTION_TIME", Integer.toString(database.getRetentionTime()));
1112 // database settings
1113 for (Map.Entry<String, String> entry : database.getSettings().getSortedSettings()) {
1114 add(session, rows, entry.getKey(), entry.getValue());
1115 }
1116 database.getStore().getMvStore().populateInfo((name, value) -> add(session, rows, name, value));
1117 break;
1118 }
1119 case HELP: {
1120 String resource = "/org/h2/res/help.csv";
1121 try {
1122 final byte[] data = Utils.getResource(resource);
1123 final Reader reader = new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8);
1124 final Csv csv = new Csv();
1125 csv.setLineCommentCharacter('#');
1126 final ResultSet rs = csv.read(reader, null);
1127 final int columnCount = rs.getMetaData().getColumnCount() - 1;
1128 final String[] values = new String[5];
1129 for (int i = 0; rs.next(); i++) {
1130 for (int j = 0; j < columnCount; j++) {
1131 String s = rs.getString(1 + j);
1132 switch (j) {
1133 case 2: // SYNTAX column
1134 // Strip out the special annotations we use to help build
1135 // the railroad/BNF diagrams
1136 s = Help.stripAnnotationsFromSyntax(s);
1137 break;
1138 case 3: // TEXT column
1139 s = Help.processHelpText(s);
1140 }
1141 values[j] = s.trim();
1142 }
1143 add(session,
1144 rows,
1145 // ID
1146 ValueInteger.get(i),
1147 // SECTION
1148 values[0],
1149 // TOPIC
1150 values[1],
1151 // SYNTAX
1152 values[2],
1153 // TEXT
1154 values[3]
1155 );
1156 }
1157 } catch (Exception e) {
1158 throw DbException.convert(e);
1159 }
1160 break;
1161 }
1162 case SEQUENCES: {
1163 for (SchemaObject obj : getAllSchemaObjects(DbObject.SEQUENCE)) {
1164 Sequence s = (Sequence) obj;
1165 TypeInfo dataType = s.getDataType();
1166 String dataTypeName = Value.getTypeName(dataType.getValueType());
1167 ValueInteger declaredScale = ValueInteger.get(dataType.getScale());
1168 add(session,
1169 rows,
1170 // SEQUENCE_CATALOG
1171 catalog,
1172 // SEQUENCE_SCHEMA
1173 s.getSchema().getName(),
1174 // SEQUENCE_NAME
1175 s.getName(),
1176 // DATA_TYPE
1177 dataTypeName,
1178 // NUMERIC_PRECISION
1179 ValueInteger.get(s.getEffectivePrecision()),
1180 // NUMERIC_PRECISION_RADIX
1181 ValueInteger.get(10),
1182 // NUMERIC_SCALE
1183 declaredScale,
1184 // START_VALUE
1185 ValueBigint.get(s.getStartValue()),
1186 // MINIMUM_VALUE
1187 ValueBigint.get(s.getMinValue()),
1188 // MAXIMUM_VALUE
1189 ValueBigint.get(s.getMaxValue()),
1190 // INCREMENT
1191 ValueBigint.get(s.getIncrement()),
1192 // CYCLE_OPTION
1193 s.getCycle().isCycle() ? "YES" : "NO",
1194 // DECLARED_DATA_TYPE
1195 dataTypeName,
1196 // DECLARED_NUMERIC_PRECISION
1197 ValueInteger.get((int) dataType.getPrecision()),
1198 // DECLARED_NUMERIC_SCALE
1199 declaredScale,
1200 // CURRENT_VALUE
1201 ValueBigint.get(s.getCurrentValue()),
1202 // IS_GENERATED
1203 ValueBoolean.get(s.getBelongsToTable()),
1204 // REMARKS
1205 replaceNullWithEmpty(s.getComment()),
1206 // CACHE
1207 ValueBigint.get(s.getCacheSize()),
1208 // ID
1209 ValueInteger.get(s.getId()),
1210 // MIN_VALUE
1211 ValueBigint.get(s.getMinValue()),
1212 // MAX_VALUE
1213 ValueBigint.get(s.getMaxValue()),
1214 // IS_CYCLE
1215 ValueBoolean.get(s.getCycle().isCycle())
1216 );
1217 }
1218 break;
1219 }
1220 case USERS: {
1221 for (RightOwner rightOwner : database.getAllUsersAndRoles()) {
1222 if (rightOwner instanceof User) {
1223 User u = (User) rightOwner;
1224 if (admin || session.getUser() == u) {
1225 add(session,
1226 rows,
1227 // NAME
1228 identifier(u.getName()),
1229 // ADMIN
1230 String.valueOf(u.isAdmin()),
1231 // REMARKS
1232 replaceNullWithEmpty(u.getComment()),
1233 // ID
1234 ValueInteger.get(u.getId())
1235 );
1236 }
1237 }
1238 }
1239 break;
1240 }
1241 case ROLES: {
1242 for (RightOwner rightOwner : database.getAllUsersAndRoles()) {
1243 if (rightOwner instanceof Role) {
1244 Role r = (Role) rightOwner;
1245 if (admin || session.getUser().isRoleGranted(r)) {
1246 add(session,
1247 rows,
1248 // NAME
1249 identifier(r.getName()),
1250 // REMARKS
1251 replaceNullWithEmpty(r.getComment()),
1252 // ID
1253 ValueInteger.get(r.getId())
1254 );
1255 }
1256 }
1257 }
1258 break;
1259 }
1260 case RIGHTS: {
1261 if (admin) {
1262 for (Right r : database.getAllRights()) {
1263 Role role = r.getGrantedRole();
1264 DbObject grantee = r.getGrantee();
1265 String rightType = grantee.getType() == DbObject.USER ? "USER" : "ROLE";
1266 if (role == null) {
1267 DbObject object = r.getGrantedObject();
1268 Schema schema = null;
1269 Table table = null;
1270 if (object != null) {
1271 if (object instanceof Schema) {
1272 schema = (Schema) object;
1273 } else if (object instanceof Table) {
1274 table = (Table) object;
1275 schema = table.getSchema();
1276 }
1277 }
1278 String tableName = (table != null) ? table.getName() : "";
1279 String schemaName = (schema != null) ? schema.getName() : "";
1280 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1281 continue;
1282 }
1283 add(session,
1284 rows,
1285 // GRANTEE
1286 identifier(grantee.getName()),
1287 // GRANTEETYPE
1288 rightType,
1289 // GRANTEDROLE
1290 "",
1291 // RIGHTS
1292 r.getRights(),
1293 // TABLE_SCHEMA
1294 schemaName,
1295 // TABLE_NAME
1296 tableName,
1297 // ID
1298 ValueInteger.get(r.getId())
1299 );
1300 } else {
1301 add(session,
1302 rows,
1303 // GRANTEE
1304 identifier(grantee.getName()),
1305 // GRANTEETYPE
1306 rightType,
1307 // GRANTEDROLE
1308 identifier(role.getName()),
1309 // RIGHTS
1310 "",
1311 // TABLE_SCHEMA
1312 "",
1313 // TABLE_NAME
1314 "",
1315 // ID
1316 ValueInteger.get(r.getId())
1317 );
1318 }
1319 }
1320 }
1321 break;
1322 }
1323 case FUNCTION_ALIASES:
1324 for (Schema schema : database.getAllSchemas()) {
1325 for (UserDefinedFunction userDefinedFunction : schema.getAllFunctionsAndAggregates()) {
1326 if (userDefinedFunction instanceof FunctionAlias) {
1327 FunctionAlias alias = (FunctionAlias) userDefinedFunction;
1328 JavaMethod[] methods;
1329 try {
1330 methods = alias.getJavaMethods();
1331 } catch (DbException e) {
1332 continue;
1333 }
1334 for (FunctionAlias.JavaMethod method : methods) {
1335 TypeInfo typeInfo = method.getDataType();
1336 if (typeInfo == null) {
1337 typeInfo = TypeInfo.TYPE_NULL;
1338 }
1339 add(session,
1340 rows,
1341 // ALIAS_CATALOG
1342 catalog,
1343 // ALIAS_SCHEMA
1344 alias.getSchema().getName(),
1345 // ALIAS_NAME
1346 alias.getName(),
1347 // JAVA_CLASS
1348 alias.getJavaClassName(),
1349 // JAVA_METHOD
1350 alias.getJavaMethodName(),
1351 // DATA_TYPE
1352 ValueInteger.get(DataType.convertTypeToSQLType(typeInfo)),
1353 // TYPE_NAME
1354 typeInfo.getDeclaredTypeName(),
1355 // COLUMN_COUNT
1356 ValueInteger.get(method.getParameterCount()),
1357 // RETURNS_RESULT
1358 ValueSmallint.get(typeInfo.getValueType() == Value.NULL
1359 ? (short) DatabaseMetaData.procedureNoResult
1360 : (short) DatabaseMetaData.procedureReturnsResult),
1361 // REMARKS
1362 replaceNullWithEmpty(alias.getComment()),
1363 // ID
1364 ValueInteger.get(alias.getId()),
1365 // SOURCE
1366 alias.getSource()
1367 // when adding more columns, see also below
1368 );
1369 }
1370 } else {
1371 add(session,
1372 rows,
1373 // ALIAS_CATALOG
1374 catalog,
1375 // ALIAS_SCHEMA
1376 database.getMainSchema().getName(),
1377 // ALIAS_NAME
1378 userDefinedFunction.getName(),
1379 // JAVA_CLASS
1380 userDefinedFunction.getJavaClassName(),
1381 // JAVA_METHOD
1382 "",
1383 // DATA_TYPE
1384 ValueInteger.get(Types.NULL),
1385 // TYPE_NAME
1386 "NULL",
1387 // COLUMN_COUNT
1388 ValueInteger.get(1),
1389 // RETURNS_RESULT
1390 ValueSmallint.get((short) DatabaseMetaData.procedureReturnsResult),
1391 // REMARKS
1392 replaceNullWithEmpty(userDefinedFunction.getComment()),
1393 // ID
1394 ValueInteger.get(userDefinedFunction.getId()),
1395 // SOURCE
1396 ""
1397 // when adding more columns, see also below
1398 );
1399 }
1400 }
1401 }
1402 break;
1403 case FUNCTION_COLUMNS:
1404 for (Schema schema : database.getAllSchemas()) {
1405 for (UserDefinedFunction userDefinedFunction : schema.getAllFunctionsAndAggregates()) {
1406 if (userDefinedFunction instanceof FunctionAlias) {
1407 FunctionAlias alias = (FunctionAlias) userDefinedFunction;
1408 JavaMethod[] methods;
1409 try {
1410 methods = alias.getJavaMethods();
1411 } catch (DbException e) {
1412 continue;
1413 }
1414 for (FunctionAlias.JavaMethod method : methods) {
1415 // Add return column index 0
1416 TypeInfo typeInfo = method.getDataType();
1417 if (typeInfo != null && typeInfo.getValueType() != Value.NULL) {
1418 DataType dt = DataType.getDataType(typeInfo.getValueType());
1419 add(session,
1420 rows,
1421 // ALIAS_CATALOG
1422 catalog,
1423 // ALIAS_SCHEMA
1424 alias.getSchema().getName(),
1425 // ALIAS_NAME
1426 alias.getName(),
1427 // JAVA_CLASS
1428 alias.getJavaClassName(),
1429 // JAVA_METHOD
1430 alias.getJavaMethodName(),
1431 // COLUMN_COUNT
1432 ValueInteger.get(method.getParameterCount()),
1433 // POS
1434 ValueInteger.get(0),
1435 // COLUMN_NAME
1436 "P0",
1437 // DATA_TYPE
1438 ValueInteger.get(DataType.convertTypeToSQLType(typeInfo)),
1439 // TYPE_NAME
1440 typeInfo.getDeclaredTypeName(),
1441 // PRECISION
1442 ValueInteger.get(MathUtils.convertLongToInt(dt.defaultPrecision)),
1443 // SCALE
1444 ValueSmallint.get(MathUtils.convertIntToShort(dt.defaultScale)),
1445 // RADIX
1446 ValueSmallint.get((short) 10),
1447 // NULLABLE
1448 ValueSmallint.get((short) DatabaseMetaData.columnNullableUnknown),
1449 // COLUMN_TYPE
1450 ValueSmallint.get((short) DatabaseMetaData.procedureColumnReturn),
1451 // REMARKS
1452 "",
1453 // COLUMN_DEFAULT
1454 null
1455 );
1456 }
1457 Class<?>[] columnList = method.getColumnClasses();
1458 for (int k = 0; k < columnList.length; k++) {
1459 if (method.hasConnectionParam() && k == 0) {
1460 continue;
1461 }
1462 Class<?> clazz = columnList[k];
1463 TypeInfo columnTypeInfo = ValueToObjectConverter2.classToType(clazz);
1464 DataType dt = DataType.getDataType(columnTypeInfo.getValueType());
1465 add(session,
1466 rows,
1467 // ALIAS_CATALOG
1468 catalog,
1469 // ALIAS_SCHEMA
1470 alias.getSchema().getName(),
1471 // ALIAS_NAME
1472 alias.getName(),
1473 // JAVA_CLASS
1474 alias.getJavaClassName(),
1475 // JAVA_METHOD
1476 alias.getJavaMethodName(),
1477 // COLUMN_COUNT
1478 ValueInteger.get(method.getParameterCount()),
1479 // POS
1480 ValueInteger.get(k + (method.hasConnectionParam() ? 0 : 1)),
1481 // COLUMN_NAME
1482 "P" + (k + 1),
1483 // DATA_TYPE
1484 ValueInteger.get(DataType.convertTypeToSQLType(columnTypeInfo)),
1485 // TYPE_NAME
1486 columnTypeInfo.getDeclaredTypeName(),
1487 // PRECISION
1488 ValueInteger.get(MathUtils.convertLongToInt(dt.defaultPrecision)),
1489 // SCALE
1490 ValueSmallint.get(MathUtils.convertIntToShort(dt.defaultScale)),
1491 // RADIX
1492 ValueSmallint.get((short) 10),
1493 // NULLABLE
1494 ValueSmallint.get(clazz.isPrimitive()
1495 ? (short) DatabaseMetaData.columnNoNulls
1496 : (short) DatabaseMetaData.columnNullable),
1497 // COLUMN_TYPE
1498 ValueSmallint.get((short) DatabaseMetaData.procedureColumnIn),
1499 // REMARKS
1500 "",
1501 // COLUMN_DEFAULT
1502 null
1503 );
1504 }
1505 }
1506 }
1507 }
1508 }
1509 break;
1510 case SCHEMATA: {
1511 String collation = database.getCompareMode().getName();
1512 for (Schema schema : database.getAllSchemas()) {
1513 add(session,
1514 rows,
1515 // CATALOG_NAME
1516 catalog,
1517 // SCHEMA_NAME
1518 schema.getName(),
1519 // SCHEMA_OWNER
1520 identifier(schema.getOwner().getName()),
1521 // DEFAULT_CHARACTER_SET_NAME
1522 CHARACTER_SET_NAME,
1523 // DEFAULT_COLLATION_NAME
1524 collation,
1525 // IS_DEFAULT
1526 ValueBoolean.get(schema.getId() == Constants.MAIN_SCHEMA_ID),
1527 // REMARKS
1528 replaceNullWithEmpty(schema.getComment()),
1529 // ID
1530 ValueInteger.get(schema.getId())
1531 );
1532 }
1533 break;
1534 }
1535 case TABLE_PRIVILEGES: {
1536 for (Right r : database.getAllRights()) {
1537 DbObject object = r.getGrantedObject();
1538 if (!(object instanceof Table)) {
1539 continue;
1540 }
1541 Table table = (Table) object;
1542 if (hideTable(table, session)) {
1543 continue;
1544 }
1545 String tableName = table.getName();
1546 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1547 continue;
1548 }
1549 addPrivileges(session, rows, r.getGrantee(), catalog, table, null, r.getRightMask());
1550 }
1551 break;
1552 }
1553 case COLUMN_PRIVILEGES: {
1554 for (Right r : database.getAllRights()) {
1555 DbObject object = r.getGrantedObject();
1556 if (!(object instanceof Table)) {
1557 continue;
1558 }
1559 Table table = (Table) object;
1560 if (hideTable(table, session)) {
1561 continue;
1562 }
1563 String tableName = table.getName();
1564 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1565 continue;
1566 }
1567 DbObject grantee = r.getGrantee();
1568 int mask = r.getRightMask();
1569 for (Column column : table.getColumns()) {
1570 addPrivileges(session, rows, grantee, catalog, table, column.getName(), mask);
1571 }
1572 }
1573 break;
1574 }
1575 case COLLATIONS: {
1576 for (Locale l : CompareMode.getCollationLocales(false)) {
1577 add(session,
1578 rows,
1579 // NAME
1580 CompareMode.getName(l), // KEY
1581 l.toString()
1582 );
1583 }
1584 break;
1585 }
1586 case VIEWS: {
1587 for (Table table : getAllTables(session)) {
1588 if (table.getTableType() != TableType.VIEW) {
1589 continue;
1590 }
1591 String tableName = table.getName();
1592 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1593 continue;
1594 }
1595 TableView view = (TableView) table;
1596 add(session,
1597 rows,
1598 // TABLE_CATALOG
1599 catalog,
1600 // TABLE_SCHEMA
1601 table.getSchema().getName(),
1602 // TABLE_NAME
1603 tableName,
1604 // VIEW_DEFINITION
1605 table.getCreateSQL(),
1606 // CHECK_OPTION
1607 "NONE",
1608 // IS_UPDATABLE
1609 "NO",
1610 // STATUS
1611 view.isInvalid() ? "INVALID" : "VALID",
1612 // REMARKS
1613 replaceNullWithEmpty(view.getComment()),
1614 // ID
1615 ValueInteger.get(view.getId())
1616 );
1617 }
1618 break;
1619 }
1620 case IN_DOUBT: {
1621 ArrayList<InDoubtTransaction> prepared = database.getInDoubtTransactions();
1622 if (prepared != null && admin) {
1623 for (InDoubtTransaction prep : prepared) {
1624 add(session,
1625 rows,
1626 // TRANSACTION
1627 prep.getTransactionName(), // STATE
1628 prep.getStateDescription()
1629 );
1630 }
1631 }
1632 break;
1633 }
1634 case CROSS_REFERENCES: {
1635 for (SchemaObject obj : getAllSchemaObjects(
1636 DbObject.CONSTRAINT)) {
1637 Constraint constraint = (Constraint) obj;
1638 if (constraint.getConstraintType() != Constraint.Type.REFERENTIAL) {
1639 continue;
1640 }
1641 ConstraintReferential ref = (ConstraintReferential) constraint;
1642 IndexColumn[] cols = ref.getColumns();
1643 IndexColumn[] refCols = ref.getRefColumns();
1644 Table tab = ref.getTable();
1645 Table refTab = ref.getRefTable();
1646 String tableName = refTab.getName();
1647 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1648 continue;
1649 }
1650 ValueSmallint update = ValueSmallint.get(getRefAction(ref.getUpdateAction()));
1651 ValueSmallint delete = ValueSmallint.get(getRefAction(ref.getDeleteAction()));
1652 for (int j = 0; j < cols.length; j++) {
1653 add(session,
1654 rows,
1655 // PKTABLE_CATALOG
1656 catalog,
1657 // PKTABLE_SCHEMA
1658 refTab.getSchema().getName(),
1659 // PKTABLE_NAME
1660 refTab.getName(),
1661 // PKCOLUMN_NAME
1662 refCols[j].column.getName(),
1663 // FKTABLE_CATALOG
1664 catalog,
1665 // FKTABLE_SCHEMA
1666 tab.getSchema().getName(),
1667 // FKTABLE_NAME
1668 tab.getName(),
1669 // FKCOLUMN_NAME
1670 cols[j].column.getName(),
1671 // ORDINAL_POSITION
1672 ValueSmallint.get((short) (j + 1)),
1673 // UPDATE_RULE
1674 update,
1675 // DELETE_RULE
1676 delete,
1677 // FK_NAME
1678 ref.getName(),
1679 // PK_NAME
1680 ref.getReferencedConstraint().getName(),
1681 // DEFERRABILITY
1682 ValueSmallint.get((short) DatabaseMetaData.importedKeyNotDeferrable)
1683 );
1684 }
1685 }
1686 break;
1687 }
1688 case CONSTRAINTS: {
1689 for (SchemaObject obj : getAllSchemaObjects(
1690 DbObject.CONSTRAINT)) {
1691 Constraint constraint = (Constraint) obj;
1692 Constraint.Type constraintType = constraint.getConstraintType();
1693 String checkExpression = null;
1694 IndexColumn[] indexColumns = null;
1695 Table table = constraint.getTable();
1696 if (hideTable(table, session)) {
1697 continue;
1698 }
1699 Index index = constraint.getIndex();
1700 String uniqueIndexName = null;
1701 if (index != null) {
1702 uniqueIndexName = index.getName();
1703 }
1704 String tableName = table.getName();
1705 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
1706 continue;
1707 }
1708 if (constraintType == Constraint.Type.CHECK) {
1709 checkExpression = constraint.getExpression().getSQL(HasSQL.DEFAULT_SQL_FLAGS);
1710 } else if (constraintType == Constraint.Type.UNIQUE ||
1711 constraintType == Constraint.Type.PRIMARY_KEY) {
1712 indexColumns = ((ConstraintUnique) constraint).getColumns();
1713 } else if (constraintType == Constraint.Type.REFERENTIAL) {
1714 indexColumns = ((ConstraintReferential) constraint).getColumns();
1715 }
1716 String columnList = null;
1717 if (indexColumns != null) {
1718 StringBuilder builder = new StringBuilder();
1719 for (int i = 0, length = indexColumns.length; i < length; i++) {
1720 if (i > 0) {
1721 builder.append(',');
1722 }
1723 builder.append(indexColumns[i].column.getName());
1724 }
1725 columnList = builder.toString();
1726 }
1727 add(session,
1728 rows,
1729 // CONSTRAINT_CATALOG
1730 catalog,
1731 // CONSTRAINT_SCHEMA
1732 constraint.getSchema().getName(),
1733 // CONSTRAINT_NAME
1734 constraint.getName(),
1735 // CONSTRAINT_TYPE
1736 constraintType == Constraint.Type.PRIMARY_KEY ?
1737 constraintType.getSqlName() : constraintType.name(),
1738 // TABLE_CATALOG
1739 catalog,
1740 // TABLE_SCHEMA
1741 table.getSchema().getName(),
1742 // TABLE_NAME
1743 tableName,
1744 // UNIQUE_INDEX_NAME
1745 uniqueIndexName,
1746 // CHECK_EXPRESSION
1747 checkExpression,
1748 // COLUMN_LIST
1749 columnList,
1750 // REMARKS
1751 replaceNullWithEmpty(constraint.getComment()),
1752 // SQL
1753 constraint.getCreateSQL(),
1754 // ID
1755 ValueInteger.get(constraint.getId())
1756 );
1757 }
1758 break;
1759 }
1760 case CONSTANTS: {
1761 for (SchemaObject obj : getAllSchemaObjects(
1762 DbObject.CONSTANT)) {
1763 Constant constant = (Constant) obj;
1764 ValueExpression expr = constant.getValue();
1765 add(session,
1766 rows,
1767 // CONSTANT_CATALOG
1768 catalog,
1769 // CONSTANT_SCHEMA
1770 constant.getSchema().getName(),
1771 // CONSTANT_NAME
1772 constant.getName(),
1773 // DATA_TYPE
1774 ValueInteger.get(DataType.convertTypeToSQLType(expr.getType())),
1775 // REMARKS
1776 replaceNullWithEmpty(constant.getComment()),
1777 // SQL
1778 expr.getSQL(DEFAULT_SQL_FLAGS),
1779 // ID
1780 ValueInteger.get(constant.getId())
1781 );
1782 }
1783 break;
1784 }
1785 case DOMAINS: {
1786 for (SchemaObject obj : getAllSchemaObjects(DbObject.DOMAIN)) {
1787 Domain domain = (Domain) obj;
1788 Domain parentDomain = domain.getDomain();
1789 TypeInfo typeInfo = domain.getDataType();
1790 add(session,
1791 rows,
1792 // DOMAIN_CATALOG
1793 catalog,
1794 // DOMAIN_SCHEMA
1795 domain.getSchema().getName(),
1796 // DOMAIN_NAME
1797 domain.getName(),
1798 // DOMAIN_DEFAULT
1799 domain.getDefaultSQL(),
1800 // DOMAIN_ON_UPDATE
1801 domain.getOnUpdateSQL(),
1802 // DATA_TYPE
1803 ValueInteger.get(DataType.convertTypeToSQLType(typeInfo)),
1804 // PRECISION
1805 ValueInteger.get(MathUtils.convertLongToInt(typeInfo.getPrecision())),
1806 // SCALE
1807 ValueInteger.get(typeInfo.getScale()),
1808 // TYPE_NAME
1809 typeInfo.getDeclaredTypeName(),
1810 // PARENT_DOMAIN_CATALOG
1811 parentDomain != null ? catalog : null,
1812 // PARENT_DOMAIN_SCHEMA
1813 parentDomain != null ? parentDomain.getSchema().getName() : null,
1814 // PARENT_DOMAIN_NAME
1815 parentDomain != null ? parentDomain.getName() : null,
1816 // SELECTIVITY INT
1817 ValueInteger.get(Constants.SELECTIVITY_DEFAULT),
1818 // REMARKS
1819 replaceNullWithEmpty(domain.getComment()),
1820 // SQL
1821 domain.getCreateSQL(),
1822 // ID
1823 ValueInteger.get(domain.getId()),
1824 // COLUMN_DEFAULT
1825 domain.getDefaultSQL(),
1826 // IS_NULLABLE
1827 "YES",
1828 // CHECK_CONSTRAINT
1829 null
1830 );
1831 }
1832 break;
1833 }
1834 case TRIGGERS: {
1835 for (SchemaObject obj : getAllSchemaObjects(
1836 DbObject.TRIGGER)) {
1837 TriggerObject trigger = (TriggerObject) obj;
1838 Table table = trigger.getTable();
1839 add(session,
1840 rows,
1841 // TRIGGER_CATALOG
1842 catalog,
1843 // TRIGGER_SCHEMA
1844 trigger.getSchema().getName(),
1845 // TRIGGER_NAME
1846 trigger.getName(),
1847 // TRIGGER_TYPE
1848 trigger.getTypeNameList(new StringBuilder()).toString(),
1849 // TABLE_CATALOG
1850 catalog,
1851 // TABLE_SCHEMA
1852 table.getSchema().getName(),
1853 // TABLE_NAME
1854 table.getName(),
1855 // BEFORE
1856 ValueBoolean.get(trigger.isBefore()),
1857 // JAVA_CLASS
1858 trigger.getTriggerClassName(),
1859 // QUEUE_SIZE
1860 ValueInteger.get(trigger.getQueueSize()),
1861 // NO_WAIT
1862 ValueBoolean.get(trigger.isNoWait()),
1863 // REMARKS
1864 replaceNullWithEmpty(trigger.getComment()),
1865 // SQL
1866 trigger.getCreateSQL(),
1867 // ID
1868 ValueInteger.get(trigger.getId())
1869 );
1870 }
1871 break;
1872 }
1873 case SESSIONS: {
1874 for (SessionLocal s : database.getSessions(false)) {
1875 if (admin || s == session) {
1876 NetworkConnectionInfo networkConnectionInfo = s.getNetworkConnectionInfo();
1877 Command command = s.getCurrentCommand();
1878 int blockingSessionId = s.getBlockingSessionId();
1879 add(session,
1880 rows,
1881 // ID
1882 ValueInteger.get(s.getId()),
1883 // USER_NAME
1884 s.getUser().getName(),
1885 // SERVER
1886 networkConnectionInfo == null ? null : networkConnectionInfo.getServer(),
1887 // CLIENT_ADDR
1888 networkConnectionInfo == null ? null : networkConnectionInfo.getClient(),
1889 // CLIENT_INFO
1890 networkConnectionInfo == null ? null : networkConnectionInfo.getClientInfo(),
1891 // SESSION_START
1892 s.getSessionStart(),
1893 // ISOLATION_LEVEL
1894 session.getIsolationLevel().getSQL(),
1895 // STATEMENT
1896 command == null ? null : command.toString(),
1897 // STATEMENT_START
1898 command == null ? null : s.getCommandStartOrEnd(),
1899 // CONTAINS_UNCOMMITTED
1900 ValueBoolean.get(s.hasPendingTransaction()),
1901 // STATE
1902 String.valueOf(s.getState()),
1903 // BLOCKER_ID
1904 blockingSessionId == 0 ? null : ValueInteger.get(blockingSessionId),
1905 // SLEEP_SINCE
1906 s.getState() == State.SLEEP ? s.getCommandStartOrEnd() : null
1907 );
1908 }
1909 }
1910 break;
1911 }
1912 case LOCKS: {
1913 for (SessionLocal s : database.getSessions(false)) {
1914 if (admin || s == session) {
1915 for (Table table : s.getLocks()) {
1916 add(session,
1917 rows,
1918 // TABLE_SCHEMA
1919 table.getSchema().getName(),
1920 // TABLE_NAME
1921 table.getName(),
1922 // SESSION_ID
1923 ValueInteger.get(s.getId()),
1924 // LOCK_TYPE
1925 table.isLockedExclusivelyBy(s) ? "WRITE" : "READ"
1926 );
1927 }
1928 }
1929 }
1930 break;
1931 }
1932 case SESSION_STATE: {
1933 for (String name : session.getVariableNames()) {
1934 Value v = session.getVariable(name);
1935 StringBuilder builder = new StringBuilder().append("SET @").append(name).append(' ');
1936 v.getSQL(builder, DEFAULT_SQL_FLAGS);
1937 add(session,
1938 rows,
1939 // KEY
1940 "@" + name,
1941 // SQL
1942 builder.toString()
1943 );
1944 }
1945 for (Table table : session.getLocalTempTables()) {
1946 add(session,
1947 rows,
1948 // KEY
1949 "TABLE " + table.getName(),
1950 // SQL
1951 table.getCreateSQL()
1952 );
1953 }
1954 String[] path = session.getSchemaSearchPath();
1955 if (path != null && path.length > 0) {
1956 StringBuilder builder = new StringBuilder("SET SCHEMA_SEARCH_PATH ");
1957 for (int i = 0, l = path.length; i < l; i++) {
1958 if (i > 0) {
1959 builder.append(", ");
1960 }
1961 StringUtils.quoteIdentifier(builder, path[i]);
1962 }
1963 add(session,
1964 rows,
1965 // KEY
1966 "SCHEMA_SEARCH_PATH",
1967 // SQL
1968 builder.toString()
1969 );
1970 }
1971 String schema = session.getCurrentSchemaName();
1972 if (schema != null) {
1973 add(session,
1974 rows,
1975 // KEY
1976 "SCHEMA",
1977 // SQL
1978 StringUtils.quoteIdentifier(new StringBuilder("SET SCHEMA "), schema).toString()
1979 );
1980 }
1981 TimeZoneProvider currentTimeZone = session.currentTimeZone();
1982 if (!currentTimeZone.equals(DateTimeUtils.getTimeZone())) {
1983 add(session,
1984 rows,
1985 // KEY
1986 "TIME ZONE",
1987 // SQL
1988 StringUtils.quoteStringSQL(new StringBuilder("SET TIME ZONE "), currentTimeZone.getId())
1989 .toString()
1990 );
1991 }
1992 break;
1993 }
1994 case QUERY_STATISTICS: {
1995 QueryStatisticsData control = database.getQueryStatisticsData();
1996 if (control != null) {
1997 for (QueryStatisticsData.QueryEntry entry : control.getQueries()) {
1998 add(session,
1999 rows,
2000 // SQL_STATEMENT
2001 entry.sqlStatement,
2002 // EXECUTION_COUNT
2003 ValueInteger.get(entry.count),
2004 // MIN_EXECUTION_TIME
2005 ValueDouble.get(entry.executionTimeMinNanos / 1_000_000d),
2006 // MAX_EXECUTION_TIME
2007 ValueDouble.get(entry.executionTimeMaxNanos / 1_000_000d),
2008 // CUMULATIVE_EXECUTION_TIME
2009 ValueDouble.get(entry.executionTimeCumulativeNanos / 1_000_000d),
2010 // AVERAGE_EXECUTION_TIME
2011 ValueDouble.get(entry.executionTimeMeanNanos / 1_000_000d),
2012 // STD_DEV_EXECUTION_TIME
2013 ValueDouble.get(entry.getExecutionTimeStandardDeviation() / 1_000_000d),
2014 // MIN_ROW_COUNT
2015 ValueBigint.get(entry.rowCountMin),
2016 // MAX_ROW_COUNT
2017 ValueBigint.get(entry.rowCountMax),
2018 // CUMULATIVE_ROW_COUNT
2019 ValueBigint.get(entry.rowCountCumulative),
2020 // AVERAGE_ROW_COUNT
2021 ValueDouble.get(entry.rowCountMean),
2022 // STD_DEV_ROW_COUNT
2023 ValueDouble.get(entry.getRowCountStandardDeviation())
2024 );
2025 }
2026 }
2027 break;
2028 }
2029 case SYNONYMS: {
2030 for (TableSynonym synonym : database.getAllSynonyms()) {
2031 add(session,
2032 rows,
2033 // SYNONYM_CATALOG
2034 catalog,
2035 // SYNONYM_SCHEMA
2036 synonym.getSchema().getName(),
2037 // SYNONYM_NAME
2038 synonym.getName(),
2039 // SYNONYM_FOR
2040 synonym.getSynonymForName(),
2041 // SYNONYM_FOR_SCHEMA
2042 synonym.getSynonymForSchema().getName(),
2043 // TYPE NAME
2044 "SYNONYM",
2045 // STATUS
2046 "VALID",
2047 // REMARKS
2048 replaceNullWithEmpty(synonym.getComment()),
2049 // ID
2050 ValueInteger.get(synonym.getId())
2051 );
2052 }
2053 break;
2054 }
2055 case TABLE_CONSTRAINTS: {
2056 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2057 Constraint constraint = (Constraint) obj;
2058 Constraint.Type constraintType = constraint.getConstraintType();
2059 if (constraintType == Constraint.Type.DOMAIN) {
2060 continue;
2061 }
2062 Table table = constraint.getTable();
2063 if (hideTable(table, session)) {
2064 continue;
2065 }
2066 String tableName = table.getName();
2067 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
2068 continue;
2069 }
2070 add(session,
2071 rows,
2072 // CONSTRAINT_CATALOG
2073 catalog,
2074 // CONSTRAINT_SCHEMA
2075 constraint.getSchema().getName(),
2076 // CONSTRAINT_NAME
2077 constraint.getName(),
2078 // CONSTRAINT_TYPE
2079 constraintType.getSqlName(),
2080 // TABLE_CATALOG
2081 catalog,
2082 // TABLE_SCHEMA
2083 table.getSchema().getName(),
2084 // TABLE_NAME
2085 tableName,
2086 // IS_DEFERRABLE
2087 "NO",
2088 // INITIALLY_DEFERRED
2089 "NO",
2090 // REMARKS
2091 replaceNullWithEmpty(constraint.getComment()),
2092 // SQL
2093 constraint.getCreateSQL(),
2094 // ID
2095 ValueInteger.get(constraint.getId())
2096 );
2097 }
2098 break;
2099 }
2100 case DOMAIN_CONSTRAINTS: {
2101 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2102 if (((Constraint) obj).getConstraintType() != Constraint.Type.DOMAIN) {
2103 continue;
2104 }
2105 ConstraintDomain constraint = (ConstraintDomain) obj;
2106 Domain domain = constraint.getDomain();
2107 add(session,
2108 rows,
2109 // CONSTRAINT_CATALOG
2110 catalog,
2111 // CONSTRAINT_SCHEMA
2112 constraint.getSchema().getName(),
2113 // CONSTRAINT_NAME
2114 constraint.getName(),
2115 // DOMAIN_CATALOG
2116 catalog,
2117 // DOMAIN_SCHEMA
2118 domain.getSchema().getName(),
2119 // DOMAIN_NAME
2120 domain.getName(),
2121 // IS_DEFERRABLE
2122 "NO",
2123 // INITIALLY_DEFERRED
2124 "NO",
2125 // REMARKS
2126 replaceNullWithEmpty(constraint.getComment()),
2127 // SQL
2128 constraint.getCreateSQL(),
2129 // ID
2130 ValueInteger.get(constraint.getId())
2131 );
2132 }
2133 break;
2134 }
2135 case KEY_COLUMN_USAGE: {
2136 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2137 Constraint constraint = (Constraint) obj;
2138 Constraint.Type constraintType = constraint.getConstraintType();
2139 IndexColumn[] indexColumns = null;
2140 if (constraintType == Constraint.Type.UNIQUE || constraintType == Constraint.Type.PRIMARY_KEY) {
2141 indexColumns = ((ConstraintUnique) constraint).getColumns();
2142 } else if (constraintType == Constraint.Type.REFERENTIAL) {
2143 indexColumns = ((ConstraintReferential) constraint).getColumns();
2144 }
2145 if (indexColumns == null) {
2146 continue;
2147 }
2148 Table table = constraint.getTable();
2149 if (hideTable(table, session)) {
2150 continue;
2151 }
2152 String tableName = table.getName();
2153 if (!checkIndex(session, tableName, indexFrom, indexTo)) {
2154 continue;
2155 }
2156 ConstraintUnique referenced;
2157 if (constraintType == Constraint.Type.REFERENTIAL) {
2158 referenced = constraint.getReferencedConstraint();
2159 } else {
2160 referenced = null;
2161 }
2162 Index index = constraint.getIndex();
2163 for (int i = 0; i < indexColumns.length; i++) {
2164 IndexColumn indexColumn = indexColumns[i];
2165 ValueInteger ordinalPosition = ValueInteger.get(i + 1);
2166 ValueInteger positionInUniqueConstraint = null;
2167 if (referenced != null) {
2168 Column c = ((ConstraintReferential) constraint).getRefColumns()[i].column;
2169 IndexColumn[] refColumns = referenced.getColumns();
2170 for (int j = 0; j < refColumns.length; j++) {
2171 if (refColumns[j].column.equals(c)) {
2172 positionInUniqueConstraint = ValueInteger.get(j + 1);
2173 break;
2174 }
2175 }
2176 }
2177 add(session,
2178 rows,
2179 // CONSTRAINT_CATALOG
2180 catalog,
2181 // CONSTRAINT_SCHEMA
2182 constraint.getSchema().getName(),
2183 // CONSTRAINT_NAME
2184 constraint.getName(),
2185 // TABLE_CATALOG
2186 catalog,
2187 // TABLE_SCHEMA
2188 table.getSchema().getName(),
2189 // TABLE_NAME
2190 tableName,
2191 // COLUMN_NAME
2192 indexColumn.columnName,
2193 // ORDINAL_POSITION
2194 ordinalPosition,
2195 // POSITION_IN_UNIQUE_CONSTRAINT
2196 positionInUniqueConstraint,
2197 // INDEX_CATALOG
2198 index != null ? catalog : null,
2199 // INDEX_SCHEMA
2200 index != null ? index.getSchema().getName() : null,
2201 // INDEX_NAME
2202 index != null ? index.getName() : null
2203 );
2204 }
2205 }
2206 break;
2207 }
2208 case REFERENTIAL_CONSTRAINTS: {
2209 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2210 if (((Constraint) obj).getConstraintType() != Constraint.Type.REFERENTIAL) {
2211 continue;
2212 }
2213 ConstraintReferential constraint = (ConstraintReferential) obj;
2214 Table table = constraint.getTable();
2215 if (hideTable(table, session)) {
2216 continue;
2217 }
2218 ConstraintUnique unique = constraint.getReferencedConstraint();
2219 add(session,
2220 rows,
2221 // CONSTRAINT_CATALOG
2222 catalog,
2223 // CONSTRAINT_SCHEMA
2224 constraint.getSchema().getName(),
2225 // CONSTRAINT_NAME
2226 constraint.getName(),
2227 // UNIQUE_CONSTRAINT_CATALOG
2228 catalog,
2229 // UNIQUE_CONSTRAINT_SCHEMA
2230 unique.getSchema().getName(),
2231 // UNIQUE_CONSTRAINT_NAME
2232 unique.getName(),
2233 // MATCH_OPTION
2234 "NONE",
2235 // UPDATE_RULE
2236 constraint.getUpdateAction().getSqlName(),
2237 // DELETE_RULE
2238 constraint.getDeleteAction().getSqlName()
2239 );
2240 }
2241 break;
2242 }
2243 case CHECK_CONSTRAINTS: {
2244 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2245 Constraint constraint = (Constraint) obj;
2246 Type constraintType = constraint.getConstraintType();
2247 if (constraintType == Constraint.Type.CHECK) {
2248 ConstraintCheck check = (ConstraintCheck) obj;
2249 Table table = check.getTable();
2250 if (hideTable(table, session)) {
2251 continue;
2252 }
2253 } else if (constraintType != Constraint.Type.DOMAIN) {
2254 continue;
2255 }
2256 add(session,
2257 rows,
2258 // CONSTRAINT_CATALOG
2259 catalog,
2260 // CONSTRAINT_SCHEMA
2261 obj.getSchema().getName(),
2262 // CONSTRAINT_NAME
2263 obj.getName(),
2264 // CHECK_CLAUSE
2265 constraint.getExpression().getSQL(DEFAULT_SQL_FLAGS, Expression.WITHOUT_PARENTHESES)
2266 );
2267 }
2268 break;
2269 }
2270 case CONSTRAINT_COLUMN_USAGE: {
2271 for (SchemaObject obj : getAllSchemaObjects(DbObject.CONSTRAINT)) {
2272 Constraint constraint = (Constraint) obj;
2273 switch (constraint.getConstraintType()) {
2274 case CHECK:
2275 case DOMAIN: {
2276 HashSet<Column> columns = new HashSet<>();
2277 constraint.getExpression().isEverything(ExpressionVisitor.getColumnsVisitor(columns, null));
2278 for (Column column: columns) {
2279 Table table = column.getTable();
2280 if (checkIndex(session, table.getName(), indexFrom, indexTo) && !hideTable(table, session)) {
2281 addConstraintColumnUsage(session, rows, catalog, constraint, column);
2282 }
2283 }
2284 break;
2285 }
2286 case REFERENTIAL: {
2287 Table table = constraint.getRefTable();
2288 if (checkIndex(session, table.getName(), indexFrom, indexTo) && !hideTable(table, session)) {
2289 for (Column column : constraint.getReferencedColumns(table)) {
2290 addConstraintColumnUsage(session, rows, catalog, constraint, column);
2291 }
2292 }
2293 }
2294 //$FALL-THROUGH$
2295 case PRIMARY_KEY:
2296 case UNIQUE: {
2297 Table table = constraint.getTable();
2298 if (checkIndex(session, table.getName(), indexFrom, indexTo) && !hideTable(table, session)) {
2299 for (Column column : constraint.getReferencedColumns(table)) {
2300 addConstraintColumnUsage(session, rows, catalog, constraint, column);
2301 }
2302 }
2303 }
2304 }
2305 }
2306 break;
2307 }
2308 default:
2309 throw DbException.getInternalError("type=" + type);
2310 }
2311 return rows;
2312 }
2313
2314 private static short getRefAction(ConstraintActionType action) {
2315 switch (action) {
2316 case CASCADE:
2317 return DatabaseMetaData.importedKeyCascade;
2318 case RESTRICT:
2319 return DatabaseMetaData.importedKeyRestrict;
2320 case SET_DEFAULT:
2321 return DatabaseMetaData.importedKeySetDefault;
2322 case SET_NULL:
2323 return DatabaseMetaData.importedKeySetNull;
2324 default:
2325 throw DbException.getInternalError("action="+action);
2326 }
2327 }
2328
2329 private void addConstraintColumnUsage(SessionLocal session, ArrayList<Row> rows, String catalog,
2330 Constraint constraint, Column column) {
2331 Table table = column.getTable();
2332 add(session,
2333 rows,
2334 // TABLE_CATALOG
2335 catalog,
2336 // TABLE_SCHEMA
2337 table.getSchema().getName(),
2338 // TABLE_NAME
2339 table.getName(),
2340 // COLUMN_NAME
2341 column.getName(),
2342 // CONSTRAINT_CATALOG
2343 catalog,
2344 // CONSTRAINT_SCHEMA
2345 constraint.getSchema().getName(),
2346 // CONSTRAINT_NAME
2347 constraint.getName()
2348 );
2349 }
2350
2351 private void addPrivileges(SessionLocal session, ArrayList<Row> rows, DbObject grantee,
2352 String catalog, Table table, String column, int rightMask) {
2353 if ((rightMask & Right.SELECT) != 0) {
2354 addPrivilege(session, rows, grantee, catalog, table, column, "SELECT");
2355 }
2356 if ((rightMask & Right.INSERT) != 0) {
2357 addPrivilege(session, rows, grantee, catalog, table, column, "INSERT");
2358 }
2359 if ((rightMask & Right.UPDATE) != 0) {
2360 addPrivilege(session, rows, grantee, catalog, table, column, "UPDATE");
2361 }
2362 if ((rightMask & Right.DELETE) != 0) {
2363 addPrivilege(session, rows, grantee, catalog, table, column, "DELETE");
2364 }
2365 }
2366
2367 private void addPrivilege(SessionLocal session, ArrayList<Row> rows, DbObject grantee,
2368 String catalog, Table table, String column, String right) {
2369 String isGrantable = "NO";
2370 if (grantee.getType() == DbObject.USER) {
2371 User user = (User) grantee;
2372 if (user.isAdmin()) {
2373 // the right is grantable if the grantee is an admin
2374 isGrantable = "YES";
2375 }
2376 }
2377 if (column == null) {
2378 add(session,
2379 rows,
2380 // GRANTOR
2381 null,
2382 // GRANTEE
2383 identifier(grantee.getName()),
2384 // TABLE_CATALOG
2385 catalog,
2386 // TABLE_SCHEMA
2387 table.getSchema().getName(),
2388 // TABLE_NAME
2389 table.getName(),
2390 // PRIVILEGE_TYPE
2391 right,
2392 // IS_GRANTABLE
2393 isGrantable
2394 );
2395 } else {
2396 add(session,
2397 rows,
2398 // GRANTOR
2399 null,
2400 // GRANTEE
2401 identifier(grantee.getName()),
2402 // TABLE_CATALOG
2403 catalog,
2404 // TABLE_SCHEMA
2405 table.getSchema().getName(),
2406 // TABLE_NAME
2407 table.getName(),
2408 // COLUMN_NAME
2409 column,
2410 // PRIVILEGE_TYPE
2411 right,
2412 // IS_GRANTABLE
2413 isGrantable
2414 );
2415 }
2416 }
2417
2418 private ArrayList<SchemaObject> getAllSchemaObjects(int type) {
2419 ArrayList<SchemaObject> list = new ArrayList<>();
2420 for (Schema schema : database.getAllSchemas()) {
2421 schema.getAll(type, list);
2422 }
2423 return list;
2424 }
2425
2426 /**
2427 * Get all tables of this database, including local temporary tables for the
2428 * session.
2429 *
2430 * @param session the session
2431 * @return the array of tables
2432 */
2433 private ArrayList<Table> getAllTables(SessionLocal session) {
2434 ArrayList<Table> tables = new ArrayList<>();
2435 for (Schema schema : database.getAllSchemas()) {
2436 tables.addAll(schema.getAllTablesAndViews(session));
2437 }
2438 tables.addAll(session.getLocalTempTables());
2439 return tables;
2440 }
2441
2442 private ArrayList<Table> getTablesByName(SessionLocal session, String tableName) {
2443 // we expect that at most one table matches, at least in most cases
2444 ArrayList<Table> tables = new ArrayList<>(1);
2445 for (Schema schema : database.getAllSchemas()) {
2446 Table table = schema.getTableOrViewByName(session, tableName);
2447 if (table != null) {
2448 tables.add(table);
2449 }
2450 }
2451 Table table = session.findLocalTempTable(tableName);
2452 if (table != null) {
2453 tables.add(table);
2454 }
2455 return tables;
2456 }
2457
2458 @Override
2459 public long getMaxDataModificationId() {
2460 switch (type) {
2461 case SETTINGS:
2462 case SEQUENCES:
2463 case IN_DOUBT:
2464 case SESSIONS:
2465 case LOCKS:
2466 case SESSION_STATE:
2467 return Long.MAX_VALUE;
2468 }
2469 return database.getModificationDataId();
2470 }
2471
2472 }