1/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package tests.java.sql;
17
18import dalvik.annotation.KnownFailure;
19import dalvik.annotation.TestTargets;
20import dalvik.annotation.TestLevel;
21import dalvik.annotation.TestTargetNew;
22import dalvik.annotation.TestTargetClass;
23
24import junit.extensions.TestSetup;
25import junit.framework.Test;
26import junit.framework.TestCase;
27import junit.framework.TestSuite;
28
29import tests.support.DatabaseCreator;
30import tests.support.Support_SQL;
31
32import java.sql.Connection;
33import java.sql.DatabaseMetaData;
34import java.sql.DriverManager;
35import java.sql.PreparedStatement;
36import java.sql.ResultSet;
37import java.sql.ResultSetMetaData;
38import java.sql.SQLException;
39import java.sql.Statement;
40import java.sql.Types;
41import java.util.ArrayList;
42import java.util.Arrays;
43import java.util.List;
44import java.util.Random;
45import java.util.StringTokenizer;
46
47@TestTargetClass(DatabaseMetaData.class)
48public class DatabaseMetaDataTest extends TestCase {
49    private static String VIEW_NAME = "myView";
50
51    private static String CREATE_VIEW_QUERY = "CREATE VIEW " + VIEW_NAME
52            + " AS SELECT * FROM " + DatabaseCreator.TEST_TABLE1;
53
54    private static String DROP_VIEW_QUERY = "DROP VIEW " + VIEW_NAME;
55
56    protected static Connection conn;
57
58    protected static DatabaseMetaData meta;
59
60    protected static Statement statement;
61
62    protected static Statement statementForward;
63
64    private static int id = 1;
65
66    public void setUp() throws Exception {
67        super.setUp();
68        Support_SQL.loadDriver();
69        try {
70            conn = Support_SQL.getConnection();
71            meta = conn.getMetaData();
72            statement = conn.createStatement();
73            statementForward = conn.createStatement(
74                    ResultSet.TYPE_FORWARD_ONLY,
75                    ResultSet.CONCUR_READ_ONLY);
76            createTestTables();
77        } catch (SQLException e) {
78            System.out.println("Error in test setup: "+e.getMessage());
79        }
80    }
81
82    protected void tearDown() throws Exception {
83        try {
84            conn = Support_SQL.getConnection();
85            meta = conn.getMetaData();
86            statement = conn.createStatement();
87            deleteTestTables();
88        } catch (SQLException e) {
89            System.out.println("Error in teardown: "+e.getMessage());
90        } finally {
91            try {
92                conn.close();
93            } catch (SQLException e) {
94            }
95        }
96        super.tearDown();
97    }
98
99            private void createTestTables() {
100                try {
101                    ResultSet userTab = meta.getTables(null, null, null, null);
102                    while (userTab.next()) {
103                        String tableName = userTab.getString("TABLE_NAME");
104                        if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
105                            statement.execute(DatabaseCreator.DROP_TABLE1);
106                        } else if (tableName
107                                .equals(DatabaseCreator.TEST_TABLE3)) {
108                            statement.execute(DatabaseCreator.DROP_TABLE3);
109                        } else if (tableName.equals(VIEW_NAME)) {
110                            statement.execute(DROP_VIEW_QUERY);
111                        }
112                    }
113                    userTab.close();
114                    statement.execute(DatabaseCreator.CREATE_TABLE3);
115                    statement.execute(DatabaseCreator.CREATE_TABLE1);
116                    statement.execute(CREATE_VIEW_QUERY);
117                    meta = conn.getMetaData();
118                } catch (SQLException e) {
119                    fail("Unexpected SQLException " + e.toString());
120                }
121            }
122
123            private void deleteTestTables() {
124                try {
125                    statement.execute(DatabaseCreator.DROP_TABLE1);
126                    statement.execute(DatabaseCreator.DROP_TABLE3);
127                    statement.execute(DROP_VIEW_QUERY);
128                } catch (SQLException e) {
129                    fail("Unexpected SQLException " + e.toString());
130                } finally {
131                    try {
132                    if (! conn.isClosed()) {
133                        conn.close();
134                    }
135                    } catch (SQLException e) {
136
137                    }
138                }
139            }
140    /*
141    public void setUp() {
142        try {
143            super.setUp();
144            try {
145                conn = Support_SQL.getConnection();
146                statement = conn.createStatement();
147                statementForward = conn.createStatement(
148                        ResultSet.TYPE_FORWARD_ONLY,
149                        ResultSet.CONCUR_READ_ONLY);
150                meta = conn.getMetaData();
151
152                assertFalse(conn.isClosed());
153            } catch (SQLException e) {
154                fail("Unexpected SQLException " + e.toString());
155            }
156
157        } catch (Exception e) {
158            // TODO Auto-generated catch block
159            e.printStackTrace();
160        }
161
162    }
163    */
164
165    /**
166     * @tests {@link java.sql.DatabaseMetaData #getBestRowIdentifier(java.lang.String,
167     *        java.lang.String, java.lang.String, int, boolean) }
168     */
169    @TestTargetNew(
170        level = TestLevel.SUFFICIENT,
171        notes = "Not all variants of parameters can be tested: updates on resultSets are not supported.",
172        method = "getBestRowIdentifier",
173        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, int.class, boolean.class}
174    )
175    public void test_getBestRowIdentifierLjava_lang_StringLjava_lang_StringLjava_lang_StringIZ()
176            throws SQLException {
177        ResultSet result = statementForward.executeQuery("SELECT * FROM "
178                + DatabaseCreator.TEST_TABLE1);
179
180        //Updatable ResultSet not supported, converted to normal insert statement
181        statementForward.executeUpdate("INSERT INTO " + DatabaseCreator.TEST_TABLE1
182                + " (id, field1) VALUES( 1234567, 'test1');");
183        /* not supported
184        try {
185         result.moveToInsertRow();
186         result.updateInt("id", 1234567);
187         result.updateString("field1", "test1");
188         result.insertRow();
189         } catch (SQLException e) {
190         fail("Unexpected SQLException " + e.toString());
191         }
192         */
193
194
195        result.close();
196
197        ResultSet rs = meta.getBestRowIdentifier(null, null,
198                DatabaseCreator.TEST_TABLE1, DatabaseMetaData.bestRowSession,
199                true);
200        ResultSetMetaData rsmd = rs.getMetaData();
201        assertTrue("Rows not obtained", rs.next());
202        int col = rsmd.getColumnCount();
203        assertEquals("Incorrect number of columns", 8, col);
204        String[] columnNames = {
205                "SCOPE", "COLUMN_NAME", "DATA_TYPE", "TYPE_NAME",
206                "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
207                "PSEUDO_COLUMN"};
208        for (int c = 1; c <= col; ++c) {
209            assertEquals("Incorrect column name", columnNames[c - 1], rsmd
210                    .getColumnName(c));
211        }
212        assertEquals("Incorrect scope", DatabaseMetaData.bestRowSession, rs
213                .getShort("SCOPE"));
214        assertEquals("Incorrect column name", "_ROWID_", rs.getString("COLUMN_NAME"));
215        assertEquals("Incorrect data type", java.sql.Types.INTEGER, rs.getInt("DATA_TYPE"));
216        assertEquals("Incorrect type name", "INTEGER", rs.getString("TYPE_NAME"));
217        rs.close();
218
219     // Exception testing
220        conn.close();
221
222        try {
223            meta.getColumns(null, null,
224            DatabaseCreator.TEST_TABLE1, "%");
225            fail("SQLException not thrown");
226        } catch (SQLException e) {
227            // ok
228        }
229    }
230
231    /**
232     * @tests java.sql.DatabaseMetaData #getColumns(java.lang.String,
233     *        java.lang.String, java.lang.String, java.lang.String)
234     *
235     */
236    @TestTargetNew(
237        level = TestLevel.PARTIAL_COMPLETE,
238        notes = "Tests Columns and search for arbitrary columns. test fails: Columns Name's not according to spec.",
239        method = "getColumns",
240        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
241    )
242    @KnownFailure("Not supported : pattern with %")
243    public void test_getColumnsArbitrary() throws SQLException {
244        ResultSet setAllNull = null;
245        ResultSet setMixed = null;
246        ResultSet allArbitrary = null;
247        String[] tablesName = {DatabaseCreator.TEST_TABLE1,
248                DatabaseCreator.TEST_TABLE3};
249        Arrays.sort(tablesName);
250        int setSize = 0;
251        try {
252            allArbitrary = meta.getColumns("%","%","%","%");
253            assertNotNull(allArbitrary);
254            checkColumnsShape(allArbitrary);
255            setSize = crossCheckGetColumnsAndResultSetMetaData(allArbitrary, false);
256            assertEquals(6, setSize);
257
258            setMixed = meta.getColumns(null, null,"%","%");
259            assertNotNull(setMixed);
260            checkColumnsShape(setMixed);
261            setSize = crossCheckGetColumnsAndResultSetMetaData(setMixed, false);
262            assertEquals(6, setSize);
263
264        } catch (SQLException e) {
265            fail("Unexpected exception: " + e.getMessage());
266        }
267
268        // Exception testing
269        conn.close();
270
271        try {
272            meta.getColumns(null, null,
273                    DatabaseCreator.TEST_TABLE1, "%");
274            fail("SQLException not thrown");
275        } catch (SQLException e) {
276            // ok
277        }
278    }
279
280    /**
281     * @tests java.sql.DatabaseMetaData #getColumns(java.lang.String,
282     *        java.lang.String, java.lang.String, java.lang.String)
283     *
284     */
285    @TestTargetNew(
286        level = TestLevel.PARTIAL_COMPLETE,
287        notes = "Tests getColumns with no Catalog and Schema. test fails on arguments: '', '', '%', '%'",
288        method = "getColumns",
289        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
290    )
291    @KnownFailure("Not supported ops applied: test fails on arguments: '', '', '%', '%' ")
292    public void test_getColumnsTableWithNoCatalogSchema() throws SQLException{
293
294        try {
295            ResultSet noSchemaTable = meta.getColumns("", "",
296                    DatabaseCreator.TEST_TABLE1, "fkey");
297            assertNotNull(noSchemaTable);
298            noSchemaTable.last();
299            int size = noSchemaTable.getRow();
300            assertEquals(
301                    "Does not support empty string as input parameter or Wildcard %",
302                    1, size);
303
304
305
306        } catch (SQLException e) {
307            fail("Unexpected exception: " + e.getMessage());
308        }
309
310        try {
311            ResultSet noSchemaTable = meta.getColumns("", "",
312                    DatabaseCreator.TEST_TABLE1, "%");
313            assertNotNull(noSchemaTable);
314            noSchemaTable.last();
315            int size = noSchemaTable.getRow();
316            assertEquals(
317                    "Does not support empty string as input parameter or Wildcard %",
318                    5, size);
319
320
321
322        } catch (SQLException e) {
323            fail("Unexpected exception: " + e.getMessage());
324        }
325
326        try {
327            ResultSet noSchemaTable = meta.getColumns("", "", "%", "%");
328            assertNotNull(noSchemaTable);
329            noSchemaTable.last();
330            int size = noSchemaTable.getRow();
331            assertEquals(
332                    "Does not support double Wildcard '%' as input",
333                    6, size);
334
335        } catch (SQLException e) {
336            fail("Unexpected exception: " + e.getMessage());
337        }
338
339        // Exception checking
340        conn.close();
341
342        try {
343            meta.getColumns(null, null,
344                    DatabaseCreator.TEST_TABLE1, "%");
345            fail("SQLException not thrown");
346        } catch (SQLException e) {
347            // ok
348        }
349    }
350
351
352
353    /**
354     * @tests java.sql.DatabaseMetaData #getColumns(java.lang.String,
355     *        java.lang.String, java.lang.String, java.lang.String)
356     *
357     */
358    @TestTargetNew(
359        level = TestLevel.PARTIAL_COMPLETE,
360        notes = "tests for specific tables. test fails: invalid nullable value.",
361        method = "getColumns",
362        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
363    )
364    @KnownFailure("Wildcard operator does not seem wo work correctly.")
365    public void test_getColumnsSpecific() throws SQLException {
366        String[] tablesName = {
367                DatabaseCreator.TEST_TABLE1, DatabaseCreator.TEST_TABLE3};
368        String[] fields = {"id", "field1", "field2", "field3", "fkey"};
369        String[] nullable = {"YES", "NO",""};
370        int[] nullableInt = {
371                DatabaseMetaData.columnNoNulls,
372                DatabaseMetaData.columnNullable,
373                DatabaseMetaData.columnNullableUnknown};
374        Arrays.sort(tablesName);
375        Arrays.sort(fields);
376        Arrays.sort(nullableInt);
377        Arrays.sort(nullable);
378        int countSingle = 0;
379        int countAll1 = 0;
380        int countAll2 = 0;
381
382        try {
383            ResultSet rs = meta.getColumns(null, null,
384                    DatabaseCreator.TEST_TABLE1, "%");
385
386            while (rs.next()) {
387                assertTrue("Invalid table name", Arrays.binarySearch(
388                        tablesName, rs.getString("TABLE_NAME")) > -1);
389                assertTrue("Invalid field name", Arrays.binarySearch(fields, rs
390                        .getString("COLUMN_NAME")) > -1);
391                assertTrue("Invalid nullable value", Arrays.binarySearch(
392                        nullable, rs.getString("IS_NULLABLE")) > -1);
393                assertTrue("Invalid nullable code", Arrays.binarySearch(
394                        nullableInt, rs.getInt("NULLABLE")) > -1);
395                countSingle++;
396            }
397            assertEquals("Not all results are found", 5, countSingle);
398            rs.close();
399
400        } catch (SQLException e) {
401            fail("Unexpected exception: " + e.getMessage());
402        }
403
404        try {
405            ResultSet rs = meta.getColumns(null, null, "%"+DatabaseCreator.CREATE_TABLE1.substring(0, 3)+"%","%" );
406            while (rs.next()) {
407                assertTrue("Wrong table name", Arrays.binarySearch(tablesName,
408                        rs.getString("TABLE_NAME")) > -1);
409                countAll1++;
410            }
411            assertEquals("Not all results are found", 6, countAll1);
412            rs.close();
413
414        } catch (SQLException e) {
415            fail("Unexpected exception: " + e.getMessage());
416        }
417
418        try {
419            ResultSet rs = meta.getColumns(null, null, "%TEST_%", "%");
420
421            while (rs.next()) {
422                assertTrue("Wrong table name", Arrays.binarySearch(tablesName,
423                        rs.getString("TABLE_NAME")) > -1);
424                countAll2++;
425            }
426            assertEquals("Not all results are found", 6, countAll2);
427            rs.close();
428
429        } catch (SQLException e) {
430            fail("Unexpected exception: " + e.getMessage());
431        }
432
433     // Exception checking
434        conn.close();
435
436        try {
437            meta.getColumns(null, null,
438                    DatabaseCreator.TEST_TABLE1, "%");
439            fail("SQLException not thrown");
440        } catch (SQLException e) {
441            // ok
442        }
443
444
445    }
446
447
448
449    /**
450     * @tests java.sql.DatabaseMetaData#getConnection()
451     */
452    @TestTargetNew(
453        level = TestLevel.COMPLETE,
454        notes = "SQLException checking test fails",
455        method = "getConnection",
456        args = {}
457    )
458    public void test_getConnection() throws SQLException {
459        assertEquals("Incorrect connection value", conn, meta.getConnection());
460
461        // Exception checking
462        conn.close();
463
464        try {
465            Connection con = meta.getConnection();
466            assertTrue(con.isClosed());
467        } catch (SQLException e) {
468            // ok
469        }
470    }
471
472    /**
473     * @tests java.sql.DatabaseMetaData #getCrossReference(java.lang.String,
474     *        java.lang.String, java.lang.String, java.lang.String,
475     *        java.lang.String, java.lang.String)
476     */
477    @TestTargetNew(
478        level = TestLevel.COMPLETE,
479        notes = "Test fails: Foreign keys not supported",
480        method = "getCrossReference",
481        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class}
482    )
483    @KnownFailure("(Ticket 91) Tables apply foreign key constraint. Catalogs not supported")
484    public void test_getCrossReferenceLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
485            throws SQLException {
486        ResultSet rs = meta.getCrossReference(conn.getCatalog(), null,
487                DatabaseCreator.TEST_TABLE3, conn.getCatalog(), null,
488                DatabaseCreator.TEST_TABLE1);
489        ResultSetMetaData rsmd = rs.getMetaData();
490        assertTrue("Rows do not obtained", rs.next());
491        int col = rsmd.getColumnCount();
492        assertEquals("Incorrect number of columns", 14, col);
493        String[] columnNames = { "PKTABLE_CAT", "PKTABLE_SCHEM",
494                "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT",
495                "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
496                "UPDATE_RULE", "DELETE_RULE", "FK_NAME", "PK_NAME",
497                "DEFERRABILITY" };
498        for (int c = 1; c <= col; ++c) {
499            assertEquals("Incorrect column name", columnNames[c - 1], rsmd
500                    .getColumnName(c));
501        }
502//      TODO getCatalog is not supported
503        assertEquals("Incorrect primary key table catalog", conn.getCatalog(),
504                rs.getString("PKTABLE_CAT"));
505        assertEquals("Incorrect primary key table schema", "", rs
506                .getString("PKTABLE_SCHEM"));
507        assertEquals("Incorrect primary key table name",
508                DatabaseCreator.TEST_TABLE3, rs.getString("PKTABLE_NAME"));
509        assertEquals("Incorrect primary key column name", "fkey", rs
510                .getString("PKCOLUMN_NAME"));
511        // TODO getCatalog is not supported
512        assertEquals("Incorrect foreign key table catalog", conn.getCatalog(),
513                rs.getString("FKTABLE_CAT"));
514        assertEquals("Incorrect foreign key table schema", "", rs
515                .getString("FKTABLE_SCHEM"));
516        assertEquals("Incorrect foreign key table name",
517                DatabaseCreator.TEST_TABLE1, rs.getString("FKTABLE_NAME"));
518        assertEquals("Incorrect foreign key column name", "fk", rs
519                .getString("FKCOLUMN_NAME"));
520        assertEquals("Incorrect sequence number within foreign key", 1, rs
521                .getShort("KEY_SEQ"));
522        assertEquals("Incorrect update rule value",
523                DatabaseMetaData.importedKeyNoAction, rs
524                        .getShort("UPDATE_RULE"));
525        assertEquals("Incorrect delete rule value",
526                DatabaseMetaData.importedKeyNoAction, rs
527                        .getShort("DELETE_RULE"));
528        assertNull("Incorrect foreign key name", rs.getString("FK_NAME"));
529        assertNull("Incorrect primary key name", rs.getString("PK_NAME"));
530        assertEquals("Incorrect deferrability",
531                DatabaseMetaData.importedKeyNotDeferrable, rs
532                        .getShort("DEFERRABILITY"));
533        rs.close();
534
535     // Exception checking
536        conn.close();
537
538        try {
539            meta.getCrossReference(conn.getCatalog(), null,
540                    DatabaseCreator.TEST_TABLE3, conn.getCatalog(), null,
541                    DatabaseCreator.TEST_TABLE1);
542            fail("SQLException not thrown");
543        } catch (SQLException e) {
544            // ok
545        }
546
547        // Exception checking
548        conn.close();
549
550        try {
551            meta.getCrossReference(conn.getCatalog(), null,
552                    DatabaseCreator.TEST_TABLE3, conn.getCatalog(), null,
553                    DatabaseCreator.TEST_TABLE1);
554            fail("SQLException not thrown");
555        } catch (SQLException e) {
556            // ok
557        }
558    }
559
560    /**
561     * @tests java.sql.DatabaseMetaData#getDatabaseMajorVersion()
562     */
563    @TestTargetNew(
564        level = TestLevel.COMPLETE,
565        notes = "SQLException checking test fails",
566        method = "getDatabaseMajorVersion",
567        args = {}
568    )
569    @KnownFailure("Ticket 98")
570    public void test_getDatabaseMajorVersion() throws SQLException {
571        assertTrue("Incorrdct database major version", meta
572                .getDatabaseMajorVersion() >= 0);
573
574        // Exception checking
575        conn.close();
576
577        try {
578            meta.getDatabaseMajorVersion();
579            fail("SQLException not thrown");
580        } catch (SQLException e) {
581            // ok
582        }
583
584    }
585
586    /**
587     * @tests java.sql.DatabaseMetaData#getDatabaseMinorVersion()
588     */
589    @TestTargetNew(
590        level = TestLevel.COMPLETE,
591        notes = "SQLException checking test fails",
592        method = "getDatabaseMinorVersion",
593        args = {}
594    )
595    @KnownFailure("Ticket 98")
596    public void test_getDatabaseMinorVersion() throws SQLException {
597        assertTrue("Incorrect database minor version", meta
598                .getDatabaseMinorVersion() >= 0);
599
600     // Exception checking
601        conn.close();
602
603        try {
604            meta.getDatabaseMinorVersion();
605            fail("SQLException not thrown");
606        } catch (SQLException e) {
607            // ok
608        }
609    }
610
611    /**
612     * @tests java.sql.DatabaseMetaData#getDatabaseProductName()
613     */
614    @TestTargetNew(
615        level = TestLevel.COMPLETE,
616        notes = "SQLException checking test fails",
617        method = "getDatabaseProductName",
618        args = {}
619    )
620    @KnownFailure("Ticket 98")
621    public void test_getDatabaseProductName() throws SQLException {
622        assertTrue("Incorrect database product name", !"".equals(meta
623                .getDatabaseProductName().trim()));
624
625        // Exception checking
626        conn.close();
627
628        try {
629            meta.getDatabaseProductName();
630            fail("SQLException not thrown");
631        } catch (SQLException e) {
632            // ok
633        }
634
635    }
636
637    /**
638     * @tests java.sql.DatabaseMetaData#getDatabaseProductVersion()
639     */
640    @TestTargetNew(
641        level = TestLevel.COMPLETE,
642        notes = "SQLException checking test fails",
643        method = "getDatabaseProductVersion",
644        args = {}
645    )
646    @KnownFailure("Ticket 98")
647    public void test_getDatabaseProductVersion() throws SQLException {
648        assertTrue("Incorrect database product version", !"".equals(meta
649                .getDatabaseProductVersion().trim()));
650        // Exception checking
651        conn.close();
652
653        try {
654            meta.getDatabaseProductVersion();
655            fail("SQLException not thrown");
656        } catch (SQLException e) {
657            // ok
658        }
659    }
660
661    /**
662     * @tests java.sql.DatabaseMetaData#getDefaultTransactionIsolation()
663     */
664    @TestTargetNew(
665        level = TestLevel.COMPLETE,
666        notes = "SQLException checking test fails",
667        method = "getDefaultTransactionIsolation",
668        args = {}
669    )
670    @KnownFailure("Ticket 98")
671    public void test_getDefaultTransactionIsolation() throws SQLException {
672        int defaultLevel = meta.getDefaultTransactionIsolation();
673        switch (defaultLevel) {
674        case Connection.TRANSACTION_NONE:
675        case Connection.TRANSACTION_READ_COMMITTED:
676        case Connection.TRANSACTION_READ_UNCOMMITTED:
677        case Connection.TRANSACTION_REPEATABLE_READ:
678        case Connection.TRANSACTION_SERIALIZABLE:
679            // these levels are OK
680            break;
681        default:
682            fail("Incorrect value of default transaction isolation level");
683        }
684
685        // Exception checking
686        conn.close();
687
688        try {
689            meta.getDefaultTransactionIsolation();
690            fail("SQLException not thrown");
691        } catch (SQLException e) {
692            // ok
693        }
694    }
695
696    /**
697     * @tests java.sql.DatabaseMetaData#getDriverMajorVersion()
698     */
699    @TestTargetNew(
700        level = TestLevel.COMPLETE,
701        notes = "",
702        method = "getDriverMajorVersion",
703        args = {}
704    )
705    public void test_getDriverMajorVersion()  throws SQLException {
706        assertTrue("Incorrect driver major version", meta
707                .getDriverMajorVersion() >= 0);
708    }
709
710    /**
711     * @tests java.sql.DatabaseMetaData#getDriverMinorVersion()
712     */
713    @TestTargetNew(
714        level = TestLevel.COMPLETE,
715        notes = "",
716        method = "getDriverMinorVersion",
717        args = {}
718    )
719    public void test_getDriverMinorVersion() {
720        assertTrue("Incorrect driver minor version", meta
721                .getDriverMinorVersion() >= 0);
722    }
723
724    /**
725     * @tests java.sql.DatabaseMetaData#getDriverName()
726     */
727    @TestTargetNew(
728        level = TestLevel.COMPLETE,
729        notes = "SQLException checking test fails",
730        method = "getDriverName",
731        args = {}
732    )
733    @KnownFailure("Ticket 98")
734    public void test_getDriverName() throws SQLException {
735        String driverName = meta.getDriverName();
736        assertTrue("Incorrect driver name", driverName.trim().startsWith(
737                "SQLite"));
738
739        // Exception checking
740        conn.close();
741
742        try {
743            meta.getDriverName();
744            fail("SQLException not thrown");
745        } catch (SQLException e) {
746            // ok
747        }
748    }
749
750    /**
751     * @tests java.sql.DatabaseMetaData#getDriverVersion()
752     */
753    @TestTargetNew(
754        level = TestLevel.COMPLETE,
755        notes = "",
756        method = "getDriverVersion",
757        args = {}
758    )
759    @KnownFailure("Ticket 98")
760    public void test_getDriverVersion() throws SQLException {
761        assertTrue("Incorrect driver version", !"".equals(meta
762                .getDriverVersion().trim()));
763
764      //Exception checking
765        conn.close();
766
767         try {
768             meta.getDriverVersion();
769             fail("SQLException not thrown");
770         } catch (SQLException e) {
771             //ok
772         }
773
774    }
775
776
777    /**
778     * @tests java.sql.DatabaseMetaData #getImportedKeys(java.lang.String,
779     *        java.lang.String, java.lang.String)
780     */
781    @TestTargetNew(
782        level = TestLevel.NOT_FEASIBLE,
783        notes = "Test fails: Keys are not supported",
784        method = "getImportedKeys",
785        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
786    )
787    @KnownFailure("Keys are not supported: Ticket 91")
788    public void test_getImportedKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
789            throws SQLException {
790        ResultSet rs = meta.getImportedKeys(conn.getCatalog(), null,
791                DatabaseCreator.TEST_TABLE1);
792        ResultSetMetaData rsmd = rs.getMetaData();
793        assertTrue("Rows do not obtained", rs.next());
794        int col = rsmd.getColumnCount();
795        assertEquals("Incorrect number of columns", 14, col);
796        String[] columnNames = { "PKTABLE_CAT", "PKTABLE_SCHEM",
797                "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT",
798                "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
799                "UPDATE_RULE", "DELETE_RULE", "FK_NAME", "PK_NAME",
800                "DEFERRABILITY" };
801        for (int c = 1; c <= col; ++c) {
802            assertEquals("Incorrect column name", columnNames[c - 1], rsmd
803                    .getColumnName(c));
804        }
805//      TODO getCatalog is not supported
806        assertEquals("Incorrect primary key table catalog", conn.getCatalog(),
807                rs.getString("PKTABLE_CAT"));
808        assertEquals("Incorrect primary key table schema", "", rs
809                .getString("PKTABLE_SCHEM"));
810        assertEquals("Incorrect primary key table name",
811                DatabaseCreator.TEST_TABLE3, rs.getString("PKTABLE_NAME"));
812        assertEquals("Incorrect primary key column name", "fkey", rs
813                .getString("PKCOLUMN_NAME"));
814        assertEquals("Incorrect foreign key table catalog", conn.getCatalog(),
815                rs.getString("FKTABLE_CAT"));
816        assertEquals("Incorrect foreign key table schema", "", rs
817                .getString("FKTABLE_SCHEM"));
818        assertEquals("Incorrect foreign key table name",
819                DatabaseCreator.TEST_TABLE1, rs.getString("FKTABLE_NAME"));
820        assertEquals("Incorrect foreign key column name", "fk", rs
821                .getString("FKCOLUMN_NAME"));
822        assertEquals("Incorrect sequence number within foreign key", 1, rs
823                .getShort("KEY_SEQ"));
824        assertEquals("Incorrect update rule value",
825                DatabaseMetaData.importedKeyNoAction, rs
826                        .getShort("UPDATE_RULE"));
827        assertEquals("Incorrect delete rule value",
828                DatabaseMetaData.importedKeyNoAction, rs
829                        .getShort("DELETE_RULE"));
830 //       assertNotNull("Incorrect foreign key name", rs.getString("FK_NAME"));
831        assertEquals("Incorrect primary key name", null, rs
832                .getString("PK_NAME"));
833        assertEquals("Incorrect deferrability",
834                DatabaseMetaData.importedKeyNotDeferrable, rs
835                        .getShort("DEFERRABILITY"));
836        rs.close();
837
838      //Exception checking
839        conn.close();
840
841         try {
842             meta.getImportedKeys(conn.getCatalog(), null,
843                     DatabaseCreator.TEST_TABLE1);
844             fail("SQLException not thrown");
845         } catch (SQLException e) {
846             //ok
847         }
848    }
849
850    /**
851     * @tests java.sql.DatabaseMetaData#getMaxCursorNameLength()
852     */
853    @TestTargetNew(
854        level = TestLevel.COMPLETE,
855        notes = "",
856        method = "getMaxCursorNameLength",
857        args = {}
858    )
859    public void test_getMaxCursorNameLength() throws SQLException {
860        int nameLength = meta.getMaxCursorNameLength();
861        if (nameLength > 0) {
862            try {
863                statement.setCursorName(new String(new byte[nameLength + 1]));
864                fail("Expected SQLException was not thrown");
865            } catch (SQLException e) {
866                // expected
867            }
868        } else if (nameLength < 0) {
869            fail("Incorrect length of cursor name");
870        }
871    }
872
873    /**
874     * @tests java.sql.DatabaseMetaData#getJDBCMinorVersion()
875     */
876    @TestTargetNew(
877        level = TestLevel.COMPLETE,
878        notes = "SQLException checking test fails",
879        method = "getJDBCMinorVersion",
880        args = {}
881    )
882    @KnownFailure("Ticket 98")
883    public void test_getJDBCMinorVersion() throws SQLException {
884        assertTrue("Incorrect JDBC minor version",
885                meta.getJDBCMinorVersion() >= 0);
886
887      //Exception checking
888        conn.close();
889
890         try {
891             meta.getJDBCMinorVersion();
892             fail("SQLException not thrown");
893         } catch (SQLException e) {
894             //ok
895         }
896
897    }
898
899    /**
900     * @tests java.sql.DatabaseMetaData#getJDBCMajorVersion()
901     */
902    @TestTargetNew(
903        level = TestLevel.COMPLETE,
904        notes = "SQLException checking test fails",
905        method = "getJDBCMajorVersion",
906        args = {}
907    )
908    @KnownFailure("Ticket 98")
909    public void test_getJDBCMajorVersion() throws SQLException {
910        assertTrue("Incorrect JDBC major version",
911                meta.getJDBCMajorVersion() >= 0);
912
913      //Exception checking
914        conn.close();
915
916         try {
917             meta.getJDBCMajorVersion();
918             fail("SQLException not thrown");
919         } catch (SQLException e) {
920             //ok
921         }
922
923    }
924
925
926    /**
927     * @tests java.sql.DatabaseMetaData#getNumericFunctions()
928     */
929    @TestTargetNew(
930        level = TestLevel.SUFFICIENT,
931        notes = "Test fails. Not implemented correctly. SQLException checking test fails",
932        method = "getNumericFunctions",
933        args = {}
934    )
935    @KnownFailure("Not supported feature, Ticket 98. Broken because "+
936            "NUMERIC_FUNCTIONS not complete. When fixed change to @KnownFailure")
937    public void test_getNumericFunctions() throws SQLException {
938        escapedFunctions(NUMERIC_FUNCTIONS, meta.getNumericFunctions());
939
940
941      //Exception checking
942        conn.close();
943
944         try {
945             meta.getNumericFunctions();
946             fail("SQLException not thrown");
947         } catch (SQLException e) {
948             //ok
949         }
950
951    }
952
953    /**
954     * @tests java.sql.DatabaseMetaData #getPrimaryKeys(java.lang.String,
955     *        java.lang.String, java.lang.String)
956     */
957    @TestTargetNew(
958        level = TestLevel.SUFFICIENT,
959        notes = "Functionality test fails: keys and catalogs are not supported.",
960        method = "getPrimaryKeys",
961        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class}
962    )
963    @KnownFailure(" Ticket 91 : relies on not supported features: getCatalog, keys")
964    public void test_getPrimaryKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
965            throws SQLException {
966        ResultSet rs = meta.getPrimaryKeys(conn.getCatalog(), null,
967                DatabaseCreator.TEST_TABLE1);
968        ResultSetMetaData rsmd = rs.getMetaData();
969        assertTrue("Rows not obtained", rs.next());
970        int col = rsmd.getColumnCount();
971        assertEquals("Incorrect number of columns", 6, col);
972        String[] columnNames = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
973                "COLUMN_NAME", "KEY_SEQ", "PK_NAME" };
974        for (int c = 1; c <= col; ++c) {
975            assertEquals("Incorrect column name", columnNames[c - 1], rsmd
976                    .getColumnName(c));
977        }
978        assertEquals("Incorrect table catalogue", conn.getCatalog(), rs
979                .getString("TABLE_CAT").toLowerCase());
980        assertEquals("Incorrect table schema", "", rs
981                .getString("TABLE_SCHEM"));
982        assertEquals("Incorrect table name", DatabaseCreator.TEST_TABLE1, rs
983                .getString("TABLE_NAME").toLowerCase());
984        assertEquals("Incorrect column name", "id", rs.getString("COLUMN_NAME")
985                .toLowerCase());
986        assertEquals("Incorrect sequence number", 1, rs.getShort("KEY_SEQ"));
987        assertEquals("Incorrect primary key name", "primary", rs.getString(
988                "PK_NAME").toLowerCase());
989        rs.close();
990
991      //Exception checking
992        conn.close();
993
994         try {
995             meta.getPrimaryKeys(conn.getCatalog(), null,
996                     DatabaseCreator.TEST_TABLE1);
997             fail("SQLException not thrown");
998         } catch (SQLException e) {
999             //ok
1000         }
1001    }
1002
1003    /**
1004     * @tests java.sql.DatabaseMetaData#getResultSetHoldability()
1005     */
1006    @TestTargetNew(
1007        level = TestLevel.COMPLETE,
1008        notes = "SQLException checking test fails",
1009        method = "getResultSetHoldability",
1010        args = {}
1011    )
1012    @KnownFailure("Ticket 98")
1013    public void test_getResultSetHoldability() throws SQLException {
1014        int hdb = meta.getResultSetHoldability();
1015        switch (hdb) {
1016        case ResultSet.HOLD_CURSORS_OVER_COMMIT:
1017        case ResultSet.CLOSE_CURSORS_AT_COMMIT:
1018            // these holdabilities are OK
1019            break;
1020        default:
1021            fail("Incorrect value of holdability");
1022        }
1023        assertFalse("Incorrect result set holdability", meta
1024                .supportsResultSetHoldability(hdb));
1025
1026      //Exception checking
1027        conn.close();
1028
1029         try {
1030             meta.getResultSetHoldability();
1031             fail("SQLException not thrown");
1032         } catch (SQLException e) {
1033             //ok
1034         }
1035
1036    }
1037
1038    /**
1039     * @tests java.sql.DatabaseMetaData#getSQLKeywords()
1040     */
1041    @TestTargetNew(
1042        level = TestLevel.COMPLETE,
1043        notes = "SQLException checking test fails",
1044        method = "getSQLKeywords",
1045        args = {}
1046    )
1047    @KnownFailure("Ticket 98")
1048    public void test_getSQLKeywords() throws SQLException {
1049        assertTrue("Incorrect SQL keywords", !"".equals(meta.getSQLKeywords()
1050                .trim()));
1051
1052      //Exception checking
1053        conn.close();
1054
1055         try {
1056             meta.getSQLKeywords();
1057             fail("SQLException not thrown");
1058         } catch (SQLException e) {
1059             //ok
1060         }
1061
1062    }
1063
1064    /**
1065     * @tests java.sql.DatabaseMetaData#getSQLStateType()
1066     */
1067    @TestTargetNew(
1068        level = TestLevel.COMPLETE,
1069        notes = "SQLException checking test fails",
1070        method = "getSQLStateType",
1071        args = {}
1072    )
1073    @KnownFailure("Ticket 98")
1074    public void test_getSQLStateType() throws SQLException {
1075        int type = meta.getSQLStateType();
1076        switch (type) {
1077        case DatabaseMetaData.sqlStateSQL99:
1078        case DatabaseMetaData.sqlStateXOpen:
1079            // these types are OK
1080            break;
1081        default:
1082            fail("Incorrect SQL state types");
1083        }
1084
1085
1086      //Exception checking
1087        conn.close();
1088
1089         try {
1090             meta.getSQLStateType();
1091             fail("SQLException not thrown");
1092         } catch (SQLException e) {
1093             //ok
1094         }
1095
1096    }
1097
1098    /**
1099     * @tests java.sql.DatabaseMetaData#getSchemas()
1100     */
1101    @TestTargetNew(
1102        level = TestLevel.PARTIAL_COMPLETE,
1103        notes = "SQLException checking test fails",
1104        method = "getSchemas",
1105        args = {}
1106    )
1107    @KnownFailure("Ticket 98")
1108    public void test_getSchemas() throws SQLException {
1109        ResultSet rs = meta.getSchemas();
1110        ResultSetMetaData rsmd = rs.getMetaData();
1111        assertTrue("Rows do not obtained", rs.next());
1112        int col = rsmd.getColumnCount();
1113        assertEquals("Incorrect number of columns", 1, col);
1114        String[] columnNames = { "TABLE_SCHEM", "TABLE_CATALOG" };
1115        for (int c = 1; c <= col; ++c) {
1116            assertEquals("Incorrect column name", columnNames[c - 1], rsmd
1117                    .getColumnName(c));
1118        }
1119        rs.close();
1120
1121
1122      //Exception checking
1123        conn.close();
1124
1125         try {
1126             meta.getSchemas();
1127             fail("SQLException not thrown");
1128         } catch (SQLException e) {
1129             //ok
1130         }
1131
1132    }
1133
1134    /**
1135     * @tests java.sql.DatabaseMetaData#getSearchStringEscape()
1136     */
1137    @TestTargetNew(
1138        level = TestLevel.COMPLETE,
1139        notes = "SQLException checking test fails",
1140        method = "getSearchStringEscape",
1141        args = {}
1142    )
1143    @KnownFailure("Ticket 98")
1144    public void test_getSearchStringEscape() throws SQLException {
1145        assertTrue("Incorrect search string escape", !"".equals(meta
1146                .getSearchStringEscape().trim()));
1147
1148      //Exception checking
1149        conn.close();
1150
1151         try {
1152             meta.getSearchStringEscape();
1153             fail("SQLException not thrown");
1154         } catch (SQLException e) {
1155             //ok
1156         }
1157
1158    }
1159
1160    /**
1161     * @tests java.sql.DatabaseMetaData#getStringFunctions()
1162     */
1163    @TestTargetNew(
1164        level = TestLevel.COMPLETE,
1165        notes = "Functionality test fails. SQLException checking test fails",
1166        method = "getStringFunctions",
1167        args = {}
1168    )
1169    @KnownFailure("not supported")
1170    public void test_getStringFunctions() throws SQLException {
1171        escapedFunctions(STRING_FUNCTIONS, meta.getStringFunctions());
1172
1173
1174      //Exception checking
1175        conn.close();
1176
1177         try {
1178             meta.getStringFunctions();
1179             fail("SQLException not thrown");
1180         } catch (SQLException e) {
1181             //ok
1182         }
1183
1184
1185    }
1186
1187
1188    /**
1189     * @tests java.sql.DatabaseMetaData#getSystemFunctions()
1190     */
1191    @TestTargetNew(
1192        level = TestLevel.COMPLETE,
1193        notes = "Functionality test fails. SQLException checking test fails",
1194        method = "getSystemFunctions",
1195        args = {}
1196    )
1197    @KnownFailure("not supported")
1198    public void test_getSystemFunctions() throws SQLException {
1199        escapedFunctions(SYSTEM_FUNCTIONS, meta.getSystemFunctions());
1200
1201
1202      //Exception checking
1203        conn.close();
1204
1205         try {
1206             meta.getSystemFunctions();
1207             fail("SQLException not thrown");
1208         } catch (SQLException e) {
1209             //ok
1210         }
1211
1212    }
1213
1214
1215    /**
1216     * @tests java.sql.DatabaseMetaData#getTableTypes()
1217     */
1218    @TestTargetNew(
1219        level = TestLevel.COMPLETE,
1220        notes = "SQLException checking test fails",
1221        method = "getTableTypes",
1222        args = {}
1223    )
1224    @KnownFailure("Ticket 98")
1225    public void test_getTableTypes() throws SQLException {
1226        String[] tableTypes = { "LOCAL TEMPORARY", "TABLE", "VIEW" };
1227        ResultSet rs = meta.getTableTypes();
1228
1229        while (rs.next()) {
1230            assertTrue("Wrong table type", Arrays.binarySearch(tableTypes, rs
1231                    .getString("TABLE_TYPE")) > -1);
1232        }
1233        rs.close();
1234
1235
1236      //Exception checking
1237        conn.close();
1238
1239         try {
1240             meta.getTableTypes();
1241             fail("SQLException not thrown");
1242         } catch (SQLException e) {
1243             //ok
1244         }
1245
1246    }
1247
1248    /**
1249     * @tests java.sql.DatabaseMetaData #getTables(java.lang.String,
1250     *        java.lang.String, java.lang.String, java.lang.String[])
1251     */
1252    @TestTargetNew(
1253        level = TestLevel.COMPLETE,
1254        notes = "Test fails.",
1255        method = "getTables",
1256        args = {java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String[].class}
1257    )
1258    @KnownFailure("If no schema is associated: returns empty string where actually null be returned?. Ticket 98")
1259    public void test_getTablesLjava_lang_StringLjava_lang_StringLjava_lang_String$Ljava_lang_String()
1260            throws SQLException {
1261        String[] tablesName = {
1262                VIEW_NAME, DatabaseCreator.TEST_TABLE1,
1263                DatabaseCreator.TEST_TABLE3};
1264        String[] tablesType = {"TABLE", "VIEW"};
1265        Arrays.sort(tablesName);
1266        Arrays.sort(tablesType);
1267
1268        // case 1. get all tables. There are two tables and one view in the
1269        // database
1270        ResultSet rs = meta.getTables(null, null, null, null);
1271        while (rs.next()) {
1272            assertTrue("Wrong table name", Arrays.binarySearch(tablesName, rs
1273                    .getString("TABLE_NAME")) > -1);
1274        //No Schema associated
1275            assertNull("Wrong table schema: "+rs.getString("TABLE_SCHEM"), rs.getString("TABLE_SCHEM"));
1276            assertTrue("Wrong table type", Arrays.binarySearch(tablesType, rs
1277                    .getString("TABLE_TYPE")) > -1);
1278            assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
1279        }
1280        rs.close();
1281
1282        // case 2. get tables with specified types. There are no tables of such
1283        // types
1284        rs = meta.getTables(conn.getCatalog(), null, null, new String[] {
1285                "SYSTEM TABLE", "LOCAL TEMPORARY" });
1286        assertFalse("Some tables exist", rs.next());
1287        rs.close();
1288
1289        // case 3. get tables with specified types. There is a table of such
1290        // types
1291        rs = meta.getTables(conn.getCatalog(), null, null, new String[] {
1292                "VIEW", "LOCAL TEMPORARY" });
1293
1294        assertTrue("No tables exist", rs.next());
1295        assertEquals("Wrong table name", VIEW_NAME, rs.getString("TABLE_NAME"));
1296        assertNull("Wrong table schema: "+rs.getString("TABLE_SCHEM"), rs.getString("TABLE_SCHEM"));
1297        assertEquals("Wrong table type", "VIEW", rs.getString("TABLE_TYPE"));
1298        assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
1299        assertFalse("Wrong size of result set", rs.next());
1300        assertFalse("Some tables exist", rs.next());
1301        rs.close();
1302
1303        // case 4. get all tables using tables pattern.
1304        // There are two tables and one view in the database
1305        rs = meta.getTables(null, null, "%", null);
1306
1307        while (rs.next()) {
1308            assertTrue("Wrong table name", Arrays.binarySearch(tablesName, rs
1309                    .getString("TABLE_NAME")) > -1);
1310            assertNull("Wrong table schema ", rs.getString("TABLE_SCHEM"));
1311            assertTrue("Wrong table type", Arrays.binarySearch(tablesType, rs
1312                    .getString("TABLE_TYPE")) > -1);
1313            assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
1314        }
1315        rs.close();
1316
1317
1318      //Exception checking
1319        conn.close();
1320
1321         try {
1322             meta.getTables(null, null, null, null);
1323             fail("SQLException not thrown");
1324         } catch (SQLException e) {
1325             //ok
1326         }
1327
1328    }
1329
1330    /**
1331     * @tests java.sql.DatabaseMetaData#getTimeDateFunctions()
1332     */
1333    @TestTargetNew(
1334        level = TestLevel.COMPLETE,
1335        notes = "Does not return any functions. test fails. SQLException checking test fails",
1336        method = "getTimeDateFunctions",
1337        args = {}
1338    )
1339    @KnownFailure("not supported")
1340    public void test_getTimeDateFunctions() throws SQLException {
1341
1342        escapedFunctions(TIMEDATE_FUNCTIONS, meta.getTimeDateFunctions());
1343
1344
1345      //Exception checking
1346        conn.close();
1347
1348         try {
1349             meta.getTimeDateFunctions();
1350             fail("SQLException not thrown");
1351         } catch (SQLException e) {
1352             //ok
1353         }
1354    }
1355
1356    /**
1357     * @tests java.sql.DatabaseMetaData#getTypeInfo()
1358     */
1359    @TestTargetNew(
1360        level = TestLevel.COMPLETE,
1361        notes = "SQLException checking test fails",
1362        method = "getTypeInfo",
1363        args = {}
1364    )
1365    @KnownFailure("not supported")
1366    public void test_getTypeInfo() throws SQLException {
1367        insertNewRecord();
1368
1369        ResultSet rs = meta.getTypeInfo();
1370
1371        final String[] names = { "TYPE_NAME", "DATA_TYPE", "PRECISION",
1372                "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS",
1373                "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE",
1374                "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT",
1375                "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE",
1376                "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX" };
1377        Arrays.sort(names);
1378
1379        for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
1380            assertTrue("wrong column was return", Arrays.binarySearch(names, rs
1381                    .getMetaData().getColumnName(i + 1)) > -1);
1382        }
1383
1384        int[] types = { Types.ARRAY, Types.BIGINT, Types.BINARY, Types.BIT,
1385                Types.BLOB, Types.BOOLEAN, Types.CHAR, Types.CLOB,
1386                Types.DATALINK, Types.DATE, Types.DECIMAL, Types.DISTINCT,
1387                Types.DOUBLE, Types.FLOAT, Types.INTEGER, Types.JAVA_OBJECT,
1388                Types.LONGVARBINARY, Types.LONGVARCHAR, Types.NULL,
1389                Types.NUMERIC, Types.OTHER, Types.REAL, Types.REF,
1390                Types.SMALLINT, Types.STRUCT, Types.TIME, Types.TIMESTAMP,
1391                Types.TINYINT, Types.VARBINARY, Types.VARCHAR };
1392        Arrays.sort(types);
1393
1394        while (rs.next()) {
1395            assertTrue("wrong type was return ", Arrays.binarySearch(types, rs
1396                    .getInt("DATA_TYPE")) > -1);
1397        }
1398        rs.close();
1399
1400      //Exception checking
1401        conn.close();
1402
1403         try {
1404             meta.getTypeInfo();
1405             fail("SQLException not thrown");
1406         } catch (SQLException e) {
1407             //ok
1408         }
1409
1410    }
1411
1412
1413    /**
1414     * @tests java.sql.DatabaseMetaData#getURL()
1415     */
1416    @TestTargetNew(
1417        level = TestLevel.COMPLETE,
1418        notes = "SQLException checking test fails",
1419        method = "getURL",
1420        args = {}
1421    )
1422    @KnownFailure("Ticket 98")
1423    public void test_getURL() throws SQLException {
1424        assertEquals("Wrong url", Support_SQL.sqlUrl, meta.getURL());
1425
1426      //Exception checking
1427        conn.close();
1428
1429         try {
1430             meta.getURL();
1431             fail("SQLException not thrown");
1432         } catch (SQLException e) {
1433             //ok
1434         }
1435
1436    }
1437
1438    /**
1439     * @tests java.sql.DatabaseMetaData#getUserName()
1440     *
1441     *  NOT_FEASIBLE not supported
1442     */
1443    @TestTargetNew(
1444        level = TestLevel.COMPLETE,
1445        notes = "SQLException checking test fails",
1446        method = "getUserName",
1447        args = {}
1448    )
1449     @KnownFailure("Ticket 98")
1450    public void s() throws SQLException {
1451      assertEquals("Wrong user name", Support_SQL.sqlUser, meta.getUserName());
1452
1453      //Exception checking
1454        conn.close();
1455
1456         try {
1457             meta.getUserName();
1458             fail("SQLException not thrown");
1459         } catch (SQLException e) {
1460             //ok
1461         }
1462
1463    }
1464
1465
1466    /**
1467     * @tests java.sql.DatabaseMetaData#insertsAreDetected(int)
1468     */
1469    @TestTargetNew(
1470        level = TestLevel.COMPLETE,
1471        notes = "SQLException checking test fails",
1472        method = "insertsAreDetected",
1473        args = {int.class}
1474    )
1475    @KnownFailure("Ticket 98")
1476    public void test_insertsAreDetectedI() throws SQLException {
1477        assertFalse(
1478                "visible row insert can be detected for TYPE_FORWARD_ONLY type",
1479                meta.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY));
1480        assertFalse(
1481                "visible row insert can be detected for TYPE_SCROLL_INSENSITIVE type",
1482                meta.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
1483        assertFalse(
1484                "visible row insert can be detected for TYPE_SCROLL_SENSITIVE type",
1485                meta.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
1486
1487
1488      //Exception checking
1489        conn.close();
1490
1491         try {
1492             meta.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE);
1493             fail("SQLException not thrown");
1494         } catch (SQLException e) {
1495             //ok
1496         }
1497
1498    }
1499
1500    /**
1501     * @tests java.sql.DatabaseMetaData#isReadOnly()
1502     */
1503    @TestTargetNew(
1504        level = TestLevel.COMPLETE,
1505        notes = "SQLException checking test fails",
1506        method = "isReadOnly",
1507        args = {}
1508    )
1509    @KnownFailure("Ticket 98")
1510    public void test_isReadOnly() throws SQLException {
1511        assertFalse("database is not read-only", meta.isReadOnly());
1512
1513
1514      //Exception checking
1515        conn.close();
1516
1517         try {
1518             meta.isReadOnly();
1519             fail("SQLException not thrown");
1520         } catch (SQLException e) {
1521             //ok
1522         }
1523    }
1524
1525    /**
1526     * @tests java.sql.DatabaseMetaData#othersDeletesAreVisible(int)
1527     */
1528    @TestTargetNew(
1529        level = TestLevel.COMPLETE,
1530        notes = "SQLException checking test fails.",
1531        method = "othersDeletesAreVisible",
1532        args = {int.class}
1533    )
1534    @KnownFailure("Ticket 98")
1535    public void test_othersDeletesAreVisibleI() throws SQLException {
1536        assertFalse(
1537                "deletes made by others are visible for TYPE_FORWARD_ONLY type",
1538                meta.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
1539        assertFalse(
1540                "deletes made by others are visible for TYPE_SCROLL_INSENSITIVE type",
1541                meta.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
1542        assertFalse(
1543                "deletes made by others are visible for TYPE_SCROLL_SENSITIVE type",
1544                meta.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
1545
1546
1547      //Exception checking
1548        conn.close();
1549
1550         try {
1551             assertFalse("inserts made by others are visible for unknown type", meta
1552                     .othersDeletesAreVisible(ResultSet.CONCUR_READ_ONLY));
1553             fail("SQLException not thrown");
1554         } catch (SQLException e) {
1555             //ok
1556         }
1557
1558    }
1559
1560    /**
1561     * @tests java.sql.DatabaseMetaData#othersInsertsAreVisible(int)
1562     */
1563    @TestTargetNew(
1564        level = TestLevel.COMPLETE,
1565        notes = "",
1566        method = "othersInsertsAreVisible",
1567        args = {int.class}
1568    )
1569    @KnownFailure("Ticket 98")
1570    public void test_othersInsertsAreVisibleI() throws SQLException {
1571        assertFalse(
1572                "inserts made by others are visible for TYPE_FORWARD_ONLY type",
1573                meta.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
1574        assertFalse(
1575                "inserts made by others are visible for TYPE_SCROLL_INSENSITIVE type",
1576                meta.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
1577        assertFalse(
1578                "inserts made by others are visible for TYPE_SCROLL_SENSITIVE type",
1579                meta.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
1580
1581
1582      //Exception checking
1583        conn.close();
1584
1585         try {
1586             assertFalse("inserts made by others are visible for unknown type", meta
1587                     .othersInsertsAreVisible(ResultSet.CONCUR_READ_ONLY));
1588             fail("SQLException not thrown");
1589         } catch (SQLException e) {
1590             //ok
1591         }
1592
1593    }
1594
1595    /**
1596     * @tests java.sql.DatabaseMetaData#othersUpdatesAreVisible(int)
1597     */
1598    @TestTargetNew(
1599        level = TestLevel.COMPLETE,
1600        notes = " Verification with invalid parameters missed.",
1601        method = "othersUpdatesAreVisible",
1602        args = {int.class}
1603    )
1604    @KnownFailure("Ticket 98")
1605    public void test_othersUpdatesAreVisibleI() throws SQLException {
1606        assertFalse(
1607                "updates made by others are visible for TYPE_FORWARD_ONLY type",
1608                meta.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
1609        assertFalse(
1610                "updates made by others are visible for TYPE_SCROLL_INSENSITIVE type",
1611                meta.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
1612        assertFalse(
1613                "updates made by others are visible for TYPE_SCROLL_SENSITIVE type",
1614                meta.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
1615
1616      //Exception checking
1617
1618         try {
1619             assertFalse("updates made by others are visible for unknown type", meta
1620                     .othersUpdatesAreVisible(ResultSet.CONCUR_READ_ONLY));
1621             fail("SQLException not thrown");
1622         } catch (SQLException e) {
1623             //ok
1624         }
1625    }
1626
1627    /**
1628     * @tests java.sql.DatabaseMetaData#storesMixedCaseQuotedIdentifiers()
1629     */
1630    @TestTargets ({
1631    @TestTargetNew(
1632        level = TestLevel.COMPLETE,
1633        notes = "SQLException checking test fails",
1634        method = "storesMixedCaseQuotedIdentifiers",
1635        args = {}
1636    ),
1637    @TestTargetNew(
1638            level = TestLevel.COMPLETE,
1639            notes = "SQLException checking test fails",
1640            method = "storesMixedCaseIdentifiers",
1641            args = {}
1642        )
1643    })
1644    public void test_storesMixedCaseQuotedIdentifiers() throws SQLException {
1645        String quote = meta.getIdentifierQuoteString();
1646
1647
1648
1649        insertNewRecord();
1650
1651        String selectQuery = "SELECT " + quote + "fieLD1" + quote + " FROM "
1652                + DatabaseCreator.TEST_TABLE1;
1653
1654        try {
1655            statement.executeQuery(selectQuery);
1656            if (!meta.storesMixedCaseIdentifiers()) {
1657                fail("mixed case is supported");
1658            }
1659        } catch (SQLException e) {
1660            if (meta.storesMixedCaseQuotedIdentifiers()) {
1661                fail("quoted case is not supported");
1662            }
1663        }
1664
1665        //Exception checking
1666        /*
1667        conn.close();
1668
1669         try {
1670             meta.storesMixedCaseIdentifiers();
1671             fail("SQLException not thrown");
1672         } catch (SQLException e) {
1673             //ok
1674         }
1675
1676         conn.close();
1677
1678         try {
1679             meta.storesMixedCaseQuotedIdentifiers();
1680             fail("SQLException not thrown");
1681         } catch (SQLException e) {
1682             //ok
1683         }
1684
1685    }
1686
1687    @TestTargetNew(
1688      level = TestLevel.COMPLETE,
1689      notes = "Exception test fails.",
1690      method = "getIdentifierQuoteString",
1691      args = {}
1692    )
1693    @KnownFailure("Ticket 98")
1694    public void testGetIdentifierQuoteString() throws SQLException {
1695       assertNotNull(
1696               meta.getIdentifierQuoteString()
1697               );
1698
1699       //Exception test
1700       /*
1701       conn.close();
1702       try {
1703           meta.getIdentifierQuoteString();
1704           fail("Should throw exception");
1705       } catch (SQLException e) {
1706           //ok
1707       }
1708       */
1709
1710    }
1711
1712
1713    /**
1714     * @tests java.sql.DatabaseMetaData#supportsColumnAliasing()
1715     */
1716    @TestTargetNew(
1717        level = TestLevel.COMPLETE,
1718        notes = "SQLException checking test fails",
1719        method = "supportsColumnAliasing",
1720        args = {}
1721    )
1722    @KnownFailure("not supported. SQLException checking test fails")
1723    public void test_supportsColumnAliasing() throws SQLException {
1724        insertNewRecord();
1725
1726        String alias = "FIELD3";
1727        String selectQuery = "SELECT field1 AS " + alias + " FROM "
1728                + DatabaseCreator.TEST_TABLE1;
1729        ResultSet rs = statement.executeQuery(selectQuery);
1730        ResultSetMetaData rsmd = rs.getMetaData();
1731
1732        if (meta.supportsColumnAliasing()) {
1733            // supports aliasing
1734            assertEquals("Wrong count of columns", 1, rsmd.getColumnCount());
1735            assertEquals("Aliasing is not supported", alias, rsmd
1736                    .getColumnLabel(1));
1737        } else {
1738            // doesn't support aliasing
1739            assertEquals("Aliasing is supported", 0, rsmd.getColumnCount());
1740        }
1741        rs.close();
1742
1743      //Exception checking
1744        conn.close();
1745
1746         try {
1747             meta.supportsColumnAliasing();
1748             fail("SQLException not thrown");
1749         } catch (SQLException e) {
1750             //ok
1751         }
1752
1753    }
1754
1755
1756    /**
1757     * @tests java.sql.DatabaseMetaData#supportsExpressionsInOrderBy()
1758     */
1759    @TestTargetNew(
1760        level = TestLevel.COMPLETE,
1761        notes = "SQLException checking test fails",
1762        method = "supportsExpressionsInOrderBy",
1763        args = {}
1764    )
1765    @KnownFailure("exception test fails")
1766    public void test_supportsExpressionsInOrderBy() throws SQLException {
1767        insertNewRecord();
1768
1769        String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
1770                + " ORDER BY id + field3";
1771
1772        try {
1773            statement.executeQuery(selectQuery);
1774            if (!meta.supportsExpressionsInOrderBy()) {
1775                fail("Expressions in order by are supported");
1776            }
1777        } catch (SQLException e) {
1778            if (meta.supportsExpressionsInOrderBy()) {
1779                fail("Expressions in order by are not supported");
1780            }
1781        }
1782
1783      //Exception checking
1784        conn.close();
1785
1786         try {
1787             meta.supportsExpressionsInOrderBy();
1788             fail("SQLException not thrown");
1789         } catch (SQLException e) {
1790             //ok
1791         }
1792
1793    }
1794
1795
1796    /**
1797     * @tests java.sql.DatabaseMetaData#supportsGroupBy()
1798     */
1799    @TestTargetNew(
1800        level = TestLevel.COMPLETE,
1801        notes = "SQLException checking test fails",
1802        method = "supportsGroupBy",
1803        args = {}
1804    )
1805    @KnownFailure("exception test fails")
1806    public void test_supportsGroupBy() throws SQLException {
1807        insertNewRecord();
1808
1809        String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
1810                + " GROUP BY field3";
1811
1812        try {
1813            statement.executeQuery(selectQuery);
1814            if (!meta.supportsGroupBy()) {
1815                fail("group by are supported");
1816            }
1817        } catch (SQLException e) {
1818            if (meta.supportsGroupBy()) {
1819                fail("group by are not supported");
1820            }
1821        }
1822
1823      //Exception checking
1824        conn.close();
1825
1826         try {
1827             meta.supportsGroupBy();
1828             fail("SQLException not thrown");
1829         } catch (SQLException e) {
1830             //ok
1831         }
1832
1833    }
1834
1835
1836    /**
1837     * @tests java.sql.DatabaseMetaData#supportsGroupByUnrelated()
1838     */
1839    @TestTargetNew(
1840        level = TestLevel.COMPLETE,
1841        notes = "SQLException checking test fails",
1842        method = "supportsGroupByUnrelated",
1843        args = {}
1844    )
1845    @KnownFailure("exception test fails")
1846    public void test_supportsGroupByUnrelated() throws SQLException {
1847        insertNewRecord();
1848
1849        String selectQuery = "SELECT field1, field2 FROM "
1850                + DatabaseCreator.TEST_TABLE1 + " GROUP BY field3";
1851
1852        try {
1853            statement.executeQuery(selectQuery);
1854            if (!meta.supportsGroupByUnrelated()) {
1855                fail("unrelated columns in group by are supported");
1856            }
1857        } catch (SQLException e) {
1858            if (meta.supportsGroupByUnrelated()) {
1859                fail("unrelated columns in group by are not supported");
1860            }
1861        }
1862
1863        //Exception checking
1864        conn.close();
1865
1866         try {
1867             meta.supportsGroupByUnrelated();
1868             fail("SQLException not thrown");
1869         } catch (SQLException e) {
1870             //ok
1871         }
1872
1873    }
1874
1875    /**
1876     * @tests java.sql.DatabaseMetaData#supportsNonNullableColumns()
1877     */
1878    @TestTargetNew(
1879        level = TestLevel.COMPLETE,
1880        notes = "SQLException thrown",
1881        method = "supportsNonNullableColumns",
1882        args = {}
1883    )
1884    @KnownFailure("Ticket 98")
1885    public void test_supportsNonNullableColumns() throws SQLException {
1886        assertTrue(
1887                "columns in this database may not be defined as non-nullable",
1888                meta.supportsNonNullableColumns());
1889        statementForward.execute("create table companies(id integer not null);");
1890        statementForward.execute("drop table companies");
1891
1892
1893      //Exception checking
1894        conn.close();
1895
1896         try {
1897             meta.supportsNonNullableColumns();
1898             fail("SQLException not thrown");
1899         } catch (SQLException e) {
1900             //ok
1901         }
1902
1903    }
1904
1905    /**
1906     * @tests java.sql.DatabaseMetaData#supportsOrderByUnrelated()
1907     */
1908    @TestTargetNew(
1909        level = TestLevel.COMPLETE,
1910        notes = "SQLException checking test fails",
1911        method = "supportsOrderByUnrelated",
1912        args = {}
1913    )
1914    @KnownFailure("exception test fails")
1915    public void test_supportsOrderByUnrelated() throws SQLException {
1916        insertNewRecord();
1917
1918        String selectQuery = "SELECT field1, field2 FROM "
1919                + DatabaseCreator.TEST_TABLE1 + " ORDER BY id + field3";
1920
1921        try {
1922            statement.executeQuery(selectQuery);
1923            if (!meta.supportsOrderByUnrelated()) {
1924                fail("unrelated columns in order by are supported");
1925            }
1926        } catch (SQLException e) {
1927            if (meta.supportsOrderByUnrelated()) {
1928                fail("unrelated columns in order by are not supported");
1929            }
1930        }
1931
1932      //Exception checking
1933        conn.close();
1934
1935         try {
1936             meta.supportsOrderByUnrelated();
1937             fail("SQLException not thrown");
1938         } catch (SQLException e) {
1939             //ok
1940         }
1941
1942    }
1943
1944    /**
1945     * @tests java.sql.DatabaseMetaData#supportsSelectForUpdate()
1946     */
1947    @TestTargetNew(
1948        level = TestLevel.COMPLETE,
1949        notes = "SQLException checking test fails",
1950        method = "supportsSelectForUpdate",
1951        args = {}
1952    )
1953    @KnownFailure("exception test fails")
1954    public void test_supportsSelectForUpdate() throws SQLException {
1955        insertNewRecord();
1956
1957        String selectQuery = "SELECT field1 FROM "
1958                + DatabaseCreator.TEST_TABLE1 + " FOR UPDATE";
1959
1960        try {
1961            statement.executeQuery(selectQuery);
1962            if (!meta.supportsSelectForUpdate()) {
1963                fail("select for update are supported");
1964            }
1965        } catch (SQLException e) {
1966            if (!meta.supportsSelectForUpdate()) {
1967                fail("select for update are not supported");
1968            }
1969        }
1970
1971
1972      //Exception checking
1973        conn.close();
1974
1975         try {
1976             meta.supportsSelectForUpdate();
1977             fail("SQLException not thrown");
1978         } catch (SQLException e) {
1979             //ok
1980         }
1981
1982    }
1983
1984    /**
1985     * @tests java.sql.DatabaseMetaData#supportsSubqueriesInExists()
1986     */
1987    @TestTargetNew(
1988        level = TestLevel.COMPLETE,
1989        notes = "SQLException checking test fails",
1990        method = "supportsSubqueriesInExists",
1991        args = {}
1992    )
1993    @KnownFailure("exception test fails")
1994    public void test_supportsSubqueriesInExists() throws SQLException {
1995        insertNewRecord();
1996
1997        String selectQuery = "SELECT field1 FROM "
1998                + DatabaseCreator.TEST_TABLE1
1999                + " WHERE EXISTS(SELECT field2 FROM "
2000                + DatabaseCreator.TEST_TABLE1 + ")";
2001
2002        try {
2003            statement.executeQuery(selectQuery);
2004            if (!meta.supportsSubqueriesInExists()) {
2005                fail("Subqueries in exists are supported");
2006            }
2007        } catch (SQLException e) {
2008            if (meta.supportsSubqueriesInExists()) {
2009                fail("Subqueries in exists are not supported");
2010            }
2011        }
2012
2013
2014      //Exception checking
2015        conn.close();
2016
2017         try {
2018             meta.supportsSubqueriesInExists();
2019             fail("SQLException not thrown");
2020         } catch (SQLException e) {
2021             //ok
2022         }
2023
2024    }
2025
2026    /**
2027     * @tests java.sql.DatabaseMetaData#supportsTableCorrelationNames()
2028     */
2029    @TestTargetNew(
2030        level = TestLevel.COMPLETE,
2031        notes = "SQLException checking test fails",
2032        method = "supportsTableCorrelationNames",
2033        args = {}
2034    )
2035    @KnownFailure("exception test fails")
2036    public void test_supportsTableCorrelationNames() throws SQLException {
2037
2038        insertNewRecord();
2039        assertFalse(conn.isClosed());
2040
2041        String corelationName = "TABLE_NAME";
2042        String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
2043                + " AS " + corelationName;
2044        ResultSet rs = statementForward.executeQuery(selectQuery);
2045        ResultSetMetaData rsmd = rs.getMetaData();
2046        int numOfColumn = rsmd.getColumnCount();
2047
2048        for (int i = 0; i < numOfColumn; i++) {
2049            if (meta.supportsTableCorrelationNames()) {
2050                assertEquals("Corelation names is now supported",
2051                        corelationName, rsmd.getTableName(i + 1));
2052            } else {
2053                assertEquals("Corelation names is supported",
2054                        DatabaseCreator.TEST_TABLE1, rsmd.getTableName(i + 1));
2055            }
2056        }
2057
2058
2059      //Exception checking
2060        conn.close();
2061
2062         try {
2063             meta.supportsTableCorrelationNames();
2064             fail("SQLException not thrown");
2065         } catch (SQLException e) {
2066             //ok
2067         }
2068
2069    }
2070
2071    /**
2072     * @tests java.sql.DatabaseMetaData#supportsTransactionIsolationLevel(int)
2073     */
2074    @TestTargetNew(
2075        level = TestLevel.SUFFICIENT,
2076        notes = " Not all Transaction isolation levels supported.",
2077        method = "supportsTransactionIsolationLevel",
2078        args = {int.class}
2079    )
2080    public void test_supportsTransactionIsolationLevelI() throws SQLException {
2081        assertFalse("database supports TRANSACTION_NONE isolation level", meta
2082                .supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE));
2083        // TODO only Connection.TRANSACTION_SERIALIZABLE is supported
2084//        assertTrue(
2085//                "database doesn't supports TRANSACTION_READ_COMMITTED isolation level",
2086//                meta
2087//                        .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
2088//        assertTrue(
2089//                "database doesn't supports TRANSACTION_READ_UNCOMMITTED isolation level",
2090//                meta
2091//                        .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));
2092//        assertTrue(
2093//               "database doesn't supports TRANSACTION_REPEATABLE_READ isolation level",
2094//                meta
2095//                        .supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));
2096        assertTrue(
2097                "database doesn't supports TRANSACTION_SERIALIZABLE isolation level",
2098                meta
2099                        .supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));
2100
2101
2102      //Exception checking
2103
2104         try {
2105             assertFalse("database supports unknown isolation level", meta
2106                     .supportsTransactionIsolationLevel(Integer.MAX_VALUE));;
2107         } catch (SQLException e) {
2108             //ok
2109         }
2110    }
2111
2112    /**
2113     * @tests java.sql.DatabaseMetaData#updatesAreDetected(int)
2114     */
2115    @TestTargetNew(
2116        level = TestLevel.COMPLETE,
2117        notes = " Verification with invalid parameters missed.",
2118        method = "updatesAreDetected",
2119        args = {int.class}
2120    )
2121    public void test_updatesAreDetectedI() throws SQLException {
2122        assertFalse(
2123                "visible row update can be detected for TYPE_FORWARD_ONLY type",
2124                meta.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
2125        assertFalse(
2126                "visible row update can be detected for TYPE_SCROLL_INSENSITIVE type",
2127                meta.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
2128        assertFalse(
2129                "visible row update can be detected for TYPE_SCROLL_SENSITIVE type",
2130                meta.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
2131        assertFalse("visible row update can be detected for unknown type", meta
2132                .updatesAreDetected(100));
2133
2134        //Exception checking
2135       conn.close();
2136
2137        try {
2138            meta.updatesAreDetected(ResultSet.CLOSE_CURSORS_AT_COMMIT);
2139            assertFalse("visible row update can be detected for unknown type", meta
2140                    .updatesAreDetected(ResultSet.CLOSE_CURSORS_AT_COMMIT));
2141
2142        } catch (SQLException e) {
2143            //ok
2144        }
2145    }
2146
2147
2148    protected static void insertNewRecord() throws SQLException {
2149        if (conn.isClosed()) {
2150            System.out.println("DatabaseMetaDataTest.insertNewRecord() : closed");
2151        }
2152
2153        String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE1
2154                + " (id, field1, field2, field3) VALUES(" + id + ", '"
2155                + "value" + id + "', " + id + ", " + id + ")";
2156        id++;
2157        statement.execute(insertQuery);
2158    }
2159
2160    //BEGIN APACHE-DERBY
2161
2162    /**
2163     * Test Method from Apache Derby Project
2164     * Class
2165     * org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
2166     *
2167     * Compare a ResultSet from getColumns() with ResultSetMetaData returned
2168     * from a SELECT * against the table. This method handles situations where a
2169     * full set of the columns are in the ResultSet. The first action is to call
2170     * rs.next(). The ResultSet will be closed by this method.
2171     *
2172     * @param rs
2173     *            resultset to crossCheck
2174     * @param partial
2175     *            used to indicate if ordinal position should get checked
2176     * @return the number of rows in the resultSet
2177     * @throws SQLException
2178     */
2179    private int crossCheckGetColumnsAndResultSetMetaData(ResultSet rs,
2180            boolean partial)
2181    throws SQLException
2182    {
2183        Statement s = conn.createStatement();
2184        while (rs.next())
2185        {
2186            String schema = rs.getString("TABLE_SCHEM");
2187            String table = rs.getString("TABLE_NAME");
2188
2189            ResultSet rst = s.executeQuery(
2190                "SELECT * FROM " + schema+"."+table);
2191            ResultSetMetaData rsmdt = rst.getMetaData();
2192
2193
2194            for (int col = 1; col <= rsmdt.getColumnCount() ; col++)
2195            {
2196                if (!partial) {
2197                    if (col != 1)
2198                        assertTrue(rs.next());
2199
2200                    assertEquals("ORDINAL_POSITION",
2201                            col, rs.getInt("ORDINAL_POSITION"));
2202                }
2203
2204                assertEquals("TABLE_CAT",
2205                        "", rs.getString("TABLE_CAT"));
2206                assertEquals("TABLE_SCHEM",
2207                        schema, rs.getString("TABLE_SCHEM"));
2208                assertEquals("TABLE_NAME",
2209                        table, rs.getString("TABLE_NAME"));
2210
2211                crossCheckGetColumnRowAndResultSetMetaData(rs, rsmdt);
2212                if (partial)
2213                    break;
2214
2215            }
2216            rst.close();
2217
2218
2219        }
2220        int count = rs.getRow();
2221        rs.close();
2222        s.close();
2223        return count;
2224    }
2225
2226    /**
2227     * * Test Method from Apache Derby Project
2228     * Class
2229     * org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
2230     *
2231     * Cross check a single row from getColumns() with ResultSetMetaData
2232     * for a SELECT * from the same table.
2233     * @param rs ResultSet from getColumns already positioned on the row.
2234     * @param rsmdt ResultSetMetaData for the SELECT *
2235     * @param odbc 0 for JDBC call, 1 for ODBC. Needed to allow for difference
2236     *    in using BUFFER_LENGTH (ODBC) or no(JDBC).
2237     * @throws SQLException
2238     */
2239    public static void crossCheckGetColumnRowAndResultSetMetaData(
2240            ResultSet rs, ResultSetMetaData rsmdt)
2241        throws SQLException
2242    {
2243        int col = rs.getInt("ORDINAL_POSITION");
2244
2245        assertEquals("RSMD.getCatalogName",
2246                rsmdt.getCatalogName(col), rs.getString("TABLE_CAT"));
2247        assertEquals("RSMD.getSchemaName",
2248                rsmdt.getSchemaName(col), rs.getString("TABLE_SCHEM"));
2249        assertEquals("RSMD.getTableName",
2250                rsmdt.getTableName(col), rs.getString("TABLE_NAME"));
2251
2252        assertEquals("COLUMN_NAME",
2253                rsmdt.getColumnName(col), rs.getString("COLUMN_NAME"));
2254
2255        // DERBY-2285 BOOLEAN columns appear different on
2256        // network client.
2257        // meta returns BOOLEAN
2258        // RSMD returns SMALLINT
2259        int metaColumnType = rs.getInt("DATA_TYPE");
2260        if (metaColumnType == Types.BOOLEAN )
2261        {
2262            assertEquals("TYPE_NAME",
2263                    "BOOLEAN", rs.getString("TYPE_NAME"));
2264            assertEquals("TYPE_NAME",
2265                    "SMALLINT", rsmdt.getColumnTypeName(col));
2266
2267            assertEquals("DATA_TYPE",
2268                    Types.SMALLINT, rsmdt.getColumnType(col));
2269        }
2270        else if (metaColumnType == Types.JAVA_OBJECT)
2271        {
2272            // meta returns JAVA_OBJECT
2273            // RSMD returns LONGVARBINARY!
2274            assertEquals("DATA_TYPE",
2275                    Types.LONGVARBINARY, rsmdt.getColumnType(col));
2276        }
2277        else if (metaColumnType == Types.VARBINARY )
2278        {
2279            // meta returns different type name to RSMD
2280            assertEquals("DATA_TYPE",
2281                    Types.VARBINARY, rsmdt.getColumnType(col));
2282        }
2283        else if (metaColumnType == Types.BINARY )
2284        {
2285            // meta returns different type name to RSMD
2286            assertEquals("DATA_TYPE",
2287                    Types.BINARY, rsmdt.getColumnType(col));
2288        }
2289        else if (metaColumnType == Types.NUMERIC )
2290        {
2291            // DERBY-584 inconsistency in numeric & decimal
2292            assertEquals("DATA_TYPE",
2293                    Types.DECIMAL, rsmdt.getColumnType(col));
2294
2295            assertEquals("TYPE_NAME",
2296                    "DECIMAL", rsmdt.getColumnTypeName(col));
2297
2298            assertEquals("TYPE_NAME",
2299                    "NUMERIC", rs.getString("TYPE_NAME"));
2300        }
2301        else
2302        {
2303            assertEquals("DATA_TYPE",
2304                rsmdt.getColumnType(col), rs.getInt("DATA_TYPE"));
2305            assertEquals("TYPE_NAME",
2306                rsmdt.getColumnTypeName(col), rs.getString("TYPE_NAME"));
2307        }
2308
2309        /*
2310        if (metaColumnType != Types.JAVA_OBJECT) {
2311        System.out.println("TYPE " + rs.getInt("DATA_TYPE"));
2312        System.out.println(JDBC.escape(schema, table) + " " + rs.getString("COLUMN_NAME"));
2313        assertEquals("COLUMN_SIZE",
2314                rsmdt.getPrecision(col), rs.getInt("COLUMN_SIZE"));
2315        }
2316        */
2317
2318        /*
2319        assertEquals("DECIMAL_DIGITS",
2320                rsmdt.getScale(col), rs.getInt("DECIMAL_DIGITS"));
2321        */
2322
2323        // This assumes the constants defined by meta and ResultSet
2324        // for nullability are equal. They are by inspection
2325        // and since they are static final and part of a defined
2326        // api by definition they cannot change. We also
2327        // check statically this is true in the testConstants fixture.
2328        assertEquals("NULLABLE",
2329                rsmdt.isNullable(col), rs.getInt("NULLABLE"));
2330
2331        // REMARKS set to empty string by Derby
2332        assertEquals("REMARKS", "", rs.getString("REMARKS"));
2333
2334
2335        // IS_NULLABLE
2336        switch (rsmdt.isNullable(col))
2337        {
2338        case ResultSetMetaData.columnNoNulls:
2339            assertEquals("IS_NULLABLE", "NO", rs.getString("IS_NULLABLE"));
2340            break;
2341        case ResultSetMetaData.columnNullable:
2342            assertEquals("IS_NULLABLE", "YES", rs.getString("IS_NULLABLE"));
2343            break;
2344        case ResultSetMetaData.columnNullableUnknown:
2345            assertEquals("IS_NULLABLE", "", rs.getString("IS_NULLABLE"));
2346            break;
2347        default:
2348            fail("invalid return from rsmdt.isNullable(col)");
2349        }
2350
2351        // SCOPE not supported
2352        assertNull("SCOPE_CATLOG", rs.getString("SCOPE_CATLOG"));
2353        assertNull("SCOPE_SCHEMA", rs.getString("SCOPE_SCHEMA"));
2354        assertNull("SCOPE_TABLE", rs.getString("SCOPE_TABLE"));
2355
2356        // DISTINCT not supported
2357        assertEquals("SOURCE_DATA_TYPE", 0, rs.getShort("SOURCE_DATA_TYPE"));
2358        assertTrue(rs.wasNull());
2359
2360        // IS_AUTOINCREMENT added in JDBC 4.0
2361       assertEquals("IS_AUTOINCREMENT",
2362               rsmdt.isAutoIncrement(col) ? "YES" : "NO",
2363               rs.getString("IS_AUTOINCREMENT"));
2364       assertFalse(rs.wasNull());
2365    }
2366
2367    /*
2368     * Check the shape of the ResultSet from any getColumns call.
2369     */
2370    private void checkColumnsShape(ResultSet rs) throws SQLException {
2371        int[] columnTypes = new int[] {
2372                Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
2373                Types.SMALLINT, Types.VARCHAR, Types.INTEGER, Types.INTEGER,
2374                Types.INTEGER, Types.INTEGER, Types.INTEGER, Types.VARCHAR,
2375                Types.VARCHAR, Types.INTEGER, Types.INTEGER, Types.INTEGER,
2376                Types.INTEGER, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
2377                Types.VARCHAR, Types.SMALLINT, Types.VARCHAR};
2378
2379        assertMetaDataResultSet(rs, new String[] {
2380                "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME", "COLUMN_NAME",
2381                "DATA_TYPE", "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH",
2382                "DECIMAL_DIGITS", "NUM_PREC_RADIX", "NULLABLE", "REMARKS",
2383                "COLUMN_DEF", "SQL_DATA_TYPE", "SQL_DATETIME_SUB",
2384                "CHAR_OCTET_LENGTH", "ORDINAL_POSITION", "IS_NULLABLE",
2385                "SCOPE_CATLOG", "SCOPE_SCHEMA", "SCOPE_TABLE",
2386                "SOURCE_DATA_TYPE", "IS_AUTOINCREMENT"}, columnTypes, null);
2387
2388    }
2389
2390    public static void assertMetaDataResultSet(ResultSet rs,
2391            String[] columnNames, int[] columnTypes,
2392            boolean[] nullability) throws SQLException
2393    {
2394     // see ResultSetGetterTest, getType() -> this test fails currently
2395        assertEquals(ResultSet.TYPE_FORWARD_ONLY, rs.getType());
2396        assertEquals(ResultSet.CONCUR_READ_ONLY, rs.getConcurrency());
2397
2398        if (columnNames != null)
2399            assertColumnNames(rs, columnNames);
2400        if (columnTypes != null)
2401            assertColumnTypes(rs, columnTypes);
2402        if (nullability != null)
2403            assertNullability(rs, nullability);
2404    }
2405
2406    /**
2407     * * Test Method from Apache Derby Project
2408     *   Class
2409     * org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
2410     *
2411     * Takes a result set and an array of expected colum names (as
2412     * Strings)  and asserts that the column names in the result
2413     * set metadata match the number, order, and names of those
2414     * in the array.
2415     *
2416     * @param rs ResultSet for which we're checking column names.
2417     * @param expectedColNames Array of expected column names.
2418     */
2419    public static void assertColumnNames(ResultSet rs,
2420        String [] expectedColNames) throws SQLException
2421    {
2422        ResultSetMetaData rsmd = rs.getMetaData();
2423        int actualCols = rsmd.getColumnCount();
2424
2425        for (int i = 0; i < actualCols; i++)
2426        {
2427        assertEquals("Column names do not match:",
2428                expectedColNames[i], rsmd.getColumnName(i+1));
2429        }
2430
2431        assertEquals("Unexpected column count:",
2432        expectedColNames.length, rsmd.getColumnCount());
2433    }
2434
2435    /**
2436     * Test Method from Apache Derby Project
2437     * Class
2438     * org.apache.derbyTesting.functionTests.tests.jdbcapi.DatabaseMetaDataTest
2439     *
2440     * Takes a result set and an array of expected column types
2441     * from java.sql.Types
2442     * and asserts that the column types in the result
2443     * set metadata match the number, order, and names of those
2444     * in the array.
2445     *
2446     * No length information for variable length types
2447     * can be passed. For ResultSets from JDBC DatabaseMetaData
2448     * the specification only indicates the types of the
2449     * columns, not the length.
2450     *
2451     * @param rs ResultSet for which we're checking column names.
2452     * @param expectedTypes Array of expected column types.
2453     */
2454    public static void assertColumnTypes(ResultSet rs,
2455        int[] expectedTypes) throws SQLException
2456    {
2457        ResultSetMetaData rsmd = rs.getMetaData();
2458        int actualCols = rsmd.getColumnCount();
2459
2460        assertEquals("Unexpected column count:",
2461                expectedTypes.length, rsmd.getColumnCount());
2462
2463        for (int i = 0; i < actualCols; i++)
2464        {
2465       assertEquals("Column types do not match for column " + (i+1),
2466                    expectedTypes[i], rsmd.getColumnType(i+1));
2467        }
2468    }
2469
2470    /**
2471     * Check the nullability of the column definitions for
2472     * the ResultSet matches the expected values.
2473     * @param rs
2474     * @param nullability
2475     * @throws SQLException
2476     */
2477    public static void assertNullability(ResultSet rs,
2478            boolean[] nullability) throws SQLException
2479    {
2480        ResultSetMetaData rsmd = rs.getMetaData();
2481        int actualCols = rsmd.getColumnCount();
2482
2483        assertEquals("Unexpected column count:",
2484                nullability.length, rsmd.getColumnCount());
2485
2486        for (int i = 0; i < actualCols; i++)
2487        {
2488            int expected = nullability[i] ?
2489               ResultSetMetaData.columnNullable : ResultSetMetaData.columnNoNulls;
2490       assertEquals("Column nullability do not match for column " + (i+1),
2491                    expected, rsmd.isNullable(i+1));
2492        }
2493    }
2494
2495    //BEGIN Apache Derby DatabaseMetaDataTest
2496
2497     /*
2498      * Escaped function testing TODO complete this list
2499      */
2500     private static final String[][] NUMERIC_FUNCTIONS = {
2501             // Section C.1 JDBC 3.0 spec.
2502             {"ABS", "-25.67"},
2503
2504//             {"ACOS", "0.0707"}, {"ASIN", "0.997"},
2505//             {"ATAN", "14.10"}, {"ATAN2", "0.56", "1.2"}, {"CEILING", "3.45"},
2506//             {"COS", "1.2"}, {"COT", "3.4"}, {"DEGREES", "2.1"}, {"EXP", "2.3"},
2507//             {"FLOOR", "3.22"}, {"LOG", "34.1"}, {"LOG10", "18.7"},
2508//             {"MOD", "124", "7"}, {"PI"}, {"POWER", "2", "3"},
2509//             {"RADIANS", "54"}, {"RAND", "17"},
2510
2511             {"ROUND", "345.345", "1"}
2512
2513//             {"SIGN", "-34"}, {"SIN", "0.32"}, {"SQRT", "6.22"},
2514//             {"TAN", "0.57",}, {"TRUNCATE", "345.395", "1"}
2515
2516             };
2517
2518     private static final String[][] TIMEDATE_FUNCTIONS = {
2519             // Section C.3 JDBC 3.0 spec.
2520
2521             {"date","'now'"}
2522
2523             //TODO Complete list
2524
2525     };
2526
2527     private static final String[][] SYSTEM_FUNCTIONS = {
2528     // Section C.4 JDBC 3.0 spec.
2529             {"IFNULL", "'this'", "'that'"}, {"USER"}
2530             };
2531
2532     /*
2533      * TODO complete or check this list
2534      */
2535     private static final String[][] STRING_FUNCTIONS = {
2536             // Section C.2 JDBC 3.0 spec.
2537//             {"ASCII", "'Yellow'"}, {"CHAR", "65"},
2538//             {"CONCAT", "'hello'", "'there'"},
2539//             {"DIFFERENCE", "'Pires'", "'Piers'"},
2540//             {"INSERT", "'Bill Clinton'", "4", "'William'"},
2541//             {"LCASE", "'Fernando Alonso'"}, {"LEFT", "'Bonjour'", "3"},
2542//             {"LENGTH", "'four    '"}, {"LOCATE", "'jour'", "'Bonjour'"},
2543             {"LTRIM", "'   left trim   '"},
2544//               {"REPEAT", "'echo'", "3"},
2545//             {"REPLACE", "'to be or not to be'", "'be'", "'England'"},
2546//             {"RTRIM", "'  right trim   '"}, {"SOUNDEX", "'Derby'"},
2547//             {"SPACE", "12"},
2548//             {"SUBSTRING", "'Ruby the Rubicon Jeep'", "10", "7",},
2549//             {"UCASE", "'Fernando Alonso'"}
2550     };
2551
2552     /**
2553      * Six combinations of valid identifiers with mixed case, to see how the
2554      * various pattern matching and returned values handle them. This test only
2555      * creates objects in these schemas.
2556      */
2557     private static final String[] IDS = {
2558             "one_meta_test", "TWO_meta_test", "ThReE_meta_test",
2559             "\"four_meta_test\"", "\"FIVE_meta_test\"", "\"sIx_meta_test\""};
2560
2561     /**
2562      * All the builtin schemas.
2563      */
2564     private static final String[] BUILTIN_SCHEMAS = {
2565             //TODO: Are there any other built in schemas?
2566
2567     };
2568
2569     public static String getStoredIdentifier(String sqlIdentifier) {
2570         if (sqlIdentifier.charAt(0) == '"')
2571             return sqlIdentifier.substring(1, sqlIdentifier.length() - 1);
2572         else
2573             return sqlIdentifier.toUpperCase();
2574     }
2575
2576     /**
2577      * Test getSchemas() without modifying the database.
2578      *
2579      * @throws SQLException
2580      */
2581     @TestTargetNew(
2582             level = TestLevel.PARTIAL_COMPLETE,
2583             notes = "Derby test for getSchema",
2584             method = "getSchemas",
2585             args = {}
2586         )
2587     public void testGetSchemasReadOnly() throws SQLException {
2588
2589         ResultSet rs = meta.getSchemas();
2590         checkSchemas(rs, new String[0]);
2591     }
2592
2593
2594     /**
2595      * Check the returned information from a getSchemas(). The passed in
2596      * String[] expected is a list of the schemas expected to be present in the
2597      * returned set. The returned set may contain additional schemas which will
2598      * be ignored, thus this test can be used regardless of the database state.
2599      * The builtin schemas are automatically checked and must not be part of the
2600      * passed in list.
2601      */
2602     public static void checkSchemas(ResultSet rs, String[] userExpected)
2603             throws SQLException {
2604
2605         // Add in the system schemas
2606         String[] expected = new String[BUILTIN_SCHEMAS.length
2607                 + userExpected.length];
2608
2609         System.arraycopy(BUILTIN_SCHEMAS, 0, expected, 0,
2610                 BUILTIN_SCHEMAS.length);
2611         System.arraycopy(userExpected, 0, expected, BUILTIN_SCHEMAS.length,
2612                 userExpected.length);
2613
2614         // Remove any quotes from user schemas and upper case
2615         // those without quotes.
2616         for (int i = BUILTIN_SCHEMAS.length; i < expected.length; i++) {
2617             expected[i] = getStoredIdentifier(expected[i]);
2618         }
2619
2620         // output is ordered by TABLE_SCHEM
2621         Arrays.sort(expected);
2622
2623         int nextMatch = 0;
2624
2625         while (rs.next()) {
2626             String schema = rs.getString("TABLE_SCHEM");
2627             assertNotNull(schema);
2628
2629             // Catalogs not supported
2630//             assertNull(rs.getString("TABLE_CATALOG"));
2631
2632             if (nextMatch < expected.length) {
2633                 if (expected[nextMatch].equals(schema)) nextMatch++;
2634             }
2635         }
2636         rs.close();
2637         assertEquals("Schemas missing ", expected.length, nextMatch);
2638     }
2639
2640     private void assertMatchesPattern(String pattern, String result) {
2641         if (!doesMatch(pattern, 0, result, 0)) {
2642             fail("Bad pattern matching:" + pattern + " result:" + result);
2643         }
2644
2645     }
2646
2647     /**
2648      * See if a string matches the pattern as defined by DatabaseMetaData. By
2649      * passing in non-zero values can check sub-sets of the pattern against the
2650      * sub strings of the result. <BR>
2651      * _ matches a single character <BR>
2652      * % matches zero or more characters <BR>
2653      * Other characters match themselves.
2654      *
2655      * @param pattern
2656      *            Pattern
2657      * @param pp
2658      *            Position in pattern to start the actual pattern from
2659      * @param result
2660      *            result string
2661      * @param rp
2662      *            position in result to starting checking
2663      * @return true if a match is found
2664      */
2665     private boolean doesMatch(String pattern, int pp, String result, int rp) {
2666         // Find a match
2667         for (;;) {
2668             if (pp == pattern.length() && rp == result.length()) return true;
2669
2670             // more characters to match in the result but
2671             // no more pattern.
2672             if (pp == pattern.length()) return false;
2673
2674             char pc = pattern.charAt(pp);
2675             if (pc == '_') {
2676                 // need to match a single character but
2677                 // exhausted result, so no match.
2678                 if (rp == result.length()) return false;
2679
2680                 pp++;
2681                 rp++;
2682             } else if (pc == '%') {
2683                 // % at end, complete match regardless of
2684                 // position of result since % matches zero or more.
2685                 if (pp == pattern.length() - 1) {
2686                     return true;
2687                 }
2688
2689                 // Brut force, we have a pattern like %X
2690                 // and we are say in the third character of
2691                 // abCdefgX
2692                 // then start a 'CdefgX' and look for a match,
2693                 // then 'defgX' etc.
2694                 for (int sp = rp; sp < result.length(); sp++) {
2695                     if (doesMatch(pattern, pp + 1, result, sp)) {
2696                         // Have a match for the pattern after the %
2697                         // which means we have a match for the pattern
2698                         // with the % since we can match 0 or mor characters
2699                         // with %.
2700                         return true;
2701                     }
2702                 }
2703
2704                 // Could not match the pattern after the %
2705                 return false;
2706             } else {
2707                 // need to match a single character but
2708                 // exhausted result, so no match.
2709                 if (rp == result.length()) return false;
2710
2711                 // Single character, must match exactly.
2712                 if (pc != result.charAt(rp)) {
2713                     // Computer says no.
2714                     return false;
2715                 }
2716                 pp++;
2717                 rp++;
2718             }
2719
2720         }
2721
2722     }
2723
2724
2725     /**
2726      * Check that the list of escaped functions provided by the driver is a
2727      * strict subet of the specified set, the list does not contain duplicates,
2728      * all the functions listed can be executed and that if a function is not in
2729      * the list but is specified it cannot be executed.
2730      */
2731     private void escapedFunctions(String[][] specList, String metaDataList)
2732             throws SQLException {
2733
2734         boolean[] seenFunction = new boolean[specList.length];
2735
2736         StringTokenizer st = new StringTokenizer(metaDataList, ",");
2737         int counter = 0;
2738         while (st.hasMoreTokens()) {
2739             counter++;
2740             String function = st.nextToken();
2741
2742             // find this function in the list
2743             boolean isSpecFunction = false;
2744             for (int f = 0; f < specList.length; f++) {
2745                 String[] specDetails = specList[f];
2746                 if (function.equals(specDetails[0])) {
2747                     // Matched spec.
2748                     if (seenFunction[f])
2749                         fail("Function in list twice: " + function);
2750                     seenFunction[f] = true;
2751                     isSpecFunction = true;
2752                     executeEscaped(specDetails);
2753                     break;
2754                 }
2755             }
2756
2757             if (!isSpecFunction) {
2758                 fail("Non-JDBC spec function in list: " + function);
2759             }
2760         }
2761
2762         // Now see if any speced functions are not in the metadata list
2763         assertSame("Function missing in metadata impl",specList.length, counter);
2764         for (int f = 0; f < specList.length; f++) {
2765             if (seenFunction[f]) continue;
2766             String[] specDetails = specList[f];
2767
2768             // bug DERBY-723 CHAR maps to wrong function
2769             if ("CHAR".equals(specDetails[0])) continue;
2770             try {
2771                 executeEscaped(specDetails);
2772                 fail("function works but not declared in list: "
2773                         + specDetails[0]);
2774             } catch (SQLException e) {
2775                 //ok
2776             }
2777         }
2778     }
2779
2780     /**
2781      * Test we can execute a function listed as a supported
2782      * JDBC escaped function. We don't care about the actual
2783      * return value, that should be tested elsewhere in
2784      * the specific test of a function.
2785      */
2786     private void executeEscaped(String[] specDetails)
2787         throws SQLException
2788     {
2789
2790         String sql = "SELECT " + specDetails[0] + "(";
2791
2792         for (int p = 0; p < specDetails.length - 1; p++)
2793         {
2794             if (p != 0)
2795                 sql = sql + ", ";
2796
2797             sql = sql + specDetails[p + 1];
2798         }
2799
2800         sql = sql + ") ;";
2801
2802         System.out.println("DatabaseMetaDataTest.executeEscaped() "+sql);
2803         Statement st = conn.createStatement();
2804         ResultSet rs = st.executeQuery(sql);
2805
2806         assertNotNull("not supported function: "+sql,rs);
2807
2808         rs.close();
2809         st.close();
2810     }
2811
2812  //END APACHE-DERBY
2813}
2814