-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDatabase.java
More file actions
1262 lines (1062 loc) · 48.8 KB
/
Database.java
File metadata and controls
1262 lines (1062 loc) · 48.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package javaxt.sql;
import java.sql.ResultSet;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import javax.sql.ConnectionPoolDataSource;
//******************************************************************************
//** Database
//******************************************************************************
/**
* Used to encapsulate database connection information, open connections to
* the database, and execute queries.
*
******************************************************************************/
public class Database implements Cloneable {
private String name; //name of the catalog used to store tables, views, etc.
private String host;
private Integer port;
private String username;
private String password;
private Driver driver;
private java.util.Properties properties;
private String querystring;
private ConnectionPoolDataSource ConnectionPoolDataSource;
private static final Class<?>[] stringType = { String.class };
private static final Class<?>[] integerType = { Integer.TYPE };
private ConnectionPool connectionPool;
private int maxConnections = 15;
private Table[] tables = null;
private String[] catalogs = null;
private boolean cacheMetadata = false;
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class. Note that you will need to set the
* name, host, port, username, password, and driver in order to create a
* connection to the database.
*/
public Database(){
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class.
* @param name Name of the catalog used to store tables, views, etc.
* @param host Server name or IP address.
* @param port Port number used to establish connections to the database.
* @param username Username used to log into the database
* @param password Password used to log into the database
*/
public Database(String name, String host, int port, String username, String password, Driver driver) {
this.name = name;
this.host = host;
this.port = port>0 ? port : null;
this.username = username;
this.password = password;
this.driver = driver;
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a java.sql.Connection.
*/
public Database(java.sql.Connection conn){
try{
DatabaseMetaData dbmd = conn.getMetaData();
this.name = conn.getCatalog();
this.username = dbmd.getUserName();
parseURL(dbmd.getURL());
//dbmd.getDriverName();
}
catch(Exception e){
//e.printStackTrace();
}
}
//**************************************************************************
//** Constructor
//**************************************************************************
/** Creates a new instance of this class using a jdbc connection string.
* Username and password may be appended to the end of the connection string
* in the property list.
* @param connStr A jdbc connection string/url. All connection URLs
* have the following form:
* <pre> jdbc:[dbVendor]://[dbName][propertyList] </pre>
*
* Examples:
* <p>Derby:</p>
* <pre> jdbc:derby://temp/my.db;user=admin;password=mypassword </pre>
* <p>SQL Server:</p>
* <pre> jdbc:sqlserver://192.168.0.80;databaseName=master;user=admin;password=mypassword </pre>
*/
public Database(String connStr){
parseURL(connStr);
}
//**************************************************************************
//** parseURL
//**************************************************************************
/** Used to parse a JDBC connection string (url)
*/
private void parseURL(String connStr){
String[] arrConnStr = connStr.split(";");
String jdbcURL = arrConnStr[0];
//Update jdbc url for URL parser
if (!jdbcURL.contains("//")){
String protocol = jdbcURL.substring(jdbcURL.indexOf(":")+1);
protocol = "jdbc:" + protocol.substring(0, protocol.indexOf(":")) + ":";
String path = jdbcURL.substring(protocol.length());
jdbcURL = protocol + "//" + path;
}
//Parse url and extract connection parameters
javaxt.utils.URL url = new javaxt.utils.URL(jdbcURL);
host = url.getHost();
port = url.getPort();
driver = Driver.findDriver(url.getProtocol());
if (driver==null){
driver = new Driver(null, null, url.getProtocol());
}
if (name==null){
name = url.getPath();
if (this.name!=null && this.name.startsWith("/")){
this.name = this.name.substring(1);
}
}
querystring = url.getQueryString();
if (querystring.length()==0) querystring = null;
//Extract additional connection parameters
for (int i=1; i<arrConnStr.length; i++) {
String[] arrParams = arrConnStr[i].split("=");
String paramName = arrParams[0].toLowerCase();
String paramValue = arrParams[1];
if (paramName.equals("database")){
this.name = paramValue;
}
else if (paramName.equals("user")){
this.username = paramValue;
}
else if (paramName.equals("password")){
this.password = paramValue;
}
else if (paramName.equalsIgnoreCase("derby.system.home")){
//if (System.getProperty("derby.system.home")==null)
System.setProperty("derby.system.home", paramValue);
}
else{
//Extract additional properties
if (properties==null) properties = new java.util.Properties();
properties.put(arrParams[0], arrParams[1]);
}
}
}
//**************************************************************************
//** setName
//**************************************************************************
/** Sets the name of the catalog used to store tables, views, etc.
*/
public void setName(String name){
this.name = name;
}
//**************************************************************************
//** getName
//**************************************************************************
/** Gets the name of the catalog used to store tables, views, etc.
*/
public String getName(){
return name;
}
//**************************************************************************
//** setHost
//**************************************************************************
/** Used to set the path to the database (server name and port).
*/
public void setHost(String host, int port){
this.host = host;
this.port = port;
}
//**************************************************************************
//** setHost
//**************************************************************************
/** Used to set the path to the database.
* @param host Server name/port (e.g. localhost:9080) or a path to a file
* (e.g. /temp/firebird.db)
*/
public void setHost(String host){
if (host==null){
this.host = null;
}
else{
host = host.trim();
if (host.contains(":")){
try{
this.host = host.substring(0, host.indexOf(":"));
this.port = Integer.valueOf(host.substring(host.indexOf(":")+1));
}
catch(Exception e){
this.host = host; //eg file paths
}
}
else{
this.host = host;
}
}
}
//**************************************************************************
//** getHost
//**************************************************************************
/** Returns the name or IP address of the server or a physical path to the
* database file.
*/
public String getHost(){
return host;
}
//**************************************************************************
//** setPort
//**************************************************************************
public void setPort(int port){
this.port = port;
}
public Integer getPort(){
return port;
}
//**************************************************************************
//** setDriver
//**************************************************************************
public void setDriver(Driver driver){
this.driver = driver;
}
//**************************************************************************
//** setDriver
//**************************************************************************
/** Used to find a driver that corresponds to a given vendor name, class
* name, or protocol.
*/
public void setDriver(String driver){ //throw exception?
this.driver = Driver.findDriver(driver);
}
public void setDriver(java.sql.Driver driver){
this.driver = new Driver(driver);
}
public void setDriver(Class driver){
this.driver = Driver.findDriver(driver.getCanonicalName());
}
//**************************************************************************
//** getDriver
//**************************************************************************
public Driver getDriver(){
return driver;
}
//**************************************************************************
//** setUserName
//**************************************************************************
public void setUserName(String username){
this.username = username;
}
public String getUserName(){
return username;
}
//**************************************************************************
//** setPassword
//**************************************************************************
public void setPassword(String password){
this.password = password;
}
public String getPassword(){
return password;
}
public void setProperties(java.util.Properties properties){
this.properties = properties;
}
public java.util.Properties getProperties(){
return properties;
}
//**************************************************************************
//** getConnectionString
//**************************************************************************
/** Returns a JDBC connection string used to connect to the database.
* Username and password are appended to the end of the url.
*/
public String getConnectionString(){
String path = getURL(false);
if (username!=null) path += ";user=" + username;
if (password!=null) path += ";password=" + password;
return path;
}
//**************************************************************************
//** getURL
//**************************************************************************
/** Used to construct a JDBC connection string
*/
protected String getURL(boolean appendProperties){
//Update Server Name
String server = host;
if (port!=null && port>0) server += ":" + port;
String vendor = driver.getVendor();
if (vendor==null) vendor = "";
if (vendor.equals("Derby") || vendor.equals("SQLite")){
server = ":" + server;
}
//Update Initial Catalog
String database = "";
if (name!=null) {
if (name.trim().length()>0){
if (vendor.equals("SQLServer")){
database = ";databaseName=" + name;
}
else if (vendor.equals("Oracle")){
database = ":" + name; //only tested with thin driver
}
else if (vendor.equals("Derby")){
database = ";databaseName=" + name;
}
else{
database = "/" + name;
}
}
}
//Append querystring as needed
if (querystring!=null) database += "?" + querystring;
//Set Path
String path = driver.getProtocol() + "://";
//Update path as needed
if (vendor.equals("Sybase")){
if (path.toLowerCase().contains((CharSequence) "tds:")==false){
path = driver.getProtocol() + "Tds:";
}
}
else if (vendor.equals("Oracle")){
path = driver.getProtocol() + ":thin:@"; //only tested with thin driver
}
else if (vendor.equals("Derby") || vendor.equals("SQLite")){
path = driver.getProtocol();
}
else if (vendor.equals("H2")){
//Special case for newer versions of H2. In the 2.x releases of H2,
//the protocol changed for embedded file databases. The following
//logic will update the path to set the correct protocol depending
//on which version of the driver we have.
if (driver.getProtocol().equals("jdbc:h2")){
java.sql.Driver d = driver.getDriver();
try{
if (d==null) d = driver.load();
if (d.getMajorVersion()>1){
if (host == null || host.trim().isEmpty() || host.equalsIgnoreCase("memory")) {
path = driver.getProtocol() + ":mem:";
} else {
path = driver.getProtocol() + ":file:";
}
}
}
catch(Exception e){
}
}
}
//Assemble Connection String
String url = path + server + database;
if (appendProperties){
StringBuilder props = new StringBuilder();
if (properties!=null){
java.util.Iterator it = properties.keySet().iterator();
while (it.hasNext()){
Object key = it.next();
Object val = properties.get(key);
props.append(";" + key + "=" + val);
}
}
url+= props.toString();
}
return url;
}
//**************************************************************************
//** getConnection
//**************************************************************************
/** Returns a connection to the database. If a connection pool has been
* initialized, a connection is returned from the pool. Otherwise, a new
* connection is created. In either case, the connection must be closed
* immediately after use. See Connection.close() for details.
*/
public Connection getConnection() throws SQLException {
Connection connection = new Connection();
connection.open(this);
return connection;
}
//**************************************************************************
//** initConnectionPool
//**************************************************************************
/** Used to initialize a connection pool. Subsequent called to the
* getConnection() method will return connections from the pool.
*/
public void initConnectionPool() throws SQLException {
if (connectionPool!=null) return;
initConnectionPool(new ConnectionPool(this, maxConnections));
}
//**************************************************************************
//** initConnectionPool
//**************************************************************************
/** Used to configure the Database class to use a specific instance of a
* javaxt.sql.ConnectionPool. Subsequent called to the getConnection()
* method will return connections from the pool.
* @param cp An instance of a javaxt.sql.ConnectionPool.
*/
public void initConnectionPool(ConnectionPool cp) throws SQLException {
if (connectionPool!=null) return;
connectionPool = cp;
//Create Shutdown Hook to clean up the connection pool on exit
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
if (connectionPool!=null){
//System.out.println("\r\nShutting down connection pool...");
try{
connectionPool.close();
}
catch(Exception e){
//e.printStackTrace();
}
}
}
});
}
//**************************************************************************
//** terminateConnectionPool
//**************************************************************************
/** Used to terminate the connection pool, closing all active connections.
*/
public void terminateConnectionPool() throws SQLException {
if (connectionPool!=null){
connectionPool.close();
connectionPool = null;
}
}
//**************************************************************************
//** setConnectionPoolSize
//**************************************************************************
/** Used to specify the size of the connection pool. The pool size must be
* set before initializing the connection pool. If the pool size is not
* defined, the connection pool will default to 15.
*/
public void setConnectionPoolSize(int maxConnections){
if (connectionPool!=null) return;
this.maxConnections = maxConnections;
}
//**************************************************************************
//** getConnectionPoolSize
//**************************************************************************
/** Returns the size of the connection pool.
*/
public int getConnectionPoolSize(){
return maxConnections;
}
//**************************************************************************
//** getConnectionPool
//**************************************************************************
/** Returns the connection pool that was created via the initConnectionPool
* method. Returns null if the connection pool has not been not initialized
* or if the connection pool has been terminated.
*/
public ConnectionPool getConnectionPool(){
return connectionPool;
}
//**************************************************************************
//** setConnectionPoolDataSource
//**************************************************************************
/** Used to set the ConnectionPoolDataSource for the database. Typically,
* the getConnectionPoolDataSource() method is used to create a
* ConnectionPoolDataSource. This method allows you to specify a different
* ConnectionPoolDataSource.
*/
public void setConnectionPoolDataSource(ConnectionPoolDataSource dataSource){
this.ConnectionPoolDataSource = dataSource;
}
//**************************************************************************
//** getConnectionPoolDataSource
//**************************************************************************
/** Used to instantiate a ConnectionPoolDataSource for the database. The
* ConnectionPoolDataSource is typically used to create a JDBC Connection
* Pool.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource() throws SQLException {
if (ConnectionPoolDataSource!=null) return ConnectionPoolDataSource;
if (driver==null) throw new SQLException(
"Failed to create a ConnectionPoolDataSource. Please specify a driver.");
String className = null;
java.util.HashMap<String, Object> methods = new java.util.HashMap<>();
if (driver.equals("sqlite")){
className = "org.sqlite.SQLiteConnectionPoolDataSource";
methods.put("setUrl", "jdbc:sqlite:" + host);
/*
javax.sql.DataSource sqliteDS = new DataSource();
sqliteDS.setURL ("jdbc:sqlite://" + name);
dataSource = sqliteDS;
*/
}
else if (driver.equals("derby")){
className = ("org.apache.derby.jdbc.EmbeddedConnectionPoolDataSource");
methods.put("setDatabaseName", host);
methods.put("setCreateDatabase", "create");
}
else if (driver.equals("h2")){
className = ("org.h2.jdbcx.JdbcDataSource");
//URL requirements changed from 1.x to 2.x. Starting with 2.x, we
//now have to add properties to the end of the url
String url = null;
java.sql.Driver d = driver.getDriver();
try{
if (d==null) d = driver.load();
if (d.getMajorVersion()>1){
url = getURL(true);
}
}
catch(Exception e){}
methods.put("setURL", url==null ? getURL(false) : url);
methods.put("setUser", username);
methods.put("setPassword", password);
}
else if (driver.equals("sqlserver")){ //mssql
className = ("com.microsoft.sqlserver.jdbc.SQLServerXADataSource");
methods.put("setDatabaseName", name);
methods.put("setServerName", host);
methods.put("setUser", username);
methods.put("setPassword", password);
}
else if (driver.equals("postgresql")){ //pgsql
className = ("org.postgresql.ds.PGConnectionPoolDataSource");
methods.put("setDatabaseName", name);
methods.put("setServerName", host);
methods.put("setPortNumber", port);
methods.put("setUser", username);
methods.put("setPassword", password);
}
else if (driver.equals("mysql")){
className = ("com.mysql.cj.jdbc.MysqlConnectionPoolDataSource");
methods.put("setDatabaseName", name);
methods.put("setServerName", host);
methods.put("setPortNumber", port); //setPort?
methods.put("setUser", username);
methods.put("setPassword", password);
}
else if (driver.equals("oracle")){
String connDriver = "thin";
String connService = "";
className = ("oracle.jdbc.pool.OracleConnectionPoolDataSource");
methods.put("setDriverType", connDriver);
methods.put("setServerName", host);
methods.put("setPortNumber", port);
methods.put("setServiceName", connService);
methods.put("setUser", username);
methods.put("setPassword", password);
}
else if (driver.equals("jtds")){
className = ("net.sourceforge.jtds.jdbcx.JtdsDataSource");
methods.put("setDatabaseName", name);
methods.put("setServerName", host);
methods.put("setUser", username);
methods.put("setPassword", password);
}
//Instantiate the ConnectionPoolDataSource
if (className!=null){
try{
Class classToLoad = Class.forName(className);
Object instance = classToLoad.newInstance();
java.util.Iterator<String> it = methods.keySet().iterator();
while (it.hasNext()){
String methodName = it.next();
Object parameter = methods.get(methodName);
if (parameter!=null){
java.lang.reflect.Method method = null;
if (parameter instanceof String)
method = classToLoad.getMethod(methodName, stringType);
else if (parameter instanceof Integer)
method = classToLoad.getMethod(methodName, integerType);
if (method!=null) method.invoke(instance, new Object[] { parameter });
}
}
ConnectionPoolDataSource = (ConnectionPoolDataSource) instance;
return ConnectionPoolDataSource;
}
catch(Exception e){
throw new SQLException("Failed to instantiate the ConnectionPoolDataSource.", e);
}
}
throw new SQLException("Failed to find a suitable ConnectionPoolDataSource.");
}
//**************************************************************************
//** getRecord
//**************************************************************************
/** Used to retrieve a single record from this database.
*/
public javaxt.sql.Record getRecord(String sql) throws SQLException {
try (Connection conn = getConnection()){
return conn.getRecord(sql);
}
}
//**************************************************************************
//** getRecords
//**************************************************************************
/** Used to retrieve records from this database. Note that this method
* relies on a Generator to yield records. This is fine for relatively
* small record sets. However, for large record sets, we recommend opening
* a database connection first and calling Connection.getRecords() like
* this:
<pre>
try (Connection conn = database.getConnection()){
return conn.getRecords(sql);
}
</pre>
*/
public Iterable<javaxt.sql.Record> getRecords(String sql) throws SQLException {
return new javaxt.utils.Generator<javaxt.sql.Record>(){
public void run() throws InterruptedException {
try (Connection conn = getConnection()){
for (javaxt.sql.Record record : conn.getRecords(sql)){
try{
this.yield(record);
}
catch(InterruptedException e){
return;
}
}
}
catch(Exception e){
RuntimeException ex = new RuntimeException(e.getMessage());
ex.setStackTrace(e.getStackTrace());
throw ex;
}
}
};
}
//**************************************************************************
//** getTables
//**************************************************************************
/** Used to retrieve an array of tables and columns found in this database.
*/
public Table[] getTables() throws SQLException {
if (tables!=null) return tables;
try (Connection conn = getConnection()){
return getTables(conn);
}
}
//**************************************************************************
//** getTables
//**************************************************************************
/** Used to retrieve an array of tables and columns found in a database.
*/
public static Table[] getTables(Connection conn){
Database database = conn.getDatabase();
if (database!=null){
if (database.tables!=null) return database.tables;
}
java.util.ArrayList<Table> tables = new java.util.ArrayList<>();
try{
DatabaseMetaData dbmd = conn.getConnection().getMetaData();
try(ResultSet rs = dbmd.getTables(null,null,null,getTableFilter(database))){
while (rs.next()) {
tables.add(new Table(rs, dbmd));
}
}
}
catch(Exception e){
}
Table[] arr = tables.toArray(new Table[tables.size()]);
if (database!=null){
if (database.cacheMetadata) database.tables = arr;
}
return arr;
}
//**************************************************************************
//** getTableNames
//**************************************************************************
/** Used to retrieve an array of table names found in the database. If a
* table is part of a schema, the schema name is prepended to the table
* name. This method is significantly faster than the getTables() method
* which returns the full metadata for each table.
*/
public String[] getTableNames() throws SQLException {
java.util.ArrayList<javaxt.utils.Record> tableNames = new java.util.ArrayList<>();
if (tables!=null){
for (Table table : tables){
javaxt.utils.Record record = new javaxt.utils.Record();
record.set("schema", table.getSchema());
record.set("table", table.getName());
tableNames.add(record);
}
}
else{
try (Connection conn = getConnection()){
DatabaseMetaData dbmd = conn.getConnection().getMetaData();
try (ResultSet rs = dbmd.getTables(null,null,null,getTableFilter(this))){
while (rs.next()) {
javaxt.utils.Record record = new javaxt.utils.Record();
record.set("schema", rs.getString("TABLE_SCHEM"));
record.set("table", rs.getString("TABLE_NAME"));
tableNames.add(record);
}
}
}
}
String[] arr = new String[tableNames.size()];
for (int i=0; i<arr.length; i++){
javaxt.utils.Record record = tableNames.get(i);
String tableName = record.get("table").toString();
String schemaName = record.get("schema").toString();
if (schemaName!=null && !schemaName.isEmpty()){
tableName = schemaName + "." + tableName;
}
arr[i] = tableName;
}
java.util.Arrays.sort(arr);
return arr;
}
//**************************************************************************
//** getTableFilter
//**************************************************************************
/** Returns a filter used to generate a list of tables via DatabaseMetaData
*/
private static String[] getTableFilter(Database database){
if (database!=null){
Driver driver = database.getDriver();
if (driver!=null && driver.equals("PostgreSQL")){
return new String[]{"TABLE", "FOREIGN TABLE"};
}
}
return new String[]{"TABLE"};
}
//**************************************************************************
//** getCatalogs
//**************************************************************************
/** Used to retrieve a list of available catalogs (aka databases) found on
* this server.
*/
public String[] getCatalogs() throws SQLException{
try (Connection conn = getConnection()){
return getCatalogs(conn);
}
}
//**************************************************************************
//** getCatalogs
//**************************************************************************
/** Used to retrieve a list of available catalogs (aka databases) found on
* a server.
*/
public static String[] getCatalogs(Connection conn){
Database database = conn.getDatabase();
if (database!=null){
if (database.catalogs!=null) return database.catalogs;
}
java.util.TreeSet<String> catalogs = new java.util.TreeSet<String>();
try{
DatabaseMetaData dbmd = conn.getConnection().getMetaData();
try (ResultSet rs = dbmd.getCatalogs()){
while (rs.next()) {
catalogs.add(rs.getString(1));
}
}
}
catch(Exception e){
return null;
}
String[] arr = catalogs.toArray(new String[catalogs.size()]);
if (database!=null){
if (database.cacheMetadata) database.catalogs = arr;
}
return arr;
}
//**************************************************************************
//** getReservedKeywords
//**************************************************************************
/** Returns a list of reserved keywords for the current database.
*/
public String[] getReservedKeywords() throws Exception {
try(Connection conn = this.getConnection()){
return getReservedKeywords(conn);
}
}
//**************************************************************************
//** getReservedKeywords
//**************************************************************************
/** Returns a list of reserved keywords for a given database.
*/
public static String[] getReservedKeywords(Connection conn){
Database database = conn.getDatabase();
javaxt.sql.Driver driver = database.getDriver();
if (driver==null) driver = new Driver("","","");
if (driver.equals("Firebird")){
return fbKeywords;
}
else if (driver.equals("SQLServer")){
return msKeywords;
}
else if (driver.equals("H2")){
//Check if a "MODE" is set
String mode = "";
java.util.Properties properties = database.getProperties();
if (properties!=null){
Object o = properties.get("MODE");
if (o!=null) mode = o.toString();
}
if (mode.equalsIgnoreCase("PostgreSQL")){
return java.util.stream.Stream.concat(
java.util.Arrays.stream(h2Keywords),
java.util.Arrays.stream(pgKeywords)
).toArray(String[]::new);
}
else{
return h2Keywords;
}
}
else if (driver.equals("PostgreSQL")){
//Try to get reserved keywords from the database. Note that in PostgreSQL
//"non-reserved" keywords are key words that are explicitly known to
//the parser but are allowed as column or table names. Therefore, we
//will ignore "non-reserved" keywords from our query.
if (pgKeywords==null){
java.util.HashSet<String> arr = new java.util.HashSet<>();
try (java.sql.Statement stmt = conn.getConnection().createStatement(
java.sql.ResultSet.TYPE_FORWARD_ONLY,
java.sql.ResultSet.CONCUR_READ_ONLY,
java.sql.ResultSet.FETCH_FORWARD)){
try (java.sql.ResultSet rs = stmt.executeQuery(
"select word from pg_get_keywords() where catcode='R'")){
while(rs.next()){
arr.add(rs.getString(1));
}
}
}
catch(java.sql.SQLException e){
e.printStackTrace();
}
String[] keywords = new String[arr.size()];
int i=0;
java.util.Iterator<String> it = arr.iterator();
while (it.hasNext()){
keywords[i] = it.next();