summaryrefslogtreecommitdiffstats
path: root/sql/src/test
diff options
context:
space:
mode:
authorThe Android Open Source Project <initial-contribution@android.com>2008-10-21 07:00:00 -0700
committerThe Android Open Source Project <initial-contribution@android.com>2008-10-21 07:00:00 -0700
commitfdb2704414a9ed92394ada0d1395e4db86889465 (patch)
tree9b591a4a50054274a197f02b3ccb51313681879f /sql/src/test
downloadlibcore-fdb2704414a9ed92394ada0d1395e4db86889465.zip
libcore-fdb2704414a9ed92394ada0d1395e4db86889465.tar.gz
libcore-fdb2704414a9ed92394ada0d1395e4db86889465.tar.bz2
Initial Contribution
Diffstat (limited to 'sql/src/test')
-rw-r--r--sql/src/test/java/SQLite/JDBCDriverTest.java86
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java57
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.java384
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ConnectionTest.java89
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.java501
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java119
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DateTest.java380
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java582
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverPropertyInfoTest.java107
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ParameterMetaDataTest.java94
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetMetaDataTest.java84
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetTest.java101
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.java541
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLPermissionTest.java74
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.java398
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/StatementTest.java92
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_ClassLoader.java219
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Connection1.java176
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver1.java116
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver2.java50
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver3.java36
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver4.java129
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver5.java44
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java113
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimeTest.java304
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimestampTest.java624
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TypesTest.java101
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java42
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.java57
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_PooledConnection.java38
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_RowSet.java738
-rw-r--r--sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/RowSetEventTest.java36
-rw-r--r--sql/src/test/java/tests/java/sql/AllTests.java48
-rwxr-xr-xsql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java2191
-rwxr-xr-xsql/src/test/java/tests/java/sql/DeleteFunctionalityTest.java219
-rwxr-xr-xsql/src/test/java/tests/java/sql/InsertFunctionalityTest.java250
-rwxr-xr-xsql/src/test/java/tests/java/sql/MultiThreadAccessTest.java445
-rwxr-xr-xsql/src/test/java/tests/java/sql/SelectFunctionalityTest.java542
-rwxr-xr-xsql/src/test/java/tests/java/sql/StressTest.java310
-rwxr-xr-xsql/src/test/java/tests/java/sql/UpdateFunctionalityTest.java365
-rwxr-xr-xsql/src/test/java/tests/java/sql/UpdateFunctionalityTest2.java296
-rw-r--r--sql/src/test/java/tests/sql/AbstractSqlTest.java212
-rw-r--r--sql/src/test/java/tests/sql/AllTests.java46
-rwxr-xr-xsql/src/test/java/tests/sql/ConnectionTest.java1958
-rwxr-xr-xsql/src/test/java/tests/sql/PreparedStatementTest.java2473
-rwxr-xr-xsql/src/test/java/tests/sql/ResultSetMetaDataTest.java252
-rwxr-xr-xsql/src/test/java/tests/sql/SQLTest.java123
-rwxr-xr-xsql/src/test/java/tests/sql/StatementTest.java955
-rwxr-xr-xsql/src/test/java/tests/support/DatabaseCreator.java401
-rw-r--r--sql/src/test/java/tests/support/Support_SQL.java90
-rw-r--r--sql/src/test/java/tests/support/ThreadPool.java116
-rw-r--r--sql/src/test/resources/connection.properties9
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.golden.serbin0 -> 1724 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.golden.serbin0 -> 1754 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.golden.serbin0 -> 2716 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.golden.serbin0 -> 2146 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/TimestampTest.golden.serbin0 -> 91 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.golden.serbin0 -> 2229 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/RowSetMetaDataImplTest.golden.serbin0 -> 671 bytes
-rw-r--r--sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.golden.serbin0 -> 1661 bytes
60 files changed, 17813 insertions, 0 deletions
diff --git a/sql/src/test/java/SQLite/JDBCDriverTest.java b/sql/src/test/java/SQLite/JDBCDriverTest.java
new file mode 100644
index 0000000..cc4d769
--- /dev/null
+++ b/sql/src/test/java/SQLite/JDBCDriverTest.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package SQLite;
+
+import tests.sql.AbstractSqlTest;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.SQLException;
+
+
+
+/**
+ * Tests the SQLite.JDBCDriver.
+ */
+public class JDBCDriverTest extends AbstractSqlTest {
+
+
+
+ /**
+ * The SQLite db file.
+ */
+ private final File dbFile = new File("sqliteTest.db");
+
+ private final String connectionURL = "jdbc:sqlite:/" + dbFile.getName();
+
+ /**
+ * Creates a new instance of this class.
+ */
+ public JDBCDriverTest(String testName) {
+ super(testName);
+ }
+
+ /**
+ * Sets up an unit test by loading the SQLite.JDBCDriver, getting two
+ * connections and calling the setUp method of the super class.
+ */
+ @Override
+ protected void setUp() throws ClassNotFoundException, SQLException,
+ java.lang.Exception { // the Exception class needs to be fully
+ // qualified since there is an Exception
+ // class in the SQLite package.
+
+ super.setUp();
+ }
+
+ /**
+ * Tears down an unit test by calling the tearDown method of the super class
+ * and deleting the SQLite test db file.
+ */
+ @Override
+ protected void tearDown() throws SQLException {
+ super.tearDown();
+ dbFile.delete();
+ }
+
+
+ @Override
+ protected String getConnectionURL() {
+ return connectionURL;
+ }
+
+ @Override
+ protected String getDriverClassName() {
+ return "SQLite.JDBCDriver";
+ }
+
+ @Override
+ protected int getTransactionIsolation() {
+ return Connection.TRANSACTION_SERIALIZABLE;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java
new file mode 100644
index 0000000..6dc7c84
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/AllTests.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * This is autogenerated source file. Includes tests for package org.apache.harmony.sql.tests.java.sql;
+ */
+
+public class AllTests {
+
+ public static void main(String[] args) {
+ junit.textui.TestRunner.run(AllTests.suite());
+ }
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.java.sql;");
+ // $JUnit-BEGIN$
+
+ suite.addTestSuite(BatchUpdateExceptionTest.class);
+ suite.addTestSuite(ConnectionTest.class);
+ suite.addTestSuite(DataTruncationTest.class);
+ suite.addTestSuite(DatabaseMetaDataTest.class);
+ suite.addTestSuite(DateTest.class);
+ suite.addTestSuite(DriverManagerTest.class);
+ suite.addTestSuite(DriverPropertyInfoTest.class);
+ suite.addTestSuite(ParameterMetaDataTest.class);
+ suite.addTestSuite(ResultSetMetaDataTest.class);
+ suite.addTestSuite(ResultSetTest.class);
+ suite.addTestSuite(SQLExceptionTest.class);
+ suite.addTestSuite(SQLPermissionTest.class);
+ suite.addTestSuite(SQLWarningTest.class);
+ suite.addTestSuite(StatementTest.class);
+ suite.addTestSuite(TimeTest.class);
+ suite.addTestSuite(TimestampTest.class);
+ suite.addTestSuite(TypesTest.class);
+
+ // $JUnit-END$
+ return suite;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.java
new file mode 100644
index 0000000..241888a
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.java
@@ -0,0 +1,384 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.Serializable;
+import java.sql.BatchUpdateException;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+public class BatchUpdateExceptionTest extends TestCase {
+
+ /*
+ * ConstructorTest
+ */
+ public void testBatchUpdateException() {
+
+ int[] theFinalStates1 = { 0 }; // Error Code state
+ int[][] theFinalStates2 = { null }; // Update Counts array state
+ String[] theFinalStates3 = { null }; // SQL State state value
+ String[] theFinalStates4 = { null }; // Message state
+
+ Exception[] theExceptions = { null };
+
+ BatchUpdateException aBatchUpdateException;
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException();
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testBatchUpdateException
+
+ /*
+ * ConstructorTest
+ */
+ public void testBatchUpdateExceptionintArray() {
+
+ int[][] init1 = { { 1, 2, 3 }, null };
+
+ int[] theFinalStates1 = { 0, 0 }; // Error Code state
+ int[][] theFinalStates2 = init1; // Update Counts array state
+ String[] theFinalStates3 = { null, null }; // SQL State state value
+ String[] theFinalStates4 = { null, null }; // Message state
+
+ Exception[] theExceptions = { null, null };
+
+ BatchUpdateException aBatchUpdateException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException(init1[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testBatchUpdateExceptionintArray
+
+ /*
+ * ConstructorTest
+ */
+ public void testBatchUpdateExceptionStringintArray() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null, "",
+ ".", "a" };
+ int[][] init2 = { { 1, 2, 3 }, {}, { 3 }, null, { 5, 5 }, { 6 },
+ { 121, 2, 1 }, { 1 }, { 1, 2 } };
+
+ int[] theFinalStates1 = { 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Error Code
+ // state
+ // Update Counts array state
+ int[][] theFinalStates2 = init2;
+ // SQL State state value
+ String[] theFinalStates3 = { null, null, null, null, null, null, null,
+ null, null };
+ String[] theFinalStates4 = init1; // Message state
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null };
+
+ BatchUpdateException aBatchUpdateException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException(init1[i],
+ init2[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testBatchUpdateExceptionStringintArray
+
+ /*
+ * ConstructorTest
+ */
+ public void testBatchUpdateExceptionStringStringintArray() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null, "",
+ ".", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "a", null,
+ "", ".", "a" };
+ int[][] init3 = { { 1, 2, 3 }, {}, { 3 }, { 5, 5 }, { 6 },
+ { 121, 2, 1 }, { 1 }, { 1, 2 }, { 1 }, { 2 }, null };
+
+ int[] theFinalStates1 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // Error
+ // Code
+ // state
+ // Update Counts array state
+ int[][] theFinalStates2 = init3;
+ // SQL State state value
+ String[] theFinalStates3 = init2;
+ String[] theFinalStates4 = init1; // Message state
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null };
+
+ BatchUpdateException aBatchUpdateException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException(init1[i],
+ init2[i], init3[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testBatchUpdateExceptionStringStringintArray
+
+ /*
+ * ConstructorTest
+ */
+ public void testBatchUpdateExceptionStringStringintintArray() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null, "",
+ ".", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "a", null,
+ "", ".", "a" };
+ int[] init3 = { -2147483648, 2147483647, 0, -492417162, -156220255,
+ -173012890, -631026360, -2147483648, -2147483648, -2147483648,
+ -2147483648 };
+ int[][] init4 = { { 1, 2, 3 }, {}, { 3 }, { 5, 5 }, { 6 },
+ { 121, 2, 1 }, { 1 }, { 1, 2 }, { 1 }, { 2 }, null };
+
+ int[] theFinalStates1 = init3; // Error Code state
+ // Update Counts array state
+ int[][] theFinalStates2 = init4;
+ // SQL State state value
+ String[] theFinalStates3 = init2;
+ String[] theFinalStates4 = init1; // Message state
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null };
+
+ BatchUpdateException aBatchUpdateException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException(init1[i],
+ init2[i], init3[i], init4[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testBatchUpdateExceptionStringStringintintArray
+
+ /*
+ * Method test for getUpdateCounts
+ */
+ public void testGetUpdateCounts() {
+
+ BatchUpdateException aBatchUpdateException;
+ int[][] init1 = { { 1, 2, 3 }, {}, null };
+
+ int[] theReturn;
+ int[][] theReturns = init1;
+
+ int[] theFinalStates1 = { 0, 0, 0 }; // Error Code state
+ int[][] theFinalStates2 = init1; // Update Counts array state
+ String[] theFinalStates3 = { null, null, null }; // SQL State state
+ // value
+ String[] theFinalStates4 = { null, null, null }; // Message state
+
+ Exception[] theExceptions = { null, null, null };
+
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aBatchUpdateException = new BatchUpdateException(init1[i]);
+ theReturn = aBatchUpdateException.getUpdateCounts();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getErrorCode(),
+ theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getUpdateCounts(),
+ theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getSQLState(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch: ",
+ aBatchUpdateException.getMessage(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetUpdateCounts
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ BatchUpdateException object = new BatchUpdateException();
+ SerializationTest.verifySelf(object, BATCHUPDATEEXCEPTION_COMPARATOR);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ int vendorCode = 10;
+ int[] updateCounts = { 1, 2, 3, 4 };
+ BatchUpdateException object = new BatchUpdateException("reason",
+ "SQLState", vendorCode, updateCounts);
+ SerializationTest.verifyGolden(this, object,
+ BATCHUPDATEEXCEPTION_COMPARATOR);
+ }
+
+ // comparator for BatchUpdateException field updateCounts
+ private static final SerializableAssert BATCHUPDATEEXCEPTION_COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ // do common checks for all throwable objects
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ BatchUpdateException initThr = (BatchUpdateException) initial;
+ BatchUpdateException dserThr = (BatchUpdateException) deserialized;
+
+ // verify updateCounts
+ int[] initUpdateCounts = initThr.getUpdateCounts();
+ int[] dserUpdateCounts = dserThr.getUpdateCounts();
+ assertTrue(Arrays.equals(initUpdateCounts, dserUpdateCounts));
+ }
+ };
+
+} // end class BatchUpdateExceptionTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ConnectionTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ConnectionTest.java
new file mode 100644
index 0000000..22409f7
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ConnectionTest.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class ConnectionTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("TRANSACTION_SERIALIZABLE", new Integer(8));
+ thePublicStatics.put("TRANSACTION_REPEATABLE_READ", new Integer(4));
+ thePublicStatics.put("TRANSACTION_READ_COMMITTED", new Integer(2));
+ thePublicStatics.put("TRANSACTION_READ_UNCOMMITTED", new Integer(1));
+ thePublicStatics.put("TRANSACTION_NONE", new Integer(0));
+
+ /*
+ * System.out.println( "TRANSACTION_SERIALIZABLE: " +
+ * Connection.TRANSACTION_SERIALIZABLE ); System.out.println(
+ * "TRANSACTION_REPEATABLE_READ: " +
+ * Connection.TRANSACTION_REPEATABLE_READ ); System.out.println(
+ * "TRANSACTION_READ_COMMITTED: " +
+ * Connection.TRANSACTION_READ_COMMITTED ); System.out.println(
+ * "TRANSACTION_READ_UNCOMMITTED: " +
+ * Connection.TRANSACTION_READ_UNCOMMITTED ); System.out.println(
+ * "TRANSACTION_NONE: " + Connection.TRANSACTION_NONE );
+ */
+
+ Class<?> connectionClass;
+ try {
+ connectionClass = Class.forName("java.sql.Connection");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.Connection class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = connectionClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class ConnectionTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.java
new file mode 100644
index 0000000..624da41
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.java
@@ -0,0 +1,501 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.Serializable;
+import java.sql.DataTruncation;
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+import junit.framework.TestCase;
+
+public class DataTruncationTest extends TestCase {
+
+ /*
+ * ConstructorTest
+ */
+ public void testDataTruncationintbooleanbooleanintint() {
+
+ int[] init1 = { -2147483648, 2147483647, 0, 329751502, 318587557,
+ -1217247045, 329474146 };
+ boolean[] init2 = { false, true, false, false, false, true, false };
+ boolean[] init3 = { false, true, false, false, false, false, true };
+ int[] init4 = { -2147483648, 2147483647, 0, 1761409290, -1331044048,
+ -576231606, 661635011 };
+ int[] init5 = { -2147483648, 2147483647, 0, 540816689, -1890783845,
+ -105552912, -85923935 };
+
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ DataTruncation aDataTruncation;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testDataTruncationintbooleanbooleanintint
+
+ /*
+ * Method test for getIndex
+ */
+ public void testGetIndex() {
+
+ DataTruncation aDataTruncation;
+ int[] init1 = { -2147483648, 2147483647, 0, -2045829673, 1977156911,
+ 478985827, 1687271915 };
+ boolean[] init2 = { false, true, false, false, true, true, true };
+ boolean[] init3 = { false, true, false, false, true, true, true };
+ int[] init4 = { -2147483648, 2147483647, 0, -631377748, 21025030,
+ 1215194589, 1064137121 };
+ int[] init5 = { -2147483648, 2147483647, 0, -897998505, 997578180,
+ 735015866, 264619424 };
+
+ int theReturn;
+ int[] theReturns = init1;
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ theReturn = aDataTruncation.getIndex();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetIndex
+
+ /*
+ * Method test for getParameter
+ */
+ public void testGetParameter() {
+
+ DataTruncation aDataTruncation;
+ int[] init1 = { -2147483648, 2147483647, 0, -492314242, 1637665948,
+ -305785075, 258819883 };
+ boolean[] init2 = { false, true, false, true, true, false, true };
+ boolean[] init3 = { false, true, false, false, false, true, true };
+ int[] init4 = { -2147483648, 2147483647, 0, 1134512579, 533874007,
+ 1709608139, 990656593 };
+ int[] init5 = { -2147483648, 2147483647, 0, -1566784226, -744009101,
+ -444614454, 356465980 };
+
+ boolean theReturn;
+ boolean[] theReturns = init2;
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ theReturn = aDataTruncation.getParameter();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetParameter
+
+ /*
+ * Method test for getRead
+ */
+ public void testGetRead() {
+
+ DataTruncation aDataTruncation;
+ int[] init1 = { -2147483648, 2147483647, 0, 2092420209, -1695764964,
+ 1832837995, -80199594 };
+ boolean[] init2 = { false, true, false, false, false, true, true };
+ boolean[] init3 = { false, true, false, false, true, true, false };
+ int[] init4 = { -2147483648, 2147483647, 0, 1762375167, -604897453,
+ 1362491587, 1007466498 };
+ int[] init5 = { -2147483648, 2147483647, 0, 1494407222, -1696982311,
+ -940493360, -1777579868 };
+
+ boolean theReturn;
+ boolean[] theReturns = init3;
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ theReturn = aDataTruncation.getRead();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetRead
+
+ /*
+ * Method test for getDataSize
+ */
+ public void testGetDataSize() {
+
+ DataTruncation aDataTruncation;
+ int[] init1 = { -2147483648, 2147483647, 0, 1146707040, -2020665632,
+ 1268632617, -1595624039 };
+ boolean[] init2 = { false, true, false, true, false, true, true };
+ boolean[] init3 = { false, true, false, true, true, false, false };
+ int[] init4 = { -2147483648, 2147483647, 0, -367493363, 328996907,
+ -1581326731, 835022052 };
+ int[] init5 = { -2147483648, 2147483647, 0, -886134194, 908213800,
+ 1123419516, -429606389 };
+
+ int theReturn;
+ int[] theReturns = init4;
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ theReturn = aDataTruncation.getDataSize();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetDataSize
+
+ /*
+ * Method test for getTransferSize
+ */
+ public void testGetTransferSize() {
+
+ DataTruncation aDataTruncation;
+ int[] init1 = { -2147483648, 2147483647, 0, 78096124, 1719192600,
+ -1661234694, -1205825753 };
+ boolean[] init2 = { false, true, false, false, true, false, true };
+ boolean[] init3 = { false, true, false, false, false, false, false };
+ int[] init4 = { -2147483648, 2147483647, 0, -493779295, -2042560243,
+ -217347438, 1357818664 };
+ int[] init5 = { -2147483648, 2147483647, 0, -1647009002, -717544563,
+ -1368171905, -918209633 };
+
+ int theReturn;
+ int[] theReturns = init5;
+ String[] theFinalStates1 = { "01004", "01004", "01004", "01004",
+ "01004", "01004", "01004" };
+ String state2 = "Data truncation";
+ String[] theFinalStates2 = { state2, state2, state2, state2, state2,
+ state2, state2 };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0 };
+ int[] theFinalStates4 = init1;
+ int[] theFinalStates5 = init4;
+ int[] theFinalStates6 = init5;
+ boolean[] theFinalStates7 = init2;
+ boolean[] theFinalStates8 = init3;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aDataTruncation = new DataTruncation(init1[i], init2[i],
+ init3[i], init4[i], init5[i]);
+ theReturn = aDataTruncation.getTransferSize();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getSQLState(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getMessage(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getIndex(), theFinalStates4[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getDataSize(), theFinalStates5[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getTransferSize(), theFinalStates6[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getParameter(), theFinalStates7[i]);
+ assertEquals(i + " Final state mismatch", aDataTruncation
+ .getRead(), theFinalStates8[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetTransferSize
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ DataTruncation object = new DataTruncation(10, true, true, 10, 10);
+ SerializationTest.verifySelf(object, DATATRUNCATION_COMPARATOR);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ DataTruncation object = new DataTruncation(10, true, true, 10, 10);
+ SerializationTest.verifyGolden(this, object, DATATRUNCATION_COMPARATOR);
+ }
+
+ // comparator for DataTruncation objects
+ private static final SerializableAssert DATATRUNCATION_COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ // do common checks for all throwable objects
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ DataTruncation initThr = (DataTruncation) initial;
+ DataTruncation dserThr = (DataTruncation) deserialized;
+
+ // verify index
+ assertEquals(initThr.getIndex(), dserThr.getIndex());
+
+ // verify parameter
+ assertEquals(initThr.getParameter(), dserThr.getParameter());
+
+ // verify read
+ assertEquals(initThr.getRead(), dserThr.getRead());
+
+ // verify dataSize
+ assertEquals(initThr.getDataSize(), dserThr.getDataSize());
+
+ // verify transferSize
+ assertEquals(initThr.getTransferSize(), dserThr.getTransferSize());
+ }
+ };
+
+} // end class DataTruncationTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java
new file mode 100644
index 0000000..c970c70
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DatabaseMetaDataTest.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class DatabaseMetaDataTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Number> thePublicStatics = new HashMap<String, Number>();
+ thePublicStatics.put("sqlStateSQL99", new Integer(2));
+ thePublicStatics.put("sqlStateXOpen", new Integer(1));
+ thePublicStatics.put("attributeNullableUnknown", new Short((short) 2));
+ thePublicStatics.put("attributeNullable", new Short((short) 1));
+ thePublicStatics.put("attributeNoNulls", new Short((short) 0));
+ thePublicStatics.put("tableIndexOther", new Short((short) 3));
+ thePublicStatics.put("tableIndexHashed", new Short((short) 2));
+ thePublicStatics.put("tableIndexClustered", new Short((short) 1));
+ thePublicStatics.put("tableIndexStatistic", new Short((short) 0));
+ thePublicStatics.put("typeSearchable", new Integer(3));
+ thePublicStatics.put("typePredBasic", new Integer(2));
+ thePublicStatics.put("typePredChar", new Integer(1));
+ thePublicStatics.put("typePredNone", new Integer(0));
+ thePublicStatics.put("typeNullableUnknown", new Integer(2));
+ thePublicStatics.put("typeNullable", new Integer(1));
+ thePublicStatics.put("typeNoNulls", new Integer(0));
+ thePublicStatics.put("importedKeyNotDeferrable", new Integer(7));
+ thePublicStatics.put("importedKeyInitiallyImmediate", new Integer(6));
+ thePublicStatics.put("importedKeyInitiallyDeferred", new Integer(5));
+ thePublicStatics.put("importedKeySetDefault", new Integer(4));
+ thePublicStatics.put("importedKeyNoAction", new Integer(3));
+ thePublicStatics.put("importedKeySetNull", new Integer(2));
+ thePublicStatics.put("importedKeyRestrict", new Integer(1));
+ thePublicStatics.put("importedKeyCascade", new Integer(0));
+ thePublicStatics.put("versionColumnPseudo", new Integer(2));
+ thePublicStatics.put("versionColumnNotPseudo", new Integer(1));
+ thePublicStatics.put("versionColumnUnknown", new Integer(0));
+ thePublicStatics.put("bestRowPseudo", new Integer(2));
+ thePublicStatics.put("bestRowNotPseudo", new Integer(1));
+ thePublicStatics.put("bestRowUnknown", new Integer(0));
+ thePublicStatics.put("bestRowSession", new Integer(2));
+ thePublicStatics.put("bestRowTransaction", new Integer(1));
+ thePublicStatics.put("bestRowTemporary", new Integer(0));
+ thePublicStatics.put("columnNullableUnknown", new Integer(2));
+ thePublicStatics.put("columnNullable", new Integer(1));
+ thePublicStatics.put("columnNoNulls", new Integer(0));
+ thePublicStatics.put("procedureNullableUnknown", new Integer(2));
+ thePublicStatics.put("procedureNullable", new Integer(1));
+ thePublicStatics.put("procedureNoNulls", new Integer(0));
+ thePublicStatics.put("procedureColumnResult", new Integer(3));
+ thePublicStatics.put("procedureColumnReturn", new Integer(5));
+ thePublicStatics.put("procedureColumnOut", new Integer(4));
+ thePublicStatics.put("procedureColumnInOut", new Integer(2));
+ thePublicStatics.put("procedureColumnIn", new Integer(1));
+ thePublicStatics.put("procedureColumnUnknown", new Integer(0));
+ thePublicStatics.put("procedureReturnsResult", new Integer(2));
+ thePublicStatics.put("procedureNoResult", new Integer(1));
+ thePublicStatics.put("procedureResultUnknown", new Integer(0));
+
+ Class<?> databaseMetaDataClass;
+ try {
+ databaseMetaDataClass = Class.forName("java.sql.DatabaseMetaData");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.DatabaseMetaData class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = databaseMetaDataClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class DatabaseMetaDataTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DateTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DateTest.java
new file mode 100644
index 0000000..903b77f
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DateTest.java
@@ -0,0 +1,380 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Date;
+import java.util.Calendar;
+import java.util.TimeZone;
+
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.Date class
+ *
+ */
+public class DateTest extends TestCase {
+
+ // A calendar object created in the GMT time zone
+ static Calendar aCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+
+ // Some interesting millisecond time values
+ // These millisecond times are all in GMT, effectively
+ static long TIME_AN_HOUR = 3600000; // 1000 * 60 * 60 ms
+
+ static long TIME_EPOCH = 0;
+
+ static long TIME_NOW = System.currentTimeMillis();
+
+ static long TIME_NEGATIVE = -3600001;
+
+ static long TIME_TESTDATE1 = getTime(1999, Calendar.DECEMBER, 31, 23, 59,
+ 59);
+
+ static long TIME_TESTDATE2 = getTime(2010, Calendar.JUNE, 10, 20, 3, 16);
+
+ static long TIME_TESTDATE3 = getTime(1931, Calendar.APRIL, 21, 1, 25, 1);
+
+ static long TIME_LOWERLIMIT = Long.MIN_VALUE;
+
+ static long TIME_UPPERLIMIT = Long.MAX_VALUE;
+
+ // Date strings
+ static String SQL_DATESTRING1 = "1999-12-31";
+
+ static String SQL_DATESTRING2 = "2010-06-10";
+
+ static String SQL_DATESTRING3 = "1931-04-21";
+
+ static String SQL_EPOCHSTRING = "1970-01-01";
+
+ static String SQL_DATEDAY1 = "1970-01-02";
+
+ static String SQL_NEGATIVE = "1969-12-31";
+
+ static long[] TIME_ARRAY = new long[] { TIME_TESTDATE1, TIME_TESTDATE2,
+ TIME_TESTDATE3, TIME_NEGATIVE, TIME_EPOCH };
+
+ // Date string array for London (GMT)
+ static String[] SQL_DATEARRAY = new String[] { SQL_DATESTRING1,
+ SQL_DATESTRING2, SQL_DATESTRING3, SQL_NEGATIVE, SQL_EPOCHSTRING };
+
+ // Date string array for New York - sometimes a day earlier than London
+ static String[] SQL_NYARRAY = new String[] { "1999-12-31", "2010-06-10",
+ "1931-04-20", "1969-12-31", "1969-12-31" };
+
+ // Date string for Tokyo
+ static String[] SQL_JAPANARRAY = new String[] { "2000-01-01", "2010-06-11",
+ "1931-04-21", "1970-01-01", "1970-01-01" };
+
+ static String[][] SQL_TZ_DATEARRAYS = new String[][] { SQL_DATEARRAY,
+ SQL_NYARRAY, SQL_JAPANARRAY };
+
+ // Timezones
+ static String TZ_LONDON = "Europe/London"; // Note: != GMT
+
+ static String TZ_PACIFIC = "America/Los_Angeles"; // GNT - 8
+
+ static String TZ_JAPAN = "Asia/Tokyo"; // GMT + 9
+
+ static String[] TIMEZONES = { TZ_LONDON, TZ_PACIFIC, TZ_JAPAN };
+
+ /*
+ * Helper method to create a long milliseconds time from a supplied date and
+ * time
+ */
+ static private long getTime(int year, int month, int date, int hour,
+ int minute, int second) {
+ aCal.set(year, month, date, hour, minute, second);
+ return aCal.getTimeInMillis();
+ } // end method getTime( int, int, int, int, int, int )
+
+ /*
+ * Test of the Date(int, int, int) constructor - now deprecated but still
+ * functioning
+ */
+ @SuppressWarnings("deprecation")
+ public void testDateintintint() {
+
+ int init1[] = { 99, 8099, 9000, 99999, 99, 99, -1, -100 };
+ int init2[] = { 11, 0, 0, 0, 999, 0, 0, -111 };
+ int init3[] = { 31, 0, 0, 0, 0, 999, 0, -999 };
+
+ for (int i = 0; i < init1.length; i++) {
+ Date theDate = new Date(init1[i], init2[i], init3[i]);
+ assertNotNull(theDate);
+ } // end for
+
+ } // end method testDateintintint
+
+ /*
+ * Test of the Date( long ) constructor
+ */
+ public void testDatelong() {
+
+ long init1[] = { TIME_TESTDATE1, TIME_TESTDATE2, TIME_TESTDATE3,
+ TIME_NEGATIVE, TIME_LOWERLIMIT, TIME_UPPERLIMIT, TIME_EPOCH,
+ TIME_NOW };
+
+ for (long element : init1) {
+ Date theDate = new Date(element);
+ assertNotNull(theDate);
+ } // end for
+
+ } // end method testDatelong
+
+ /*
+ * Test of the (deprecated) int Date.getHours() method - which always throws
+ * an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetHours() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.getHours();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+ } // end method testGetHours()
+
+ /*
+ * Test of the (deprecated) int Date.getMinutes() method - which always
+ * throws an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetMinutes() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.getMinutes();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+ } // end method testGetMinutes()
+
+ /*
+ * Test of the (deprecated) int Date.getSeconds() method - which always
+ * throws an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetSeconds() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.getSeconds();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+ } // end method testGetSeconds()
+
+ /*
+ * Test of the (deprecated) Date.setHours( int ) method - which always
+ * throws an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testSetHours() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.setHours(22);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+ } // end method testSetHours( int )
+
+ /*
+ * Test of the (deprecated) Date.setMinutes( int ) method - which always
+ * throws an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testSetMinutes() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.setMinutes(54);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+
+ } // end method testSetMinutes( int )
+
+ /*
+ * Test of the (deprecated) Date.setSeconds( int ) method - which always
+ * throws an IllegalArgumentException
+ */
+ @SuppressWarnings("deprecation")
+ public void testSetSeconds() {
+ Date theDate = new Date(TIME_TESTDATE1);
+ try {
+ theDate.setSeconds(36);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException ie) {
+ //expected
+ } // end try
+ } // end method testSetSeconds( int )
+
+ /*
+ * Test of the String Date.toString() method This method is sensitive to the
+ * time zone setting and this test sets the time zone before calling the
+ * toString() method.
+ */
+ public void testToString() {
+ // This test is set up for GMT time zone, so need to set the time zone
+ // to GMT first
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Date theDate = new Date(TIME_ARRAY[i]);
+ assertEquals(SQL_DATEARRAY[i], theDate.toString());
+ } // end for
+
+ } // end method testToString()
+
+ /*
+ * Test of the void setTime(int) method This does depend on the Time Zone
+ * settings and sets up the time zone to one of a group of specific time
+ * zones and tests the method using each of these time zones in turn.
+ */
+ public void testSetTimelong() {
+
+ // Loop over the array of test timezones
+ for (int i = 0; i < TIMEZONES.length; i++) {
+ testSetTimelong(TIMEZONES[i], SQL_TZ_DATEARRAYS[i]);
+ } // end for
+
+ } // end method testSetTimelong()
+
+ /*
+ * Internal method for testing Date.setTime with a specific time zone
+ */
+ private void testSetTimelong(String timeZoneName, String[] dateArray) {
+
+ if (timeZoneName != null) {
+ TimeZone.setDefault(TimeZone.getTimeZone(timeZoneName));
+ } // end if
+
+ Date theDate = new Date(TIME_TESTDATE1);
+
+ // Loop over the array of test times & dates
+ for (int i = 0; i < dateArray.length; i++) {
+ theDate.setTime(TIME_ARRAY[i]);
+ assertEquals(dateArray[i], theDate.toString());
+ } // end for
+
+ } // end method testSetTimelong()
+
+ /*
+ * Test of the Date.valueOf( String ) method This test is not dependent on
+ * the default Time Zone setting
+ */
+ public void testValueOf() {
+ String SQL_NOTVALID1 = "ABCDEF"; // Invalid date string
+ String SQL_NOTVALID2 = "12321.43.56"; // Invalid date string
+ String SQL_NOTVALID3 = null; // Invalid date string
+ String[] SQL_INVALIDARRAY = { SQL_NOTVALID1, SQL_NOTVALID2,
+ SQL_NOTVALID3 };
+
+ Date theDate;
+
+ for (String element : SQL_DATEARRAY) {
+ theDate = Date.valueOf(element);
+ assertEquals(element, theDate.toString());
+ } // end for
+
+ for (String element : SQL_INVALIDARRAY) {
+ try {
+ theDate = Date.valueOf(element);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end for
+
+ } // end method testValueOf()
+
+ /**
+ * @tests java.sql.Date#valueOf(String )
+ */
+ public void test_valueOf_IllegalArgumentException() {
+ try{
+ Date.valueOf("1996-10-07-01");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("-10-07-01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("--01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("1991--");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("-01-");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("-10-w2-01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("07-w2-");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("1997-w2-w2");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+
+ try{
+ Date.valueOf("1996--01");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+ }
+
+} // end class DateTest
+
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java
new file mode 100644
index 0000000..73b415b
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverManagerTest.java
@@ -0,0 +1,582 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.lang.reflect.Method;
+import java.security.Permission;
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.SQLPermission;
+import java.util.Enumeration;
+import java.util.Properties;
+
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.DriverManager class
+ *
+ */
+public class DriverManagerTest extends TestCase {
+
+ // Set of driver names to use
+ static final String DRIVER1 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver1";
+
+ static final String DRIVER2 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver2";
+
+ static final String DRIVER3 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
+
+ static final String DRIVER4 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver4";
+
+ static final String DRIVER5 = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver5";
+
+ static final String INVALIDDRIVER1 = "abc.klm.Foo";
+
+ static String[] driverNames = { DRIVER1, DRIVER2 };
+
+ static int numberLoaded;
+
+ static String baseURL1 = "jdbc:mikes1";
+
+ static String baseURL4 = "jdbc:mikes4";
+
+ static final String JDBC_PROPERTY = "jdbc.drivers";
+
+ static TestHelper_ClassLoader testClassLoader = new TestHelper_ClassLoader();
+
+ // Static initializer to load the drivers so that they are available to all
+ // the
+ // test methods as needed.
+ @Override
+ public void setUp() {
+ numberLoaded = loadDrivers();
+ } // end setUp()
+
+ /**
+ * Test for the method DriverManager.deregisterDriver
+ * @throws SQLException
+ */
+ public void testDeregisterDriver() throws SQLException {
+ // First get one of the drivers loaded by the test
+ Driver aDriver;
+ aDriver = DriverManager.getDriver(baseURL4);
+
+ // Deregister this driver
+ DriverManager.deregisterDriver(aDriver);
+
+ assertFalse("testDeregisterDriver: Driver was not deregistered.",
+ isDriverLoaded(aDriver));
+
+ // Re-register this driver (so subsequent tests have it available)
+ DriverManager.registerDriver(aDriver);
+ assertTrue("testDeregisterDriver: Driver did not reload.",
+ isDriverLoaded(aDriver));
+
+ // Test deregistering a null driver
+ DriverManager.deregisterDriver(null);
+
+ // Test deregistering a driver which was not loaded by this test's
+ // classloader
+ // TODO - need to load a driver with a different classloader!!
+ aDriver = DriverManager.getDriver(baseURL1);
+
+ try {
+ Class<?> driverClass = Class.forName(
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_DriverManager", true,
+ testClassLoader);
+
+ // Give the Helper class one of our drivers....
+ Class<?>[] methodClasses = { Class.forName("java.sql.Driver") };
+ Method theMethod = driverClass.getDeclaredMethod("setDriver",
+ methodClasses);
+ Object[] args = { aDriver };
+ theMethod.invoke(null, args);
+ } catch (Exception e) {
+ System.out
+ .println("testDeregisterDriver: Got exception allocating TestHelper");
+ e.printStackTrace();
+ return;
+ } // end try
+
+ // Check that the driver was not deregistered
+ assertTrue(
+ "testDeregisterDriver: Driver was incorrectly deregistered.",
+ DriverManagerTest.isDriverLoaded(aDriver));
+
+ } // end method testDeregisterDriver()
+
+ static void printClassLoader(Object theObject) {
+ Class<? extends Object> theClass = theObject.getClass();
+ ClassLoader theClassLoader = theClass.getClassLoader();
+ System.out.println("ClassLoader is: " + theClassLoader.toString()
+ + " for object: " + theObject.toString());
+ } // end method printClassLoader( Object )
+
+ static boolean isDriverLoaded(Driver theDriver) {
+ Enumeration<?> driverList = DriverManager.getDrivers();
+ while (driverList.hasMoreElements()) {
+ if ((Driver) driverList.nextElement() == theDriver) {
+ return true;
+ }
+ } // end while
+ return false;
+ } // end method isDriverLoaded( Driver )
+
+ /*
+ * Class under test for Connection getConnection(String)
+ */
+ // valid connection - data1 does not require a user and password...
+ static String validConnectionURL = "jdbc:mikes1:data1";
+
+ // invalid connection - data2 requires a user & password
+ static String invalidConnectionURL1 = "jdbc:mikes1:data2";
+
+ // invalid connection - URL is gibberish
+ static String invalidConnectionURL2 = "xyz1:abc3:456q";
+
+ // invalid connection - URL is null
+ static String invalidConnectionURL3 = null;
+
+ static String[] invalidConnectionURLs = { invalidConnectionURL2,
+ invalidConnectionURL3 };
+
+ public void testGetConnectionString() throws SQLException {
+ Connection theConnection = null;
+ // validConnection - no user & password required
+ theConnection = DriverManager.getConnection(validConnectionURL);
+ assertNotNull(theConnection);
+ assertNotNull(DriverManager.getConnection(invalidConnectionURL1));
+
+ for (String element : invalidConnectionURLs) {
+ try {
+ theConnection = DriverManager
+ .getConnection(element);
+ fail("Should throw SQLException");
+ } catch (SQLException e) {
+ //expected
+ } // end try
+ } // end for
+ } // end method testGetConnectionString()
+
+ /**
+ * @tests java.sql.DriverManager#getConnection(String, Properties)
+ */
+ public void test_getConnection_LStringLProperties() {
+ try {
+ DriverManager.getConnection("fff", //$NON-NLS-1$
+ new Properties());
+ fail("Should throw SQLException.");
+ } catch (SQLException e) {
+ assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
+ }
+
+ try {
+ DriverManager.getConnection(null,
+ new Properties());
+ fail("Should throw SQLException.");
+ } catch (SQLException e) {
+ assertEquals("08001", e.getSQLState()); //$NON-NLS-1$
+ }
+ }
+
+ /*
+ * Class under test for Connection getConnection(String, Properties)
+ */
+ public void testGetConnectionStringProperties() throws SQLException {
+ String validURL1 = "jdbc:mikes1:data2";
+ String validuser1 = "theuser";
+ String validpassword1 = "thepassword";
+ String invalidURL1 = "xyz:abc1:foo";
+ String invalidURL2 = "jdbc:mikes1:crazyone";
+ String invalidURL3 = "";
+ String invaliduser1 = "jonny nouser";
+ String invalidpassword1 = "whizz";
+ Properties nullProps = null;
+ Properties validProps = new Properties();
+ validProps.setProperty("user", validuser1);
+ validProps.setProperty("password", validpassword1);
+ Properties invalidProps1 = new Properties();
+ invalidProps1.setProperty("user", invaliduser1);
+ invalidProps1.setProperty("password", invalidpassword1);
+ String[] invalidURLs = { null, invalidURL1,
+ invalidURL2, invalidURL3 };
+ Properties[] invalidProps = { nullProps, invalidProps1};
+
+
+
+ Connection theConnection = null;
+ // validConnection - user & password required
+ theConnection = DriverManager.getConnection(validURL1, validProps);
+ assertNotNull(theConnection);
+
+ // invalid Connections
+ for (int i = 0; i < invalidURLs.length; i++) {
+ theConnection = null;
+ try {
+ theConnection = DriverManager.getConnection(invalidURLs[i],
+ validProps);
+ fail("Should throw SQLException");
+ } catch (SQLException e) {
+ //expected
+ } // end try
+ } // end for
+ for (Properties invalidProp : invalidProps) {
+ assertNotNull(DriverManager.getConnection(validURL1, invalidProp));
+ }
+ } // end method testGetConnectionStringProperties()
+
+ /*
+ * Class under test for Connection getConnection(String, String, String)
+ */
+ public void testGetConnectionStringStringString() throws SQLException {
+ String validURL1 = "jdbc:mikes1:data2";
+ String validuser1 = "theuser";
+ String validpassword1 = "thepassword";
+ String invalidURL1 = "xyz:abc1:foo";
+ String invaliduser1 = "jonny nouser";
+ String invalidpassword1 = "whizz";
+ String[] invalid1 = { null, validuser1, validpassword1 };
+ String[] invalid2 = { validURL1, null, validpassword1 };
+ String[] invalid3 = { validURL1, validuser1, null };
+ String[] invalid4 = { invalidURL1, validuser1, validpassword1 };
+ String[] invalid5 = { validURL1, invaliduser1, invalidpassword1 };
+ String[] invalid6 = { validURL1, validuser1, invalidpassword1 };
+ String[][] invalids1 = { invalid1, invalid4};
+ String[][] invalids2 = {invalid2, invalid3, invalid5, invalid6 };
+
+ Connection theConnection = null;
+ // validConnection - user & password required
+ theConnection = DriverManager.getConnection(validURL1, validuser1,
+ validpassword1);
+ assertNotNull(theConnection);
+ for (String[] theData : invalids1) {
+ theConnection = null;
+ try {
+ theConnection = DriverManager.getConnection(theData[0],
+ theData[1], theData[2]);
+ fail("Should throw SQLException.");
+ } catch (SQLException e) {
+ //expected
+ } // end try
+ } // end for
+ for (String[] theData : invalids2) {
+ assertNotNull(DriverManager.getConnection(theData[0], theData[1],
+ theData[2]));
+ }
+ } // end method testGetConnectionStringStringString()
+
+ static String validURL1 = "jdbc:mikes1";
+
+ static String validURL2 = "jdbc:mikes2";
+
+ static String invalidURL1 = "xyz:acb";
+
+ static String invalidURL2 = null;
+
+ static String[] validURLs = { validURL1, validURL2 };
+
+ static String[] invalidURLs = { invalidURL1, invalidURL2 };
+
+ static String exceptionMsg1 = "No suitable driver";
+
+ public void testGetDriver() throws SQLException {
+ for (String element : validURLs) {
+ Driver validDriver = DriverManager.getDriver(element);
+ assertNotNull(validDriver);
+ } // end for
+
+ for (String element : invalidURLs) {
+ try {
+ DriverManager.getDriver(element);
+ fail("Should throw SQLException");
+ } catch (SQLException e) {
+ assertEquals("08001", e.getSQLState());
+ assertEquals(exceptionMsg1, e.getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetDriver()
+
+ public void testGetDrivers() {
+ // Load a driver manager
+ Enumeration<Driver> driverList = DriverManager.getDrivers();
+ int i = 0;
+ while (driverList.hasMoreElements()) {
+ Driver theDriver = driverList.nextElement();
+ assertNotNull(theDriver);
+ i++;
+ } // end while
+
+ // Check that all the drivers are in the list...
+ assertEquals("testGetDrivers: Don't see all the loaded drivers - ", i,
+ numberLoaded);
+ } // end method testGetDrivers()
+
+ static int timeout1 = 25;
+
+ public void testGetLoginTimeout() {
+ DriverManager.setLoginTimeout(timeout1);
+ assertEquals(timeout1, DriverManager.getLoginTimeout());
+ } // end method testGetLoginTimeout()
+
+ @SuppressWarnings("deprecation")
+ public void testGetLogStream() {
+ assertNull(DriverManager.getLogStream());
+
+ DriverManager.setLogStream(testPrintStream);
+ assertTrue(DriverManager.getLogStream() == testPrintStream);
+
+ DriverManager.setLogStream(null);
+ } // end method testGetLogStream()
+
+ public void testGetLogWriter() {
+ assertNull(DriverManager.getLogWriter());
+
+ DriverManager.setLogWriter(testPrintWriter);
+
+ assertTrue(DriverManager.getLogWriter() == testPrintWriter);
+
+ DriverManager.setLogWriter(null);
+ } // end method testGetLogWriter()
+
+ static String testMessage = "DriverManagerTest: test message for print stream";
+
+ @SuppressWarnings("deprecation")
+ public void testPrintln() {
+ // System.out.println("testPrintln");
+ DriverManager.println(testMessage);
+
+ DriverManager.setLogWriter(testPrintWriter);
+ DriverManager.println(testMessage);
+
+ String theOutput = outputStream.toString();
+ // System.out.println("testPrintln: output= " + theOutput );
+ assertTrue(theOutput.startsWith(testMessage));
+
+ DriverManager.setLogWriter(null);
+
+ DriverManager.setLogStream(testPrintStream);
+ DriverManager.println(testMessage);
+
+ theOutput = outputStream2.toString();
+ // System.out.println("testPrintln: output= " + theOutput );
+ assertTrue(theOutput.startsWith(testMessage));
+
+ DriverManager.setLogStream(null);
+ } // end method testPrintln()
+
+ public void testRegisterDriver() throws ClassNotFoundException,
+ SQLException, IllegalAccessException, InstantiationException {
+ String EXTRA_DRIVER_NAME = "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver3";
+
+ try {
+ DriverManager.registerDriver(null);
+ fail("Should throw NullPointerException.");
+ } catch (NullPointerException e) {
+ // expected
+ } // end try
+
+ Driver theDriver = null;
+ // Load another Driver that isn't in the basic set
+ Class<?> driverClass = Class.forName(EXTRA_DRIVER_NAME);
+ theDriver = (Driver) driverClass.newInstance();
+ DriverManager.registerDriver(theDriver);
+
+ assertTrue("testRegisterDriver: driver not in loaded set",
+ isDriverLoaded(theDriver));
+
+ } // end testRegisterDriver()
+
+ static int validTimeout1 = 15;
+
+ static int validTimeout2 = 0;
+
+ static int[] validTimeouts = { validTimeout1, validTimeout2 };
+
+ static int invalidTimeout1 = -10;
+
+ public void testSetLoginTimeout() {
+ for (int element : validTimeouts) {
+ DriverManager.setLoginTimeout(element);
+
+ assertEquals(element, DriverManager.getLoginTimeout());
+ } // end for
+ // Invalid timeouts
+ DriverManager.setLoginTimeout(invalidTimeout1);
+ assertEquals(invalidTimeout1, DriverManager.getLoginTimeout());
+ } // end testSetLoginTimeout()
+
+ static ByteArrayOutputStream outputStream2 = new ByteArrayOutputStream();
+
+ static PrintStream testPrintStream = new PrintStream(outputStream2);
+
+ @SuppressWarnings("deprecation")
+ public void testSetLogStream() {
+ // System.out.println("testSetLogStream");
+ DriverManager.setLogStream(testPrintStream);
+
+ assertSame(testPrintStream, DriverManager.getLogStream());
+
+ DriverManager.setLogStream(null);
+
+ assertNull(DriverManager.getLogStream());
+
+ // Now let's deal with the case where there is a SecurityManager in
+ // place
+ TestSecurityManager theSecManager = new TestSecurityManager();
+ System.setSecurityManager(theSecManager);
+
+ theSecManager.setLogAccess(false);
+
+ try {
+ DriverManager.setLogStream(testPrintStream);
+ fail("Should throw SecurityException.");
+ } catch (SecurityException s) {
+ //expected
+ }
+
+ theSecManager.setLogAccess(true);
+
+ DriverManager.setLogStream(testPrintStream);
+
+ System.setSecurityManager(null);
+ } // end method testSetLogStream()
+
+ static ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
+
+ static PrintWriter testPrintWriter = new PrintWriter(outputStream);
+
+ /**
+ * Test for the setLogWriter method
+ */
+ public void testSetLogWriter() {
+ // System.out.println("testSetLogWriter");
+ DriverManager.setLogWriter(testPrintWriter);
+
+ assertSame(testPrintWriter, DriverManager.getLogWriter());
+
+ DriverManager.setLogWriter(null);
+
+ assertNull("testDriverManager: Log writer not null:", DriverManager
+ .getLogWriter());
+
+ // Now let's deal with the case where there is a SecurityManager in
+ // place
+ TestSecurityManager theSecManager = new TestSecurityManager();
+ System.setSecurityManager(theSecManager);
+
+ theSecManager.setLogAccess(false);
+
+ try {
+ DriverManager.setLogWriter(testPrintWriter);
+ fail("Should throw SecurityException.");
+ } catch (SecurityException s) {
+ //expected
+ }
+
+ theSecManager.setLogAccess(true);
+ DriverManager.setLogWriter(testPrintWriter);
+
+ System.setSecurityManager(null);
+ } // end method testSetLogWriter()
+
+ /*
+ * Method which loads a set of JDBC drivers ready for use by the various
+ * tests @return the number of drivers loaded
+ */
+ static boolean driversLoaded = false;
+
+ private static int loadDrivers() {
+ if (driversLoaded) {
+ return numberLoaded;
+ }
+ /*
+ * First define a value for the System property "jdbc.drivers" - before
+ * the DriverManager class is loaded - this property defines a set of
+ * drivers which the DriverManager will load during its initialization
+ * and which will be loaded on the System ClassLoader - unlike the ones
+ * loaded later by this method which are loaded on the Application
+ * ClassLoader.
+ */
+ int numberLoaded = 0;
+ String theSystemDrivers = DRIVER4 + ":" + DRIVER5 + ":"
+ + INVALIDDRIVER1;
+ System.setProperty(JDBC_PROPERTY, theSystemDrivers);
+ numberLoaded += 2;
+
+ for (String element : driverNames) {
+ try {
+ Class<?> driverClass = Class.forName(element);
+ assertNotNull(driverClass);
+ // System.out.println("Loaded driver - classloader = " +
+ // driverClass.getClassLoader());
+ numberLoaded++;
+ } catch (ClassNotFoundException e) {
+ System.out.println("DriverManagerTest: failed to load Driver: "
+ + element);
+ } // end try
+ } // end for
+ /*
+ * System.out.println("DriverManagerTest: number of drivers loaded: " +
+ * numberLoaded);
+ */
+ driversLoaded = true;
+ return numberLoaded;
+ } // end method loadDrivers()
+
+ class TestSecurityManager extends SecurityManager {
+
+ boolean logAccess = true;
+
+ SQLPermission sqlPermission = new SQLPermission("setLog");
+
+ RuntimePermission setManagerPermission = new RuntimePermission(
+ "setSecurityManager");
+
+ TestSecurityManager() {
+ super();
+ } // end method TestSecurityManager()
+
+ void setLogAccess(boolean allow) {
+ logAccess = allow;
+ } // end method setLogAccess( boolean )
+
+ @Override
+ public void checkPermission(Permission thePermission) {
+ if (thePermission.equals(sqlPermission)) {
+ if (!logAccess) {
+ throw new SecurityException("Cannot set the sql Log Writer");
+ } // end if
+ return;
+ } // end if
+
+ if (thePermission.equals(setManagerPermission)) {
+ return;
+ } // end if
+ // super.checkPermission( thePermission );
+ } // end method checkPermission( Permission )
+
+ } // end class TestSecurityManager
+
+} // end class DriverManagerTest
+
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverPropertyInfoTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverPropertyInfoTest.java
new file mode 100644
index 0000000..ec38988
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/DriverPropertyInfoTest.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.DriverPropertyInfo;
+import java.util.Arrays;
+
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.DriverPropertyInfo class
+ *
+ */
+
+public class DriverPropertyInfoTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ } // end method testPublicStatics
+
+ /*
+ * Constructor test
+ */
+ public void testDriverPropertyInfoStringString() {
+
+ DriverPropertyInfo aDriverPropertyInfo = new DriverPropertyInfo(
+ validName, validValue);
+
+ assertNotNull(aDriverPropertyInfo);
+
+ aDriverPropertyInfo = new DriverPropertyInfo(null, null);
+
+ } // end method testDriverPropertyInfoStringString
+
+ /*
+ * Public fields test
+ */
+ static String validName = "testname";
+
+ static String validValue = "testvalue";
+
+ static String[] updateChoices = { "Choice1", "Choice2", "Choice3" };
+
+ static String updateValue = "updateValue";
+
+ static boolean updateRequired = true;
+
+ static String updateDescription = "update description";
+
+ static String updateName = "updateName";
+
+ public void testPublicFields() {
+
+ // Constructor here...
+ DriverPropertyInfo aDriverPropertyInfo = new DriverPropertyInfo(
+ validName, validValue);
+
+ assertTrue(Arrays.equals(testChoices, aDriverPropertyInfo.choices));
+ assertEquals(testValue, aDriverPropertyInfo.value);
+ assertEquals(testRequired, aDriverPropertyInfo.required);
+ assertEquals(testDescription, aDriverPropertyInfo.description);
+ assertEquals(testName, aDriverPropertyInfo.name);
+
+ aDriverPropertyInfo.choices = updateChoices;
+ aDriverPropertyInfo.value = updateValue;
+ aDriverPropertyInfo.required = updateRequired;
+ aDriverPropertyInfo.description = updateDescription;
+ aDriverPropertyInfo.name = updateName;
+
+ assertTrue(Arrays.equals(updateChoices, aDriverPropertyInfo.choices));
+ assertEquals(updateValue, aDriverPropertyInfo.value);
+ assertEquals(updateRequired, aDriverPropertyInfo.required);
+ assertEquals(updateDescription, aDriverPropertyInfo.description);
+ assertEquals(updateName, aDriverPropertyInfo.name);
+
+ } // end method testPublicFields
+
+ // Default values...
+ static String[] testChoices = null;
+
+ static java.lang.String testValue = validValue;
+
+ static boolean testRequired = false;
+
+ static java.lang.String testDescription = null;
+
+ static java.lang.String testName = validName;
+
+} // end class DriverPropertyInfoTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ParameterMetaDataTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ParameterMetaDataTest.java
new file mode 100644
index 0000000..d3e000d
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ParameterMetaDataTest.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class ParameterMetaDataTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("parameterModeOut", new Integer(4));
+ thePublicStatics.put("parameterModeInOut", new Integer(2));
+ thePublicStatics.put("parameterModeIn", new Integer(1));
+ thePublicStatics.put("parameterModeUnknown", new Integer(0));
+ thePublicStatics.put("parameterNullableUnknown", new Integer(2));
+ thePublicStatics.put("parameterNullable", new Integer(1));
+ thePublicStatics.put("parameterNoNulls", new Integer(0));
+
+ /*
+ * System.out.println( "parameterModeOut: " +
+ * ParameterMetaData.parameterModeOut ); System.out.println(
+ * "parameterModeInOut: " + ParameterMetaData.parameterModeInOut );
+ * System.out.println( "parameterModeIn: " +
+ * ParameterMetaData.parameterModeIn ); System.out.println(
+ * "parameterModeUnknown: " + ParameterMetaData.parameterModeUnknown );
+ * System.out.println( "parameterNullableUnknown: " +
+ * ParameterMetaData.parameterNullableUnknown ); System.out.println(
+ * "parameterNullable: " + ParameterMetaData.parameterNullable );
+ * System.out.println( "parameterNoNulls: " +
+ * ParameterMetaData.parameterNoNulls );
+ */
+
+ Class<?> parameterMetaDataClass;
+ try {
+ parameterMetaDataClass = Class
+ .forName("java.sql.ParameterMetaData");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.ParameterMetaData class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = parameterMetaDataClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class ParameterMetaDataTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetMetaDataTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetMetaDataTest.java
new file mode 100644
index 0000000..07a25c2
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetMetaDataTest.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class ResultSetMetaDataTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("columnNullableUnknown", new Integer(2));
+ thePublicStatics.put("columnNullable", new Integer(1));
+ thePublicStatics.put("columnNoNulls", new Integer(0));
+
+ /*
+ * System.out.println( "columnNullableUnknown: " +
+ * ResultSetMetaData.columnNullableUnknown ); System.out.println(
+ * "columnNullable: " + ResultSetMetaData.columnNullable );
+ * System.out.println( "columnNoNulls: " +
+ * ResultSetMetaData.columnNoNulls );
+ */
+
+ Class<?> resultSetMetaDataClass;
+ try {
+ resultSetMetaDataClass = Class
+ .forName("java.sql.ResultSetMetaData");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.ResultSetMetaData class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = resultSetMetaDataClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class ResultSetMetaDataTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetTest.java
new file mode 100644
index 0000000..26e61fe
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/ResultSetTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class ResultSetTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("CLOSE_CURSORS_AT_COMMIT",
+ new java.lang.Integer(2));
+ thePublicStatics.put("HOLD_CURSORS_OVER_COMMIT", new java.lang.Integer(
+ 1));
+ thePublicStatics.put("CONCUR_UPDATABLE", new java.lang.Integer(1008));
+ thePublicStatics.put("CONCUR_READ_ONLY", new java.lang.Integer(1007));
+ thePublicStatics.put("TYPE_SCROLL_SENSITIVE", new java.lang.Integer(
+ 1005));
+ thePublicStatics.put("TYPE_SCROLL_INSENSITIVE", new java.lang.Integer(
+ 1004));
+ thePublicStatics.put("TYPE_FORWARD_ONLY", new java.lang.Integer(1003));
+ thePublicStatics.put("FETCH_UNKNOWN", new java.lang.Integer(1002));
+ thePublicStatics.put("FETCH_REVERSE", new java.lang.Integer(1001));
+ thePublicStatics.put("FETCH_FORWARD", new java.lang.Integer(1000));
+
+ /*
+ * System.out.println( "CLOSE_CURSORS_AT_COMMIT: " +
+ * ResultSet.CLOSE_CURSORS_AT_COMMIT ); System.out.println(
+ * "HOLD_CURSORS_OVER_COMMIT: " + ResultSet.HOLD_CURSORS_OVER_COMMIT );
+ * System.out.println( "CONCUR_UPDATABLE: " + ResultSet.CONCUR_UPDATABLE );
+ * System.out.println( "CONCUR_READ_ONLY: " + ResultSet.CONCUR_READ_ONLY );
+ * System.out.println( "TYPE_SCROLL_SENSITIVE: " +
+ * ResultSet.TYPE_SCROLL_SENSITIVE ); System.out.println(
+ * "TYPE_SCROLL_INSENSITIVE: " + ResultSet.TYPE_SCROLL_INSENSITIVE );
+ * System.out.println( "TYPE_FORWARD_ONLY: " +
+ * ResultSet.TYPE_FORWARD_ONLY ); System.out.println( "FETCH_UNKNOWN: " +
+ * ResultSet.FETCH_UNKNOWN ); System.out.println( "FETCH_REVERSE: " +
+ * ResultSet.FETCH_REVERSE ); System.out.println( "FETCH_FORWARD: " +
+ * ResultSet.FETCH_FORWARD );
+ */
+
+ Class<?> resultSetClass;
+ try {
+ resultSetClass = Class.forName("java.sql.ResultSet");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.ResultSet class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = resultSetClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class ResultSetTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.java
new file mode 100644
index 0000000..bb73343
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.java
@@ -0,0 +1,541 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.Serializable;
+import java.lang.reflect.Field;
+import java.sql.SQLException;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+import junit.framework.Assert;
+import junit.framework.TestCase;
+
+public class SQLExceptionTest extends TestCase {
+
+ static long theFixedSUID = 2135244094396331484L;
+
+ /*
+ * SUID test
+ */
+ public void testSUID() {
+
+ try {
+ Class<?> theClass = Class.forName("java.sql.SQLException");
+ Field theField = theClass.getDeclaredField("serialVersionUID");
+ theField.setAccessible(true);
+ long theSUID = theField.getLong(null);
+ assertEquals("SUID mismatch: ", theFixedSUID, theSUID);
+ } catch (Exception e) {
+ System.out.println("SUID check got exception: " + e.getMessage());
+ // assertTrue("Exception while testing SUID ", false );
+ } // end catch
+
+ } // end method testSUID
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLExceptionStringStringint() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", "1", "a",
+ null, "", "\u0000", "a", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "a",
+ "&valid*", "a", "a", "a", null, "", "\u0000" };
+ int[] init3 = { -2147483648, 2147483647, 0, 48429456, 1770127344,
+ 1047282235, -545472907, -2147483648, -2147483648, -2147483648,
+ -2147483648, -2147483648, -2147483648 };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLException[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null, null, null, null, null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null, null, null };
+
+ SQLException aSQLException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i], init3[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLExceptionStringStringint
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLExceptionStringString() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null, "",
+ "\u0000", "a", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "a", "a",
+ "a", null, "", "\u0000" };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0 };
+ SQLException[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null, null, null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null };
+
+ SQLException aSQLException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLExceptionStringString
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLExceptionString() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null,
+ "", "\u0000" };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = { null, null, null, null, null, null, null,
+ null };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0,
+ 0, 0, 0 };
+ SQLException[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null };
+
+ SQLException aSQLException;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLExceptionString
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLException() {
+
+ String[] theFinalStates1 = { null };
+ String[] theFinalStates2 = { null };
+ int[] theFinalStates3 = { 0 };
+ SQLException[] theFinalStates4 = { null };
+
+ Exception[] theExceptions = { null };
+
+ SQLException aSQLException;
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException();
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLException
+
+ /*
+ * Method test for getErrorCode
+ */
+ public void testGetErrorCode() {
+
+ SQLException aSQLException;
+ String[] init1 = { "a", "1", "valid1", "----", null, "&valid*", "1" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", null, "a" };
+ int[] init3 = { -2147483648, 2147483647, 0, 48429456, 1770127344,
+ 1047282235, -545472907 };
+
+ int theReturn;
+ int[] theReturns = init3;
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLException[] theFinalStates4 = { null, null, null, null, null, null,
+ null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i], init3[i]);
+ theReturn = aSQLException.getErrorCode();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetErrorCode
+
+ /*
+ * Method test for getNextException
+ */
+ public void testGetNextException() {
+
+ SQLException aSQLException;
+ String[] init1 = { "a", "1", "valid1", "----", null, "&valid*", "1" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", null, "a" };
+ int[] init3 = { -2147483648, 2147483647, 0, 48429456, 1770127344,
+ 1047282235, -545472907 };
+ SQLException[] init4 = { new SQLException(), null, new SQLException(),
+ new SQLException(), new SQLException(), null,
+ new SQLException() };
+
+ SQLException theReturn;
+ SQLException[] theReturns = init4;
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLException[] theFinalStates4 = init4;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i], init3[i]);
+ aSQLException.setNextException(init4[i]);
+ theReturn = aSQLException.getNextException();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetNextException
+
+ /*
+ * Method test for getSQLState
+ */
+ public void testGetSQLState() {
+
+ SQLException aSQLException;
+ String[] init1 = { "a", "1", "valid1", "----", null, "&valid*", "1" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", null, "a" };
+ int[] init3 = { -2147483648, 2147483647, 0, 48429456, 1770127344,
+ 1047282235, -545472907 };
+
+ String theReturn;
+ String[] theReturns = init2;
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLException[] theFinalStates4 = { null, null, null, null, null, null,
+ null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i], init3[i]);
+ theReturn = aSQLException.getSQLState();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetSQLState
+
+ /*
+ * Method test for setNextException
+ */
+ public void testSetNextExceptionSQLException() {
+
+ SQLException[] parm1 = { new SQLException(), null, new SQLException(),
+ new SQLException(), new SQLException(), null,
+ new SQLException() };
+
+ SQLException aSQLException;
+
+ String[] init1 = { "a", "1", "valid1", "----", null, "&valid*", "1" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", null, "a" };
+ int[] init3 = { -2147483648, 2147483647, 0, 48429456, 1770127344,
+ 1047282235, -545472907 };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLException[] theFinalStates4 = parm1;
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null };
+
+ int loopCount = parm1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLException = new SQLException(init1[i], init2[i], init3[i]);
+ aSQLException.setNextException(parm1[i]);
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLException
+ .getNextException(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSetNextExceptionSQLException
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ SQLException object = new SQLException();
+ SerializationTest.verifySelf(object, SQLEXCEPTION_COMPARATOR);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+
+ SQLException nextSQLException = new SQLException("nextReason",
+ "nextSQLState", 33);
+
+ int vendorCode = 10;
+ SQLException object = new SQLException("reason", "SQLState", vendorCode);
+
+ object.setNextException(nextSQLException);
+
+ SerializationTest.verifyGolden(this, object, SQLEXCEPTION_COMPARATOR);
+ }
+
+ // comparator for SQLException objects
+ private static final SerializableAssert SQLEXCEPTION_COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ // do common checks for all throwable objects
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ SQLException initThr = (SQLException) initial;
+ SQLException dserThr = (SQLException) deserialized;
+
+ // verify SQLState
+ Assert.assertEquals("SQLState", initThr.getSQLState(), dserThr
+ .getSQLState());
+
+ // verify vendorCode
+ Assert.assertEquals("vendorCode", initThr.getErrorCode(), dserThr
+ .getErrorCode());
+
+ // verify next
+ if (initThr.getNextException() == null) {
+ assertNull(dserThr.getNextException());
+ } else {
+ // use the same comparator
+ SQLEXCEPTION_COMPARATOR.assertDeserialized(initThr
+ .getNextException(), dserThr.getNextException());
+ }
+ }
+ };
+
+ /**
+ * @tests java.sql.SQLException#setNextException(java.sql.SQLException)
+ */
+ public void test_setNextException_LSQLException() {
+ SQLException se1 = new SQLException("reason" , "SQLState" , 1);
+ SQLException se2 = new SQLException("reason" , "SQLState" , 2);
+ SQLException se3 = new SQLException("reason" , "SQLState" , 3);
+ SQLException se4 = new SQLException("reason" , "SQLState" , 4);
+
+ se1.setNextException(se2);
+ assertSame(se2, se1.getNextException());
+
+ se1.setNextException(se3);
+ assertSame(se2, se1.getNextException());
+ assertSame(se3, se2.getNextException());
+ assertNull(se3.getNextException());
+
+ se3.setNextException(null);
+ assertNull(se3.getNextException());
+
+ se3.setNextException(se4);
+ assertSame(se4, se3.getNextException());
+ }
+
+} // end class SQLExceptionTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLPermissionTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLPermissionTest.java
new file mode 100644
index 0000000..0cf1d45
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLPermissionTest.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.SQLPermission;
+
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.SQLPermission class
+ *
+ * Note that the SQLPermission class only defines 2 constructors and all other
+ * methods are inherited. This testcase explicitly tets the constructors but also
+ * implicitly tests some of the inherited query methods.
+ *
+ */
+
+public class SQLPermissionTest extends TestCase {
+
+ /*
+ * Constructor test
+ */
+ public void testSQLPermissionStringString() {
+ String validName = "setLog";
+ String validActions = "theActions";
+
+ SQLPermission thePermission = new SQLPermission(validName, validActions);
+
+ assertNotNull(thePermission);
+ assertEquals(validName, thePermission.getName());
+ // System.out.println("The actions: " + thePermission.getActions() + "."
+ // );
+ assertEquals("", thePermission.getActions());
+ } // end method testSQLPermissionStringString
+
+ /*
+ * Constructor test
+ */
+ public void testSQLPermissionString() {
+ String validName = "setLog";
+
+ SQLPermission thePermission = new SQLPermission(validName);
+
+ assertNotNull(thePermission);
+ assertEquals(validName, thePermission.getName());
+
+ // Set an invalid name ...
+ String invalidName = "foo";
+
+ thePermission = new SQLPermission(invalidName);
+
+ assertNotNull(thePermission);
+ assertEquals(invalidName, thePermission.getName());
+ assertEquals("", thePermission.getActions());
+ } // end method testSQLPermissionString
+
+} // end class SQLPermissionTest
+
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.java
new file mode 100644
index 0000000..d0998ce
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.java
@@ -0,0 +1,398 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.Serializable;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import org.apache.harmony.testframework.serialization.SerializationTest.SerializableAssert;
+
+import junit.framework.TestCase;
+
+public class SQLWarningTest extends TestCase {
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLWarning() {
+
+ String[] theFinalStates1 = { null };
+ String[] theFinalStates2 = { null };
+ int[] theFinalStates3 = { 0 };
+ SQLWarning[] theFinalStates4 = { null };
+
+ Exception[] theExceptions = { null };
+
+ SQLWarning aSQLWarning;
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning();
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLWarning
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLWarningString() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null,
+ "", "\u0000" };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = { null, null, null, null, null, null, null,
+ null };
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0, 0 };
+ SQLWarning[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null };
+
+ SQLWarning aSQLWarning;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning(init1[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLWarningString
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLWarningStringString() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", null, "",
+ "\u0000", "a", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "a", "a",
+ "a", null, "", "\u0000" };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
+ SQLWarning[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null, null, null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null };
+
+ SQLWarning aSQLWarning;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning(init1[i], init2[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLWarningStringString
+
+ /*
+ * ConstructorTest
+ */
+ public void testSQLWarningStringStringint() {
+
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*", "----",
+ "----", null, "", "\u0000", "a", "a", "a" };
+ String[] init2 = { "a", "1", "valid1", "----", "&valid*", "valid1",
+ "----", "a", "a", "a", null, "", "\u0000" };
+ int[] init3 = { -2147483648, 2147483647, 0, 1412862821, -733923487,
+ 488067774, -1529953616, -2147483648, -2147483648, -2147483648,
+ -2147483648, -2147483648, -2147483648 };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = init2;
+ int[] theFinalStates3 = init3;
+ SQLWarning[] theFinalStates4 = { null, null, null, null, null, null,
+ null, null, null, null, null, null, null };
+
+ Exception[] theExceptions = { null, null, null, null, null, null, null,
+ null, null, null, null, null, null };
+
+ SQLWarning aSQLWarning;
+ int loopCount = init1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning(init1[i], init2[i], init3[i]);
+ if (theExceptions[i] != null) {
+ fail();
+ }
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSQLWarningStringStringint
+
+ /*
+ * Method test for getNextWarning
+ */
+ public void testGetNextWarning() {
+
+ SQLWarning aSQLWarning;
+ String[] init1 = { "a", "1", "valid1", "----", "&valid*" };
+
+ SQLWarning theReturn;
+ SQLWarning[] theReturns = { null };
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = { null };
+ int[] theFinalStates3 = { 0 };
+ SQLWarning[] theFinalStates4 = { null };
+
+ Exception[] theExceptions = { null };
+
+ int loopCount = 1;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning(init1[i]);
+ theReturn = aSQLWarning.getNextWarning();
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + "Return value mismatch", theReturn,
+ theReturns[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testGetNextWarning
+
+ /*
+ * Method test for setNextWarning
+ */
+ public void testSetNextWarningSQLWarning() {
+
+ SQLWarning[] parm1 = { new SQLWarning(), null };
+
+ SQLWarning aSQLWarning;
+ String[] init1 = { "a", "1" };
+
+ String[] theFinalStates1 = init1;
+ String[] theFinalStates2 = { null, null };
+ int[] theFinalStates3 = { 0, 0 };
+ SQLWarning[] theFinalStates4 = parm1;
+
+ Exception[] theExceptions = { null, null };
+
+ int loopCount = parm1.length;
+ for (int i = 0; i < loopCount; i++) {
+ try {
+ aSQLWarning = new SQLWarning(init1[i]);
+ aSQLWarning.setNextWarning(parm1[i]);
+ if (theExceptions[i] != null) {
+ fail(i + "Exception missed");
+ }
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getMessage(), theFinalStates1[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getSQLState(), theFinalStates2[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getErrorCode(), theFinalStates3[i]);
+ assertEquals(i + " Final state mismatch", aSQLWarning
+ .getNextWarning(), theFinalStates4[i]);
+
+ } catch (Exception e) {
+ if (theExceptions[i] == null) {
+ fail(i + "Unexpected exception");
+ }
+ assertEquals(i + "Exception mismatch", e.getClass(),
+ theExceptions[i].getClass());
+ assertEquals(i + "Exception mismatch", e.getMessage(),
+ theExceptions[i].getMessage());
+ } // end try
+ } // end for
+
+ } // end method testSetNextWarningSQLWarning
+
+ /**
+ * @tests java.sql.SQLWarning#setNextWarning(java.sql.SQLWarning)
+ */
+ public void test_setNextWarning_SQLWarning() {
+ SQLWarning sw = new SQLWarning("reason", "SQLState", 0);
+ SQLWarning sw1 = new SQLWarning("reason", "SQLState", 1);
+ SQLWarning sw2 = new SQLWarning("reason", "SQLState", 2);
+ SQLWarning sw3 = new SQLWarning("reason", "SQLState", 3);
+
+ SQLException se = new SQLException("reason", "SQLState", 4);
+
+ sw.setNextWarning(sw1);
+ assertSame(sw1, sw.getNextException());
+ assertSame(sw1, sw.getNextWarning());
+
+
+ sw.setNextWarning(sw2);
+ assertSame(sw2, sw1.getNextException());
+ assertSame(sw2, sw1.getNextWarning());
+
+ sw.setNextException(sw3);
+ assertSame(sw3, sw2.getNextException());
+ assertSame(sw3, sw2.getNextWarning());
+
+ sw.setNextException(se);
+ assertSame(se, sw3.getNextException());
+ try {
+ sw3.getNextWarning();
+ fail("should throw Error");
+ } catch (Error e) {
+ //expected
+ }
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ SQLWarning object = new SQLWarning();
+ SerializationTest.verifySelf(object, SQLWARNING_COMPARATOR);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ SQLWarning object = new SQLWarning();
+
+ SQLWarning nextSQLWarning = new SQLWarning("nextReason",
+ "nextSQLState", 10);
+
+ object.setNextWarning(nextSQLWarning);
+
+ SerializationTest.verifyGolden(this, object, SQLWARNING_COMPARATOR);
+ }
+
+ // comparator for SQLWarning objects
+ private static final SerializableAssert SQLWARNING_COMPARATOR = new SerializableAssert() {
+ public void assertDeserialized(Serializable initial,
+ Serializable deserialized) {
+
+ // do common checks for all throwable objects
+ SerializationTest.THROWABLE_COMPARATOR.assertDeserialized(initial,
+ deserialized);
+
+ SQLWarning initThr = (SQLWarning) initial;
+ SQLWarning dserThr = (SQLWarning) deserialized;
+
+ // verify getNextWarning() method
+ if (initThr.getNextWarning() == null) {
+ assertNull(dserThr.getNextWarning());
+ } else {
+ // use the same comparator
+ SQLWARNING_COMPARATOR.assertDeserialized(initThr
+ .getNextWarning(), dserThr.getNextWarning());
+ }
+ }
+ };
+
+} // end class SQLWarningTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/StatementTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/StatementTest.java
new file mode 100644
index 0000000..d0febeb
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/StatementTest.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class StatementTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("NO_GENERATED_KEYS", new Integer(2));
+ thePublicStatics.put("RETURN_GENERATED_KEYS", new Integer(1));
+ thePublicStatics.put("EXECUTE_FAILED", new Integer(-3));
+ thePublicStatics.put("SUCCESS_NO_INFO", new Integer(-2));
+ thePublicStatics.put("CLOSE_ALL_RESULTS", new Integer(3));
+ thePublicStatics.put("KEEP_CURRENT_RESULT", new Integer(2));
+ thePublicStatics.put("CLOSE_CURRENT_RESULT", new Integer(1));
+
+ /*
+ * System.out.println( "NO_GENERATED_KEYS: " +
+ * Statement.NO_GENERATED_KEYS ); System.out.println(
+ * "RETURN_GENERATED_KEYS: " + Statement.RETURN_GENERATED_KEYS );
+ * System.out.println( "EXECUTE_FAILED: " + Statement.EXECUTE_FAILED );
+ * System.out.println( "SUCCESS_NO_INFO: " + Statement.SUCCESS_NO_INFO );
+ * System.out.println( "CLOSE_ALL_RESULTS: " +
+ * Statement.CLOSE_ALL_RESULTS ); System.out.println(
+ * "KEEP_CURRENT_RESULT: " + Statement.KEEP_CURRENT_RESULT );
+ * System.out.println( "CLOSE_CURRENT_RESULT: " +
+ * Statement.CLOSE_CURRENT_RESULT );
+ */
+
+ Class<?> statementClass;
+ try {
+ statementClass = Class.forName("java.sql.Statement");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.Statement class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = statementClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class StatementTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_ClassLoader.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_ClassLoader.java
new file mode 100644
index 0000000..940a3aa
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_ClassLoader.java
@@ -0,0 +1,219 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+public class TestHelper_ClassLoader extends ClassLoader {
+
+ public TestHelper_ClassLoader() {
+ super(null);
+ }
+
+ /**
+ * Loads a class specified by its name
+ * <p>
+ * This classloader makes the assumption that any class it is asked to load
+ * is in the current directory....
+ */
+ @Override
+ public Class<?> findClass(String className) throws ClassNotFoundException {
+ Class<?> theClass = null;
+
+ if (!className.equals("org.apache.harmony.sql.tests.java.sql.TestHelper_DriverManager")) {
+ return null;
+ }
+
+ String classNameAsFile = className.replace('.', '/') + ".class";
+ // System.out.println("findClass - class filename = " + classNameAsFile
+ // );
+
+ String classPath = System.getProperty("java.class.path");
+ // System.out.println("Test class loader - classpath = " + classPath );
+
+ String theSeparator = String.valueOf(File.pathSeparatorChar);
+ String[] theClassPaths = classPath.split(theSeparator);
+ for (int i = 0; (i < theClassPaths.length) && (theClass == null); i++) {
+ // Ignore jar files...
+ if (theClassPaths[i].endsWith(".jar")) {
+ theClass = loadClassFromJar(theClassPaths[i], className,
+ classNameAsFile);
+ } else {
+ theClass = loadClassFromFile(theClassPaths[i], className,
+ classNameAsFile);
+ } // end if
+ } // end for
+
+ return theClass;
+ } // end method findClass( String )
+
+ @Override
+ public Class<?> loadClass(String className) throws ClassNotFoundException {
+ // Allowed classes:
+ String[] disallowedClasses = { "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver1",
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver2",
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver4",
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_Driver5" };
+
+ Class<?> theClass;
+
+ theClass = findLoadedClass(className);
+ if (theClass != null) {
+ return theClass;
+ }
+
+ theClass = this.findClass(className);
+
+ if (theClass == null) {
+ for (String element : disallowedClasses) {
+ if (element.equals(className)) {
+ return null;
+ } // end if
+ } // end for
+ theClass = Class.forName(className);
+ } // end if
+
+ return theClass;
+ } // end method loadClass( String )
+
+ private Class<?> loadClassFromFile(String pathName, String className,
+ String classNameAsFile) {
+ Class<?> theClass = null;
+ FileInputStream theInput = null;
+ File theFile = null;
+ try {
+ theFile = new File(pathName, classNameAsFile);
+ if (theFile.exists()) {
+ int length = (int) theFile.length();
+ theInput = new FileInputStream(theFile);
+ byte[] theBytes = new byte[length + 100];
+ int dataRead = 0;
+ while (dataRead < length) {
+ int count = theInput.read(theBytes, dataRead,
+ theBytes.length - dataRead);
+ if (count == -1) {
+ break;
+ }
+ dataRead += count;
+ }
+
+ if (dataRead > 0) {
+ // Create the class from the bytes read in...
+ theClass = this.defineClass(className, theBytes, 0, dataRead);
+ ClassLoader testClassLoader = theClass.getClassLoader();
+ if (testClassLoader != this) {
+ System.out.println("findClass - wrong classloader!!");
+ }
+ }
+ }
+ } catch (Exception e) {
+ System.out.println("findClass - exception reading class file.");
+ e.printStackTrace();
+ } finally {
+ try {
+ if (theInput != null) {
+ theInput.close();
+ }
+ } catch (Exception e) {
+ }
+ }
+ return theClass;
+ }
+
+ /*
+ * Loads a named class from a specified JAR file
+ */
+ private Class<?> loadClassFromJar(String jarfileName, String className,
+ String classNameAsFile) {
+ Class<?> theClass = null;
+
+ // First, try to open the Jar file
+ JarFile theJar = null;
+ try {
+ theJar = new JarFile(jarfileName);
+ JarEntry theEntry = theJar.getJarEntry(classNameAsFile);
+
+ if (theEntry == null) {
+ // System.out.println("TestHelper_Classloader - did not find
+ // class file in Jar " + jarfileName );
+ return theClass;
+ } // end if
+
+ theEntry.getMethod();
+ InputStream theStream = theJar.getInputStream(theEntry);
+
+ long size = theEntry.getSize();
+ if (size < 0) {
+ size = 100000;
+ }
+ byte[] theBytes = new byte[(int) size + 100];
+
+ int dataRead = 0;
+ while (dataRead < size) {
+ int count = theStream.read(theBytes, dataRead, theBytes.length
+ - dataRead);
+ if (count == -1) {
+ break;
+ }
+ dataRead += count;
+ } // end while
+
+ // System.out.println("loadClassFromJar: read " + dataRead + " bytes
+ // from class file");
+ if (dataRead > 0) {
+ // Create the class from the bytes read in...
+ theClass = this.defineClass(className, theBytes, 0, dataRead);
+ /* System.out.println("findClass: created Class object."); */
+ ClassLoader testClassLoader = theClass.getClassLoader();
+ if (testClassLoader != this) {
+ System.out.println("findClass - wrong classloader!!");
+ } else {
+ System.out
+ .println("Testclassloader loaded class from jar: "
+ + className);
+ } // end if
+ } // end if
+ } catch (IOException ie) {
+ System.out
+ .println("TestHelper_ClassLoader: IOException opening Jar "
+ + jarfileName);
+ } catch (Exception e) {
+ System.out
+ .println("TestHelper_ClassLoader: Exception loading class from Jar ");
+ } catch (ClassFormatError ce) {
+ System.out
+ .println("TestHelper_ClassLoader: ClassFormatException loading class from Jar ");
+ } finally {
+ try {
+ if (theJar != null) {
+ theJar.close();
+ }
+ } catch (Exception e) {
+ } // end try
+ } // end try
+
+ return theClass;
+ } // end method loadClassFromJar(
+
+} // end class TestHelper_ClassLoader
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Connection1.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Connection1.java
new file mode 100644
index 0000000..8b1fd60
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Connection1.java
@@ -0,0 +1,176 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.CallableStatement;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.util.Map;
+
+/**
+ * Helper class for the java.sql tests - a skeleton class which implements the
+ * java.sql.Connection interface
+ *
+ */
+public class TestHelper_Connection1 implements Connection {
+ public void clearWarnings() throws SQLException {
+ }
+
+ public void close() throws SQLException {
+ }
+
+ public void commit() throws SQLException {
+ }
+
+ public Statement createStatement() throws SQLException {
+ return null;
+ }
+
+ public Statement createStatement(int resultSetType, int resultSetConcurrency,
+ int resultSetHoldability) throws SQLException {
+ return null;
+ }
+
+ public Statement createStatement(int resultSetType, int resultSetConcurrency)
+ throws SQLException {
+ return null;
+ }
+
+ public boolean getAutoCommit() throws SQLException {
+ return false;
+ }
+
+ public String getCatalog() throws SQLException {
+ return null;
+ }
+
+ public int getHoldability() throws SQLException {
+ return 0;
+ }
+
+ public DatabaseMetaData getMetaData() throws SQLException {
+ return null;
+ }
+
+ public int getTransactionIsolation() throws SQLException {
+ return 0;
+ }
+
+ public Map<String, Class<?>> getTypeMap() throws SQLException {
+ return null;
+ }
+
+ public SQLWarning getWarnings() throws SQLException {
+ return null;
+ }
+
+ public boolean isClosed() throws SQLException {
+ return false;
+ }
+
+ public boolean isReadOnly() throws SQLException {
+ return false;
+ }
+
+ public String nativeSQL(String sql) throws SQLException {
+ return null;
+ }
+
+ public CallableStatement prepareCall(String sql, int resultSetType,
+ int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ return null;
+ }
+
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
+ throws SQLException {
+ return null;
+ }
+
+ public CallableStatement prepareCall(String sql) throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql, int resultSetType,
+ int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql, int resultSetType,
+ int resultSetConcurrency) throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
+ throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
+ throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql, String[] columnNames)
+ throws SQLException {
+ return null;
+ }
+
+ public PreparedStatement prepareStatement(String sql) throws SQLException {
+ return null;
+ }
+
+ public void releaseSavepoint(Savepoint savepoint) throws SQLException {
+ }
+
+ public void rollback() throws SQLException {
+ }
+
+ public void rollback(Savepoint savepoint) throws SQLException {
+ }
+
+ public void setAutoCommit(boolean autoCommit) throws SQLException {
+ }
+
+ public void setCatalog(String catalog) throws SQLException {
+ }
+
+ public void setHoldability(int holdability) throws SQLException {
+ }
+
+ public void setReadOnly(boolean readOnly) throws SQLException {
+ }
+
+ public Savepoint setSavepoint() throws SQLException {
+ return null;
+ }
+
+ public Savepoint setSavepoint(String name) throws SQLException {
+ return null;
+ }
+
+ public void setTransactionIsolation(int level) throws SQLException {
+ }
+
+ public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver1.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver1.java
new file mode 100644
index 0000000..ae09f94
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver1.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.util.Properties;
+
+/**
+ * A simple implementation of a class implementing a JDBC Driver, for use in the
+ * testing of the java.sql.DriverManager class
+ *
+ */
+public class TestHelper_Driver1 implements Driver {
+ int majorVersion = 1;
+
+ int minorVersion = 0;
+
+ String baseURL = "jdbc:mikes1";
+
+ String[] dataSources = { "data1", "data2", "data3" };
+
+ static Driver theDriver;
+ static {
+ theDriver = new TestHelper_Driver1();
+ try {
+ DriverManager.registerDriver(theDriver);
+ } catch (SQLException e) {
+ System.out.println("Failed to register driver!");
+ }
+ } // end static block initializer
+
+ protected TestHelper_Driver1() {
+ super();
+ } // end constructor TestHelper_Driver1()
+
+ public boolean acceptsURL(String url) throws SQLException {
+ // Check on the supplied String...
+ if (url == null) {
+ return false;
+ }
+ // Everything's fine if the quoted url starts with the base url for this
+ // driver
+ if (url.startsWith(baseURL)) {
+ return true;
+ }
+ return false;
+ } // end method acceptsURL
+
+ static String validuser = "theuser";
+
+ static String validpassword = "thepassword";
+
+ static String userProperty = "user";
+
+ static String passwordProperty = "password";
+
+ public Connection connect(String url, Properties info) throws SQLException {
+ // Does the URL have the right form?
+ if (this.acceptsURL(url)) {
+ // The datasource name is the remainder of the url after the ":"
+ String datasource = url.substring(baseURL.length() + 1);
+ for (String element : dataSources) {
+ if (datasource.equals(element)) {
+ /*
+ * Check for user and password, except for datasource =
+ * data1 which is set up not to require a user/password
+ * combination
+ */
+ // It all checks out - so return a connection
+ Connection connection = new TestHelper_Connection1();
+ return connection;
+ } // end if
+ } // end for
+ } // end if
+ return null;
+ } // end method connect(String, Properties)
+
+ public int getMajorVersion() {
+ return majorVersion;
+ } // end method getMajorVersion()
+
+ public int getMinorVersion() {
+ return minorVersion;
+ } // end method getMinorVersion()
+
+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
+ throws SQLException {
+ DriverPropertyInfo[] theInfos = { new DriverPropertyInfo(userProperty, "*"),
+ new DriverPropertyInfo(passwordProperty, "*"), };
+ return theInfos;
+ }
+
+ public boolean jdbcCompliant() {
+ // Basic version here returns false
+ return false;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver2.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver2.java
new file mode 100644
index 0000000..6d495d6
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver2.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/**
+ * Basic JDBC driver implementation to help with tests
+ *
+ */
+public class TestHelper_Driver2 extends TestHelper_Driver1 {
+
+ static {
+ Driver theDriver = new TestHelper_Driver2();
+ /*
+ * System.out.println("Driver2 classloader: " +
+ * theDriver.getClass().getClassLoader() ); System.out.println("Driver2
+ * object is: " + theDriver );
+ */
+ try {
+ DriverManager.registerDriver(theDriver);
+ } catch (SQLException e) {
+ System.out.println("Failed to register driver!");
+ }
+ } // end static block initializer
+
+ protected TestHelper_Driver2() {
+ super();
+ baseURL = "jdbc:mikes2";
+ } // end constructor TestHelper_Driver1()
+
+} // end class TestHelper_Driver2
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver3.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver3.java
new file mode 100644
index 0000000..f02bdc3
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver3.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+
+/**
+ * TODO Type description
+ *
+ */
+public class TestHelper_Driver3 extends TestHelper_Driver1 {
+
+ /*
+ * This driver does NOT automatically register itself...
+ */
+
+ public TestHelper_Driver3() {
+ super();
+ baseURL = "jdbc:mikes3";
+ } // end constructor TestHelper_Driver1()
+
+} // end class TestHelper_Driver3
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver4.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver4.java
new file mode 100644
index 0000000..655436d
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver4.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.util.Properties;
+
+/**
+ * Basic JDBC driver implementation to help with tests
+ *
+ */
+public class TestHelper_Driver4 implements Driver {
+ int majorVersion = 1;
+
+ int minorVersion = 0;
+
+ String baseURL;
+
+ String[] dataSources = { "data1", "data2", "data3" };
+ static {
+ Driver theDriver = new TestHelper_Driver4();
+ try {
+ DriverManager.registerDriver(theDriver);
+ } catch (SQLException e) {
+ System.out.println("Failed to register driver!");
+ }
+ } // end static block initializer
+
+ protected TestHelper_Driver4() {
+ super();
+ baseURL = "jdbc:mikes4";
+ } // end constructor TestHelper_Driver4()
+
+ public boolean acceptsURL(String url) throws SQLException {
+ // Check on the supplied String...
+ if (url == null) {
+ return false;
+ }
+ // Everything's fine if the quoted url starts with the base url for this
+ // driver
+ if (url.startsWith(baseURL)) {
+ return true;
+ }
+ return false;
+ } // end method acceptsURL
+
+ static String validuser = "theuser";
+
+ static String validpassword = "thepassword";
+
+ static String userProperty = "user";
+
+ static String passwordProperty = "password";
+
+ public Connection connect(String url, Properties info) throws SQLException {
+ // Does the URL have the right form?
+ if (this.acceptsURL(url)) {
+ // The datasource name is the remainder of the url after the ":"
+ String datasource = url.substring(baseURL.length() + 1);
+ for (String element : dataSources) {
+ if (datasource.equals(element)) {
+ /*
+ * Check for user and password, except for datasource =
+ * data1 which is set up not to require a user/password
+ * combination
+ */
+ if (datasource.equals("data1")) {
+ // do nothing...
+ } else {
+ if (info == null) {
+ throw new SQLException("Properties bundle is null");
+ }
+ String user = (String) info.get(userProperty);
+ String password = (String) info.get(passwordProperty);
+ if (user == null || password == null) {
+ throw new SQLException("Userid and/or password not supplied");
+ }
+ if (!user.equals(validuser) || !password.equals(validpassword)) {
+ throw new SQLException("Userid and/or password not valid");
+ } // end if
+ } // end if
+ // It all checks out - so return a connection
+ Connection connection = new TestHelper_Connection1();
+ return connection;
+ } // end if
+ } // end for
+ } // end if
+ return null;
+ } // end method connect(String, Properties)
+
+ public int getMajorVersion() {
+ return majorVersion;
+ } // end method getMajorVersion()
+
+ public int getMinorVersion() {
+ return minorVersion;
+ } // end method getMinorVersion()
+
+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info)
+ throws SQLException {
+ DriverPropertyInfo[] theInfos = { new DriverPropertyInfo(userProperty, "*"),
+ new DriverPropertyInfo(passwordProperty, "*"), };
+ return theInfos;
+ }
+
+ public boolean jdbcCompliant() {
+ // Basic version here returns false
+ return false;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver5.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver5.java
new file mode 100644
index 0000000..b228466
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_Driver5.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+/**
+ * Basic JDBC driver implementation to help with tests
+ *
+ */
+public class TestHelper_Driver5 extends TestHelper_Driver4 {
+
+ static {
+ Driver theDriver = new TestHelper_Driver5();
+ try {
+ DriverManager.registerDriver(theDriver);
+ } catch (SQLException e) {
+ System.out.println("Failed to register driver!");
+ }
+ } // end static block initializer
+
+ protected TestHelper_Driver5() {
+ super();
+ baseURL = "jdbc:mikes5";
+ } // end constructor TestHelper_Driver5()
+
+} // end class TestHelper_Driver5
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java
new file mode 100644
index 0000000..299c33a
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TestHelper_DriverManager.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+
+import junit.framework.TestCase;
+
+/**
+ * Helper class for the Driver manager tes - it allows the test code to be
+ * loaded under a different classloader, necessary for testing the
+ * DeregisterDriver function of DriverManager
+ *
+ */
+public class TestHelper_DriverManager extends TestCase {
+
+ static Driver testDriver = null;
+
+ static TestHelper_DriverManager theHelper;
+
+ static {
+ theHelper = new TestHelper_DriverManager();
+ // theHelper.testDeregister();
+ } // end static
+
+ public TestHelper_DriverManager() {
+ super();
+ } // end constructor TestHelper_DriverManager()
+
+ public static void setDriver(Driver theDriver) {
+ testDriver = theDriver;
+ // System.out.println("TestHelper_DriverManager: Test Driver set!");
+
+ theHelper.checkDeregister();
+ } // end method setDriver( Driver )
+
+ public void checkDeregister() {
+
+ String baseURL = "jdbc:mikes1";
+
+ // System.out.println("Calling checkDeregister in
+ // TestHelper_DriverManager....");
+
+ Driver aDriver;
+
+ // System.out.println("checkDeregister classloader: " +
+ // this.getClass().getClassLoader() );
+
+ // Try to get a driver from the general pool... this should fail
+ try {
+ aDriver = DriverManager.getDriver(baseURL);
+ fail(
+ "testDeregisterDriver: Didn't get exception when getting valid driver from other classloader.");
+ } catch (SQLException e) {
+ // e.printStackTrace();
+ assertTrue(
+ "testDeregisterDriver: Got exception when getting valid driver from other classloader.",
+ true);
+ // return;
+ } // end try
+
+ // OK, now THIS driver was loaded by someone else....
+ aDriver = testDriver;
+
+ // printClassLoader( aDriver );
+
+ // Deregister this driver
+ try {
+ DriverManager.deregisterDriver(aDriver);
+ // We shouldn't get here - but if we do, we need to re-register the
+ // driver to
+ // prevent subsequent tests from failing due to inability to get to
+ // this driver...
+ DriverManager.registerDriver(aDriver);
+ fail(
+ "checkDeregisterDriver: Didn't get Security Exception deregistering invalid driver.");
+ } catch (SecurityException s) {
+ // This is the exception we should get...
+ // System.out.println("checkDeregisterDriver: got expected Security
+ // Exception");
+ } catch (Exception e) {
+ fail(
+ "checkDeregisterDriver: Got wrong exception type when deregistering invalid driver.");
+ } // end try
+
+ } // end method testDeRegister
+
+ static void printClassLoader(Object theObject) {
+ Class<? extends Object> theClass = theObject.getClass();
+ ClassLoader theClassLoader = theClass.getClassLoader();
+ System.out.println("ClassLoader is: " + theClassLoader.toString()
+ + " for object: " + theObject.toString());
+ } // end method printClassLoader( Object )
+
+} // end class TestHelper_DriverManager
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimeTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimeTest.java
new file mode 100644
index 0000000..a523b39
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimeTest.java
@@ -0,0 +1,304 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Time;
+import java.util.TimeZone;
+
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.Time class
+ *
+ */
+public class TimeTest extends TestCase {
+
+ static long TIME_TEST1 = 38720000; // 10:45:20 GMT
+
+ static long TIME_TEST2 = 80279000; // 22:17:59 GMT
+
+ static long TIME_TEST3 = -38720000; // 13:14:40 GMT
+
+ static String STRING_TEST1 = "10:45:20";
+
+ static String STRING_TEST2 = "22:17:59";
+
+ static String STRING_TEST3 = "13:14:40";
+
+ static String STRING_INVALID1 = "ABCDEFGHI";
+
+ static String STRING_INVALID2 = "233104";
+
+ static String STRING_INVALID3 = "21-43-48";
+
+ static String STRING_OUTRANGE = "35:99:66";
+
+ static long[] TIME_ARRAY = { TIME_TEST1, TIME_TEST2, TIME_TEST3 };
+
+ static String[] STRING_GMT_ARRAY = { STRING_TEST1, STRING_TEST2,
+ STRING_TEST3 };
+
+ static String[] STRING_LA_ARRAY = { "02:45:20", "14:17:59", "05:14:40" };
+
+ static String[] STRING_JP_ARRAY = { "19:45:20", "07:17:59", "22:14:40" };
+
+ static String[] INVALID_STRINGS = { STRING_INVALID1, STRING_INVALID2,
+ STRING_INVALID3 };
+
+ // Timezones
+ static String TZ_LONDON = "GMT"; // GMT (!) PS London != GMT (?!?)
+
+ static String TZ_PACIFIC = "America/Los_Angeles"; // GMT - 8
+
+ static String TZ_JAPAN = "Asia/Tokyo"; // GMT + 9
+
+ static String[] TIMEZONES = { TZ_LONDON, TZ_PACIFIC, TZ_JAPAN };
+
+ static String[][] STRING_ARRAYS = { STRING_GMT_ARRAY, STRING_LA_ARRAY,
+ STRING_JP_ARRAY };
+
+ @SuppressWarnings("deprecation")
+ public void testTimeintintint() {
+ Time theTime = new Time(10, 45, 20);
+
+ // The date should have been created
+ assertNotNull(theTime);
+ } // end method testTimeintintint()
+
+ public void testTime() {
+ Time theTime = new Time(TIME_TEST1);
+
+ // The date should have been created
+ assertNotNull(theTime);
+ } // end method testTime()
+
+ public void testToString() {
+ // Loop through the timezones testing the String conversion for each
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ testToString(TIMEZONES[i], TIME_ARRAY, STRING_ARRAYS[i]);
+ } // end for
+
+ } // end method test
+
+ private void testToString(String timeZone, long[] theTimes,
+ String[] theTimeStrings) {
+ // Set the timezone
+ TimeZone.setDefault(TimeZone.getTimeZone(timeZone));
+
+ for (int i = 0; i < theTimes.length; i++) {
+ // Create the Time object
+ Time theTime = new Time(theTimes[i]);
+ // Convert to a time string ... and compare
+ String JDBCString = theTime.toString();
+ assertEquals(theTimeStrings[i], JDBCString);
+ } // end for
+
+ } // end testToString( String, long[], String[] )
+
+ /*
+ * Method test for valueOf
+ */
+ public void testValueOfString() {
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+
+
+ Time[] theReturns = { new Time(38720000), new Time(80279000),
+ new Time(47680000)};
+ String[] validTime = { "10:45:20", "22:17:59", "13:14:40", };
+ String[] invalidTime = { null, "ABCDEFGHI", "233104", "21-43-48" };
+
+ for (int i = 0; i < validTime.length; i++) {
+ Time theReturn = Time.valueOf(validTime[i]);
+ assertEquals(theReturns[i], theReturn);
+ } // end for
+
+ for (String element : invalidTime) {
+ try {
+ Time.valueOf(element);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ } // end method testValueOfString
+
+ public void testSetTime() {
+ // Ensure that the timezone is set to GMT
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+
+ Time theTime = new Time(TIME_TEST1);
+ assertEquals(STRING_TEST1, theTime.toString());
+
+ theTime.setTime(TIME_TEST2);
+ assertEquals(STRING_TEST2, theTime.toString());
+ } // end method testSetTime()
+
+ @SuppressWarnings("deprecation")
+ public void testSetDate() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.setDate(10);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method testSetDate()
+
+ @SuppressWarnings("deprecation")
+ public void testSetMonth() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.setMonth(2);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method testSetMonth()
+
+ @SuppressWarnings("deprecation")
+ public void testSetYear() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.setYear(99);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method testSetYear()
+
+ @SuppressWarnings("deprecation")
+ public void testGetDate() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.getDate();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method test
+
+ @SuppressWarnings("deprecation")
+ public void testGetDay() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.getDay();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method test
+
+ @SuppressWarnings("deprecation")
+ public void testGetMonth() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.getMonth();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method test
+
+ @SuppressWarnings("deprecation")
+ public void testGetYear() {
+ Time theTime = new Time(TIME_TEST1);
+
+ try {
+ theTime.getYear();
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+ } // end method test
+
+ /**
+ * @tests java.sql.Time#valueOf(String )
+ */
+ public void test_valueOf_IllegalArgumentException() {
+ try{
+ Time.valueOf("15:43:12:34");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf(":10:07:01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf("::01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf("11::");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf(":01:");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf(":10:w2:01");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf("07:w2:");
+ fail("should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf("17:w2:w2");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+
+ try{
+ Time.valueOf("16::01");
+ fail("should throw NumberFormatException");
+ } catch (NumberFormatException e) {
+ //expected
+ }
+ }
+} // end class TimeTest
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimestampTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimestampTest.java
new file mode 100644
index 0000000..7c5d7ab
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TimestampTest.java
@@ -0,0 +1,624 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.sql.Timestamp;
+import java.util.Date;
+import java.util.TimeZone;
+
+import org.apache.harmony.testframework.serialization.SerializationTest;
+import junit.framework.TestCase;
+
+/**
+ * JUnit Testcase for the java.sql.Timestamp class
+ *
+ */
+
+public class TimestampTest extends TestCase {
+
+ static long TIME_TEST1 = 38720231; // 10:45:20.231 GMT
+
+ static long TIME_TEST2 = 80279000; // 22:17:59.000 GMT
+
+ static long TIME_TEST3 = -38720691; // 13:14:39.309 GMT
+
+ static long TIME_COMPARE = 123498845;
+
+ static long TIME_EARLY = -2347889122L;// A time well before the Epoch
+
+ static long TIME_LATE = 2347889122L; // A time well after the Epoch
+
+ static String STRING_TEST1 = "1970-01-01 10:45:20.231"; // "1970-01-01
+ // 10:45:20.231000000";
+
+ static String STRING_TEST2 = "1970-01-01 22:17:59.0"; // "1970-01-01
+ // 22:17:59.000000000";
+
+ static String STRING_TEST3 = "1969-12-31 13:14:39.309"; // "1969-12-31
+ // 13:14:39.309000000";
+
+ static String STRING_INVALID1 = "ABCDEFGHI";
+
+ static String STRING_INVALID2 = "233104";
+
+ static String STRING_INVALID3 = "21-43-48";
+
+ // A timepoint in the correct format but with numeric values out of range
+ // ...this is accepted despite being a crazy date specification
+ // ...it is treated as the correct format date 3000-06-08 12:40:06.875 !!
+ static String STRING_OUTRANGE = "2999-15-99 35:99:66.875";
+
+ static long[] TIME_ARRAY = { TIME_TEST1, TIME_TEST2, TIME_TEST3 };
+
+ static int[] YEAR_ARRAY = { 70, 70, 69 };
+
+ static int[] MONTH_ARRAY = { 0, 0, 11 };
+
+ static int[] DATE_ARRAY = { 1, 1, 31 };
+
+ static int[] HOURS_ARRAY = { 10, 22, 13 };
+
+ static int[] MINUTES_ARRAY = { 45, 17, 14 };
+
+ static int[] SECONDS_ARRAY = { 20, 59, 39 };
+
+ static int[] NANOS_ARRAY = { 231000000, 000000000, 309000000 };
+
+ static int[] NANOS_ARRAY2 = { 137891990, 635665198, 109985421 };
+
+ static String[] STRING_NANOS_ARRAY = { "1970-01-01 10:45:20.13789199",
+ "1970-01-01 22:17:59.635665198", "1969-12-31 13:14:39.109985421" };
+
+ static String[] STRING_GMT_ARRAY = { STRING_TEST1, STRING_TEST2,
+ STRING_TEST3 };
+
+ static String[] STRING_LA_ARRAY = { "02:45:20", "14:17:59", "05:14:40" };
+
+ static String[] STRING_JP_ARRAY = { "19:45:20", "07:17:59", "22:14:40" };
+
+ static String[] INVALID_STRINGS = { STRING_INVALID1, STRING_INVALID2,
+ STRING_INVALID3 };
+
+ // Timezones
+ static String TZ_LONDON = "GMT"; // GMT (!) PS London != GMT (?!?)
+
+ static String TZ_PACIFIC = "America/Los_Angeles"; // GMT - 8
+
+ static String TZ_JAPAN = "Asia/Tokyo"; // GMT + 9
+
+ static String[] TIMEZONES = { TZ_LONDON, TZ_PACIFIC, TZ_JAPAN };
+
+ static String[][] STRING_ARRAYS = { STRING_GMT_ARRAY, STRING_LA_ARRAY,
+ STRING_JP_ARRAY };
+
+ /*
+ * Constructor test
+ */
+ public void testTimestamplong() {
+ Timestamp theTimestamp = new Timestamp(TIME_TEST1);
+
+ // The Timestamp should have been created
+ assertNotNull(theTimestamp);
+ } // end method testTimestamplong
+
+ /*
+ * Constructor test
+ */
+ @SuppressWarnings("deprecation")
+ public void testTimestampintintintintintintint() {
+ int[][] valid = { { 99, 2, 14, 17, 52, 3, 213577212 }, // 0 valid
+ { 0, 0, 1, 0, 0, 0, 0 }, // 1 valid
+ { 106, 11, 31, 23, 59, 59, 999999999 }, // 2 valid
+ { 106, 11, 31, 23, 59, 61, 999999999 }, // 5 Seconds out of
+ // range
+ { 106, 11, 31, 23, 59, -1, 999999999 }, // 6 Seconds out of
+ // range
+ { 106, 11, 31, 23, 61, 59, 999999999 }, // 7 Minutes out of
+ // range
+ { 106, 11, 31, 23, -1, 59, 999999999 }, // 8 Minutes out of
+ // range
+ { 106, 11, 31, 25, 59, 59, 999999999 }, // 9 Hours out of range
+ { 106, 11, 31, -1, 59, 59, 999999999 }, // 10 Hours out of range
+ { 106, 11, 35, 23, 59, 59, 999999999 }, // 11 Days out of range
+ { 106, 11, -1, 23, 59, 59, 999999999 }, // 12 Days out of range
+ { 106, 15, 31, 23, 59, 59, 999999999 }, // 13 Months out of
+ // range
+ { 106, -1, 31, 23, 59, 59, 999999999 }, // 14 Months out of
+ // range
+ { -10, 11, 31, 23, 59, 59, 999999999 }, // 15 valid - Years
+ // negative
+ };
+
+ for (int[] element : valid) {
+ Timestamp theTimestamp = new Timestamp(element[0],
+ element[1], element[2], element[3],
+ element[4], element[5], element[6]);
+ assertNotNull("Timestamp not generated: ", theTimestamp);
+ } // end for
+
+ int[][] invalid = {
+ { 106, 11, 31, 23, 59, 59, 1999999999 },
+ { 106, 11, 31, 23, 59, 59, -999999999 },
+ };
+ for (int[] element : invalid) {
+ try {
+ new Timestamp(element[0],
+ element[1], element[2], element[3],
+ element[4], element[5], element[6]);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ }
+
+ } // end method testTimestampintintintintintintint
+
+ /*
+ * Method test for setTime
+ */
+ public void testSetTimelong() {
+ // First set the timezone to GMT
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+
+ Timestamp theTimestamp = new Timestamp(TIME_TEST1);
+
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ theTimestamp.setTime(TIME_ARRAY[i]);
+
+ assertEquals(TIME_ARRAY[i], theTimestamp.getTime());
+ assertEquals(NANOS_ARRAY[i], theTimestamp.getNanos());
+ } // end for
+
+ } // end method testsetTimelong
+
+ /*
+ * Method test for getTime
+ */
+ public void testGetTime() {
+ // First set the timezone to GMT
+ TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+ assertEquals(element, theTimestamp.getTime());
+ } // end for
+
+ } // end method testgetTime
+
+ /*
+ * Method test for getYear
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetYear() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(YEAR_ARRAY[i], theTimestamp.getYear());
+ } // end for
+
+ } // end method testgetYear
+
+ /*
+ * Method test for getMonth
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetMonth() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(MONTH_ARRAY[i], theTimestamp.getMonth());
+ } // end for
+
+ } // end method testgetMonth
+
+ /*
+ * Method test for getDate
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetDate() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(DATE_ARRAY[i], theTimestamp.getDate());
+ } // end for
+
+ } // end method testgetDate
+
+ /*
+ * Method test for getHours
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetHours() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(HOURS_ARRAY[i], theTimestamp.getHours());
+ } // end for
+
+ } // end method testgetHours
+
+ /*
+ * Method test for getMinutes
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetMinutes() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(MINUTES_ARRAY[i], theTimestamp.getMinutes());
+ } // end for
+
+ } // end method testgetMinutes
+
+ /*
+ * Method test for getSeconds
+ */
+ @SuppressWarnings("deprecation")
+ public void testGetSeconds() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(SECONDS_ARRAY[i], theTimestamp.getSeconds());
+ } // end for
+
+ } // end method testgetSeconds
+
+ /*
+ * Method test for valueOf
+ */
+ static String theExceptionMessage = "Timestamp format must be yyyy-mm-dd hh:mm:ss.fffffffff";
+
+ public void testValueOfString() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ Timestamp theTimestamp2 = Timestamp.valueOf(STRING_GMT_ARRAY[i]);
+ assertEquals(theTimestamp, theTimestamp2);
+ } // end for
+
+ // Test for a string in correct format but with number values out of
+ // range
+ Timestamp theTimestamp = Timestamp.valueOf(STRING_OUTRANGE);
+ assertNotNull(theTimestamp);
+ /*
+ * System.out.println("testValueOfString: outrange timestamp: " +
+ * theTimestamp.toString() );
+ */
+
+ for (String element : INVALID_STRINGS) {
+ try {
+ Timestamp.valueOf(element);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+
+ } // end for
+
+ } // end method testvalueOfString
+
+ /*
+ * Method test for valueOf
+ */
+ public void testValueOfString1() {
+
+ Timestamp theReturn;
+ long[] theReturnTime = { 38720231, 38720231, 80279000, -38720691,
+ 38720000};
+ int[] theReturnNanos = { 231000000, 231987654, 0, 309000000, 0,};
+
+ String[] valid = {
+ "1970-01-01 10:45:20.231",
+ "1970-01-01 10:45:20.231987654",
+ "1970-01-01 22:17:59.0",
+ "1969-12-31 13:14:39.309",
+ "1970-01-01 10:45:20",
+ };
+ String[] invalid = {
+ null,
+ "ABCDEFGHI",
+ "233104", "1970-01-01 22:17:59.",
+ "1970-01-01 10:45:20.231987654690645322",
+ "1970-01-01 10:45:20&231987654",
+ "1970-01-01 10:45:20.-31987654",
+ "1970-01-01 10:45:20.ABCD87654",
+ "21-43-48",
+ };
+
+ for (int i = 0; i < valid.length; i++) {
+ theReturn = Timestamp.valueOf(valid[i]);
+ assertEquals(theReturnTime[i], theReturn.getTime());
+ assertEquals(theReturnNanos[i], theReturn.getNanos());
+ } // end for
+
+ for (String element : invalid) {
+ try {
+ theReturn = Timestamp.valueOf(element);
+ fail("Should throw IllegalArgumentException.");
+ } catch (IllegalArgumentException e) {
+ //expected
+ }
+ }
+
+ } // end method testValueOfString
+
+ /*
+ * Method test for toString
+ */
+ public void testToString() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(STRING_GMT_ARRAY[i], theTimestamp.toString());
+ } // end for
+
+ } // end method testtoString
+
+ /*
+ * Method test for getNanos
+ */
+ public void testGetNanos() {
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ assertEquals(NANOS_ARRAY[i], theTimestamp.getNanos());
+ } // end for
+
+ } // end method testgetNanos
+
+ /*
+ * Method test for setNanos
+ */
+ public void testSetNanosint() {
+ int[] NANOS_INVALID = { -137891990, 1635665198, -1 };
+ for (int i = 0; i < TIME_ARRAY.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+
+ theTimestamp.setNanos(NANOS_ARRAY2[i]);
+
+ assertEquals(NANOS_ARRAY2[i], theTimestamp.getNanos());
+ // Also check that these Timestamps with detailed nanos values
+ // convert to
+ // strings correctly
+ assertEquals(STRING_NANOS_ARRAY[i], theTimestamp.toString());
+ } // end for
+
+ for (int i = 0; i < NANOS_INVALID.length; i++) {
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[i]);
+ int originalNanos = theTimestamp.getNanos();
+ try {
+ theTimestamp.setNanos(NANOS_INVALID[i]);
+ fail("Should throw IllegalArgumentException");
+ } catch (IllegalArgumentException e) {
+ //expected
+ } // end try
+
+ assertEquals(originalNanos, theTimestamp.getNanos());
+ } // end for
+
+ } // end method testsetNanosint
+
+ /*
+ * Method test for equals
+ */
+ public void testEqualsTimestamp() {
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+ Timestamp theTimestamp2 = new Timestamp(element);
+
+ assertTrue(theTimestamp.equals(theTimestamp2));
+ } // end for
+
+ Timestamp theTest = new Timestamp(TIME_COMPARE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+ assertFalse(theTimestamp.equals(theTest));
+ } // end for
+
+ // Regression for HARMONY-526
+ assertFalse(new Timestamp(0).equals((Timestamp) null));
+ } // end method testequalsTimestamp
+
+ /*
+ * Method test for equals
+ */
+ public void testEqualsObject() {
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ Object theTimestamp2 = new Timestamp(element);
+
+ assertTrue(theTimestamp.equals(theTimestamp2));
+ } // end for
+
+ Object theTest = new Timestamp(TIME_COMPARE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertFalse(theTimestamp.equals(theTest));
+ } // end for
+
+ Object nastyTest = new String("Test ");
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[1]);
+ assertFalse(theTimestamp.equals(nastyTest));
+
+ // Regression for HARMONY-526
+ assertFalse(new Timestamp(0).equals((Object) null));
+ } // end method testequalsObject
+
+ /*
+ * Method test for before
+ */
+ public void testBeforeTimestamp() {
+ Timestamp theTest = new Timestamp(TIME_LATE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertTrue(theTimestamp.before(theTest));
+ } // end for
+
+ theTest = new Timestamp(TIME_EARLY);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertFalse(theTimestamp.before(theTest));
+ } // end for
+
+ for (long element : TIME_ARRAY) {
+ theTest = new Timestamp(element);
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertFalse(theTimestamp.before(theTest));
+ theTest.setNanos(theTest.getNanos() + 1);
+ assertTrue(theTimestamp.before(theTest));
+ } // end for
+
+ } // end method testbeforeTimestamp
+
+ /*
+ * Method test for after
+ */
+ public void testAfterTimestamp() {
+ Timestamp theTest = new Timestamp(TIME_LATE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertFalse(theTimestamp.after(theTest));
+ } // end for
+
+ theTest = new Timestamp(TIME_EARLY);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertTrue(theTimestamp.after(theTest));
+ } // end for
+
+ for (long element : TIME_ARRAY) {
+ theTest = new Timestamp(element);
+ Timestamp theTimestamp = new Timestamp(element);
+
+ assertFalse(theTimestamp.after(theTest));
+ theTimestamp.setNanos(theTimestamp.getNanos() + 1);
+ assertTrue(theTimestamp.after(theTest));
+ } // end for
+
+ } // end method testafterTimestamp
+
+ /*
+ * Method test for compareTo
+ */
+ @SuppressWarnings("deprecation")
+ public void testCompareToTimestamp() {
+ Timestamp theTest = new Timestamp(TIME_EARLY);
+ Timestamp theTest2 = new Timestamp(TIME_LATE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+ Timestamp theTimestamp2 = new Timestamp(element);
+
+ assertTrue(theTimestamp.compareTo(theTest) > 0);
+ assertTrue(theTimestamp.compareTo(theTest2) < 0);
+ assertEquals(0, theTimestamp.compareTo(theTimestamp2));
+ } // end for
+
+ Timestamp t1 = new Timestamp(-1L);
+ Timestamp t2 = new Timestamp(-1L);
+
+ t1.setTime(Long.MIN_VALUE);
+ t2.setDate(Integer.MIN_VALUE);
+ assertEquals(1, t1.compareTo(t2));
+ assertEquals(-1, t2.compareTo(t1));
+
+ t1.setTime(Long.MAX_VALUE);
+ t2.setTime(Long.MAX_VALUE - 1);
+ assertEquals(1, t1.compareTo(t2));
+ assertEquals(-1, t2.compareTo(t1));
+
+ t1.setTime(Integer.MAX_VALUE);
+ t2.setTime(Integer.MAX_VALUE);
+ assertEquals(0, t1.compareTo(t2));
+ assertEquals(0, t2.compareTo(t1));
+
+ } // end method testcompareToTimestamp
+
+ /**
+ * @tests java.sql.Timestamp#compareTo(java.util.Date)
+ */
+ public void testCompareToDate() {
+ Date theTest = new Timestamp(TIME_EARLY);
+ Date theTest2 = new Timestamp(TIME_LATE);
+
+ for (long element : TIME_ARRAY) {
+ Timestamp theTimestamp = new Timestamp(element);
+ Date theTimestamp2 = new Timestamp(element);
+
+ assertTrue(theTimestamp.compareTo(theTest) > 0);
+ assertTrue(theTimestamp.compareTo(theTest2) < 0);
+ assertEquals(0, theTimestamp.compareTo(theTimestamp2));
+ } // end for
+
+ Date nastyTest = new Date();
+ Timestamp theTimestamp = new Timestamp(TIME_ARRAY[1]);
+ try {
+ theTimestamp.compareTo(nastyTest);
+ // It throws ClassCastException in JDK 1.5.0_06 but in 1.5.0_07 it
+ // does not throw the expected exception.
+ fail("testCompareToObject: Did not get expected ClassCastException");
+ } catch (ClassCastException e) {
+ // Should get here
+ /*
+ * System.out.println("testCompareToObject: ClassCastException as
+ * expected"); System.out.println("Exception message: " +
+ * e.getMessage());
+ */
+ } // end try
+
+ } // end method testcompareToObject
+
+ /**
+ * @tests serialization/deserialization compatibility.
+ */
+ public void testSerializationSelf() throws Exception {
+ Timestamp object = new Timestamp(100L);
+ SerializationTest.verifySelf(object);
+ }
+
+ /**
+ * @tests serialization/deserialization compatibility with RI.
+ */
+ public void testSerializationCompatibility() throws Exception {
+ Timestamp object = new Timestamp(100L);
+ SerializationTest.verifyGolden(this, object);
+ }
+
+ /**
+ * @tests java.sql.Timestamp#toString()
+ */
+ public void test_toString() {
+
+ Timestamp t1 = new Timestamp(Long.MIN_VALUE);
+ assertEquals("292278994-08-17 07:12:55.192", t1.toString()); //$NON-NLS-1$
+
+ Timestamp t2 = new Timestamp(Long.MIN_VALUE + 1);
+ assertEquals("292278994-08-17 07:12:55.193", t2.toString()); //$NON-NLS-1$
+
+ Timestamp t3 = new Timestamp(Long.MIN_VALUE + 807);
+ assertEquals("292278994-08-17 07:12:55.999", t3.toString()); //$NON-NLS-1$
+
+ Timestamp t4 = new Timestamp(Long.MIN_VALUE + 808);
+ assertEquals("292269055-12-02 16:47:05.0", t4.toString()); //$NON-NLS-1$
+ }
+
+} // end class TimestampTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TypesTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TypesTest.java
new file mode 100644
index 0000000..5ee8860
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/java/sql/TypesTest.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.java.sql;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+public class TypesTest extends TestCase {
+
+ /*
+ * Public statics test
+ */
+ public void testPublicStatics() {
+
+ HashMap<String, Integer> thePublicStatics = new HashMap<String, Integer>();
+ thePublicStatics.put("BOOLEAN", new Integer(16));
+ thePublicStatics.put("DATALINK", new Integer(70));
+ thePublicStatics.put("REF", new Integer(2006));
+ thePublicStatics.put("CLOB", new Integer(2005));
+ thePublicStatics.put("BLOB", new Integer(2004));
+ thePublicStatics.put("ARRAY", new Integer(2003));
+ thePublicStatics.put("STRUCT", new Integer(2002));
+ thePublicStatics.put("DISTINCT", new Integer(2001));
+ thePublicStatics.put("JAVA_OBJECT", new Integer(2000));
+ thePublicStatics.put("OTHER", new Integer(1111));
+ thePublicStatics.put("NULL", new Integer(0));
+ thePublicStatics.put("LONGVARBINARY", new Integer(-4));
+ thePublicStatics.put("VARBINARY", new Integer(-3));
+ thePublicStatics.put("BINARY", new Integer(-2));
+ thePublicStatics.put("TIMESTAMP", new Integer(93));
+ thePublicStatics.put("TIME", new Integer(92));
+ thePublicStatics.put("DATE", new Integer(91));
+ thePublicStatics.put("LONGVARCHAR", new Integer(-1));
+ thePublicStatics.put("VARCHAR", new Integer(12));
+ thePublicStatics.put("CHAR", new Integer(1));
+ thePublicStatics.put("DECIMAL", new Integer(3));
+ thePublicStatics.put("NUMERIC", new Integer(2));
+ thePublicStatics.put("DOUBLE", new Integer(8));
+ thePublicStatics.put("REAL", new Integer(7));
+ thePublicStatics.put("FLOAT", new Integer(6));
+ thePublicStatics.put("BIGINT", new Integer(-5));
+ thePublicStatics.put("INTEGER", new Integer(4));
+ thePublicStatics.put("SMALLINT", new Integer(5));
+ thePublicStatics.put("TINYINT", new Integer(-6));
+ thePublicStatics.put("BIT", new Integer(-7));
+
+ Class<?> typesClass;
+ try {
+ typesClass = Class.forName("java.sql.Types");
+ } catch (ClassNotFoundException e) {
+ fail("java.sql.Types class not found!");
+ return;
+ } // end try
+
+ Field[] theFields = typesClass.getDeclaredFields();
+ int requiredModifier = Modifier.PUBLIC + Modifier.STATIC
+ + Modifier.FINAL;
+
+ int countPublicStatics = 0;
+ for (Field element : theFields) {
+ String fieldName = element.getName();
+ int theMods = element.getModifiers();
+ if (Modifier.isPublic(theMods) && Modifier.isStatic(theMods)) {
+ try {
+ Object fieldValue = element.get(null);
+ Object expectedValue = thePublicStatics.get(fieldName);
+ if (expectedValue == null) {
+ fail("Field " + fieldName + " missing!");
+ } // end
+ assertEquals("Field " + fieldName + " value mismatch: ",
+ expectedValue, fieldValue);
+ assertEquals("Field " + fieldName + " modifier mismatch: ",
+ requiredModifier, theMods);
+ countPublicStatics++;
+ } catch (IllegalAccessException e) {
+ fail("Illegal access to Field " + fieldName);
+ } // end try
+ } // end if
+ } // end for
+
+ } // end method testPublicStatics
+
+} // end class TypesTest
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java
new file mode 100644
index 0000000..f1553f2
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/AllTests.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.javax.sql;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * This is autogenerated source file. Includes tests for package org.apache.harmony.sql.tests.javax.sql;
+ */
+
+public class AllTests {
+
+ public static void main(String[] args) {
+ junit.textui.TestRunner.run(AllTests.suite());
+ }
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All tests for package org.apache.harmony.sql.tests.javax.sql;");
+ // $JUnit-BEGIN$
+
+ suite.addTestSuite(ConnectionEventTest.class);
+ suite.addTestSuite(RowSetEventTest.class);
+
+ // $JUnit-END$
+ return suite;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.java
new file mode 100644
index 0000000..a5d7617
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.javax.sql;
+
+import java.sql.SQLException;
+import javax.sql.ConnectionEvent;
+import junit.framework.TestCase;
+
+public class ConnectionEventTest extends TestCase {
+
+ public void testConstructorConnection() {
+ try {
+ new ConnectionEvent(null);
+ fail("illegal argument exception expected");
+ } catch (IllegalArgumentException e) {
+ }
+
+ Impl_PooledConnection ipc = new Impl_PooledConnection();
+ ConnectionEvent ce = new ConnectionEvent(ipc);
+ assertSame(ipc, ce.getSource());
+ assertNull(ce.getSQLException());
+ }
+
+ public void testConstructorConnectionSQLException() {
+ try {
+ new ConnectionEvent(null, null);
+ fail("illegal argument exception expected");
+ } catch (IllegalArgumentException e) {
+ }
+
+ Impl_PooledConnection ipc = new Impl_PooledConnection();
+ ConnectionEvent ce = new ConnectionEvent(ipc, null);
+ assertSame(ipc, ce.getSource());
+ assertNull(ce.getSQLException());
+
+ SQLException e = new SQLException();
+ ce = new ConnectionEvent(ipc, e);
+ assertSame(ipc, ce.getSource());
+ assertSame(e, ce.getSQLException());
+ }
+}
+
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_PooledConnection.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_PooledConnection.java
new file mode 100644
index 0000000..d135ced
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_PooledConnection.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.javax.sql;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+import javax.sql.ConnectionEventListener;
+import javax.sql.PooledConnection;
+
+class Impl_PooledConnection implements PooledConnection {
+ public void addConnectionEventListener(ConnectionEventListener theListener) {
+ }
+
+ public void close() throws SQLException {
+ }
+
+ public Connection getConnection() throws SQLException {
+ return null;
+ }
+
+ public void removeConnectionEventListener(ConnectionEventListener theListener) {
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_RowSet.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_RowSet.java
new file mode 100644
index 0000000..ace6b9a
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/Impl_RowSet.java
@@ -0,0 +1,738 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.javax.sql;
+
+import java.io.InputStream;
+import java.io.Reader;
+import java.math.BigDecimal;
+import java.net.URL;
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.Clob;
+import java.sql.Date;
+import java.sql.Ref;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.util.Calendar;
+import java.util.Map;
+import javax.sql.RowSet;
+import javax.sql.RowSetListener;
+
+@SuppressWarnings("deprecation")
+class Impl_RowSet implements RowSet {
+ public void addRowSetListener(RowSetListener theListener) {
+ }
+
+ public void clearParameters() throws SQLException {
+ }
+
+ public void execute() throws SQLException {
+ }
+
+ public String getCommand() {
+ return null;
+ }
+
+ public String getDataSourceName() {
+ return null;
+ }
+
+ public boolean getEscapeProcessing() throws SQLException {
+ return false;
+ }
+
+ public int getMaxFieldSize() throws SQLException {
+ return 0;
+ }
+
+ public int getMaxRows() throws SQLException {
+ return 0;
+ }
+
+ public String getPassword() {
+ return null;
+ }
+
+ public int getQueryTimeout() throws SQLException {
+ return 0;
+ }
+
+ public int getTransactionIsolation() {
+ return 0;
+ }
+
+ public Map<String, Class<?>> getTypeMap() throws SQLException {
+ return null;
+ }
+
+ public String getUrl() throws SQLException {
+ return null;
+ }
+
+ public String getUsername() {
+ return null;
+ }
+
+ public boolean isReadOnly() {
+ return false;
+ }
+
+ public void removeRowSetListener(RowSetListener theListener) {
+ }
+
+ public void setArray(int parameterIndex, Array theArray) throws SQLException {
+ }
+
+ public void setAsciiStream(int parameterIndex, InputStream theInputStream, int length)
+ throws SQLException {
+ }
+
+ public void setBigDecimal(int parameterIndex, BigDecimal theBigDecimal) throws SQLException {
+ }
+
+ public void setBinaryStream(int parameterIndex, InputStream theInputStream, int length)
+ throws SQLException {
+ }
+
+ public void setBlob(int parameterIndex, Blob theBlob) throws SQLException {
+ }
+
+ public void setBoolean(int parameterIndex, boolean theBoolean) throws SQLException {
+ }
+
+ public void setByte(int parameterIndex, byte theByte) throws SQLException {
+ }
+
+ public void setBytes(int parameterIndex, byte[] theByteArray) throws SQLException {
+ }
+
+ public void setCharacterStream(int parameterIndex, Reader theReader, int length)
+ throws SQLException {
+ }
+
+ public void setClob(int parameterIndex, Clob theClob) throws SQLException {
+ }
+
+ public void setCommand(String cmd) throws SQLException {
+ }
+
+ public void setConcurrency(int concurrency) throws SQLException {
+ }
+
+ public void setDataSourceName(String name) throws SQLException {
+ }
+
+ public void setDate(int parameterIndex, Date theDate, Calendar theCalendar)
+ throws SQLException {
+ }
+
+ public void setDate(int parameterIndex, Date theDate) throws SQLException {
+ }
+
+ public void setDouble(int parameterIndex, double theDouble) throws SQLException {
+ }
+
+ public void setEscapeProcessing(boolean enable) throws SQLException {
+ }
+
+ public void setFloat(int parameterIndex, float theFloat) throws SQLException {
+ }
+
+ public void setInt(int parameterIndex, int theInteger) throws SQLException {
+ }
+
+ public void setLong(int parameterIndex, long theLong) throws SQLException {
+ }
+
+ public void setMaxFieldSize(int max) throws SQLException {
+ }
+
+ public void setMaxRows(int max) throws SQLException {
+ }
+
+ public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
+ }
+
+ public void setNull(int parameterIndex, int sqlType) throws SQLException {
+ }
+
+ public void setObject(int parameterIndex, Object theObject, int targetSqlType, int scale)
+ throws SQLException {
+ }
+
+ public void setObject(int parameterIndex, Object theObject, int targetSqlType)
+ throws SQLException {
+ }
+
+ public void setObject(int parameterIndex, Object theObject) throws SQLException {
+ }
+
+ public void setPassword(String password) throws SQLException {
+ }
+
+ public void setQueryTimeout(int seconds) throws SQLException {
+ }
+
+ public void setReadOnly(boolean readOnly) throws SQLException {
+ }
+
+ public void setRef(int parameterIndex, Ref theRef) throws SQLException {
+ }
+
+ public void setShort(int parameterIndex, short theShort) throws SQLException {
+ }
+
+ public void setString(int parameterIndex, String theString) throws SQLException {
+ }
+
+ public void setTime(int parameterIndex, Time theTime, Calendar theCalendar)
+ throws SQLException {
+ }
+
+ public void setTime(int parameterIndex, Time theTime) throws SQLException {
+ }
+
+ public void setTimestamp(int parameterIndex, Timestamp theTimestamp, Calendar theCalendar)
+ throws SQLException {
+ }
+
+ public void setTimestamp(int parameterIndex, Timestamp theTimestamp) throws SQLException {
+ }
+
+ public void setTransactionIsolation(int level) throws SQLException {
+ }
+
+ public void setType(int type) throws SQLException {
+ }
+
+ public void setTypeMap(Map<String, Class<?>> theTypeMap) throws SQLException {
+ }
+
+ public void setUrl(String theURL) throws SQLException {
+ }
+
+ public void setUsername(String theUsername) throws SQLException {
+ }
+
+ public boolean absolute(int row) throws SQLException {
+ return false;
+ }
+
+ public void afterLast() throws SQLException {
+ }
+
+ public void beforeFirst() throws SQLException {
+ }
+
+ public void cancelRowUpdates() throws SQLException {
+ }
+
+ public void clearWarnings() throws SQLException {
+ }
+
+ public void close() throws SQLException {
+ }
+
+ public void deleteRow() throws SQLException {
+ }
+
+ public int findColumn(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public boolean first() throws SQLException {
+ return false;
+ }
+
+ public Array getArray(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Array getArray(String colName) throws SQLException {
+ return null;
+ }
+
+ public InputStream getAsciiStream(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public InputStream getAsciiStream(String columnName) throws SQLException {
+ return null;
+ }
+
+ public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException {
+ return null;
+ }
+
+ public BigDecimal getBigDecimal(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException {
+ return null;
+ }
+
+ public BigDecimal getBigDecimal(String columnName) throws SQLException {
+ return null;
+ }
+
+ public InputStream getBinaryStream(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public InputStream getBinaryStream(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Blob getBlob(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Blob getBlob(String columnName) throws SQLException {
+ return null;
+ }
+
+ public boolean getBoolean(int columnIndex) throws SQLException {
+ return false;
+ }
+
+ public boolean getBoolean(String columnName) throws SQLException {
+ return false;
+ }
+
+ public byte getByte(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public byte getByte(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public byte[] getBytes(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public byte[] getBytes(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Reader getCharacterStream(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Reader getCharacterStream(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Clob getClob(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Clob getClob(String colName) throws SQLException {
+ return null;
+ }
+
+ public int getConcurrency() throws SQLException {
+ return 0;
+ }
+
+ public String getCursorName() throws SQLException {
+ return null;
+ }
+
+ public Date getDate(int columnIndex, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Date getDate(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Date getDate(String columnName, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Date getDate(String columnName) throws SQLException {
+ return null;
+ }
+
+ public double getDouble(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public double getDouble(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public int getFetchDirection() throws SQLException {
+ return 0;
+ }
+
+ public int getFetchSize() throws SQLException {
+ return 0;
+ }
+
+ public float getFloat(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public float getFloat(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public int getInt(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public int getInt(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public long getLong(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public long getLong(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public ResultSetMetaData getMetaData() throws SQLException {
+ return null;
+ }
+
+ public Object getObject(int columnIndex, Map<String, Class<?>> map) throws SQLException {
+ return null;
+ }
+
+ public Object getObject(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Object getObject(String columnName, Map<String, Class<?>> map) throws SQLException {
+ return null;
+ }
+
+ public Object getObject(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Ref getRef(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Ref getRef(String colName) throws SQLException {
+ return null;
+ }
+
+ public int getRow() throws SQLException {
+ return 0;
+ }
+
+ public short getShort(int columnIndex) throws SQLException {
+ return 0;
+ }
+
+ public short getShort(String columnName) throws SQLException {
+ return 0;
+ }
+
+ public Statement getStatement() throws SQLException {
+ return null;
+ }
+
+ public String getString(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public String getString(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Time getTime(int columnIndex, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Time getTime(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Time getTime(String columnName, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Time getTime(String columnName) throws SQLException {
+ return null;
+ }
+
+ public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Timestamp getTimestamp(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException {
+ return null;
+ }
+
+ public Timestamp getTimestamp(String columnName) throws SQLException {
+ return null;
+ }
+
+ public int getType() throws SQLException {
+ return 0;
+ }
+
+ public InputStream getUnicodeStream(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public InputStream getUnicodeStream(String columnName) throws SQLException {
+ return null;
+ }
+
+ public URL getURL(int columnIndex) throws SQLException {
+ return null;
+ }
+
+ public URL getURL(String columnName) throws SQLException {
+ return null;
+ }
+
+ public SQLWarning getWarnings() throws SQLException {
+ return null;
+ }
+
+ public void insertRow() throws SQLException {
+ }
+
+ public boolean isAfterLast() throws SQLException {
+ return false;
+ }
+
+ public boolean isBeforeFirst() throws SQLException {
+ return false;
+ }
+
+ public boolean isFirst() throws SQLException {
+ return false;
+ }
+
+ public boolean isLast() throws SQLException {
+ return false;
+ }
+
+ public boolean last() throws SQLException {
+ return false;
+ }
+
+ public void moveToCurrentRow() throws SQLException {
+ }
+
+ public void moveToInsertRow() throws SQLException {
+ }
+
+ public boolean next() throws SQLException {
+ return false;
+ }
+
+ public boolean previous() throws SQLException {
+ return false;
+ }
+
+ public void refreshRow() throws SQLException {
+ }
+
+ public boolean relative(int rows) throws SQLException {
+ return false;
+ }
+
+ public boolean rowDeleted() throws SQLException {
+ return false;
+ }
+
+ public boolean rowInserted() throws SQLException {
+ return false;
+ }
+
+ public boolean rowUpdated() throws SQLException {
+ return false;
+ }
+
+ public void setFetchDirection(int direction) throws SQLException {
+ }
+
+ public void setFetchSize(int rows) throws SQLException {
+ }
+
+ public void updateArray(int columnIndex, Array x) throws SQLException {
+ }
+
+ public void updateArray(String columnName, Array x) throws SQLException {
+ }
+
+ public void updateAsciiStream(int columnIndex, InputStream x, int length)
+ throws SQLException {
+ }
+
+ public void updateAsciiStream(String columnName, InputStream x, int length)
+ throws SQLException {
+ }
+
+ public void updateBigDecimal(int columnIndex, BigDecimal x) throws SQLException {
+ }
+
+ public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException {
+ }
+
+ public void updateBinaryStream(int columnIndex, InputStream x, int length)
+ throws SQLException {
+ }
+
+ public void updateBinaryStream(String columnName, InputStream x, int length)
+ throws SQLException {
+ }
+
+ public void updateBlob(int columnIndex, Blob x) throws SQLException {
+ }
+
+ public void updateBlob(String columnName, Blob x) throws SQLException {
+ }
+
+ public void updateBoolean(int columnIndex, boolean x) throws SQLException {
+ }
+
+ public void updateBoolean(String columnName, boolean x) throws SQLException {
+ }
+
+ public void updateByte(int columnIndex, byte x) throws SQLException {
+ }
+
+ public void updateByte(String columnName, byte x) throws SQLException {
+ }
+
+ public void updateBytes(int columnIndex, byte[] x) throws SQLException {
+ }
+
+ public void updateBytes(String columnName, byte[] x) throws SQLException {
+ }
+
+ public void updateCharacterStream(int columnIndex, Reader x, int length)
+ throws SQLException {
+ }
+
+ public void updateCharacterStream(String columnName, Reader reader, int length)
+ throws SQLException {
+ }
+
+ public void updateClob(int columnIndex, Clob x) throws SQLException {
+ }
+
+ public void updateClob(String columnName, Clob x) throws SQLException {
+ }
+
+ public void updateDate(int columnIndex, Date x) throws SQLException {
+ }
+
+ public void updateDate(String columnName, Date x) throws SQLException {
+ }
+
+ public void updateDouble(int columnIndex, double x) throws SQLException {
+ }
+
+ public void updateDouble(String columnName, double x) throws SQLException {
+ }
+
+ public void updateFloat(int columnIndex, float x) throws SQLException {
+ }
+
+ public void updateFloat(String columnName, float x) throws SQLException {
+ }
+
+ public void updateInt(int columnIndex, int x) throws SQLException {
+ }
+
+ public void updateInt(String columnName, int x) throws SQLException {
+ }
+
+ public void updateLong(int columnIndex, long x) throws SQLException {
+ }
+
+ public void updateLong(String columnName, long x) throws SQLException {
+ }
+
+ public void updateNull(int columnIndex) throws SQLException {
+ }
+
+ public void updateNull(String columnName) throws SQLException {
+ }
+
+ public void updateObject(int columnIndex, Object x, int scale) throws SQLException {
+ }
+
+ public void updateObject(int columnIndex, Object x) throws SQLException {
+ }
+
+ public void updateObject(String columnName, Object x, int scale) throws SQLException {
+ }
+
+ public void updateObject(String columnName, Object x) throws SQLException {
+ }
+
+ public void updateRef(int columnIndex, Ref x) throws SQLException {
+ }
+
+ public void updateRef(String columnName, Ref x) throws SQLException {
+ }
+
+ public void updateRow() throws SQLException {
+ }
+
+ public void updateShort(int columnIndex, short x) throws SQLException {
+ }
+
+ public void updateShort(String columnName, short x) throws SQLException {
+ }
+
+ public void updateString(int columnIndex, String x) throws SQLException {
+ }
+
+ public void updateString(String columnName, String x) throws SQLException {
+ }
+
+ public void updateTime(int columnIndex, Time x) throws SQLException {
+ }
+
+ public void updateTime(String columnName, Time x) throws SQLException {
+ }
+
+ public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException {
+ }
+
+ public void updateTimestamp(String columnName, Timestamp x) throws SQLException {
+ }
+
+ public boolean wasNull() throws SQLException {
+ return false;
+ }
+}
diff --git a/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/RowSetEventTest.java b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/RowSetEventTest.java
new file mode 100644
index 0000000..e78280b
--- /dev/null
+++ b/sql/src/test/java/org/apache/harmony/sql/tests/javax/sql/RowSetEventTest.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.harmony.sql.tests.javax.sql;
+
+import javax.sql.RowSetEvent;
+import junit.framework.TestCase;
+
+public class RowSetEventTest extends TestCase {
+
+ public void testConstructor() {
+ try {
+ new RowSetEvent(null);
+ fail("illegal argument exception expected");
+ } catch (IllegalArgumentException e) {
+ }
+
+ Impl_RowSet irs = new Impl_RowSet();
+ RowSetEvent rse = new RowSetEvent(irs);
+ assertSame(irs, rse.getSource());
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/AllTests.java b/sql/src/test/java/tests/java/sql/AllTests.java
new file mode 100644
index 0000000..8ee9e9a
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/AllTests.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * This is autogenerated source file. Includes tests for package tests.java.sql;
+ */
+
+public class AllTests {
+
+ public static void main(String[] args) {
+ junit.textui.TestRunner.run(AllTests.suite());
+ }
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All tests for package tests.java.sql;");
+ // $JUnit-BEGIN$
+
+ suite.addTest(DatabaseMetaDataTest.suite());
+ suite.addTest(MultiThreadAccessTest.suite());
+ suite.addTest(StressTest.suite());
+ suite.addTest(UpdateFunctionalityTest.suite());
+ suite.addTest(SelectFunctionalityTest.suite());
+ suite.addTest(UpdateFunctionalityTest2.suite());
+ suite.addTest(DeleteFunctionalityTest.suite());
+ suite.addTest(InsertFunctionalityTest.suite());
+
+ // $JUnit-END$
+ return suite;
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java b/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java
new file mode 100755
index 0000000..42ae249
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/DatabaseMetaDataTest.java
@@ -0,0 +1,2191 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+import java.util.Arrays;
+import java.util.HashSet;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class DatabaseMetaDataTest extends TestCase {
+ private static String VIEW_NAME = "myView";
+
+ private static String CREATE_VIEW_QUERY = "CREATE VIEW " + VIEW_NAME
+ + " AS SELECT * FROM " + DatabaseCreator.TEST_TABLE1;
+
+ private static String DROP_VIEW_QUERY = "DROP VIEW " + VIEW_NAME;
+
+ private static Connection conn;
+
+ private static DatabaseMetaData meta;
+
+ private static Statement statement;
+
+ private static Statement statementForward;
+
+ private static int id = 1;
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ DatabaseMetaDataTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ statementForward = conn.createStatement(
+ ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_UPDATABLE);
+ meta = conn.getMetaData();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ statement.close();
+ statementForward.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ ResultSet userTab = meta.getTables(null, null, null, null);
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE3)) {
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ } else if (tableName.equals(VIEW_NAME)) {
+ statement.execute(DROP_VIEW_QUERY);
+ }
+ }
+ userTab.close();
+ statement.execute(DatabaseCreator.CREATE_TABLE3);
+ statement.execute(DatabaseCreator.CREATE_TABLE1);
+ statement.execute(CREATE_VIEW_QUERY);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ statement.execute(DROP_VIEW_QUERY);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#allProceduresAreCallable()
+ */
+ public void test_allProceduresAreCallable() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#allTablesAreSelectable()
+ *
+ * // TODO GRANT and REVOKE are not supported
+ */
+/* public void test_allTablesAreSelectable() throws SQLException {
+ // grant SELECT privileges
+
+ String query = "GRANT CREATE, SELECT ON " + DatabaseCreator.TEST_TABLE1
+ + " TO " + Support_SQL.sqlUser;
+ statement.execute(query);
+ Connection userConn = Support_SQL.getConnection(Support_SQL.sqlUrl,
+ Support_SQL.sqlUser, Support_SQL.sqlUser);
+ DatabaseMetaData userMeta = userConn.getMetaData();
+ ResultSet userTab = userMeta.getTables(null, null, null, null);
+
+ assertTrue("Tables are not obtained", userTab.next());
+ assertEquals("Incorrect name of obtained table",
+ DatabaseCreator.TEST_TABLE1.toLowerCase(), userTab.getString(
+ "TABLE_NAME").toLowerCase());
+ assertTrue("Not all of obtained tables are selectable", userMeta
+ .allTablesAreSelectable());
+
+ userTab.close();
+ // revoke SELECT privileges
+ query = "REVOKE SELECT ON " + DatabaseCreator.TEST_TABLE1 + " FROM "
+ + Support_SQL.sqlUser;
+ statement.execute(query);
+
+ userTab = userMeta.getTables(null, null, null, null);
+
+ assertTrue("Tables are not obtained", userTab.next());
+ assertEquals("Incorrect name of obtained table",
+ DatabaseCreator.TEST_TABLE1.toLowerCase(), userTab.getString(
+ "TABLE_NAME").toLowerCase());
+ assertFalse("No SELECT privileges", userMeta.allTablesAreSelectable());
+
+ userTab.close();
+ // revoke CREATE privileges
+ query = "REVOKE CREATE ON " + DatabaseCreator.TEST_TABLE1 + " FROM "
+ + Support_SQL.sqlUser;
+ statement.execute(query);
+ userConn.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#dataDefinitionCausesTransactionCommit()
+ */
+ public void test_dataDefinitionCausesTransactionCommit()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#dataDefinitionIgnoredInTransactions()
+ */
+ public void test_dataDefinitionIgnoredInTransactions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#deletesAreDetected(int)
+ */
+ public void test_deletesAreDetectedI() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#doesMaxRowSizeIncludeBlobs()
+ */
+ public void test_doesMaxRowSizeIncludeBlobs() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getAttributes(java.lang.String,
+ * java.lang.String, java.lang.String, java.lang.String)
+ */
+ public void test_getAttributesLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getBestRowIdentifier(java.lang.String,
+ * java.lang.String, java.lang.String, int, boolean)
+ */
+ public void test_getBestRowIdentifierLjava_lang_StringLjava_lang_StringLjava_lang_StringIZ()
+ throws SQLException {
+ ResultSet result = statementForward.executeQuery("SELECT * FROM "
+ + DatabaseCreator.TEST_TABLE1);
+
+ // TODO not supported
+// try {
+// result.moveToInsertRow();
+// result.updateInt("id", 1234567);
+// result.updateString("field1", "test1");
+// result.insertRow();
+// } catch (SQLException e) {
+// fail("Unexpected SQLException " + e.toString());
+// }
+
+ result.close();
+
+ ResultSet rs = meta.getBestRowIdentifier(null, null,
+ DatabaseCreator.TEST_TABLE1, DatabaseMetaData.bestRowSession,
+ true);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 8, col);
+ String[] columnNames = { "SCOPE", "COLUMN_NAME", "DATA_TYPE",
+ "TYPE_NAME", "COLUMN_SIZE", "BUFFER_LENGTH", "DECIMAL_DIGITS",
+ "PSEUDO_COLUMN" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+ assertEquals("Incorrect scope", DatabaseMetaData.bestRowSession, rs
+ .getShort("SCOPE"));
+// assertEquals("Incorrect column name", "id", rs.getString("COLUMN_NAME"));
+ assertEquals("Incorrect data type", java.sql.Types.INTEGER, rs
+ .getInt("DATA_TYPE"));
+ assertEquals("Incorrect type name", "INTEGER", rs.getString("TYPE_NAME"));
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getCatalogSeparator()
+ */
+ public void test_getCatalogSeparator() throws SQLException {
+ assertTrue("Incorrect catalog separator", "".equals(meta
+ .getCatalogSeparator().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getCatalogTerm()
+ */
+ public void test_getCatalogTerm() throws SQLException {
+ assertTrue("Incorrect catalog term", "".equals(meta
+ .getCatalogSeparator().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getCatalogs()
+ */
+ public void test_getCatalogs() throws SQLException {
+ ResultSet rs = meta.getCatalogs();
+ // TODO getCatalog is not supported
+// while (rs.next()) {
+ //if (rs.getString("TABLE_CAT").equalsIgnoreCase(conn.getCatalog())) {
+ // rs.close();
+ // return;
+ //}
+// }
+ rs.close();
+// fail("Incorrect a set of catalogs");
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getColumnPrivileges(java.lang.String,
+ * java.lang.String, java.lang.String, java.lang.String)
+ *
+ * TODO GRANT is not supported
+ */
+/* public void test_getColumnPrivilegesLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ ResultSet rs = meta.getColumnPrivileges(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1, "id");
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertFalse("Rows are obtained", rs.next());
+ rs.close();
+
+ String query = "GRANT REFERENCES(id) ON " + DatabaseCreator.TEST_TABLE1
+ + " TO " + Support_SQL.sqlLogin;
+ statement.execute(query);
+
+ rs = meta.getColumnPrivileges(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1, "id");
+ rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 8, col);
+ String[] columnNames = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
+ "COLUMN_NAME", "GRANTOR", "GRANTEE", "PRIVILEGE",
+ "IS_GRANTABLE" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+ assertEquals("Incorrect table catalogue", conn.getCatalog(), rs
+ .getString("TABLE_CAT").toLowerCase());
+ assertEquals("Incorrect table schema", null, rs
+ .getString("TABLE_SCHEM"));
+ assertEquals("Incorrect table name", DatabaseCreator.TEST_TABLE1, rs
+ .getString("TABLE_NAME").toLowerCase());
+ assertEquals("Incorrect column name", "id", rs.getString("COLUMN_NAME")
+ .toLowerCase());
+ assertEquals("Incorrect grantor", Support_SQL.sqlLogin + "@"
+ + Support_SQL.sqlHost, rs.getString("GRANTOR").toLowerCase());
+ assertTrue("Incorrect grantee",
+ rs.getString("GRANTEE").indexOf("root") != -1);
+ assertEquals("Incorrect privilege", "references", rs.getString(
+ "PRIVILEGE").toLowerCase());
+
+ query = "REVOKE REFERENCES(id) ON " + DatabaseCreator.TEST_TABLE1
+ + " FROM " + Support_SQL.sqlLogin;
+ statement.execute(query);
+ rs.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#getConnection()
+ */
+ public void test_getConnection() throws SQLException {
+ assertEquals("Incorrect connection value", conn, meta.getConnection());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getCrossReference(java.lang.String,
+ * java.lang.String, java.lang.String, java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getCrossReferenceLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ ResultSet rs = meta.getCrossReference(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE3, conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 14, col);
+ String[] columnNames = { "PKTABLE_CAT", "PKTABLE_SCHEM",
+ "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT",
+ "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
+ "UPDATE_RULE", "DELETE_RULE", "FK_NAME", "PK_NAME",
+ "DEFERRABILITY" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+// TODO getCatalog is not supported
+// assertEquals("Incorrect primary key table catalog", conn.getCatalog(),
+// rs.getString("PKTABLE_CAT"));
+ assertEquals("Incorrect primary key table schema", "", rs
+ .getString("PKTABLE_SCHEM"));
+ assertEquals("Incorrect primary key table name",
+ DatabaseCreator.TEST_TABLE3, rs.getString("PKTABLE_NAME"));
+ assertEquals("Incorrect primary key column name", "fkey", rs
+ .getString("PKCOLUMN_NAME"));
+ // TODO getCatalog is not supported
+// assertEquals("Incorrect foreign key table catalog", conn.getCatalog(),
+// rs.getString("FKTABLE_CAT"));
+ assertEquals("Incorrect foreign key table schema", "", rs
+ .getString("FKTABLE_SCHEM"));
+ assertEquals("Incorrect foreign key table name",
+ DatabaseCreator.TEST_TABLE1, rs.getString("FKTABLE_NAME"));
+ assertEquals("Incorrect foreign key column name", "fk", rs
+ .getString("FKCOLUMN_NAME"));
+ assertEquals("Incorrect sequence number within foreign key", 1, rs
+ .getShort("KEY_SEQ"));
+ assertEquals("Incorrect update rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("UPDATE_RULE"));
+ assertEquals("Incorrect delete rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("DELETE_RULE"));
+ assertNull("Incorrect foreign key name", rs.getString("FK_NAME"));
+ assertNull("Incorrect primary key name", rs.getString("PK_NAME"));
+ assertEquals("Incorrect deferrability",
+ DatabaseMetaData.importedKeyNotDeferrable, rs
+ .getShort("DEFERRABILITY"));
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDatabaseMajorVersion()
+ */
+ public void test_getDatabaseMajorVersion() throws SQLException {
+ assertTrue("Incorrdct database major version", meta
+ .getDatabaseMajorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDatabaseMinorVersion()
+ */
+ public void test_getDatabaseMinorVersion() throws SQLException {
+ assertTrue("Incorrect database minor version", meta
+ .getDatabaseMinorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDatabaseProductName()
+ */
+ public void test_getDatabaseProductName() throws SQLException {
+ assertTrue("Incorrect database product name", !"".equals(meta
+ .getDatabaseProductName().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDatabaseProductVersion()
+ */
+ public void test_getDatabaseProductVersion() throws SQLException {
+ assertTrue("Incorrect database product version", !"".equals(meta
+ .getDatabaseProductVersion().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDefaultTransactionIsolation()
+ */
+ public void test_getDefaultTransactionIsolation() throws SQLException {
+ int defaultLevel = meta.getDefaultTransactionIsolation();
+ switch (defaultLevel) {
+ case Connection.TRANSACTION_NONE:
+ case Connection.TRANSACTION_READ_COMMITTED:
+ case Connection.TRANSACTION_READ_UNCOMMITTED:
+ case Connection.TRANSACTION_REPEATABLE_READ:
+ case Connection.TRANSACTION_SERIALIZABLE:
+ // these levels are OK
+ break;
+ default:
+ fail("Incorrect value of default transaction isolation level");
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDriverMajorVersion()
+ */
+ public void test_getDriverMajorVersion() {
+ assertTrue("Incorrect driver major version", meta
+ .getDriverMajorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDriverMinorVersion()
+ */
+ public void test_getDriverMinorVersion() {
+ assertTrue("Incorrect driver minor version", meta
+ .getDriverMinorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDriverName()
+ */
+ public void test_getDriverName() throws SQLException {
+ assertTrue("Incorrect driver name", !"".equals(meta.getDriverName()
+ .trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getDriverVersion()
+ */
+ public void test_getDriverVersion() throws SQLException {
+ assertTrue("Incorrect driver version", !"".equals(meta
+ .getDriverVersion().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getExportedKeys(java.lang.String,
+ * java.lang.String, java.lang.String)
+ *
+ * TODO getCatalog is not supported
+ */
+/* public void test_getExportedKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ ResultSet rs = meta.getExportedKeys(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE3);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 14, col);
+ String[] columnNames = { "PKTABLE_CAT", "PKTABLE_SCHEM",
+ "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT",
+ "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
+ "UPDATE_RULE", "DELETE_RULE", "FK_NAME", "PK_NAME",
+ "DEFERRABILITY" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+
+ assertEquals("Incorrect primary key table catalog", conn.getCatalog(),
+ rs.getString("PKTABLE_CAT"));
+ assertEquals("Incorrect primary key table schema", null, rs
+ .getString("PKTABLE_SCHEM"));
+ assertEquals("Incorrect primary key table name",
+ DatabaseCreator.TEST_TABLE3, rs.getString("PKTABLE_NAME"));
+ assertEquals("Incorrect primary key column name", "fk", rs
+ .getString("PKCOLUMN_NAME"));
+ assertEquals("Incorrect foreign key table catalog", conn.getCatalog(),
+ rs.getString("FKTABLE_CAT"));
+ assertEquals("Incorrect foreign key table schema", null, rs
+ .getString("FKTABLE_SCHEM"));
+ assertEquals("Incorrect foreign key table name",
+ DatabaseCreator.TEST_TABLE1, rs.getString("FKTABLE_NAME"));
+ assertEquals("Incorrect foreign key column name", "fkey", rs
+ .getString("FKCOLUMN_NAME"));
+ assertEquals("Incorrect sequence number within foreign key", 1, rs
+ .getShort("KEY_SEQ"));
+ assertEquals("Incorrect update rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("UPDATE_RULE"));
+ assertEquals("Incorrect delete rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("DELETE_RULE"));
+ assertNotNull("Incorrect foreign key name", rs.getString("FK_NAME"));
+ assertEquals("Incorrect primary key name", null, rs
+ .getString("PK_NAME"));
+ assertEquals("Incorrect deferrability",
+ DatabaseMetaData.importedKeyNotDeferrable, rs
+ .getShort("DEFERRABILITY"));
+ rs.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#getExtraNameCharacters()
+ */
+ public void test_getExtraNameCharacters() throws SQLException {
+ assertNotNull("Incorrect extra name characters", meta
+ .getExtraNameCharacters());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getIdentifierQuoteString()
+ */
+ public void test_getIdentifierQuoteString() throws SQLException {
+ assertTrue("Incorrect identifier of quoted string", !"".equals(meta
+ .getIdentifierQuoteString().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getImportedKeys(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getImportedKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ ResultSet rs = meta.getImportedKeys(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 14, col);
+ String[] columnNames = { "PKTABLE_CAT", "PKTABLE_SCHEM",
+ "PKTABLE_NAME", "PKCOLUMN_NAME", "FKTABLE_CAT",
+ "FKTABLE_SCHEM", "FKTABLE_NAME", "FKCOLUMN_NAME", "KEY_SEQ",
+ "UPDATE_RULE", "DELETE_RULE", "FK_NAME", "PK_NAME",
+ "DEFERRABILITY" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+// TODO getCatalog is not supported
+// assertEquals("Incorrect primary key table catalog", conn.getCatalog(),
+// rs.getString("PKTABLE_CAT"));
+ assertEquals("Incorrect primary key table schema", "", rs
+ .getString("PKTABLE_SCHEM"));
+ assertEquals("Incorrect primary key table name",
+ DatabaseCreator.TEST_TABLE3, rs.getString("PKTABLE_NAME"));
+ assertEquals("Incorrect primary key column name", "fkey", rs
+ .getString("PKCOLUMN_NAME"));
+// assertEquals("Incorrect foreign key table catalog", conn.getCatalog(),
+// rs.getString("FKTABLE_CAT"));
+ assertEquals("Incorrect foreign key table schema", "", rs
+ .getString("FKTABLE_SCHEM"));
+ assertEquals("Incorrect foreign key table name",
+ DatabaseCreator.TEST_TABLE1, rs.getString("FKTABLE_NAME"));
+ assertEquals("Incorrect foreign key column name", "fk", rs
+ .getString("FKCOLUMN_NAME"));
+ assertEquals("Incorrect sequence number within foreign key", 1, rs
+ .getShort("KEY_SEQ"));
+ assertEquals("Incorrect update rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("UPDATE_RULE"));
+ assertEquals("Incorrect delete rule value",
+ DatabaseMetaData.importedKeyNoAction, rs
+ .getShort("DELETE_RULE"));
+ // assertNotNull("Incorrect foreign key name", rs.getString("FK_NAME"));
+ assertEquals("Incorrect primary key name", null, rs
+ .getString("PK_NAME"));
+ assertEquals("Incorrect deferrability",
+ DatabaseMetaData.importedKeyNotDeferrable, rs
+ .getShort("DEFERRABILITY"));
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getIndexInfo(java.lang.String,
+ * java.lang.String, java.lang.String, boolean, boolean)
+ *
+ * TODO getCatalog is not supported
+ */
+/* public void test_getIndexInfoLjava_lang_StringLjava_lang_StringLjava_lang_StringZZ()
+ throws SQLException {
+ boolean unique = false;
+ ResultSet rs = meta.getIndexInfo(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1, unique, true);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 13, col);
+ String[] columnNames = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
+ "NON_UNIQUE", "INDEX_QUALIFIER", "INDEX_NAME", "TYPE",
+ "ORDINAL_POSITION", "COLUMN_NAME", "ASC_OR_DESC",
+ "CARDINALITY", "PAGES", "FILTER_CONDITION" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+
+ assertEquals("Incorrect table catalog", conn.getCatalog(), rs
+ .getString("TABLE_CAT"));
+ assertEquals("Incorrect table schema", null, rs
+ .getString("TABLE_SCHEM"));
+ assertEquals("Incorrect table name", DatabaseCreator.TEST_TABLE1, rs
+ .getString("TABLE_NAME"));
+ assertEquals("Incorrect state of uniquess", unique, rs
+ .getBoolean("NON_UNIQUE"));
+ assertEquals("Incorrect index catalog", "", rs
+ .getString("INDEX_QUALIFIER"));
+ assertEquals("Incorrect index name", "primary", rs.getString(
+ "INDEX_NAME").toLowerCase());
+ assertEquals("Incorrect index type", DatabaseMetaData.tableIndexOther,
+ rs.getShort("TYPE"));
+ assertEquals("Incorrect column sequence number within index", 1, rs
+ .getShort("ORDINAL_POSITION"));
+ assertEquals("Incorrect column name", "id", rs.getString("COLUMN_NAME"));
+ assertEquals("Incorrect column sort sequence", "a", rs.getString(
+ "ASC_OR_DESC").toLowerCase());
+ assertEquals("Incorrect cardinality", 1, rs.getInt("CARDINALITY"));
+ assertEquals("Incorrect value of pages", 0, rs.getInt("PAGES"));
+ assertEquals("Incorrect filter condition", null, rs
+ .getString("FILTER_CONDITION"));
+ rs.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#getJDBCMajorVersion()
+ */
+ public void test_getJDBCMajorVersion() throws SQLException {
+ assertTrue("Incorrect JDBC major version",
+ meta.getJDBCMajorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getJDBCMinorVersion()
+ */
+ public void test_getJDBCMinorVersion() throws SQLException {
+ assertTrue("Incorrect JDBC minor version",
+ meta.getJDBCMinorVersion() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxBinaryLiteralLength()
+ */
+ public void test_getMaxBinaryLiteralLength() throws SQLException {
+ assertTrue("Incorrect binary literal length", meta
+ .getMaxBinaryLiteralLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxCatalogNameLength()
+ */
+ public void test_getMaxCatalogNameLength() throws SQLException {
+ assertTrue("Incorrect name length", meta.getMaxCatalogNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxCharLiteralLength()
+ */
+ public void test_getMaxCharLiteralLength() throws SQLException {
+ assertTrue("Incorrect char literal length", meta
+ .getMaxCharLiteralLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnNameLength()
+ */
+ public void test_getMaxColumnNameLength() throws SQLException {
+ assertTrue("Incorrect column name length", meta
+ .getMaxColumnNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnsInGroupBy()
+ */
+ public void test_getMaxColumnsInGroupBy() throws SQLException {
+ assertTrue("Incorrect number of columns",
+ meta.getMaxColumnsInGroupBy() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnsInIndex()
+ */
+ public void test_getMaxColumnsInIndex() throws SQLException {
+ assertTrue("Incorrect number of columns",
+ meta.getMaxColumnsInIndex() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnsInOrderBy()
+ */
+ public void test_getMaxColumnsInOrderBy() throws SQLException {
+ assertTrue("Incorrect number of columns",
+ meta.getMaxColumnsInOrderBy() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnsInSelect()
+ */
+ public void test_getMaxColumnsInSelect() throws SQLException {
+ assertTrue("Incorrect number of columns",
+ meta.getMaxColumnsInSelect() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxColumnsInTable()
+ */
+ public void test_getMaxColumnsInTable() throws SQLException {
+ assertTrue("Incorrect number of columns",
+ meta.getMaxColumnsInTable() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxConnections()
+ */
+ public void test_getMaxConnections() throws SQLException {
+ assertTrue("Incorrect number of connections",
+ meta.getMaxConnections() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxCursorNameLength()
+ */
+ public void test_getMaxCursorNameLength() throws SQLException {
+ int nameLength = meta.getMaxCursorNameLength();
+ if (nameLength > 0) {
+ try {
+ statement.setCursorName(new String(new byte[nameLength + 1]));
+ fail("Expected SQLException was not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ } else if (nameLength < 0) {
+ fail("Incorrect length of cursor name");
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxIndexLength()
+ */
+ public void test_getMaxIndexLength() throws SQLException {
+ assertTrue("Incorrect length of index", meta.getMaxIndexLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxProcedureNameLength()
+ */
+ public void test_getMaxProcedureNameLength() throws SQLException {
+ assertTrue("Incorrect length of procedure name", meta
+ .getMaxProcedureNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxRowSize()
+ */
+ public void test_getMaxRowSize() throws SQLException {
+ assertTrue("Incorrect size of row", meta.getMaxRowSize() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxSchemaNameLength()
+ */
+ public void test_getMaxSchemaNameLength() throws SQLException {
+ assertTrue("Incorrect length of schema name", meta
+ .getMaxSchemaNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxStatementLength()
+ */
+ public void test_getMaxStatementLength() throws SQLException {
+ assertTrue("Incorrect length of statement", meta
+ .getMaxStatementLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxStatements()
+ */
+ public void test_getMaxStatements() throws SQLException {
+ assertTrue("Incorrect number of statements",
+ meta.getMaxStatements() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxTableNameLength()
+ */
+ public void test_getMaxTableNameLength() throws SQLException {
+ assertTrue("Incorrect length of table name", meta
+ .getMaxTableNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxTablesInSelect()
+ */
+ public void test_getMaxTablesInSelect() throws SQLException {
+ assertTrue("Incorrect number of tables",
+ meta.getMaxTablesInSelect() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getMaxUserNameLength()
+ */
+ public void test_getMaxUserNameLength() throws SQLException {
+ assertTrue("Incorrect length of user name",
+ meta.getMaxUserNameLength() >= 0);
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getNumericFunctions()
+ */
+ public void test_getNumericFunctions() throws SQLException {
+ assertTrue("Incorrect list of math functions", "".equals(meta
+ .getNumericFunctions().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getPrimaryKeys(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getPrimaryKeysLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ ResultSet rs = meta.getPrimaryKeys(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 6, col);
+ String[] columnNames = { "TABLE_CAT", "TABLE_SCHEM", "TABLE_NAME",
+ "COLUMN_NAME", "KEY_SEQ", "PK_NAME" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+// assertEquals("Incorrect table catalogue", conn.getCatalog(), rs
+// .getString("TABLE_CAT").toLowerCase());
+ assertEquals("Incorrect table schema", "", rs
+ .getString("TABLE_SCHEM"));
+ assertEquals("Incorrect table name", DatabaseCreator.TEST_TABLE1, rs
+ .getString("TABLE_NAME").toLowerCase());
+ assertEquals("Incorrect column name", "id", rs.getString("COLUMN_NAME")
+ .toLowerCase());
+ assertEquals("Incorrect sequence number", 1, rs.getShort("KEY_SEQ"));
+ // assertEquals("Incorrect primary key name", "primary", rs.getString(
+ // "PK_NAME").toLowerCase());
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getProcedureColumns(java.lang.String,
+ * java.lang.String, java.lang.String, java.lang.String)
+ */
+ public void test_getProcedureColumnsLjava_lang_StringLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getProcedureTerm()
+ */
+ public void test_getProcedureTerm() throws SQLException {
+ assertTrue("Incorrect procedure term", "".equals(meta
+ .getProcedureTerm().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getProcedures(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getProceduresLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getResultSetHoldability()
+ */
+ public void test_getResultSetHoldability() throws SQLException {
+ int hdb = meta.getResultSetHoldability();
+ switch (hdb) {
+ case ResultSet.HOLD_CURSORS_OVER_COMMIT:
+ case ResultSet.CLOSE_CURSORS_AT_COMMIT:
+ // these holdabilities are OK
+ break;
+ default:
+ fail("Incorrect value of holdability");
+ }
+ assertFalse("Incorrect result set holdability", meta
+ .supportsResultSetHoldability(hdb));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSQLKeywords()
+ */
+ public void test_getSQLKeywords() throws SQLException {
+ assertTrue("Incorrect SQL keywords", !"".equals(meta.getSQLKeywords()
+ .trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSQLStateType()
+ */
+ public void test_getSQLStateType() throws SQLException {
+ int type = meta.getSQLStateType();
+ switch (type) {
+ case DatabaseMetaData.sqlStateSQL99:
+ case DatabaseMetaData.sqlStateXOpen:
+ // these types are OK
+ break;
+ default:
+ fail("Incorrect SQL state types");
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSchemaTerm()
+ */
+ public void test_getSchemaTerm() throws SQLException {
+ assertNotNull("Incorrect schema term", meta.getSchemaTerm());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSchemas()
+ */
+ public void test_getSchemas() throws SQLException {
+ ResultSet rs = meta.getSchemas();
+ ResultSetMetaData rsmd = rs.getMetaData();
+ assertTrue("Rows do not obtained", rs.next());
+ int col = rsmd.getColumnCount();
+ assertEquals("Incorrect number of columns", 1, col);
+ String[] columnNames = { "TABLE_SCHEM", "TABLE_CATALOG" };
+ for (int c = 1; c <= col; ++c) {
+ assertEquals("Incorrect column name", columnNames[c - 1], rsmd
+ .getColumnName(c));
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSearchStringEscape()
+ */
+ public void test_getSearchStringEscape() throws SQLException {
+ assertTrue("Incorrect search string escape", !"".equals(meta
+ .getSearchStringEscape().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getStringFunctions()
+ */
+ public void test_getStringFunctions() throws SQLException {
+ assertTrue("Incorrect string functions", "".equals(meta
+ .getStringFunctions().trim()));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getSuperTables(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getSuperTablesLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getSuperTypes(java.lang.String,
+ * java.lang.String, java.lang.String)
+ */
+ public void test_getSuperTypesLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getSystemFunctions()
+ */
+ public void test_getSystemFunctions() throws SQLException {
+ assertTrue("No system function exist", meta.getSystemFunctions()
+ .trim().equals(""));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getTablePrivileges(java.lang.String,
+ * java.lang.String, java.lang.String)
+ *
+ * TODO GRANT is not supported
+ */
+/* public void test_getTablePrivilegesLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ // case 1. Get privileges when no privilegies exist for one table
+ ResultSet privileges = meta.getTablePrivileges(conn.getCatalog(), "%",
+ DatabaseCreator.TEST_TABLE3);
+ assertFalse("Some privilegies exist", privileges.next());
+ privileges.close();
+
+ // case 2. Get privileges when no privilegies exist for all tables
+ privileges = meta.getTablePrivileges(null, null, null);
+ assertFalse("Some privilegies exist", privileges.next());
+ privileges.close();
+
+ // case 3. grant CREATE and SELECT privileges ang get them
+ HashSet<String> expectedPrivs = new HashSet<String>();
+ expectedPrivs.add("CREATE");
+ expectedPrivs.add("SELECT");
+
+ String query = "GRANT CREATE, SELECT ON " + DatabaseCreator.TEST_TABLE3
+ + " TO " + Support_SQL.sqlUser;
+ statement.execute(query);
+
+ privileges = meta.getTablePrivileges(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE3);
+
+ while (privileges.next()) {
+ assertEquals("Wrong catalog name", Support_SQL.sqlCatalog,
+ privileges.getString("TABLE_CAT"));
+ assertNull("Wrong schema", privileges.getString("TABLE_SCHEM"));
+ assertEquals("Wrong table name", DatabaseCreator.TEST_TABLE3,
+ privileges.getString("TABLE_NAME"));
+ assertTrue("Wrong privilege " + privileges.getString("PRIVILEGE"),
+ expectedPrivs.remove(privileges.getString("PRIVILEGE")));
+ assertEquals("Wrong grantor", Support_SQL.sqlLogin + "@"
+ + Support_SQL.sqlHost, privileges.getString("GRANTOR"));
+ assertEquals("Wrong grantee", Support_SQL.sqlUser + "@%",
+ privileges.getString("GRANTEE"));
+ assertNull("Wrong value of IS_GRANTABLE", privileges
+ .getString("IS_GRANTABLE"));
+ }
+ privileges.close();
+ assertTrue("Wrong privileges were returned", expectedPrivs.isEmpty());
+
+ query = "REVOKE CREATE, SELECT ON " + DatabaseCreator.TEST_TABLE3
+ + " FROM " + Support_SQL.sqlUser;
+ statement.execute(query);
+
+ // case 4. grant all privileges ang get them
+ String[] privs = new String[] { "ALTER", "CREATE", "CREATE VIEW",
+ "DELETE", "DROP", "INDEX", "INSERT", "REFERENCES", "SELECT",
+ "SHOW VIEW", "UPDATE" };
+ expectedPrivs = new HashSet<String>();
+ for (int i = 0; i < privs.length; i++) {
+ expectedPrivs.add(privs[i]);
+ }
+ query = "GRANT ALL ON " + DatabaseCreator.TEST_TABLE3 + " TO "
+ + Support_SQL.sqlUser;
+ statement.execute(query);
+
+ privileges = meta.getTablePrivileges(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE3);
+
+ while (privileges.next()) {
+ assertEquals("Wrong catalog name", Support_SQL.sqlCatalog,
+ privileges.getString("TABLE_CAT"));
+ assertNull("Wrong schema", privileges.getString("TABLE_SCHEM"));
+ assertEquals("Wrong table name", DatabaseCreator.TEST_TABLE3,
+ privileges.getString("TABLE_NAME"));
+ assertTrue("Wrong privilege " + privileges.getString("PRIVILEGE"),
+ expectedPrivs.remove(privileges.getString("PRIVILEGE")));
+ assertEquals("Wrong grantor", Support_SQL.sqlLogin + "@"
+ + Support_SQL.sqlHost, privileges.getString("GRANTOR"));
+ assertEquals("Wrong grantee", Support_SQL.sqlUser + "@%",
+ privileges.getString("GRANTEE"));
+ assertNull("Wrong value of IS_GRANTABLE", privileges
+ .getString("IS_GRANTABLE"));
+ }
+ privileges.close();
+ assertTrue("Wrong privileges were returned", expectedPrivs.isEmpty());
+
+ query = "REVOKE ALL ON " + DatabaseCreator.TEST_TABLE3 + " FROM "
+ + Support_SQL.sqlUser;
+ statement.execute(query);
+
+ // case 5. check no privelegies after revoke
+ privileges = meta.getTablePrivileges(conn.getCatalog(), "%",
+ DatabaseCreator.TEST_TABLE3);
+ assertFalse("Some privilegies exist", privileges.next());
+ privileges.close();
+
+ privileges = meta.getTablePrivileges(null, null, null);
+ assertFalse("Some privilegies exist", privileges.next());
+ privileges.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#getTableTypes()
+ */
+ public void test_getTableTypes() throws SQLException {
+ String[] tableTypes = { "LOCAL TEMPORARY", "TABLE", "VIEW" };
+ ResultSet rs = meta.getTableTypes();
+
+ while (rs.next()) {
+ assertTrue("Wrong table type", Arrays.binarySearch(tableTypes, rs
+ .getString("TABLE_TYPE")) > -1);
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getTables(java.lang.String,
+ * java.lang.String, java.lang.String, java.lang.String[])
+ */
+ public void test_getTablesLjava_lang_StringLjava_lang_StringLjava_lang_String$Ljava_lang_String()
+ throws SQLException {
+ String[] tablesName = { VIEW_NAME, DatabaseCreator.TEST_TABLE1,
+ DatabaseCreator.TEST_TABLE3 };
+ String[] tablesType = { "TABLE", "VIEW" };
+
+ // case 1. get all tables. There are two tables and one view in the
+ // database
+ ResultSet rs = meta.getTables(null, null, null, null);
+
+ while (rs.next()) {
+ assertTrue("Wrong table name", Arrays.binarySearch(tablesName, rs
+ .getString("TABLE_NAME")) > -1);
+ // assertNull("Wrong table schema", rs.getString("TABLE_SCHEM"));
+ assertTrue("Wrong table type", Arrays.binarySearch(tablesType, rs
+ .getString("TABLE_TYPE")) > -1);
+ assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
+ }
+ rs.close();
+
+ // case 2. get tables with specified types. There are no tables of such
+ // types
+ rs = meta.getTables(conn.getCatalog(), null, null, new String[] {
+ "SYSTEM TABLE", "LOCAL TEMPORARY" });
+ assertFalse("Some tables exist", rs.next());
+ rs.close();
+
+ // case 3. get tables with specified types. There is a table of such
+ // types
+ rs = meta.getTables(conn.getCatalog(), null, null, new String[] {
+ "VIEW", "LOCAL TEMPORARY" });
+
+ assertTrue("No tables exist", rs.next());
+ assertEquals("Wrong table name", VIEW_NAME, rs.getString("TABLE_NAME"));
+// assertNull("Wrong table schema", rs.getString("TABLE_SCHEM"));
+ assertEquals("Wrong table type", "VIEW", rs.getString("TABLE_TYPE"));
+ assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
+ assertFalse("Wrong size of result set", rs.next());
+ assertFalse("Some tables exist", rs.next());
+ rs.close();
+
+ // case 4. get all tables using tables pattern.
+ // There are two tables and one view in the database
+ rs = meta.getTables(null, null, "%", null);
+
+ while (rs.next()) {
+ assertTrue("Wrong table name", Arrays.binarySearch(tablesName, rs
+ .getString("TABLE_NAME")) > -1);
+// assertNull("Wrong table schema", rs.getString("TABLE_SCHEM"));
+ assertTrue("Wrong table type", Arrays.binarySearch(tablesType, rs
+ .getString("TABLE_TYPE")) > -1);
+ assertEquals("Wrong parameter REMARKS", "", rs.getString("REMARKS"));
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getTimeDateFunctions()
+ */
+ public void test_getTimeDateFunctions() throws SQLException {
+ assertFalse("No time and data functions exist", !meta
+ .getTimeDateFunctions().trim().equals(""));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getTypeInfo()
+ */
+ public void test_getTypeInfo() throws SQLException {
+ insertNewRecord();
+
+ ResultSet rs = meta.getTypeInfo();
+
+ final String[] names = { "TYPE_NAME", "DATA_TYPE", "PRECISION",
+ "LITERAL_PREFIX", "LITERAL_SUFFIX", "CREATE_PARAMS",
+ "NULLABLE", "CASE_SENSITIVE", "SEARCHABLE",
+ "UNSIGNED_ATTRIBUTE", "FIXED_PREC_SCALE", "AUTO_INCREMENT",
+ "LOCAL_TYPE_NAME", "MINIMUM_SCALE", "MAXIMUM_SCALE",
+ "SQL_DATA_TYPE", "SQL_DATETIME_SUB", "NUM_PREC_RADIX" };
+ Arrays.sort(names);
+
+ for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
+ assertTrue("wrong column was return", Arrays.binarySearch(names, rs
+ .getMetaData().getColumnName(i + 1)) > -1);
+ }
+
+ int[] types = { Types.ARRAY, Types.BIGINT, Types.BINARY, Types.BIT,
+ Types.BLOB, Types.BOOLEAN, Types.CHAR, Types.CLOB,
+ Types.DATALINK, Types.DATE, Types.DECIMAL, Types.DISTINCT,
+ Types.DOUBLE, Types.FLOAT, Types.INTEGER, Types.JAVA_OBJECT,
+ Types.LONGVARBINARY, Types.LONGVARCHAR, Types.NULL,
+ Types.NUMERIC, Types.OTHER, Types.REAL, Types.REF,
+ Types.SMALLINT, Types.STRUCT, Types.TIME, Types.TIMESTAMP,
+ Types.TINYINT, Types.VARBINARY, Types.VARCHAR };
+ Arrays.sort(types);
+
+ while (rs.next()) {
+ assertTrue("wrong type was return ", Arrays.binarySearch(types, rs
+ .getInt("DATA_TYPE")) > -1);
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData #getUDTs(java.lang.String,
+ * java.lang.String, java.lang.String, int[])
+ */
+ public void test_getUDTsLjava_lang_StringLjava_lang_StringLjava_lang_String$I()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getURL()
+ */
+ public void test_getURL() throws SQLException {
+ assertEquals("Wrong url", Support_SQL.sqlUrl, meta.getURL());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#getUserName()
+ *
+ * TODO not supported
+ */
+/* public void test_getUserName() throws SQLException {
+ assertEquals("Wrong user name", Support_SQL.sqlLogin + "@"
+ + Support_SQL.sqlHost, meta.getUserName());
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData #getVersionColumns(java.lang.String,
+ * java.lang.String, java.lang.String)
+ *
+ * TODO trigger is not supported
+ */
+/* public void test_getVersionColumnsLjava_lang_StringLjava_lang_StringLjava_lang_String()
+ throws SQLException {
+ insertNewRecord();
+
+ String triggerName = "updateTrigger";
+ String triggerQuery = "CREATE TRIGGER " + triggerName
+ + " AFTER UPDATE ON " + DatabaseCreator.TEST_TABLE1
+ + " FOR EACH ROW BEGIN INSERT INTO "
+ + DatabaseCreator.TEST_TABLE3 + " SET fk = 10; END;";
+ statementForward.execute(triggerQuery);
+
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field1='fffff' WHERE id=1";
+ statementForward.execute(updateQuery);
+
+ ResultSet rs = meta.getVersionColumns(conn.getCatalog(), null,
+ DatabaseCreator.TEST_TABLE1);
+ assertTrue("Result set is empty", rs.next());
+ rs.close();
+ }
+*/
+ /**
+ * @tests java.sql.DatabaseMetaData#insertsAreDetected(int)
+ */
+ public void test_insertsAreDetectedI() throws SQLException {
+ assertFalse(
+ "visible row insert can be detected for TYPE_FORWARD_ONLY type",
+ meta.insertsAreDetected(ResultSet.TYPE_FORWARD_ONLY));
+ assertFalse(
+ "visible row insert can be detected for TYPE_SCROLL_INSENSITIVE type",
+ meta.insertsAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
+ assertFalse(
+ "visible row insert can be detected for TYPE_SCROLL_SENSITIVE type",
+ meta.insertsAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#isCatalogAtStart()
+ */
+ public void test_isCatalogAtStart() throws SQLException {
+ assertFalse(
+ "catalog doesn't appear at the start of a fully qualified table name",
+ meta.isCatalogAtStart());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#isReadOnly()
+ */
+ public void test_isReadOnly() throws SQLException {
+ assertFalse("database is not read-only", meta.isReadOnly());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#locatorsUpdateCopy()
+ */
+ public void test_locatorsUpdateCopy() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#nullPlusNonNullIsNull()
+ */
+ public void test_nullPlusNonNullIsNull() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#nullsAreSortedAtEnd()
+ */
+ public void test_nullsAreSortedAtEnd() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#nullsAreSortedAtStart()
+ */
+ public void test_nullsAreSortedAtStart() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#nullsAreSortedHigh()
+ */
+ public void test_nullsAreSortedHigh() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#nullsAreSortedLow()
+ */
+ public void test_nullsAreSortedLow() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#othersDeletesAreVisible(int)
+ */
+ public void test_othersDeletesAreVisibleI() throws SQLException {
+ assertFalse(
+ "deletes made by others are visible for TYPE_FORWARD_ONLY type",
+ meta.othersDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+ assertFalse(
+ "deletes made by others are visible for TYPE_SCROLL_INSENSITIVE type",
+ meta.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+ assertFalse(
+ "deletes made by others are visible for TYPE_SCROLL_SENSITIVE type",
+ meta.othersDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("deletes made by others are visible for unknown type", meta
+ .othersDeletesAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#othersInsertsAreVisible(int)
+ */
+ public void test_othersInsertsAreVisibleI() throws SQLException {
+ assertFalse(
+ "inserts made by others are visible for TYPE_FORWARD_ONLY type",
+ meta.othersInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+ assertFalse(
+ "inserts made by others are visible for TYPE_SCROLL_INSENSITIVE type",
+ meta.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+ assertFalse(
+ "inserts made by others are visible for TYPE_SCROLL_SENSITIVE type",
+ meta.othersInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("inserts made by others are visible for unknown type", meta
+ .othersInsertsAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#othersUpdatesAreVisible(int)
+ */
+ public void test_othersUpdatesAreVisibleI() throws SQLException {
+ assertFalse(
+ "updates made by others are visible for TYPE_FORWARD_ONLY type",
+ meta.othersUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+ assertFalse(
+ "updates made by others are visible for TYPE_SCROLL_INSENSITIVE type",
+ meta.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+ assertFalse(
+ "updates made by others are visible for TYPE_SCROLL_SENSITIVE type",
+ meta.othersUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("updates made by others are visible for unknown type", meta
+ .othersUpdatesAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#ownDeletesAreVisible(int)
+ */
+ public void test_ownDeletesAreVisibleI() throws SQLException {
+ // TODO not supported
+// assertFalse(
+// "result set's own deletes are visible for TYPE_FORWARD_ONLY type",
+// meta.ownDeletesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+// assertFalse(
+// "result set's own deletes are visible for TYPE_SCROLL_INSENSITIVE type",
+// meta.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+// assertFalse(
+// "result set's own deletes are visible for TYPE_SCROLL_SENSITIVE type",
+// meta.ownDeletesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("result set's own deletes are visible for unknown type",
+ meta.ownDeletesAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#ownInsertsAreVisible(int)
+ */
+ public void test_ownInsertsAreVisibleI() throws SQLException {
+// assertFalse(
+// "result set's own inserts are visible for TYPE_FORWARD_ONLY type",
+// meta.ownInsertsAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+// assertFalse(
+// "result set's own inserts are visible for TYPE_SCROLL_INSENSITIVE type",
+// meta.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+// assertFalse(
+// "result set's own inserts are visible for TYPE_SCROLL_SENSITIVE type",
+// meta.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("result set's own inserts are visible for unknown type",
+ meta.ownInsertsAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#ownUpdatesAreVisible(int)
+ */
+ public void test_ownUpdatesAreVisibleI() throws SQLException {
+ // TODO not supported
+// assertFalse(
+// "result set's own updates are visible for TYPE_FORWARD_ONLY type",
+// meta.ownUpdatesAreVisible(ResultSet.TYPE_FORWARD_ONLY));
+// assertFalse(
+// "result set's own updates are visible for TYPE_SCROLL_INSENSITIVE type",
+// meta.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_INSENSITIVE));
+// assertFalse(
+// "result set's own updates are visible for TYPE_SCROLL_SENSITIVE type",
+// meta.ownUpdatesAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("result set's own updates are visible for unknown type",
+ meta.ownUpdatesAreVisible(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesLowerCaseIdentifiers()
+ */
+ public void test_storesLowerCaseIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesLowerCaseQuotedIdentifiers()
+ */
+ public void test_storesLowerCaseQuotedIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesMixedCaseIdentifiers()
+ */
+ public void test_storesMixedCaseIdentifiers() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT fieLD1 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.storesMixedCaseQuotedIdentifiers()) {
+ fail("mixed case are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.storesMixedCaseQuotedIdentifiers()) {
+ fail("mixed case are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesMixedCaseQuotedIdentifiers()
+ */
+ public void test_storesMixedCaseQuotedIdentifiers() throws SQLException {
+ String quote = meta.getIdentifierQuoteString();
+
+ insertNewRecord();
+
+ String selectQuery = "SELECT " + quote + "fieLD1" + quote + " FROM "
+ + DatabaseCreator.TEST_TABLE1;
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.storesMixedCaseQuotedIdentifiers()) {
+ fail("mixed case is supported");
+ }
+ } catch (SQLException e) {
+ if (meta.storesMixedCaseQuotedIdentifiers()) {
+ fail("mixed case is not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesUpperCaseIdentifiers()
+ */
+ public void test_storesUpperCaseIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#storesUpperCaseQuotedIdentifiers()
+ */
+ public void test_storesUpperCaseQuotedIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsANSI92EntryLevelSQL()
+ */
+ public void test_supportsANSI92EntryLevelSQL() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsANSI92FullSQL()
+ */
+ public void test_supportsANSI92FullSQL() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsANSI92IntermediateSQL()
+ */
+ public void test_supportsANSI92IntermediateSQL() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsAlterTableWithAddColumn()
+ */
+ public void test_supportsAlterTableWithAddColumn() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsAlterTableWithDropColumn()
+ */
+ public void test_supportsAlterTableWithDropColumn() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsBatchUpdates()
+ */
+ public void test_supportsBatchUpdates() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCatalogsInDataManipulation()
+ */
+ public void test_supportsCatalogsInDataManipulation() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCatalogsInIndexDefinitions()
+ */
+ public void test_supportsCatalogsInIndexDefinitions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCatalogsInPrivilegeDefinitions()
+ */
+ public void test_supportsCatalogsInPrivilegeDefinitions()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCatalogsInProcedureCalls()
+ */
+ public void test_supportsCatalogsInProcedureCalls() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCatalogsInTableDefinitions()
+ */
+ public void test_supportsCatalogsInTableDefinitions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsColumnAliasing()
+ */
+ public void test_supportsColumnAliasing() throws SQLException {
+ insertNewRecord();
+
+ String alias = "FIELD3";
+ String selectQuery = "SELECT field1 AS " + alias + " FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet rs = statement.executeQuery(selectQuery);
+ ResultSetMetaData rsmd = rs.getMetaData();
+
+ if (meta.supportsColumnAliasing()) {
+ // supports aliasing
+ assertEquals("Wrong count of columns", 1, rsmd.getColumnCount());
+ assertEquals("Aliasing is not supported", alias, rsmd
+ .getColumnLabel(1));
+ } else {
+ // doesn't support aliasing
+ assertEquals("Aliasing is supported", 0, rsmd.getColumnCount());
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsConvert()
+ */
+ public void test_supportsConvert() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsConvert(int, int)
+ */
+ public void test_supportsConvertII() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCoreSQLGrammar()
+ */
+ public void test_supportsCoreSQLGrammar() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsCorrelatedSubqueries()
+ */
+ public void test_supportsCorrelatedSubqueries() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsDataDefinitionAndDataManipulationTransactions()
+ */
+ public void test_supportsDataDefinitionAndDataManipulationTransactions()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsDataManipulationTransactionsOnly()
+ */
+ public void test_supportsDataManipulationTransactionsOnly()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsDifferentTableCorrelationNames()
+ */
+ public void test_supportsDifferentTableCorrelationNames()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsExpressionsInOrderBy()
+ */
+ public void test_supportsExpressionsInOrderBy() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
+ + " ORDER BY id + field3";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsExpressionsInOrderBy()) {
+ fail("Expressions in order by are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.supportsExpressionsInOrderBy()) {
+ fail("Expressions in order by are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsExtendedSQLGrammar()
+ */
+ public void test_supportsExtendedSQLGrammar() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsFullOuterJoins()
+ */
+ public void test_supportsFullOuterJoins() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsGetGeneratedKeys()
+ */
+ public void test_supportsGetGeneratedKeys() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsGroupBy()
+ */
+ public void test_supportsGroupBy() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
+ + " GROUP BY field3";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsGroupBy()) {
+ fail("group by are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.supportsGroupBy()) {
+ fail("group by are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsGroupByBeyondSelect()
+ */
+ public void test_supportsGroupByBeyondSelect() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsGroupByUnrelated()
+ */
+ public void test_supportsGroupByUnrelated() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT field1, field2 FROM "
+ + DatabaseCreator.TEST_TABLE1 + " GROUP BY field3";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsGroupByUnrelated()) {
+ fail("unrelated columns in group by are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.supportsGroupByUnrelated()) {
+ fail("unrelated columns in group by are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsIntegrityEnhancementFacility()
+ */
+ public void test_supportsIntegrityEnhancementFacility() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsLikeEscapeClause()
+ */
+ public void test_supportsLikeEscapeClause() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsLimitedOuterJoins()
+ */
+ public void test_supportsLimitedOuterJoins() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMinimumSQLGrammar()
+ */
+ public void test_supportsMinimumSQLGrammar() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMixedCaseIdentifiers()
+ */
+ public void test_supportsMixedCaseIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMixedCaseQuotedIdentifiers()
+ */
+ public void test_supportsMixedCaseQuotedIdentifiers() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMultipleOpenResults()
+ */
+ public void test_supportsMultipleOpenResults() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMultipleResultSets()
+ */
+ public void test_supportsMultipleResultSets() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsMultipleTransactions()
+ */
+ public void test_supportsMultipleTransactions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsNamedParameters()
+ */
+ public void test_supportsNamedParameters() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsNonNullableColumns()
+ */
+ public void test_supportsNonNullableColumns() throws SQLException {
+ assertTrue(
+ "columns in this database may not be defined as non-nullable",
+ meta.supportsNonNullableColumns());
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOpenCursorsAcrossCommit()
+ */
+ public void test_supportsOpenCursorsAcrossCommit() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOpenCursorsAcrossRollback()
+ */
+ public void test_supportsOpenCursorsAcrossRollback() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOpenStatementsAcrossCommit()
+ */
+ public void test_supportsOpenStatementsAcrossCommit() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOpenStatementsAcrossRollback()
+ */
+ public void test_supportsOpenStatementsAcrossRollback() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOrderByUnrelated()
+ */
+ public void test_supportsOrderByUnrelated() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT field1, field2 FROM "
+ + DatabaseCreator.TEST_TABLE1 + " ORDER BY id + field3";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsOrderByUnrelated()) {
+ fail("unrelated columns in order by are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.supportsOrderByUnrelated()) {
+ fail("unrelated columns in order by are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsOuterJoins()
+ */
+ public void test_supportsOuterJoins() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsPositionedDelete()
+ */
+ public void test_supportsPositionedDelete() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsPositionedUpdate()
+ */
+ public void test_supportsPositionedUpdate() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsResultSetConcurrency(int, int)
+ */
+ public void test_supportsResultSetConcurrencyII() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsResultSetHoldability(int)
+ */
+ public void test_supportsResultSetHoldabilityI() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsResultSetType(int)
+ */
+ public void test_supportsResultSetTypeI() throws SQLException {
+ // TODO not supported
+// assertFalse("database supports TYPE_FORWARD_ONLY type", meta
+// .supportsResultSetType(ResultSet.TYPE_FORWARD_ONLY));
+// assertTrue("database doesn't support TYPE_SCROLL_INSENSITIVE type",
+// meta.supportsResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE));
+// assertFalse("database supports TYPE_SCROLL_SENSITIVE type", meta
+// .supportsResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("database supports unknown type", meta
+ .supportsResultSetType(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSavepoints()
+ */
+ public void test_supportsSavepoints() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSchemasInDataManipulation()
+ */
+ public void test_supportsSchemasInDataManipulation() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSchemasInIndexDefinitions()
+ */
+ public void test_supportsSchemasInIndexDefinitions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSchemasInPrivilegeDefinitions()
+ */
+ public void test_supportsSchemasInPrivilegeDefinitions()
+ throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSchemasInProcedureCalls()
+ */
+ public void test_supportsSchemasInProcedureCalls() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSchemasInTableDefinitions()
+ */
+ public void test_supportsSchemasInTableDefinitions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSelectForUpdate()
+ */
+ public void test_supportsSelectForUpdate() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT field1 FROM "
+ + DatabaseCreator.TEST_TABLE1 + " FOR UPDATE";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsSelectForUpdate()) {
+ fail("select for update are supported");
+ }
+ } catch (SQLException e) {
+ if (!meta.supportsSelectForUpdate()) {
+ fail("select for update are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsStatementPooling()
+ */
+ public void test_supportsStatementPooling() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsStoredProcedures()
+ */
+ public void test_supportsStoredProcedures() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSubqueriesInComparisons()
+ */
+ public void test_supportsSubqueriesInComparisons() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSubqueriesInExists()
+ */
+ public void test_supportsSubqueriesInExists() throws SQLException {
+ insertNewRecord();
+
+ String selectQuery = "SELECT field1 FROM "
+ + DatabaseCreator.TEST_TABLE1
+ + " WHERE EXISTS(SELECT field2 FROM "
+ + DatabaseCreator.TEST_TABLE1 + ")";
+
+ try {
+ statement.executeQuery(selectQuery);
+ if (!meta.supportsSubqueriesInExists()) {
+ fail("Subqueries in exists are supported");
+ }
+ } catch (SQLException e) {
+ if (meta.supportsSubqueriesInExists()) {
+ fail("Subqueries in exists are not supported");
+ }
+ }
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSubqueriesInIns()
+ */
+ public void test_supportsSubqueriesInIns() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsSubqueriesInQuantifieds()
+ */
+ public void test_supportsSubqueriesInQuantifieds() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsTableCorrelationNames()
+ */
+ public void test_supportsTableCorrelationNames() throws SQLException {
+ insertNewRecord();
+
+ String corelationName = "TABLE_NAME";
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
+ + " AS " + corelationName;
+ ResultSet rs = statement.executeQuery(selectQuery);
+ ResultSetMetaData rsmd = rs.getMetaData();
+ int numOfColumn = rsmd.getColumnCount();
+
+ for (int i = 0; i < numOfColumn; i++) {
+ if (meta.supportsTableCorrelationNames()) {
+ assertEquals("Corelation names is not supported",
+ corelationName, rsmd.getTableName(i + 1));
+ } else {
+ assertEquals("Corelation names is supported",
+ DatabaseCreator.TEST_TABLE1, rsmd.getTableName(i + 1));
+ }
+ }
+ rs.close();
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsTransactionIsolationLevel(int)
+ */
+ public void test_supportsTransactionIsolationLevelI() throws SQLException {
+ assertFalse("database supports TRANSACTION_NONE isolation level", meta
+ .supportsTransactionIsolationLevel(Connection.TRANSACTION_NONE));
+ // TODO only Connection.TRANSACTION_SERIALIZABLE is supported
+// assertTrue(
+// "database doesn't supports TRANSACTION_READ_COMMITTED isolation level",
+// meta
+// .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_COMMITTED));
+// assertTrue(
+// "database doesn't supports TRANSACTION_READ_UNCOMMITTED isolation level",
+// meta
+// .supportsTransactionIsolationLevel(Connection.TRANSACTION_READ_UNCOMMITTED));
+// assertTrue(
+// "database doesn't supports TRANSACTION_REPEATABLE_READ isolation level",
+// meta
+// .supportsTransactionIsolationLevel(Connection.TRANSACTION_REPEATABLE_READ));
+ assertTrue(
+ "database doesn't supports TRANSACTION_SERIALIZABLE isolation level",
+ meta
+ .supportsTransactionIsolationLevel(Connection.TRANSACTION_SERIALIZABLE));
+ assertFalse("database supports unknown isolation level", meta
+ .supportsTransactionIsolationLevel(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsTransactions()
+ */
+ public void test_supportsTransactions() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsUnion()
+ */
+ public void test_supportsUnion() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#supportsUnionAll()
+ */
+ public void test_supportsUnionAll() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#updatesAreDetected(int)
+ */
+ public void test_updatesAreDetectedI() throws SQLException {
+ assertFalse(
+ "visible row update can be detected for TYPE_FORWARD_ONLY type",
+ meta.updatesAreDetected(ResultSet.TYPE_FORWARD_ONLY));
+ assertFalse(
+ "visible row update can be detected for TYPE_SCROLL_INSENSITIVE type",
+ meta.updatesAreDetected(ResultSet.TYPE_SCROLL_INSENSITIVE));
+ assertFalse(
+ "visible row update can be detected for TYPE_SCROLL_SENSITIVE type",
+ meta.updatesAreDetected(ResultSet.TYPE_SCROLL_SENSITIVE));
+ assertFalse("visible row update can be detected for unknown type", meta
+ .updatesAreDetected(100));
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#usesLocalFilePerTable()
+ */
+ public void test_usesLocalFilePerTable() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ /**
+ * @tests java.sql.DatabaseMetaData#usesLocalFiles()
+ */
+ public void test_usesLocalFiles() throws SQLException {
+ // TODO: JDBC does not implement this functionality
+ }
+
+ private void insertNewRecord() throws SQLException {
+ String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id + ", '"
+ + "value" + id + "', " + id + ", " + id + ")";
+ id++;
+ statement.execute(insertQuery);
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/DeleteFunctionalityTest.java b/sql/src/test/java/tests/java/sql/DeleteFunctionalityTest.java
new file mode 100755
index 0000000..f00a7cf
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/DeleteFunctionalityTest.java
@@ -0,0 +1,219 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class DeleteFunctionalityTest extends TestCase {
+
+ private static Connection conn = null;
+
+ private static Statement statement = null;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ DatabaseCreator.fillParentTable(conn);
+ }
+
+ protected void tearDown() throws Exception {
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKCASCADE_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.TEST_TABLE5);
+ super.tearDown();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ DeleteFunctionalityTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ statement.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.PARENT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_PARENT);
+ } else if (tableName
+ .equals(DatabaseCreator.FKCASCADE_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ } else if (tableName
+ .equals(DatabaseCreator.FKSTRICT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE5)) {
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ }
+ }
+ userTab.close();
+ statement.execute(DatabaseCreator.CREATE_TABLE_PARENT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.CREATE_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.DROP_TABLE_PARENT);
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests DeleteFunctionalityTest#testDelete1(). Deletes row with no
+ * referencing ones and RESTRICT action
+ */
+ public void testDelete1() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE
+ + " WHERE id = 3;");
+ }
+
+ /**
+ * @tests DeleteFunctionalityTest#testDelete2(). Attempts to delete row with
+ * referencing ones and RESTRICT action - expecting SQLException
+ * TODO foreign key functionality is not supported
+ */
+/* public void testDelete2() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ try {
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE
+ + " WHERE id = 1;");
+ fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @tests DeleteFunctionalityTest#testDelete3(). Deletes all referencing
+ * rows and then deletes referenced one
+ */
+ public void testDelete3() throws SQLException {
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE
+ + " WHERE name_id = 1;");
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE
+ + " WHERE id = 1;");
+ }
+
+ /**
+ * @tests DeleteFunctionalityTest#testDelete4(). Deletes row with no
+ * referencing ones and CASCADE action
+ */
+ public void testDelete4() throws SQLException {
+ DatabaseCreator.fillFKCascadeTable(conn);
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE
+ + " WHERE id = 3;");
+ }
+
+ /**
+ * @tests DeleteFunctionalityTest#testDelete5(). Attempts to delete row with
+ * referencing ones and CASCADE action - expecting all referencing
+ * rows will also be deleted
+ */
+ public void testDelete5() throws SQLException {
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE
+ + " WHERE id = 1;");
+
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.FKCASCADE_TABLE + " WHERE name_id = 1;");
+ r.next();
+ assertEquals("Should be no rows", 0, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests DeleteFunctionalityTest#testDelete6(). Deletes rows using subquery
+ * in WHERE clause
+ * TODO Foreign key functionality is not supported
+ */
+/* public void testDelete6() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE
+ + " WHERE name_id = ANY (SELECT id FROM "
+ + DatabaseCreator.PARENT_TABLE + " WHERE id > 1)");
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.FKSTRICT_TABLE + " WHERE name_id = 1;");
+ r.next();
+ assertEquals("Should be 2 rows", 2, r.getInt(1));
+ r.close();
+ }
+*/
+ /**
+ * @tests DeleteFunctionalityTest#testDelete7(). Deletes rows using
+ * PreparedStatement
+ */
+ public void testDelete7() throws SQLException {
+ DatabaseCreator.fillTestTable5(conn);
+ PreparedStatement stat = conn.prepareStatement("DELETE FROM "
+ + DatabaseCreator.TEST_TABLE5 + " WHERE testID = ?");
+ stat.setInt(1, 1);
+ stat.execute();
+ stat.setInt(1, 2);
+ stat.execute();
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.TEST_TABLE5 + " WHERE testID < 3 ");
+ r.next();
+ assertEquals(0, r.getInt(1));
+ r.close();
+ stat.close();
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/InsertFunctionalityTest.java b/sql/src/test/java/tests/java/sql/InsertFunctionalityTest.java
new file mode 100755
index 0000000..7ad2d3e
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/InsertFunctionalityTest.java
@@ -0,0 +1,250 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import tests.support.Support_SQL;
+import tests.support.DatabaseCreator;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class InsertFunctionalityTest extends TestCase {
+
+ private static Connection conn = null;
+
+ private static Statement statement = null;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ Support_SQL.loadDriver();
+ conn = Support_SQL.getConnection();
+
+ }
+
+ protected void tearDown() throws Exception {
+ statement.execute("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE2);
+ statement.execute("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKCASCADE_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.TEST_TABLE5);
+ super.tearDown();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ InsertFunctionalityTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ statement.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.PARENT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_PARENT);
+ } else if (tableName
+ .equals(DatabaseCreator.FKCASCADE_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ } else if (tableName
+ .equals(DatabaseCreator.FKSTRICT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ } else if (tableName
+ .equals(DatabaseCreator.SIMPLE_TABLE1)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_SIMPLE1);
+ } else if (tableName
+ .equals(DatabaseCreator.SIMPLE_TABLE2)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_SIMPLE2);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE5)) {
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ }
+ }
+ userTab.close();
+ statement.execute(DatabaseCreator.CREATE_TABLE_PARENT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE2);
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
+ statement.execute(DatabaseCreator.CREATE_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.DROP_TABLE_PARENT);
+ statement.execute(DatabaseCreator.DROP_TABLE_SIMPLE2);
+ statement.execute(DatabaseCreator.DROP_TABLE_SIMPLE1);
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert1(). Attempts to insert row into
+ * table with integrity checking
+ */
+ public void testInsert1() throws SQLException {
+ DatabaseCreator.fillParentTable(conn);
+ DatabaseCreator.fillFKStrictTable(conn);
+ DatabaseCreator.fillFKCascadeTable(conn);
+ statement.execute("INSERT INTO " + DatabaseCreator.FKSTRICT_TABLE
+ + " VALUES(4, 1, 'testInsert')");
+ statement.execute("INSERT INTO " + DatabaseCreator.FKCASCADE_TABLE
+ + " VALUES(4, 1, 'testInsert')");
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert2(). Attempts to insert row into
+ * table with integrity checking when row has incorrect foreign key
+ * value - expecting SQLException
+ */
+ public void testInsert2() throws SQLException {
+ DatabaseCreator.fillParentTable(conn);
+ DatabaseCreator.fillFKStrictTable(conn);
+ DatabaseCreator.fillFKCascadeTable(conn);
+ try {
+ statement.execute("INSERT INTO " + DatabaseCreator.FKSTRICT_TABLE
+ + " VALUES(4, 4, 'testInsert')");
+ // TODO Foreign key functionality isn't supported
+ // fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+ }
+ try {
+ statement.execute("INSERT INTO " + DatabaseCreator.FKCASCADE_TABLE
+ + " VALUES(4, 4, 'testInsert')");
+ // TODO Foreign key functionality isn't supported
+ // fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+ }
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert3(). Tests INSERT ... SELECT
+ * functionality
+ */
+ public void testInsert3() throws SQLException {
+ DatabaseCreator.fillParentTable(conn);
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("INSERT INTO " + DatabaseCreator.TEST_TABLE5
+ + " SELECT id AS testId, value AS testValue " + "FROM "
+ + DatabaseCreator.FKSTRICT_TABLE + " WHERE name_id = 1");
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.TEST_TABLE5);
+ r.next();
+ assertEquals("Should be 2 rows", 2, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert4(). Tests INSERT ... SELECT
+ * with expressions in SELECT query
+ */
+ public void testInsert4() throws SQLException {
+ DatabaseCreator.fillSimpleTable1(conn);
+ statement.execute("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE2
+ + " SELECT id, speed*10 AS speed, size-1 AS size FROM "
+ + DatabaseCreator.SIMPLE_TABLE1);
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.SIMPLE_TABLE2 + " AS a JOIN "
+ + DatabaseCreator.SIMPLE_TABLE1
+ + " AS b ON a.speed = 10*b.speed AND a.size = b.size-1");
+ r.next();
+ assertEquals("Should be 2 rows", 2, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert5(). Inserts multiple rows using
+ * UNION ALL
+ */
+ public void testInsert5() throws SQLException {
+ statement.execute("INSERT INTO " + DatabaseCreator.TEST_TABLE5
+ + " SELECT 1 as testId, 2 as testValue "
+ + "UNION SELECT 2 as testId, 3 as testValue "
+ + "UNION SELECT 3 as testId, 4 as testValue");
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.TEST_TABLE5);
+ r.next();
+ assertEquals("Should be 3 rows", 3, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests InsertFunctionalityTest#testInsert6(). Tests INSERT with
+ * PreparedStatement
+ */
+ public void testInsertPrepared() throws SQLException {
+ PreparedStatement stat = conn.prepareStatement("INSERT INTO "
+ + DatabaseCreator.TEST_TABLE5 + " VALUES(?, ?)");
+ stat.setInt(1, 1);
+ stat.setString(2, "1");
+ stat.execute();
+ stat.setInt(1, 2);
+ stat.setString(2, "3");
+ stat.execute();
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.TEST_TABLE5
+ + " WHERE (testId = 1 AND testValue = '1') "
+ + "OR (testId = 2 AND testValue = '3')");
+ r.next();
+ assertEquals("Incorrect number of records", 2, r.getInt(1));
+ r.close();
+ stat.close();
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/MultiThreadAccessTest.java b/sql/src/test/java/tests/java/sql/MultiThreadAccessTest.java
new file mode 100755
index 0000000..b88aa4e
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/MultiThreadAccessTest.java
@@ -0,0 +1,445 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+import tests.support.ThreadPool;
+
+public class MultiThreadAccessTest extends TestCase {
+
+ private static Connection conn;
+
+ private static Statement statement;
+
+ private static final int numThreads = 10;
+
+ private static final int numOfRecords = 20;
+
+ private ThreadPool threadPool;
+
+ protected void setUp() throws Exception {
+ threadPool = new ThreadPool(numThreads);
+ }
+
+ protected void tearDown() throws Exception {
+ threadPool.join();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ MultiThreadAccessTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ conn.close();
+ statement.close();
+ }
+
+ private void createTestTables() {
+ try {
+ ResultSet userTab = conn.getMetaData().getTables(null,
+ null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE2)) {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE4)) {
+ statement.execute(DatabaseCreator.DROP_TABLE4);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE3)) {
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ }
+ }
+
+ userTab.close();
+ statement.execute(DatabaseCreator.CREATE_TABLE3);
+ statement.execute(DatabaseCreator.CREATE_TABLE4);
+ statement.execute(DatabaseCreator.CREATE_TABLE1);
+ statement.execute(DatabaseCreator.CREATE_TABLE2);
+
+ DatabaseCreator.fillTestTable1(conn, numOfRecords);
+ DatabaseCreator.fillTestTable2(conn, numOfRecords);
+ DatabaseCreator.fillTestTable4(conn, numOfRecords);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ statement.execute(DatabaseCreator.DROP_TABLE4);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * A few threads execute select operation in the same time for one table in
+ * the database. Number of threads is defined by numThreads variable
+ *
+ * @throws SQLException
+ */
+ public void test_MultipleAccessToOneTable() throws SQLException {
+ for (int i = 0; i < numThreads; i++) {
+ threadPool.runTask(createTask1(i));
+ }
+ }
+
+ /**
+ * A few threads execute select operation in the same time for different
+ * tables in the database. Number of threads is defined by numThreads
+ * variable
+ *
+ * @throws SQLException
+ */
+ public void test_MultipleAccessToSeveralTables() throws SQLException {
+ threadPool.runTask(createTask1(1));
+ threadPool.runTask(createTask2(2));
+ threadPool.runTask(createTask3(3));
+ }
+
+ /**
+ * A few threads execute update, insert and delete operations in the same
+ * time for one table in the database. Number of threads is defined by
+ * numThreads variable
+ *
+ * @throws SQLException
+ */
+ public void test_MultipleOperationsInSeveralTables() throws SQLException {
+ int id1 = numOfRecords - 1;
+ threadPool.runTask(createTask4(id1));
+
+ int id2 = numOfRecords + 1;
+ threadPool.runTask(createTask5(id2));
+
+ int oldID = 5;
+ int newID = 100;
+ threadPool.runTask(createTask6(oldID, newID));
+
+ threadPool.join();
+
+ Statement statement = conn.createStatement();
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
+ + " WHERE id=";
+
+ ResultSet result = statement.executeQuery(selectQuery + id1);
+ assertFalse("The record was not deleted", result.next());
+
+ result = statement.executeQuery(selectQuery + id2);
+ assertTrue("The record was not inserted", result.next());
+
+ assertEquals("Wrong value of field1", DatabaseCreator.defaultString
+ + id2, result.getString("field1"));
+ // TODO getBigDecimal is not supported
+// assertEquals("Wrong value of field2", BigDecimal.valueOf(id2), result
+// .getBigDecimal("field2"));
+// assertEquals("Wrong value of field3", BigDecimal.valueOf(id2), result
+// .getBigDecimal("field3"));
+ result.close();
+
+ result = statement.executeQuery(selectQuery + oldID);
+ assertFalse("The record was not deleted", result.next());
+ result.close();
+
+ result = statement.executeQuery(selectQuery + newID);
+ assertTrue("The record was not updated", result.next());
+
+ assertEquals("Wrong value of field1", DatabaseCreator.defaultString
+ + newID, result.getString("field1"));
+ // TODO getBigDecimal is not supported
+// assertEquals("Wrong value of field2", BigDecimal.valueOf(newID), result
+// .getBigDecimal("field2"));
+// assertEquals("Wrong value of field3", BigDecimal.valueOf(newID), result
+// .getBigDecimal("field3"));
+ result.close();
+ }
+
+ /**
+ * A few threads execute update operation in the same time for one tables in
+ * the database. Number of threads is defined by numThreads variable
+ *
+ * @throws SQLException
+ */
+ public void test_MultipleUpdatesInOneTables() throws SQLException {
+ int id = 1;
+ String field = "field3";
+
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1
+ + " WHERE id=" + id;
+ Statement statement = conn.createStatement();
+
+ ResultSet result = statement.executeQuery(selectQuery);
+ assertTrue("There is no records with id = " + id, result.next());
+ // TODO getBigDecimal is not supported
+// assertEquals("Wrong value of field " + field, BigDecimal.valueOf(id),
+// result.getBigDecimal(field));
+ result.close();
+
+ for (int i = 0; i < numThreads; i++) {
+ threadPool.runTask(createTask7(id, field));
+ }
+
+ threadPool.join();
+
+ double expectedVal = id + numThreads;
+ result = statement.executeQuery(selectQuery);
+ assertTrue("There is no records with id = " + id, result.next());
+ // TODO getBigDecimal is not supported
+// assertEquals("Wrong value of field " + field, expectedVal, result
+// .getBigDecimal(field).doubleValue());
+ result.close();
+ }
+
+ /**
+ * This method creates a Runnable that executes select operation for the
+ * first table
+ *
+ * @param taskID
+ * @return
+ */
+ private static Runnable createTask1(final int taskID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ ResultSet result = statement.executeQuery("SELECT * FROM "
+ + DatabaseCreator.TEST_TABLE1);
+
+ while (result.next()) {
+ assertEquals("Wrong value of id ",
+ DatabaseCreator.defaultString
+ + result.getInt("id"), result
+ .getString("field1"));
+ assertEquals("Wrong value of field2 ", BigDecimal
+ .valueOf(result.getInt("id")), result
+ .getBigDecimal("field2"));
+ assertEquals("Wrong value of field3 ", BigDecimal
+ .valueOf(result.getInt("id")), result
+ .getBigDecimal("field3"));
+ }
+ result.close();
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that execute select operation for the
+ * second table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask2(final int taskID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ ResultSet result = statement.executeQuery("SELECT * FROM "
+ + DatabaseCreator.TEST_TABLE2);
+
+ while (result.next()) {
+ while (result.next()) {
+ int id = result.getInt("finteger");
+ assertEquals("Wrong value of ftext",
+ DatabaseCreator.defaultString + id, result
+ .getString("ftext"));
+ assertEquals("Wrong value of fcharacter",
+ DatabaseCreator.defaultCharacter + id,
+ result.getString("fcharacter"));
+ assertEquals("Wrong value of fdecimal",
+ DatabaseCreator.defaultDouble + id, result
+ .getDouble("fdecimal"));
+ assertEquals("Wrong value of fnumeric",
+ DatabaseCreator.defaultDouble + id, result
+ .getDouble("fnumeric"));
+ assertEquals("Wrong value of fsmallint", result
+ .getInt("finteger"), result
+ .getShort("fsmallint"));
+ assertEquals("Wrong value of ffloat",
+ (float) DatabaseCreator.defaultDouble + id,
+ result.getFloat("ffloat"));
+ assertEquals("Wrong value of freal",
+ (float) DatabaseCreator.defaultDouble + id,
+ result.getFloat("freal"));
+ assertEquals("Wrong value of fdouble",
+ DatabaseCreator.defaultDouble + id, result
+ .getDouble("fdouble"));
+ }
+ }
+ result.close();
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that execute select operation for the
+ * third table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask3(final int taskID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ ResultSet result = statement.executeQuery("SELECT * FROM "
+ + DatabaseCreator.TEST_TABLE4);
+
+ while (result.next()) {
+ assertEquals("Wrong value of field1",
+ DatabaseCreator.defaultString
+ + result.getInt("fk"), result
+ .getString("field1"));
+ }
+ result.close();
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes delete operation for the
+ * first table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask4(final int id) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ statement.execute("DELETE FROM "
+ + DatabaseCreator.TEST_TABLE1 + " WHERE id=" + id);
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes insert operation for the
+ * first table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask5(final int id) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ String value = DatabaseCreator.defaultString + id;
+
+ String insertQuery = "INSERT INTO "
+ + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id
+ + ", '" + value + "', " + id + ", " + id + ")";
+ statement.execute(insertQuery);
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes update operation for the one
+ * record of the first table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask6(final int oldID, final int newID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ String value = DatabaseCreator.defaultString + newID;
+ String updateQuery = "UPDATE "
+ + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID
+ + ", field1='" + value + "', field2=" + newID
+ + ", field3=" + newID + " WHERE id=" + oldID;
+ statement.execute(updateQuery);
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+
+ /**
+ * This method creates a Runnable that executes update operation for the one
+ * field of one record with identifier id in the first table
+ *
+ * @param taskID
+ */
+ private static Runnable createTask7(final int id, final String field) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Statement statement = conn.createStatement();
+ String updateQuery = "UPDATE "
+ + DatabaseCreator.TEST_TABLE1 + " SET " + field
+ + "= " + field + "+ 1 WHERE id=" + id;
+ statement.execute(updateQuery);
+ } catch (Exception e) {
+ System.err.println(e.getMessage());
+ }
+ }
+ };
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java b/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java
new file mode 100755
index 0000000..a0ded6a
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/SelectFunctionalityTest.java
@@ -0,0 +1,542 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.io.CharArrayReader;
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Time;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.HashMap;
+import java.util.HashSet;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class SelectFunctionalityTest extends TestCase {
+
+ private static Connection conn;
+
+ private static Statement statement;
+
+ private static Date date;
+
+ private static Time time;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ }
+
+ protected void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ SelectFunctionalityTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ conn.close();
+ statement.close();
+ }
+
+ private void createTestTables() {
+ try {
+ ResultSet userTab = conn.getMetaData().getTables(null,
+ null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE2)) {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ } else if (tableName
+ .equals(DatabaseCreator.SALESPEOPLE_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_SALESPEOPLE);
+ } else if (tableName
+ .equals(DatabaseCreator.CUSTOMERS_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_CUSTOMERS);
+ } else if (tableName
+ .equals(DatabaseCreator.ORDERS_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_ORDERS);
+ }
+ }
+ userTab.close();
+
+ statement.execute(DatabaseCreator.CREATE_TABLE2);
+ statement.execute(DatabaseCreator.CREATE_TABLE_SALESPEOPLE);
+ statement.execute(DatabaseCreator.CREATE_TABLE_CUSTOMERS);
+ statement.execute(DatabaseCreator.CREATE_TABLE_ORDERS);
+
+ long currentTime = Calendar.getInstance().getTimeInMillis();
+ date = new Date(currentTime);
+ time = new Time(currentTime);
+
+ DatabaseCreator.fillTestTable2(conn, 1, 5, currentTime);
+ DatabaseCreator.fillCustomersTable(conn);
+ DatabaseCreator.fillOrdersTable(conn);
+ DatabaseCreator.fillSalesPeopleTable(conn);
+
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ statement.execute(DatabaseCreator.DROP_TABLE_SALESPEOPLE);
+ statement.execute(DatabaseCreator.DROP_TABLE_CUSTOMERS);
+ statement.execute(DatabaseCreator.DROP_TABLE_ORDERS);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectSimple(). Selects all records
+ * from the table
+ */
+ public void test_SelectSimple() throws SQLException {
+ String sql = "SELECT * FROM " + DatabaseCreator.TEST_TABLE2;
+ ResultSet result = statement.executeQuery(sql);
+ int counter = 0;
+
+ while (result.next()) {
+ int id = result.getInt("finteger");
+ assertEquals("expected value doesn't equal actual",
+ DatabaseCreator.defaultString + id, result
+ .getString("ftext"));
+ assertEquals("expected value doesn't equal actual",
+ DatabaseCreator.defaultCharacter + id, result
+ .getString("fcharacter"));
+
+ // TODO getBigDecimal is not supported
+// assertEquals("expected value doesn't equal actual", BigDecimal
+// .valueOf(id + 0.1), result.getBigDecimal("fdecimal"));
+// assertEquals("expected value doesn't equal actual", BigDecimal
+// .valueOf(id + 0.1), result.getBigDecimal("fnumeric"));
+// assertEquals("expected value doesn't equal actual", id, result
+// .getInt("fsmallint"));
+ assertEquals("expected value doesn't equal actual", BigDecimal
+ .valueOf(id + 0.1).floatValue(), result.getFloat("ffloat"));
+ assertEquals("expected value doesn't equal actual", BigDecimal
+ .valueOf(id + 0.1).doubleValue(), result.getDouble("freal"));
+ assertEquals("expected value doesn't equal actual", BigDecimal
+ .valueOf(id + 0.1).doubleValue(), result
+ .getDouble("fdouble"));
+ assertEquals("expected value doesn't equal actual",
+ date.toString(), result.getDate("fdate").toString());
+ assertEquals("expected value doesn't equal actual",
+ time.toString(), result.getTime("ftime").toString());
+ counter++;
+ }
+
+ assertEquals("number of rows in ResultSet is wrong", 5, counter);
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectPrepared(). Selects all records
+ * from the table using parametric query
+ */
+ public void test_SelectPrepared() throws SQLException {
+ String sql = "SELECT finteger, ftext, fcharacter, fdecimal, fnumeric,"
+ + " fsmallint, ffloat, freal, fdouble, fdate, ftime" + " FROM "
+ + DatabaseCreator.TEST_TABLE2
+ + " WHERE finteger = ? AND ftext = ? AND fcharacter = ? AND"
+ + " fdecimal = ? AND fnumeric = ? AND fsmallint = ? AND"
+ + " freal = ? AND fdouble = ? AND fdate = ?" + " AND ftime = ?";
+ PreparedStatement prepStatement = conn.prepareStatement(sql);
+
+ CharArrayReader reader = new CharArrayReader(new String(
+ DatabaseCreator.defaultCharacter + "1").toCharArray());
+ prepStatement.setInt(1, 1);
+ prepStatement.setString(2, DatabaseCreator.defaultString + "1");
+// TODO setCharacterStream and setBigDecimal are not supported
+// prepStatement.setCharacterStream(3, reader, 4);
+// prepStatement.setBigDecimal(4, BigDecimal.valueOf(1.1));
+// prepStatement.setBigDecimal(5, BigDecimal.valueOf(1.1));
+ prepStatement.setInt(6, 1);
+ prepStatement.setDouble(7, 1.1);
+ prepStatement.setDouble(8, 1.1);
+ prepStatement.setDate(9, date);
+ prepStatement.setTime(10, time);
+
+ int counter = 0;
+ ResultSet result = prepStatement.executeQuery();
+ while (result.next()) {
+ int id = result.getInt("finteger");
+ assertEquals("expected value doesn't equal actual",
+ DatabaseCreator.defaultString + id, result
+ .getString("ftext"));
+ assertEquals("expected value doesn't equal actual",
+ DatabaseCreator.defaultCharacter + id, result
+ .getString("fcharacter"));
+// TODO getBigDecimal is not supported
+// assertEquals("expected value doesn't equal actual", BigDecimal
+// .valueOf(1.1), result.getBigDecimal("fdecimal"));
+// assertEquals("expected value doesn't equal actual", BigDecimal
+// .valueOf(1.1), result.getBigDecimal("fnumeric"));
+ assertEquals("expected value doesn't equal actual", id, result
+ .getInt("fsmallint"));
+ assertEquals("expected value doesn't equal actual",
+ (float) (id + 0.1), result.getFloat("ffloat"));
+ assertEquals("expected value doesn't equal actual",
+ (double) (id + 0.1), result.getDouble("freal"));
+ assertEquals("expected value doesn't equal actual",
+ (double) (id + 0.1), result.getDouble("fdouble"));
+ assertEquals("expected value doesn't equal actual",
+ date.toString(), result.getDate("fdate").toString());
+ assertEquals("expected value doesn't equal actual",
+ time.toString(), result.getTime("ftime").toString());
+ counter++;
+ }
+// TODO query wasn't executed due to "not supported" methods
+// assertEquals("number of rows in ResultSet is wrong", 1, counter);
+ prepStatement.close();
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SubSelect(). Selects records from the
+ * table using subselect
+ */
+ public void test_SubSelect() throws SQLException {
+ String sql = "SELECT finteger," + " (SELECT ftext FROM "
+ + DatabaseCreator.TEST_TABLE2 + " WHERE finteger = 1) as ftext"
+ + " FROM " + DatabaseCreator.TEST_TABLE2;
+ ResultSet result = statement.executeQuery(sql);
+
+ HashMap<Integer, String> value = new HashMap<Integer, String>();
+ value.put(1, DatabaseCreator.defaultString + "1");
+ value.put(2, DatabaseCreator.defaultString + "1");
+ value.put(3, DatabaseCreator.defaultString + "1");
+ value.put(4, DatabaseCreator.defaultString + "1");
+ value.put(5, DatabaseCreator.defaultString + "1");
+
+ while (result.next()) {
+ int key = result.getInt("finteger");
+ String val = result.getString("ftext");
+ assertTrue("wrong value of finteger field", value.containsKey(key));
+ assertEquals("wrong value of ftext field", value.get(key), val);
+ value.remove(key);
+ }
+ assertTrue("expected rows number doesn't equal actual rows number",
+ value.isEmpty());
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectThreeTables(). Selects records
+ * from a few tables
+ */
+ public void test_SelectThreeTables() throws SQLException {
+ String sql = "SELECT onum, " + DatabaseCreator.ORDERS_TABLE + ".cnum"
+ + " FROM " + DatabaseCreator.SALESPEOPLE_TABLE + ", "
+ + DatabaseCreator.CUSTOMERS_TABLE + ", "
+ + DatabaseCreator.ORDERS_TABLE + " WHERE "
+ + DatabaseCreator.CUSTOMERS_TABLE + ".city <> "
+ + DatabaseCreator.SALESPEOPLE_TABLE + ".city" + " AND "
+ + DatabaseCreator.ORDERS_TABLE + ".cnum = "
+ + DatabaseCreator.CUSTOMERS_TABLE + ".cnum" + " AND "
+ + DatabaseCreator.ORDERS_TABLE + ".snum = "
+ + DatabaseCreator.SALESPEOPLE_TABLE + ".snum";
+ ResultSet result = statement.executeQuery(sql);
+
+ HashMap<Integer, Integer> value = new HashMap<Integer, Integer>();
+ value.put(3001, 2008);
+ value.put(3002, 2007);
+ value.put(3006, 2008);
+ value.put(3009, 2002);
+ value.put(3007, 2004);
+ value.put(3010, 2004);
+
+ while (result.next()) {
+ int key = result.getInt("onum");
+ int val = result.getInt("cnum");
+ assertTrue("wrong value of onum field", value.containsKey(key));
+ assertEquals("wrong value of cnum field", value.get(key),
+ (Integer) val);
+ value.remove(key);
+ }
+ assertTrue("expected rows number doesn't equal actual rows number",
+ value.isEmpty());
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectThreeTables(). Selects records
+ * from a table using union
+ */
+ public void test_SelectUnionItself() throws SQLException {
+ String sql = "SELECT b.cnum, b.cname" + " FROM "
+ + DatabaseCreator.CUSTOMERS_TABLE + " a, "
+ + DatabaseCreator.CUSTOMERS_TABLE + " b"
+ + " WHERE a.snum = 1002" + " AND b.city = a.city";
+ ResultSet result = statement.executeQuery(sql);
+
+ HashMap<Integer, String> value = new HashMap<Integer, String>();
+ value.put(2003, "Liu");
+ value.put(2004, "Grass");
+ value.put(2008, "Cisneros");
+
+ while (result.next()) {
+ int key = result.getInt("cnum");
+ String val = result.getString("cname");
+ assertTrue("wrong value of cnum field", value.containsKey(key));
+ assertEquals("wrong value of cname field", value.get(key), val);
+ value.remove(key);
+ }
+ assertTrue("expected rows number doesn't equal actual rows number",
+ value.isEmpty());
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectLeftOuterJoin(). Selects
+ * records from a table using left join
+ */
+ public void test_SelectLeftOuterJoin() throws SQLException {
+ String sql = "SELECT distinct s.snum as ssnum, c.snum as ccnum FROM "
+ + DatabaseCreator.CUSTOMERS_TABLE + " c left outer join "
+ + DatabaseCreator.SALESPEOPLE_TABLE + " s on s.snum=c.snum";
+ ResultSet result = statement.executeQuery(sql);
+
+ HashMap<Integer, Integer> value = new HashMap<Integer, Integer>();
+ value.put(1001, 1001);
+ value.put(1002, 1002);
+ value.put(1003, 1003);
+ value.put(1004, 1004);
+ value.put(1007, 1007);
+
+ while (result.next()) {
+ int key = result.getInt("ssnum");
+ Object val = result.getObject("ccnum");
+ assertTrue("wrong value of ssnum field", value.containsKey(key));
+ assertEquals("wrong value of ccnum field", value.get(key),
+ (Integer) val);
+ value.remove(key);
+ }
+ assertTrue("expected rows number doesn't equal actual rows number",
+ value.isEmpty());
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectRightOuterJoin(). Selects
+ * records from a table using right join
+ *
+ * TODO RIGHT and FULL OUTER JOINs are not supported
+ */
+/* public void test_SelectRightOuterJoin() throws SQLException {
+ String sql = "SELECT distinct s.snum as ssnum, c.snum as ccnum FROM "
+ + DatabaseCreator.CUSTOMERS_TABLE + " c right outer join "
+ + DatabaseCreator.SALESPEOPLE_TABLE + " s on s.snum=c.snum";
+ ResultSet result = statement.executeQuery(sql);
+
+ HashMap<Integer, Integer> value = new HashMap<Integer, Integer>();
+ value.put(1001, 1001);
+ value.put(1002, 1002);
+ value.put(1003, 1003);
+ value.put(1004, 1004);
+ value.put(1007, 1007);
+ value.put(1013, null);
+
+ while (result.next()) {
+ int key = result.getInt("ssnum");
+ Object val = result.getObject("ccnum");
+ assertTrue("wrong value of ssnum field", value.containsKey(key));
+ assertEquals("wrong value of ccnum field", value.get(key),
+ (Integer) val);
+ value.remove(key);
+ }
+ assertTrue("expected rows number doesn't equal actual rows number",
+ value.isEmpty());
+ result.close();
+ }
+*/
+ /**
+ * @tests SelectFunctionalityTest#test_SelectGroupBy(). Selects records from
+ * a table using group by
+ */
+ public void test_SelectGroupBy() throws SQLException {
+ String selectQuery = "SELECT rating, SUM(snum) AS sum FROM "
+ + DatabaseCreator.CUSTOMERS_TABLE + " GROUP BY rating";
+ ResultSet result = statement.executeQuery(selectQuery);
+
+ HashMap<Integer, Integer> values = new HashMap<Integer, Integer>();
+ values.put(100, 3006);
+ values.put(200, 2005);
+ values.put(300, 2009);
+
+ while (result.next()) {
+ int rating = result.getInt("rating");
+ int sum = result.getInt("sum");
+ assertTrue("Wrong value of rating field", values
+ .containsKey(rating));
+ assertEquals("Wrong value of sum field", values.get(rating),
+ new Integer(sum));
+ assertEquals(new Integer(sum), values.remove(rating));
+ }
+ result.close();
+ assertTrue("Result set has wrong size", values.isEmpty());
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectOrderBy(). Selects records from
+ * a table using order by
+ */
+ public void test_SelectOrderBy() throws SQLException {
+ String selectQuery = "SELECT onum FROM " + DatabaseCreator.ORDERS_TABLE
+ + " ORDER BY onum";
+ ResultSet result = statement.executeQuery(selectQuery);
+
+ ArrayList<Integer> values = new ArrayList<Integer>();
+ values.add(Integer.valueOf(3001));
+ values.add(Integer.valueOf(3002));
+ values.add(Integer.valueOf(3003));
+ values.add(Integer.valueOf(3005));
+ values.add(Integer.valueOf(3006));
+ values.add(Integer.valueOf(3007));
+ values.add(Integer.valueOf(3008));
+ values.add(Integer.valueOf(3009));
+ values.add(Integer.valueOf(3010));
+ values.add(Integer.valueOf(3011));
+
+ int index = 0;
+ while (result.next()) {
+ Integer onum = result.getInt("onum");
+ assertTrue("result set doesn't contain value", values
+ .contains(onum));
+ assertEquals("result set is not sorted", index, values
+ .indexOf(onum));
+ index++;
+ }
+ result.close();
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectDistinct(). Selects records
+ * from a table using distinct
+ */
+ public void test_SelectDistinct() throws SQLException {
+ String selectQuery = "SELECT DISTINCT rating FROM "
+ + DatabaseCreator.CUSTOMERS_TABLE;
+ ResultSet result = statement.executeQuery(selectQuery);
+
+ HashSet<Integer> values = new HashSet<Integer>();
+ values.add(Integer.valueOf(100));
+ values.add(Integer.valueOf(200));
+ values.add(Integer.valueOf(300));
+
+ while (result.next()) {
+ Integer rating = result.getInt("rating");
+ assertTrue("result set doesn't contain value", values
+ .contains(rating));
+ assertTrue("wrong value in the result set", values.remove(rating));
+ }
+ result.close();
+ assertTrue("Result set has wrong size", values.isEmpty());
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectAgregateFunctions(). Selects
+ * records from a table using agregate functions
+ */
+ public void test_SelectAgregateFunctions() throws SQLException {
+ String selectCount = "SELECT count(onum) as count FROM "
+ + DatabaseCreator.ORDERS_TABLE;
+ String selectSum = "SELECT sum(onum) as sum FROM "
+ + DatabaseCreator.ORDERS_TABLE;
+ String selectAvg = "SELECT avg(onum) as avg FROM "
+ + DatabaseCreator.ORDERS_TABLE;
+ String selectMax = "SELECT max(onum) as max FROM "
+ + DatabaseCreator.ORDERS_TABLE;
+ String selectMin = "SELECT min(onum) as min FROM "
+ + DatabaseCreator.ORDERS_TABLE;
+
+ func("count", selectCount, 10);
+ func("sum", selectSum, 30062);
+ func("avg", selectAvg, 3006);
+ func("max", selectMax, 3011);
+ func("min", selectMin, 3001);
+ }
+
+ private void func(String name, String query, int expected) {
+ try {
+ ResultSet result = statement.executeQuery(query);
+ while (result.next()) {
+ assertEquals("wrong value of " + name + " field", expected,
+ result.getInt(name));
+ }
+ assertFalse("wrong size of result set", result.next());
+ result.close();
+ } catch (SQLException e) {
+ fail(e.getMessage());
+ }
+ }
+
+ /**
+ * @tests SelectFunctionalityTest#test_SelectHaving(). Selects records from
+ * a table using having
+ */
+ public void test_SelectHaving() throws SQLException {
+ String selectQuery = "SELECT snum, max(amt) AS max FROM "
+ + DatabaseCreator.ORDERS_TABLE
+ + " GROUP BY snum HAVING max(amt) > 3000";
+ ResultSet result = statement.executeQuery(selectQuery);
+
+ HashSet<Double> values = new HashSet<Double>();
+ values.add(Double.valueOf(9891.88));
+ values.add(Double.valueOf(5160.45));
+
+ while (result.next()) {
+ Double max = result.getDouble("max");
+ assertTrue("result set doesn't contain value", values.contains(max));
+ assertTrue("wrong value in the result set", values.remove(max));
+ }
+ result.close();
+ assertTrue("Result set has wrong size", values.isEmpty());
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/StressTest.java b/sql/src/test/java/tests/java/sql/StressTest.java
new file mode 100755
index 0000000..fbafe82
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/StressTest.java
@@ -0,0 +1,310 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.Vector;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+import tests.support.ThreadPool;
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class StressTest extends TestCase {
+ Vector<Connection> vc = new Vector<Connection>();
+
+ private static Connection conn;
+
+ private static Statement statement;
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(StressTest.class)) {
+
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ }
+
+ protected void tearDown() throws Exception {
+ dropTestTables();
+ statement.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE2)) {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ }
+ }
+ statement.execute(DatabaseCreator.CREATE_TABLE2);
+ } catch (SQLException sql) {
+ fail("Unexpected SQLException " + sql.toString());
+ }
+ return;
+ }
+
+ private void dropTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ } catch (SQLException sql) {
+ fail("Unexpected SQLException " + sql.toString());
+ }
+ return;
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @see junit.framework.TestCase#setUp()
+ */
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ vc.clear();
+ }
+
+ /**
+ * @see junit.framework.TestCase#tearDown()
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ closeConnections();
+ statement.execute("DELETE FROM " + DatabaseCreator.TEST_TABLE2);
+ super.tearDown();
+ }
+
+ /**
+ * @tests StressTest#testManyConnectionsUsingOneThread(). Create many
+ * connections to the DataBase using one thread.
+ */
+ public void testManyConnectionsUsingOneThread() {
+ try {
+ int maxConnections = getConnectionNum();
+ openConnections(maxConnections);
+ assertEquals("Incorrect number of created connections",
+ maxConnections, vc.size());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.toString());
+ }
+ }
+
+ /**
+ * @tests StressTest#testManyConnectionsUsingManyThreads(). Create many
+ * connections to the DataBase using some threads.
+ */
+ public void testManyConnectionsUsingManyThreads() {
+ int numTasks = getConnectionNum();
+
+ ThreadPool threadPool = new ThreadPool(numTasks);
+
+ // run example tasks
+ for (int i = 0; i < numTasks; i++) {
+ threadPool.runTask(createTask(i));
+ }
+ // close the pool and wait for all tasks to finish.
+ threadPool.join();
+ assertEquals("Unable to create a connection", numTasks, vc.size());
+ if (numTasks != Support_SQL.sqlMaxConnections) {
+ try {
+ // try to create connection n + 1
+ Connection c = Support_SQL.getConnection();
+ c.close();
+ fail("It is possible to create more than " + numTasks
+ + "connections");
+ } catch (SQLException sql) {
+ // expected
+ }
+ }
+ }
+
+ /**
+ * @tests StressTest#testInsertOfManyRowsUsingOneThread(). Insert a lot of
+ * records to the DataBase using a maximum number of connections.
+ */
+ public void testInsertOfManyRowsUsingOneThread() {
+ // TODO Crashes VM. Fix later.
+ /*
+ * int maxConnections = getConnectionNum();
+ * openConnections(maxConnections); int tasksPerConnection =
+ * Support_SQL.sqlMaxTasks / maxConnections; int pk = 1; for (int i = 0;
+ * i < vc.size(); ++i) { Connection c = vc.elementAt(i); for (int j = 0;
+ * j < tasksPerConnection; ++j) { insertNewRecord(c, pk++); } } try {
+ * ResultSet rs = statement.executeQuery("SELECT COUNT(*) as counter
+ * FROM " + DatabaseCreator.TEST_TABLE2); assertTrue("RecordSet is
+ * empty", rs.next()); assertEquals("Incorrect number of records",
+ * tasksPerConnection * maxConnections, rs.getInt("counter"));
+ * rs.close(); } catch (SQLException sql) { fail("Unexpected
+ * SQLException " + sql.toString()); }
+ */
+ }
+
+ /**
+ * @tests
+ */
+ public void testInsertOfManyRowsUsingManyThreads() {
+ // TODO Crashes VM. Fix later.
+ /*
+ * int numConnections = getConnectionNum();
+ *
+ * ThreadPool threadPool = new ThreadPool(numConnections);
+ *
+ * for (int i = 0; i < numConnections; ++i) {
+ * threadPool.runTask(insertTask(numConnections, i)); }
+ * // close the pool and wait for all tasks to finish.
+ * threadPool.join(); assertEquals("Unable to create a connection",
+ * numConnections, vc.size()); try { ResultSet rs =
+ * statement.executeQuery("SELECT COUNT(*) as counter FROM " +
+ * DatabaseCreator.TEST_TABLE2); assertTrue("RecordSet is empty",
+ * rs.next()); int tasksPerConnection = Support_SQL.sqlMaxTasks /
+ * numConnections; assertEquals("Incorrect number of records",
+ * tasksPerConnection * numConnections, rs.getInt("counter"));
+ * rs.close(); } catch (SQLException sql) { fail("Unexpected
+ * SQLException " + sql.toString()); }
+ */
+ }
+
+ private int getConnectionNum() {
+ int num = Support_SQL.sqlMaxConnections;
+ try {
+ int mc = conn.getMetaData().getMaxConnections();
+ if (mc != 0) {
+ if (num != mc) {
+ System.err.println("Will be used no more than " + mc
+ + " connections to the DataBase");
+ }
+ num = mc;
+ }
+ } catch (SQLException sql) {
+ fail("Unexpected SQLException " + sql.toString());
+ }
+ return num;
+ }
+
+ private void openConnections(int maxConnections) {
+ int i = 0;
+ try {
+ for (; i < maxConnections; ++i) {
+ Connection c = Support_SQL.getConnection();
+ if (c == null) {
+ assertEquals("Unable to create a connection",
+ maxConnections, i);
+ }
+ vc.add(c);
+ }
+ } catch (SQLException sql) {
+ assertEquals("Unable to create a connection", maxConnections, i);
+ }
+ return;
+ }
+
+ private void closeConnections() {
+ int i = 0;
+ try {
+ for (; i < vc.size(); ++i) {
+ vc.elementAt(i).close();
+ }
+ } catch (SQLException sql) {
+ assertEquals("Unable to close a connection", vc.size(), i);
+ }
+ return;
+ }
+
+ private Runnable createTask(final int taskID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Connection c = Support_SQL.getConnection();
+ if (c == null) {
+ return;
+ }
+ synchronized (this) {
+ vc.add(c);
+ }
+ } catch (SQLException sql) {
+ // nothing to do
+ }
+ }
+ };
+ }
+
+ private Runnable insertTask(final int numConnections, final int taskID) {
+ return new Runnable() {
+ public void run() {
+ try {
+ Connection c = Support_SQL.getConnection();
+ if (c == null) {
+ return;
+ }
+ synchronized (this) {
+ vc.add(c);
+ }
+ int tasksPerConnection = Support_SQL.sqlMaxTasks
+ / numConnections;
+ for (int i = 0; i < tasksPerConnection; ++i) {
+ insertNewRecord(c, (i + 1) + tasksPerConnection
+ * taskID);
+ }
+ } catch (SQLException sql) {
+ // do nothing
+ }
+ }
+ };
+ }
+
+ private void insertNewRecord(Connection c, int pk) {
+ String query = "INSERT INTO " + DatabaseCreator.TEST_TABLE2
+ + "(finteger, ftext, fcharacter, fdecimal, fnumeric,"
+ + " fsmallint, ffloat, freal, fdouble, fdate, ftime)"
+ + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+ try {
+ PreparedStatement ps = c.prepareStatement(query);
+ ps.setInt(1, pk);
+ ps.setString(2, "text");
+ ps.setString(3, "chr");
+ ps.setFloat(4, 0.1f);
+ ps.setFloat(5, 0.2f);
+ ps.setShort(6, (short) 3);
+ ps.setFloat(7, 0.4f);
+ ps.setDouble(8, 0.5);
+ ps.setDouble(9, 0.6);
+ ps.setDate(10, new java.sql.Date(System.currentTimeMillis()));
+ ps.setTime(11, new java.sql.Time(System.currentTimeMillis()));
+ ps.execute();
+ ps.close();
+ } catch (SQLException sql) {
+ fail("Unexpected SQLException " + sql.toString());
+ }
+ return;
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest.java b/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest.java
new file mode 100755
index 0000000..b9761cd
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest.java
@@ -0,0 +1,365 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.HashSet;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class UpdateFunctionalityTest extends TestCase {
+
+ private static final int numberOfRecords = 20;
+
+ private static Connection conn;
+
+ private static Statement statement;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ DatabaseCreator.fillTestTable1(conn, numberOfRecords);
+ DatabaseCreator.fillTestTable2(conn, numberOfRecords);
+ }
+
+ protected void tearDown() throws Exception {
+ String deleteQuery1 = "DELETE FROM " + DatabaseCreator.TEST_TABLE1;
+ String deleteQuery2 = "DELETE FROM " + DatabaseCreator.TEST_TABLE2;
+
+ statement.execute(deleteQuery1);
+ statement.execute(deleteQuery2);
+ super.tearDown();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ UpdateFunctionalityTest.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ statement.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.TEST_TABLE1)) {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE2)) {
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE3)) {
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ }
+ }
+ userTab.close();
+
+ statement.execute(DatabaseCreator.CREATE_TABLE3);
+ statement.execute(DatabaseCreator.CREATE_TABLE2);
+ statement.execute(DatabaseCreator.CREATE_TABLE1);
+
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE1);
+ statement.execute(DatabaseCreator.DROP_TABLE2);
+ statement.execute(DatabaseCreator.DROP_TABLE3);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate1(). Updates all values in one
+ * column in the table
+ */
+ public void testUpdate1() {
+ String newValue = "newValue";
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field1='" + newValue + "'";
+ try {
+ int num = statement.executeUpdate(updateQuery);
+ assertEquals("Not all records in the database were updated",
+ numberOfRecords, num);
+ String selectQuery = "SELECT field1 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ assertEquals("The field field1 was not updated", newValue,
+ result.getString("field1"));
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate2(). Updates values in one
+ * column in the table using where condition in update command
+ */
+ public void testUpdate2() {
+ String newValue = "newValue";
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field1='" + newValue + "' WHERE (id > 2) and (id < 10)";
+ try {
+ int num = statement.executeUpdate(updateQuery);
+ int expectedUpdated = 7;
+ assertEquals("Not all records in the database were updated",
+ expectedUpdated, num);
+ String selectQuery = "SELECT * FROM " + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ int id = result.getInt("id");
+ String field1 = result.getString("field1");
+ if ((id > 2) && (id < 10)) {
+ assertEquals("The field field1 was not updated", newValue,
+ field1);
+ } else {
+ assertEquals("The field field1 was not updated",
+ DatabaseCreator.defaultString + id, field1);
+ }
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate3(). Updates values in a several
+ * columns in the table
+ */
+ public void testUpdate3() {
+ int newValue1 = -1;
+ int newValue2 = -2;
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2=" + newValue1 + ", field3=" + newValue2;
+ try {
+ int num = statement.executeUpdate(updateQuery);
+ assertEquals("Not all records in the database were updated",
+ numberOfRecords, num);
+ String selectQuery = "SELECT field2, field3 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ // TODO getBigDecimal is not supported
+// assertEquals("The field field2 was not updated", newValue1,
+// result.getBigDecimal("field2").intValue());
+// assertEquals("The field field3 was not updated", newValue2,
+// result.getBigDecimal("field3").intValue());
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate4(). Updates values in a several
+ * columns in the table using where condition in update command
+ */
+ public void testUpdate4() {
+ int newValue1 = -1;
+ int newValue2 = -2;
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2=" + newValue1 + ", field3=" + newValue2
+ + " WHERE id > 10";
+ try {
+ int num = statement.executeUpdate(updateQuery);
+ int expectedUpdated = 9;
+ assertEquals("Not all records in the database were updated",
+ expectedUpdated, num);
+ String selectQuery = "SELECT id, field2, field3 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ int id = result.getInt("id");
+ // TODO getBigDecimal is not supported
+// int value2 = result.getBigDecimal("field2").intValue();
+// int value3 = result.getBigDecimal("field3").intValue();
+// if (id > expectedUpdated + 1) {
+// assertEquals("The field field2 was not updated", newValue1,
+// value2);
+// assertEquals("The field field3 was not updated", newValue2,
+// value3);
+// } else {
+// assertEquals("The field field2 was not updated", id, value2);
+// assertEquals("The field field3 was not updated", id, value3);
+// }
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate5(). Updates values in one
+ * columns in the table using condition
+ */
+ public void testUpdate5() {
+ int factor = 3;
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2=field2 *" + factor;
+ try {
+ String selectQuery = "SELECT field2 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ HashSet<BigDecimal> values = new HashSet<BigDecimal>();
+ // TODO getBigDecimal is not supported
+// while (result.next()) {
+// values.add(BigDecimal.valueOf(result.getBigDecimal("field2")
+// .intValue()
+// * factor));
+// }
+
+ int num = statement.executeUpdate(updateQuery);
+ assertEquals("Not all records in the database were updated",
+ numberOfRecords, num);
+ result = statement.executeQuery(selectQuery);
+ // TODO getBigDecimal is not supported
+// while (result.next()) {
+// BigDecimal value = result.getBigDecimal("field2");
+// assertTrue("Wrong value of field2 after update"
+// + value.intValue(), values.remove(value));
+// }
+ assertTrue("Not all records were updated", values.isEmpty());
+
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate6(). Sets value of field2 to
+ * default
+ */
+ public void testUpdate6() {
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2='1'";
+ try {
+
+ int num = statement.executeUpdate(updateQuery);
+ assertEquals("Not all records in the database were updated",
+ numberOfRecords, num);
+ String selectQuery = "SELECT field2 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ // TODO getBigDecimal is not supported
+// while (result.next()) {
+// assertEquals("value of field2 should be default ",
+// DatabaseCreator.defaultInt, result.getBigDecimal(
+// "field2").intValue());
+// }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate7(). Updates records in the
+ * table using subquery in update command
+ */
+ public void testUpdate7() {
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2='1' WHERE id < ( SELECT COUNT(*) FROM "
+ + DatabaseCreator.TEST_TABLE2 + " WHERE finteger > 15)";
+ try {
+ int num = statement.executeUpdate(updateQuery);
+ int expectedUpdated = 4;
+ assertEquals("Not all records in the database were updated",
+ expectedUpdated, num);
+ String selectQuery = "SELECT id, field2 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ // TODO getBigDecimal is not supported
+// int value = result.getBigDecimal("field2").intValue();
+// int id = result.getInt("id");
+// if (id < expectedUpdated) {
+// assertEquals("value of field2 should be default ",
+// DatabaseCreator.defaultInt, value);
+// } else {
+// assertEquals("wrong value of field2", id, value);
+// }
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest#testUpdate8(). Sets value of field2 to
+ * NULL
+ */
+ public void testUpdate8() {
+ String updateQuery = "UPDATE " + DatabaseCreator.TEST_TABLE1
+ + " SET field2=NULL";
+ try {
+
+ int num = statement.executeUpdate(updateQuery);
+ assertEquals("Not all records in the database were updated",
+ numberOfRecords, num);
+ String selectQuery = "SELECT field2 FROM "
+ + DatabaseCreator.TEST_TABLE1;
+ ResultSet result = statement.executeQuery(selectQuery);
+ while (result.next()) {
+ assertNull("value of field2 should be NULL", result
+ .getObject("field2"));
+ }
+ result.close();
+ } catch (SQLException e) {
+ fail("Unexpected exception" + e.getMessage());
+ }
+ }
+}
diff --git a/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest2.java b/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest2.java
new file mode 100755
index 0000000..7bcbff6
--- /dev/null
+++ b/sql/src/test/java/tests/java/sql/UpdateFunctionalityTest2.java
@@ -0,0 +1,296 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.java.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import tests.support.DatabaseCreator;
+import tests.support.Support_SQL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class UpdateFunctionalityTest2 extends TestCase {
+
+ private static Connection conn = null;
+
+ private static Statement statement = null;
+
+ protected void setUp() throws Exception {
+ super.setUp();
+ DatabaseCreator.fillParentTable(conn);
+ DatabaseCreator.fillSimpleTable3(conn);
+ DatabaseCreator.fillSimpleTable1(conn);
+ }
+
+ protected void tearDown() throws Exception {
+ statement.execute("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE3);
+ statement.execute("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKCASCADE_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.PARENT_TABLE);
+ statement.execute("DELETE FROM " + DatabaseCreator.TEST_TABLE5);
+ super.tearDown();
+ }
+
+ public static Test suite() {
+ TestSetup setup = new TestSetup(new TestSuite(
+ UpdateFunctionalityTest2.class)) {
+ protected void setUp() throws Exception {
+ Support_SQL.loadDriver();
+ try {
+ conn = Support_SQL.getConnection();
+ statement = conn.createStatement();
+ createTestTables();
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ protected void tearDown() throws Exception {
+ deleteTestTables();
+ statement.close();
+ conn.close();
+ }
+
+ private void createTestTables() {
+ try {
+ DatabaseMetaData meta = conn.getMetaData();
+ ResultSet userTab = meta.getTables(null, null, null, null);
+
+ while (userTab.next()) {
+ String tableName = userTab.getString("TABLE_NAME");
+ if (tableName.equals(DatabaseCreator.PARENT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_PARENT);
+ } else if (tableName
+ .equals(DatabaseCreator.FKCASCADE_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ } else if (tableName
+ .equals(DatabaseCreator.FKSTRICT_TABLE)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ } else if (tableName
+ .equals(DatabaseCreator.SIMPLE_TABLE1)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_SIMPLE1);
+ } else if (tableName
+ .equals(DatabaseCreator.SIMPLE_TABLE3)) {
+ statement
+ .execute(DatabaseCreator.DROP_TABLE_SIMPLE3);
+ } else if (tableName
+ .equals(DatabaseCreator.TEST_TABLE5)) {
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ }
+ }
+ userTab.close();
+ statement.execute(DatabaseCreator.CREATE_TABLE_PARENT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.CREATE_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE3);
+ statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1);
+ statement.execute(DatabaseCreator.CREATE_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+
+ private void deleteTestTables() {
+ try {
+ statement.execute(DatabaseCreator.DROP_TABLE_FKCASCADE);
+ statement.execute(DatabaseCreator.DROP_TABLE_FKSTRICT);
+ statement.execute(DatabaseCreator.DROP_TABLE_PARENT);
+ statement.execute(DatabaseCreator.DROP_TABLE_SIMPLE3);
+ statement.execute(DatabaseCreator.DROP_TABLE_SIMPLE1);
+ statement.execute(DatabaseCreator.DROP_TABLE5);
+ } catch (SQLException e) {
+ fail("Unexpected SQLException " + e.toString());
+ }
+ }
+ };
+ return setup;
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate1(). Updates row with no
+ * referencing ones and RESTRICT action
+ */
+ public void testUpdate1() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("UPDATE " + DatabaseCreator.PARENT_TABLE
+ + " SET id = 4 WHERE id = 3");
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate2(). Attempts to update row
+ * with referencing ones and RESTRICT action - expecting SQLException
+ *
+ * TODO not supported
+ */
+/* public void testUpdate2() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ try {
+ statement.execute("UPDATE " + DatabaseCreator.PARENT_TABLE
+ + " SET id = 5 WHERE id = 1;");
+ fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+
+ }
+ }
+*/
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate3(). Deletes all referencing
+ * rows and then updates referenced one
+ */
+ public void testUpdate3() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("DELETE FROM " + DatabaseCreator.FKSTRICT_TABLE
+ + " WHERE name_id = 1;");
+ statement.execute("UPDATE " + DatabaseCreator.PARENT_TABLE
+ + " SET id = 5 WHERE id = 1;");
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate4(). Attempts to set incorrect
+ * foreign key value - expecting SQLException
+ *
+ * TODO foreign key functionality is not supported
+ */
+/* public void testUpdate4() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ try {
+ statement.execute("UPDATE " + DatabaseCreator.FKSTRICT_TABLE
+ + " SET name_id = 6 WHERE name_id = 2");
+ fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate5(). Updates row with
+ * referencing ones and CASCADE action - expecting that all
+ * referencing rows will also be updated
+ */
+ public void testUpdate5() throws SQLException {
+ DatabaseCreator.fillFKCascadeTable(conn);
+ statement.execute("UPDATE " + DatabaseCreator.PARENT_TABLE
+ + " SET id = 5 WHERE id = 1;");
+
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) " + "FROM "
+ + DatabaseCreator.FKCASCADE_TABLE + " WHERE name_id = 1;");
+ r.next();
+ assertEquals("Should be 2 rows", 2, r.getInt(1));
+ r = statement.executeQuery("SELECT COUNT(*) " + "FROM "
+ + DatabaseCreator.FKCASCADE_TABLE + " WHERE name_id = 5;");
+ r.next();
+ assertEquals("Should be 0 rows", 0, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate6(). Attempts to set incorrect
+ * foreign key value to row with CASCADE action - expecting
+ * SQLException
+ *
+ * TODO Foreign key functionality is not supported
+ */
+ /* public void testUpdate6() throws SQLException {
+ DatabaseCreator.fillFKCascadeTable(conn);
+ try {
+ statement.execute("UPDATE " + DatabaseCreator.FKCASCADE_TABLE
+ + " SET name_id = 6 WHERE name_id = 2");
+ fail("expecting SQLException");
+ } catch (SQLException ex) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate7(). Updates table using
+ * subquery in WHERE clause
+ *
+ * TODO Foreign key functionality is not supported
+ */
+/* public void testUpdate7() throws SQLException {
+ DatabaseCreator.fillFKStrictTable(conn);
+ statement.execute("UPDATE " + DatabaseCreator.FKSTRICT_TABLE
+ + " SET value = 'updated' WHERE name_id = ANY (SELECT id FROM "
+ + DatabaseCreator.PARENT_TABLE + " WHERE id > 1)");
+ ResultSet r = statement.executeQuery("SELECT COUNT(*) FROM "
+ + DatabaseCreator.FKSTRICT_TABLE + " WHERE value = 'updated';");
+ r.next();
+ assertEquals("Should be 1 row", 1, r.getInt(1));
+ r.close();
+ }
+*/
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate8(). Updates table using scalar
+ * subquery as new field value
+ */
+ public void testUpdate8() throws SQLException {
+ statement.execute("UPDATE " + DatabaseCreator.SIMPLE_TABLE3
+ + " SET speed = (SELECT MAX(speed) FROM "
+ + DatabaseCreator.SIMPLE_TABLE1
+ + ") WHERE id = (SELECT id FROM "
+ + DatabaseCreator.SIMPLE_TABLE1
+ + " WHERE speed = (SELECT MAX(speed) FROM "
+ + DatabaseCreator.SIMPLE_TABLE1 + "))");
+ ResultSet r = statement.executeQuery("SELECT id FROM "
+ + DatabaseCreator.SIMPLE_TABLE3
+ + " WHERE speed = (SELECT MAX(speed) FROM "
+ + DatabaseCreator.SIMPLE_TABLE1 + ");");
+ r.next();
+ assertEquals("Incorrect id updated", 1, r.getInt(1));
+ r.close();
+ }
+
+ /**
+ * @tests UpdateFunctionalityTest2#testUpdate9(). Updates table using
+ * PreparedStatement
+ */
+ public void testUpdate9() throws SQLException {
+ DatabaseCreator.fillTestTable5(conn);
+ PreparedStatement stat = conn.prepareStatement("UPDATE "
+ + DatabaseCreator.TEST_TABLE5
+ + " SET testValue = ? WHERE testID = ?");
+ stat.setString(1, "1");
+ stat.setInt(2, 1);
+ stat.execute();
+ stat.setString(1, "2");
+ stat.setInt(2, 2);
+ stat.execute();
+ ResultSet r = statement.executeQuery("SELECT testId, testValue FROM "
+ + DatabaseCreator.TEST_TABLE5
+ + " WHERE testID < 3 ORDER BY testID");
+ while (r.next()) {
+ assertEquals("Incorrect value was returned", new Integer(r
+ .getInt(1)).toString(), r.getString(2));
+ }
+ r.close();
+ stat.close();
+ }
+}
diff --git a/sql/src/test/java/tests/sql/AbstractSqlTest.java b/sql/src/test/java/tests/sql/AbstractSqlTest.java
new file mode 100644
index 0000000..9d922db
--- /dev/null
+++ b/sql/src/test/java/tests/sql/AbstractSqlTest.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import junit.framework.TestCase;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+
+/**
+ * This class provides SQL unit test, which can be used by subclasses eg. to
+ * test JDBC drivers.
+ */
+public abstract class AbstractSqlTest extends TestCase {
+
+ /**
+ * The first connection.
+ */
+ private Connection firstConnection;
+
+ /**
+ * The second connection.
+ */
+ private Connection secondConnection;
+
+ /**
+ * The statement from the first connection.
+ */
+ private Statement firstStmt;
+
+ /**
+ * The statement from the second connection.
+ */
+ private Statement secondStmt;
+
+ /**
+ * The values of the first column "one".
+ */
+ private final String[] ones = {"hello!", "goodbye"};
+
+ /**
+ * The values of the second column "two".
+ */
+ private final short[] twos = {10, 20};
+
+ /**
+ * The updated values of the first column "one".
+ */
+ private final String[] ones_updated;
+
+ /** Creates a new instance of this class */
+ public AbstractSqlTest(String testName) {
+ super(testName);
+ ones_updated = new String[ones.length];
+ for (int i = 0; i < ones.length; i++) {
+ ones_updated[i] = ones[i] + twos[i];
+ }
+ }
+
+ /**
+ * Sets up a unit test, by creating two statements from two connections and
+ * creating a test table.
+ *
+ * @exception SQLException if there is a problem accessing the database
+ * @exception Exception may be thrown by subclasses
+ */
+ @Override
+ protected void setUp() throws SQLException, Exception {
+ Class.forName(getDriverClassName()).newInstance();
+ firstConnection = DriverManager.getConnection(getConnectionURL());
+ firstConnection.setTransactionIsolation(getTransactionIsolation());
+ secondConnection = DriverManager.getConnection(getConnectionURL());
+ secondConnection.setTransactionIsolation(getTransactionIsolation());
+ firstStmt = firstConnection.createStatement();
+ firstStmt.execute("create table tbl1(one varchar(10), two smallint)");
+ secondStmt = secondConnection.createStatement();
+ }
+
+ /**
+ * Tears down a unit test, by setting the auto commit property of the first
+ * connection back to true, dropping the test table and closing the two
+ * connections.
+ */
+ @Override
+ protected void tearDown() throws SQLException {
+ firstStmt.close();
+ secondStmt.close();
+ firstConnection.setAutoCommit(true);
+ firstStmt = firstConnection.createStatement();
+ firstStmt.execute("drop table tbl1");
+ firstStmt.close();
+ firstConnection.close();
+ secondConnection.close();
+ }
+
+ /**
+ * Adds some rows to the test table and asserts that the rows can be
+ * retrieved again.
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void autoCommitInsertSelect() throws SQLException {
+ firstStmt.getConnection().setAutoCommit(true);
+ for (int i = 0; i < ones.length; i++) {
+ firstStmt.execute("insert into tbl1 values('" + ones[i] + "',"
+ + twos[i] + ")");
+ }
+ assertAllFromTbl1(firstStmt, ones, twos);
+ }
+
+ /**
+ * Asserts that the expected values can be selected from the test table.
+ *
+ * @param stmt the statement to be used for the selection of the data
+ * @param ones the expected values of the column 'one'
+ * @param twos the expected values of the column 'two'
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void assertAllFromTbl1(Statement stmt, String[] ones, short[] twos)
+ throws SQLException {
+ ResultSet rs = stmt.executeQuery("select * from tbl1");
+ int i = 0;
+ for (; rs.next(); i++) {
+ assertTrue(i < ones.length);
+ assertEquals(ones[i], rs.getString("one"));
+ assertEquals(twos[i], rs.getShort("two"));
+ }
+ assertTrue(i == ones.length);
+ }
+
+ public void testAutoCommitInsertSelect() throws SQLException{
+ autoCommitInsertSelect();
+ }
+
+ /**
+ * Tests the following sequence after successful insertion of some test
+ * data:
+ * - update data from connection one
+ * - select data from connection two (-> should have the old values)
+ * - commit data from connection one
+ * - select data from connection two (-> should have the new values)
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ public void testUpdateSelectCommitSelect() throws SQLException {
+ autoCommitInsertSelect();
+ firstStmt.getConnection().setAutoCommit(false);
+ updateOnes(firstStmt, ones_updated, twos);
+ assertAllFromTbl1(secondStmt, ones, twos);
+ firstStmt.getConnection().commit();
+ assertAllFromTbl1(secondStmt, ones_updated, twos);
+ }
+
+ /**
+ * Tests the following sequence after successful insertion of some test
+ * data:
+ * - update data from connection one
+ * - select data from connection two (-> should have the old values)
+ * - rollback data from connection one
+ * - select data from connection two (-> should still have the old values)
+ *
+ * @throws SQLException if there is a problem accessing the database
+ */
+ public void testUpdateSelectRollbackSelect() throws SQLException {
+ autoCommitInsertSelect();
+ firstStmt.getConnection().setAutoCommit(false);
+ updateOnes(firstStmt, ones_updated, twos);
+ assertAllFromTbl1(secondStmt, ones, twos);
+ firstStmt.getConnection().rollback();
+ assertAllFromTbl1(secondStmt, ones, twos);
+ }
+
+ /**
+ * Updates the values in column 'one'
+ * @param stmt the statement to be used to update the data
+ * @param ones_updated the updated valus of column 'one'
+ * @param twos the reference values of column 'two'
+ * @throws SQLException if there is a problem accessing the database
+ */
+ private void updateOnes(Statement stmt, String[] ones_updated, short[] twos)
+ throws SQLException {
+ for (int i = 0; i < ones_updated.length; i++) {
+ stmt.execute("UPDATE tbl1 SET one = '" + ones_updated[i]
+ + "' WHERE two = " + twos[i]);
+ }
+ }
+
+ protected abstract String getConnectionURL();
+
+ protected abstract String getDriverClassName();
+
+ protected abstract int getTransactionIsolation();
+
+}
diff --git a/sql/src/test/java/tests/sql/AllTests.java b/sql/src/test/java/tests/sql/AllTests.java
new file mode 100644
index 0000000..afd9ba3
--- /dev/null
+++ b/sql/src/test/java/tests/sql/AllTests.java
@@ -0,0 +1,46 @@
+/* Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * Test suite that includes all tests for the Math project.
+ */
+public class AllTests {
+
+ public static void main(String[] args) {
+ junit.textui.TestRunner.run(AllTests.suite());
+ }
+
+ public static Test suite() {
+ TestSuite suite = new TestSuite("All SQL test suites");
+ // $JUnit-BEGIN$
+ suite.addTest(org.apache.harmony.sql.tests.java.sql.AllTests.suite());
+ suite.addTest(org.apache.harmony.sql.tests.javax.sql.AllTests.suite());
+ suite.addTest(tests.java.sql.AllTests.suite());
+
+ suite.addTestSuite(SQLite.JDBCDriverTest.class);
+ suite.addTestSuite(tests.sql.ConnectionTest.class);
+ suite.addTestSuite(tests.sql.PreparedStatementTest.class);
+ suite.addTestSuite(tests.sql.ResultSetMetaDataTest.class);
+ suite.addTestSuite(tests.sql.StatementTest.class);
+ // $JUnit-END$
+ return suite;
+ }
+}
diff --git a/sql/src/test/java/tests/sql/ConnectionTest.java b/sql/src/test/java/tests/sql/ConnectionTest.java
new file mode 100755
index 0000000..ba6fff2
--- /dev/null
+++ b/sql/src/test/java/tests/sql/ConnectionTest.java
@@ -0,0 +1,1958 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.SQLWarning;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+
+import java.sql.CallableStatement;
+
+import junit.framework.Test;
+
+public class ConnectionTest extends SQLTest {
+
+ /**
+ * @test java.sql.Connection#createStatement()
+ */
+ public void testCreateStatement() {
+
+ Statement statement = null;
+ try {
+ statement = conn.createStatement();
+ statement.close();
+ } catch (SQLException sqle) {
+ fail("SQL Exception was thrown: " + sqle.getMessage());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.getMessage());
+ }
+ try {
+ statement.executeQuery("select * from zoo");
+ fail("SQLException is not thrown after close");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#createStatement(int resultSetType, int
+ * resultSetConcurrency)
+ */
+ public void testCreateStatement_int_int() {
+ Statement st = null;
+ ResultSet rs = null;
+ try {
+ st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ st.execute("select id, name from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.deleteRow();
+ fail("Can delete row for READ_ONLY ResultSet");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("parrot", (rs.getString(1)));
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("bird", (rs.getString(1)));
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ // exception is not specified for this case
+ conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, -1);
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ // exception is not specified for this case
+ conn.createStatement(Integer.MIN_VALUE, ResultSet.CONCUR_READ_ONLY);
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#createStatement(int resultSetType, int
+ * resultSetConcurrency, int resultSetHoldability)
+ */
+ public void testCreateStatement_int_int_int() {
+ Statement st = null;
+ try {
+ st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ st.execute("select id, name from zoo");
+ ResultSet rs = st.getResultSet();
+ try {
+ rs.close();
+ } catch (SQLException sqle) {
+ fail("Unexpected exception was thrown during closing ResultSet");
+ }
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ /*
+ * ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
+ */
+/* try {
+ st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.CLOSE_CURSORS_AT_COMMIT);
+ st.execute("select id, name from zoo");
+ ResultSet rs = st.getResultSet();
+ try {
+ rs.close();
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+*/
+ try {
+ conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY, -100);
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ }
+
+ /**
+ * @test java.sql.Connection#getMetaData()
+ */
+ public void testGetMetaData() {
+ try {
+ DatabaseMetaData md = conn.getMetaData();
+ Connection con = md.getConnection();
+ assertEquals(conn, con);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#clearWarnings()
+ *
+ * TODO clearWarnings is not supported
+ */
+/* public void testClearWarnings() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute("select animals from zoo");
+ fail("SQLException was not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.clearWarnings();
+ SQLWarning w = conn.getWarnings();
+ assertNull(w);
+
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+
+ try {
+ st = conn.createStatement();
+ st.execute("select monkey from zoo");
+ fail("SQLException was not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ SQLWarning w = conn.getWarnings();
+ assertNotNull(w);
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#getWarnings()
+ *
+ * TODO GetWarnings is not supported: returns null
+ */
+ /* public void testGetWarnings() {
+
+ Statement st = null;
+ int errorCode1 = -1;
+ int errorCode2 = -1;
+
+ try {
+ st = conn.createStatement();
+ st.execute("select animals from zoooo");
+ fail("SQLException was not thrown");
+ } catch (SQLException e) {
+ // expected
+ errorCode1 = e.getErrorCode();
+ }
+
+ try {
+ SQLWarning wrs = conn.getWarnings();
+ assertEquals(errorCode1, wrs.getErrorCode());
+ assertNull(wrs.getNextWarning());
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+ try {
+ st.execute("select horse from zoooooo");
+ } catch (SQLException e) {
+ // expected
+ errorCode2 = e.getErrorCode();
+ }
+
+ try {
+ SQLWarning wrs = conn.getWarnings();
+ assertEquals(errorCode1, wrs.getErrorCode());
+ assertNotNull(wrs.getNextWarning());
+ assertEquals(errorCode2, wrs.getErrorCode());
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#getAutoCommit()
+ */
+ public void testGetAutoCommit() {
+ try {
+ conn.setAutoCommit(true);
+ assertTrue(conn.getAutoCommit());
+ conn.setAutoCommit(false);
+ assertFalse(conn.getAutoCommit());
+ conn.setAutoCommit(true);
+ assertTrue(conn.getAutoCommit());
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setAutoCommit(boolean)
+ */
+ public void testSetAutoCommit() {
+ Statement st = null;
+ ResultSet rs = null;
+ ResultSet rs1 = null;
+ try {
+ conn.setAutoCommit(true);
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Chichichi', 'monkey');");
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(3, getCount(rs));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.setAutoCommit(false);
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Burenka', 'cow');");
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(4, getCount(rs));
+ conn.commit();
+ rs1 = st.getResultSet();
+ assertEquals(0, getCount(rs1));
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ rs1.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#isReadOnly()
+ */
+ public void testIsReadOnly() {
+ try {
+ conn.setReadOnly(true);
+ assertTrue(conn.isReadOnly());
+ conn.setReadOnly(false);
+ assertFalse(conn.isReadOnly());
+ conn.setReadOnly(true);
+ assertTrue(conn.isReadOnly());
+ conn.setReadOnly(false);
+ assertFalse(conn.isReadOnly());
+ } catch (SQLException sqle) {
+ fail("SQLException was thrown: " + sqle.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setReadOnly(boolean)
+ */
+ public void testSetReadOnly() {
+ Statement st = null;
+ try {
+ conn.setReadOnly(true);
+ st = conn.createStatement();
+ st.execute("insert into zoo (id, name, family) values (3, 'ChiChiChi', 'monkey');");
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.setReadOnly(false);
+ st = conn.createStatement();
+ st.execute("insert into zoo (id, name, family) values (4, 'ChiChiChi', 'monkey');");
+ } catch (SQLException sqle) {
+ fail("SQLException was thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#getHoldability()
+ *
+ * TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
+ */
+ public void testGetHoldability() {
+ try {
+ // conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
+ // assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn
+ // .getHoldability());
+ conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn
+ .getHoldability());
+ } catch (SQLException sqle) {
+ fail("SQLException was thrown: " + sqle.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setHoldability(int)
+ *
+ * TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
+ */
+ public void testSetHoldability() {
+ Statement st = null;
+ try {
+// conn.setHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT);
+// assertEquals(ResultSet.CLOSE_CURSORS_AT_COMMIT, conn
+// .getHoldability());
+ st = conn.createStatement();
+ st.execute("select id, name from zoo");
+ ResultSet rs = st.getResultSet();
+ try {
+ rs.close();
+ } catch (SQLException sqle) {
+ fail("Unexpected exception was thrown during closing ResultSet");
+ }
+ conn.commit();
+ conn.setHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ assertEquals(ResultSet.HOLD_CURSORS_OVER_COMMIT, conn
+ .getHoldability());
+ } catch (SQLException sqle) {
+ fail("SQLException was thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ conn.setHoldability(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#getTransactionIsolation()
+ *
+ * TODO only Connection.TRANSACTION_SERIALIZABLE is supported
+ */
+ public void testGetTransactionIsolation() {
+ try {
+// conn
+// .setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
+// assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn
+// .getTransactionIsolation());
+// conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+// assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn
+// .getTransactionIsolation());
+// conn
+// .setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
+// assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn
+// .getTransactionIsolation());
+ conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
+ assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn
+ .getTransactionIsolation());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setTransactionIsolation(int)
+ *
+ * TODO only Connection.TRANSACTION_SERIALIZABLE is supported
+ */
+ public void testSetTransactionIsolation() {
+ try {
+// conn
+// .setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
+// assertEquals(Connection.TRANSACTION_READ_UNCOMMITTED, conn
+// .getTransactionIsolation());
+// conn.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
+// assertEquals(Connection.TRANSACTION_READ_COMMITTED, conn
+// .getTransactionIsolation());
+// conn
+// .setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
+// assertEquals(Connection.TRANSACTION_REPEATABLE_READ, conn
+// .getTransactionIsolation());
+ conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
+ assertEquals(Connection.TRANSACTION_SERIALIZABLE, conn
+ .getTransactionIsolation());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+
+ try {
+ conn.setTransactionIsolation(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setCatalog(String catalog)
+ *
+ * TODO setCatalog method does nothing
+ */
+/* public void testSetCatalog() {
+ String[] catalogs = { "test", "test1", "test" };
+ Statement st = null;
+ try {
+ for (int i = 0; i < catalogs.length; i++) {
+ conn.setCatalog(catalogs[i]);
+ assertEquals(catalogs[i], conn.getCatalog());
+ st = conn.createStatement();
+ st
+ .equals("create table test_table (id integer not null, name varchar(20), primary key(id));");
+ st.equals("drop table test_table;");
+
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ conn.setCatalog(null);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+
+ try {
+ conn.setCatalog("not_exist");
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#getCatalog()
+ *
+ * TODO getCatalog method returns ""
+ */
+ /* public void testGetCatalog() {
+ try {
+ assertEquals("test", conn.getCatalog());
+ } catch (SQLException sqle) {
+ fail("SQL Exception " + sqle.getMessage());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.getMessage());
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#setTypeMap(Map<String,Class<?>> map)
+ *
+ * TODO setTypeMap is not supported
+ */
+/* public void testSetTypeMap() {
+ try {
+ java.util.Map map = conn.getTypeMap();
+ map
+ .put(
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_Connection1",
+ Class.forName("TestHelper_Connection1"));
+ conn.setTypeMap(map);
+ assertEquals(map, conn.getTypeMap());
+ } catch (SQLException sqle) {
+ fail("SQL Exception " + sqle.getMessage());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.getMessage());
+ }
+
+ try {
+ conn.setTypeMap(null);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#getTypeMap()
+ *
+ * TODO getTypeMap is not supported
+ */
+/* public void testGetTypeMap() {
+ try {
+ java.util.Map map = conn.getTypeMap();
+ map
+ .put(
+ "org.apache.harmony.sql.tests.java.sql.TestHelper_Connection1",
+ Class.forName("TestHelper_Connection1"));
+ conn.setTypeMap(map);
+ assertEquals(map, conn.getTypeMap());
+ } catch (SQLException sqle) {
+ fail("SQL Exception " + sqle.getMessage());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.getMessage());
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#nativeSQL(String sql)
+ *
+ * TODO nativeSQL is not supported
+ */
+/* public void testNativeSQL() {
+ String[] queries = {
+ "select * from zoo;",
+ "insert into zoo (id, name, family) values (3, 'Chichichi', 'monkey');",
+ "create table zoo_office(id integer not null, name varchar(20), primary key(id));",
+ "drop table zoo_office;" };
+ String[] native_queries = {
+ "select * from zoo;",
+ "insert into zoo (id, name, family) values (3, 'Chichichi', 'monkey');",
+ "create table zoo_office(id integer not null, name varchar(20), primary key(id));",
+ "drop table zoo_office;" };
+ Statement st = null;
+ try {
+ for (int i = 0; i < queries.length; i++) {
+ String nativeQuery = conn.nativeSQL(queries[i]);
+ assertEquals(native_queries[i], nativeQuery);
+ st = conn.createStatement();
+ st.execute(nativeQuery);
+ }
+ } catch (SQLException sqle) {
+ fail("SQL Exception " + sqle.getMessage());
+ } catch (Exception e) {
+ fail("Unexpected Exception " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ String[] inc_queries = { "", " ", "not query" };
+ for (int i = 0; i < inc_queries.length; i++) {
+ try {
+ String nativeQuery = conn.nativeSQL(inc_queries[i]);
+ assertEquals(inc_queries[i], nativeQuery);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareCall(String sql)
+ *
+ * TODO prepareCall is not supported
+ */
+/* public void testPrepareCall() {
+ createProcedure();
+ CallableStatement cstmt = null;
+ ResultSet rs = null;
+ ResultSet rs1 = null;
+ Statement st = null;
+ Statement st1 = null;
+ try {
+ cstmt = conn.prepareCall("call welcomeAnimal(3, 'Petya', 'Cock')");
+ st = conn.createStatement();
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ cstmt.execute();
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(3, getCount(rs1));
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown");
+ } finally {
+ try {
+ st.close();
+ st1.close();
+ rs.close();
+ rs1.close();
+ cstmt.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.prepareCall("welcomeAnimal(4, 'Petya', 'Cock')");
+ fail("SQL Exception is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+
+ try {
+ conn.prepareCall(null);
+ fail("SQL Exception is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareCall(String sql, int resultSetType, int
+ * resultSetConcurrency)
+ *
+ * TODO prepareCall is not supported
+ */
+/* public void testPrepareCall_String_int_int() {
+ CallableStatement cstmt = null;
+ ResultSet rs = null;
+ try {
+ String query = "call welcomeAnimal(3, 'Petya', 'Cock')";
+ cstmt = conn.prepareCall(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ cstmt.execute("select id, name from zoo");
+ rs = cstmt.getResultSet();
+ try {
+ rs.deleteRow();
+ fail("Can delete row for READ_ONLY ResultSet");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ rs.absolute(0);
+ fail("Can move cursor to the last position for TYPE_FORWARD_ONLY ResultSet");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ cstmt.close();
+ } catch (Exception ee) {
+ }
+ }
+ Statement st = null;
+ try {
+ st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("parrot", (rs.getString(1)));
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("bird", (rs.getString(1)));
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, -1);
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ conn.createStatement(Integer.MIN_VALUE, ResultSet.CONCUR_READ_ONLY);
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareCall(String sql, int resultSetType, int
+ * resultSetConcurrency, int resultSetHoldability)
+ *
+ * TODO prepareCall is not supported
+ */
+/* public void testPrepareCall_String_int_int_int() {
+ CallableStatement cstmt = null;
+ ResultSet rs = null;
+ try {
+ String query = "call welcomeAnimal(?, ?, ?)";
+ cstmt = conn.prepareCall(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ cstmt.setInt(1, 3);
+ cstmt.setString(2, "Petya");
+ cstmt.setString(3, "Cock");
+ cstmt.execute("select id, name from zoo");
+ rs = cstmt.getResultSet();
+ try {
+ rs.close();
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ fail("Unexpected exception was thrown during closing ResultSet");
+ }
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ cstmt.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ Statement st = null;
+
+ try {
+ st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.CLOSE_CURSORS_AT_COMMIT);
+ st.execute("select id, name from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.close();
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ }
+
+ try {
+ conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY, -100);
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql)
+ */
+ /*
+ * TODO Crashes VM. Fix later.
+ *
+ * public void testPrepareStatement() {
+ * PreparedStatement prst = null;
+ * Statement st = null;
+ * ResultSet rs = null;
+ * ResultSet rs1 = null; *
+ * try {
+ * String update = "update zoo set family = ? where name = ?;";
+ * prst = conn.prepareStatement(update); prst.setString(1, "cat");
+ * prst.setString(2, "Yasha");
+ * st = conn.createStatement();
+ * st.execute("select * from zoo where family = 'cat'");
+ * rs = st.getResultSet();
+ * assertEquals(0, getCount(rs));
+ * prst.executeUpdate();
+ * st.execute("select * from zoo where family = 'cat'");
+ * rs1 = st.getResultSet();
+ * assertEquals(1, getCount(rs1));
+ * } catch(SQLException e) {
+ * fail("SQLException is thrown: " + e.getMessage());
+ * } finally {
+ * try {
+ * rs.close();
+ * rs1.close();
+ * prst.close();
+ * st.close();
+ * } catch(SQLException ee) { }
+ * }
+ *
+ * try {
+ * prst = conn.prepareStatement("");
+ * prst.execute();
+ * fail("SQLException is not thrown");
+ * } catch (SQLException e) {
+ * //expected
+ * }
+ *
+ * try {
+ * conn.prepareStatement(null);
+ * fail("SQLException is not thrown");
+ * } catch (SQLException e) {
+ * // expected
+ * }
+ * }
+ */
+
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql, int
+ * autoGeneratedKeys)
+ */
+// TODO Crashes VM. Fix later.
+/* public void testPrepareStatement_String_int() {
+ PreparedStatement prst = null;
+ PreparedStatement prst1 = null;
+ Statement st = null;
+ ResultSet rs = null;
+ ResultSet rs1 = null;
+ ResultSet rs4 = null;
+ ResultSet rs5 = null;
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+
+ // TODO Statement.RETURN_GENERATED_KEYS is not supported
+ prst = conn.prepareStatement(insert,
+ Statement.RETURN_GENERATED_KEYS);
+ prst.setInt(1, 8);
+ prst.setString(2, "Tuzik");
+ prst.setString(3, "dog");
+ st = conn.createStatement();
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ prst.execute();
+ st.execute("select * from zoo where family = 'dog'");
+ rs1 = st.getResultSet();
+ assertEquals(1, getCount(rs1));
+
+ rs4 = prst.getGeneratedKeys();
+ assertEquals(0, getCount(rs4));
+
+
+ prst1 = conn.prepareStatement(insert, Statement.NO_GENERATED_KEYS);
+ prst1.setInt(1, 5);
+ prst1.setString(2, "Layka");
+ prst1.setString(3, "dog");
+
+ prst1.execute();
+
+// TODO getGeneratedKeys is not supported
+
+ rs5 = prst1.getGeneratedKeys();
+ assertEquals(0, getCount(rs5));
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ rs1.close();
+ rs4.close();
+ rs5.close();
+ prst.close();
+ prst1.close();
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#commit()
+ */
+ public void testCommit() {
+ Statement st = null;
+ Statement st1 = null;
+ Statement st2 = null;
+ Statement st3 = null;
+ ResultSet rs1 = null;
+ ResultSet rs2 = null;
+ ResultSet rs3 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ conn.commit();
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch(SQLException ee) {}
+ }
+ try {
+ conn.commit();
+ st3 = conn.createStatement();
+ st3.execute("select * from zoo");
+ rs3 = st3.getResultSet();
+ assertEquals(4, getCount(rs3));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs3.close();
+ st3.close();
+ } catch(SQLException ee) {}
+ }
+
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ conn.commit();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException was thrown: " + sqle.toString());
+ } finally {
+ try {
+ rs1.close();
+ st.close();
+ st1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#rollback()
+ */
+ public void testRollback() {
+ Statement st = null;
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ ResultSet rs2 = null;
+ ResultSet rs3 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ Statement st2 = null;
+ Statement st3 = null;
+ try {
+ conn.commit();
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ conn.rollback();
+ st3 = conn.createStatement();
+ st3.execute("select * from zoo");
+ rs3 = st3.getResultSet();
+ assertEquals(4, getCount(rs3));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ rs3.close();
+ st2.close();
+ st3.close();
+ } catch (SQLException ee) {
+ }
+ }
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ conn.rollback();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } finally {
+ try {
+ st.close();
+ st1.close();
+ rs1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Connection#setSavepoint()
+ *
+ * TODO setSavepoint is not supported
+ */
+/* public void testSetSavepoint() {
+ Statement st = null;
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ Statement st2 = null;
+ ResultSet rs2 = null;
+ try {
+ Savepoint sp = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback(sp1);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback();
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ Savepoint sp = conn.setSavepoint();
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } finally {
+ try {
+ rs1.close();
+ st.close();
+ st1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#setSavepoint(String name)
+ *
+ * TODO setSavepoint is not supported
+ */
+/* public void testSetSavepoint_String() {
+ Statement st = null;
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ Statement st2 = null;
+ ResultSet rs2 = null;
+ try {
+ Savepoint sp = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint("two");
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback(sp1);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint("three");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint("four");
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback();
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ Savepoint sp = conn.setSavepoint("five");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } finally {
+ try {
+ rs1.close();
+ st.close();
+ st1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#rollback(Savepoint savepoint)
+ *
+ * TODO Savepoint is not supported
+ */
+/* public void testRollback_Savepoint() {
+ Statement st = null;
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ Statement st2 = null;
+ ResultSet rs2 = null;
+ try {
+ Savepoint sp = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint("two");
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback(sp1);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint("three");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint("four");
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.rollback();
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ Savepoint sp = conn.setSavepoint("five");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } finally {
+ try {
+ rs1.close();
+ st.close();
+ st1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#releaseSavepoint(Savepoint savepoint)
+ *
+ * TODO Savepoint is not supported
+ */
+/* public void testReleaseSavepoint_Savepoint() {
+ Statement st = null;
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ try {
+ conn.setAutoCommit(false);
+
+ st = conn.createStatement();
+ st
+ .execute("insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');");
+ st
+ .execute("insert into zoo (id, name, family) values (4, 'Orel', 'eagle');");
+
+ if (!conn.getAutoCommit()) {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ Statement st2 = null;
+ ResultSet rs2 = null;
+ try {
+ Savepoint sp = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.rollback(sp);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.releaseSavepoint(sp);
+ try {
+ conn.rollback(sp);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ conn.rollback();
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ Savepoint sp1 = conn.setSavepoint("one");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ Savepoint sp2 = conn.setSavepoint("two");
+ st
+ .execute("insert into zoo (id, name, family) values (6, 'grach', 'rook');");
+ conn.releaseSavepoint(sp1);
+ try {
+ conn.rollback(sp1);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ conn.commit();
+ conn.rollback(sp2);
+ st2 = conn.createStatement();
+ st2.execute("select * from zoo");
+ rs2 = st2.getResultSet();
+ assertEquals(4, getCount(rs2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ rs2.close();
+ st2.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ } else {
+ st1 = conn.createStatement();
+ st1.execute("select * from zoo");
+ rs1 = st1.getResultSet();
+ assertEquals(4, getCount(rs1));
+ try {
+ Savepoint sp = conn.setSavepoint("five");
+ st
+ .execute("insert into zoo (id, name, family) values (5, 'chayka', 'gull');");
+ conn.releaseSavepoint(sp);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } finally {
+ try {
+ rs1.close();
+ st.close();
+ st1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql, int[]
+ * columnIndexes)
+ *
+ * TODO prepareStatement(String sql, int[] columnIndexes) is not
+ * supported
+ */
+/* public void testPrepareStatement_String_intArray() {
+ Statement st = null;
+ PreparedStatement prst1 = null;
+ PreparedStatement prst = null;
+ ResultSet rs = null;
+ ResultSet rs1 = null;
+ ResultSet rs4 = null;
+ ResultSet rs5 = null;
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ prst = conn.prepareStatement(insert, new int[] { 0, 1, 2 });
+ prst.setInt(1, 8);
+ prst.setString(2, "Tuzik");
+ prst.setString(3, "dog");
+
+ st = conn.createStatement();
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ prst.execute();
+ st.execute("select * from zoo where family = 'dog'");
+ rs1 = st.getResultSet();
+ assertEquals(1, getCount(rs1));
+
+ rs4 = prst.getGeneratedKeys();
+ assertEquals(0, getCount(rs4));
+
+ prst1 = conn.prepareStatement(insert, new int[] { 0, 1, 2, 10 });
+ prst1.setInt(1, 5);
+ prst1.setString(2, "Layka");
+ prst1.setString(3, "dog");
+
+ prst1.execute();
+
+ rs5 = prst1.getGeneratedKeys();
+ assertEquals(0, getCount(rs5));
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ rs1.close();
+ rs4.close();
+ rs5.close();
+ st.close();
+ prst1.close();
+ prst.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ conn.prepareStatement(insert, new int[] {});
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ conn.prepareStatement(insert, (int[]) null);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql, int resultSetType,
+ * int resultSetConcurrency)
+ */
+// TODO Crashes VM. Fix later.
+/* public void testPrepareStatement_String_int_int() {
+ String query = "insert into zoo (id, name, family) values (?, ?, ?);";
+ PreparedStatement st = null;
+ ResultSet rs = null;
+ try {
+
+ st = conn.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY);
+ st.execute("select id, name from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.deleteRow();
+ fail("Can delete row for READ_ONLY ResultSet");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.prepareStatement(query,
+ ResultSet.TYPE_SCROLL_INSENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("parrot", (rs.getString(1)));
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE,
+ ResultSet.CONCUR_UPDATABLE);
+ st.execute("select name, family from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.insertRow();
+ rs.updateObject("family", "bird");
+ rs.next();
+ rs.previous();
+ assertEquals("bird", (rs.getString(1)));
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, -1);
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ conn.prepareStatement(query, Integer.MIN_VALUE,
+ ResultSet.CONCUR_READ_ONLY);
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql, int resultSetType,
+ * int resultSetConcurrency, int resultSetHoldability)
+ */
+ // TODO Crashes VM. Fix later.
+/* public void testPrepareStatement_String_int_int_int() {
+ String query = "insert into zoo (id, name, family) values (?, ?, ?);";
+ PreparedStatement st = null;
+ ResultSet rs = null;
+ try {
+ st = conn.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.HOLD_CURSORS_OVER_COMMIT);
+ st.setInt(1, 3);
+ st.setString(2, "Petya");
+ st.setString(3, "Cock");
+ st.execute("select id, name from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.close();
+ } catch (SQLException sqle) {
+ fail("Unexpected exception was thrown during closing ResultSet");
+ }
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ //TODO ResultSet.CLOSE_CURSORS_AT_COMMIT is not supported
+ try {
+ st = conn.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY,
+ ResultSet.CLOSE_CURSORS_AT_COMMIT);
+ st.execute("select id, name from zoo");
+ rs = st.getResultSet();
+ try {
+ rs.close();
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException was thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ rs.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ conn.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY,
+ ResultSet.CONCUR_READ_ONLY, -100);
+ fail("SQLException was not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ }
+*/
+ /**
+ * @test java.sql.Connection#prepareStatement(String sql, String[]
+ * columnNames)
+ *
+ * TODO prepareStatement(String sql, String[] columnNames) method is
+ * not supported
+ */
+ /* public void testPrepareStatement_String_StringArray() {
+ PreparedStatement prst = null;
+ PreparedStatement prst1 = null;
+ ResultSet rs = null;
+ ResultSet rs1 = null;
+ ResultSet rs4 = null;
+ ResultSet rs5 = null;
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ prst = conn.prepareStatement(insert, new String[] { "id", "name",
+ "family" });
+ prst.setInt(1, 8);
+ prst.setString(2, "Tuzik");
+ prst.setString(3, "dog");
+
+ Statement st = conn.createStatement();
+ st.execute("select * from zoo");
+ rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ prst.execute();
+ st.execute("select * from zoo where family = 'dog'");
+ rs1 = st.getResultSet();
+ assertEquals(1, getCount(rs1));
+
+ rs4 = prst.getGeneratedKeys();
+ assertEquals(0, getCount(rs4));
+
+ prst1 = conn.prepareStatement(insert, new String[] { "id", "name", "" });
+ prst1.setInt(1, 5);
+ prst1.setString(2, "Layka");
+ prst1.setString(3, "dog");
+
+ prst1.execute();
+
+ rs5 = prst1.getGeneratedKeys();
+ assertEquals(0, getCount(rs5));
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ rs1.close();
+ rs4.close();
+ rs5.close();
+ prst.close();
+ prst1.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ conn.prepareStatement(insert, new String[] {});
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ String insert = "insert into zoo (id, name, family) values (?, ?, ?);";
+ conn.prepareStatement(insert, (String[]) null);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+*/
+}
diff --git a/sql/src/test/java/tests/sql/PreparedStatementTest.java b/sql/src/test/java/tests/sql/PreparedStatementTest.java
new file mode 100755
index 0000000..1e6b124
--- /dev/null
+++ b/sql/src/test/java/tests/sql/PreparedStatementTest.java
@@ -0,0 +1,2473 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import java.math.BigDecimal;
+import java.sql.ParameterMetaData;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.sql.Types;
+import java.sql.Date;
+import java.util.Calendar;
+import java.util.Locale;
+import java.util.TimeZone;
+
+public class PreparedStatementTest extends SQLTest {
+
+ String queryAllSelect = "select * from type";
+
+ String[] queries = {
+ "create table type (" +
+
+ " BoolVal BOOLEAN," + " IntVal INT," + " LongVal LONG,"
+ + " Bint BIGINT," + " Tint TINYINT," + " Sint SMALLINT,"
+ + " Mint MEDIUMINT, " +
+
+ " IntegerVal INTEGER, " + " RealVal REAL, "
+ + " DoubleVal DOUBLE, " + " FloatVal FLOAT, "
+ + " DecVal DECIMAL, " +
+
+ " NumVal NUMERIC, " + " charStr CHAR(20), "
+ + " dateVal DATE, " + " timeVal TIME, " + " TS TIMESTAMP, "
+ +
+
+ " DT DATETIME, " + " TBlob TINYBLOB, " + " BlobVal BLOB, "
+ + " MBlob MEDIUMBLOB, " + " LBlob LONGBLOB, " +
+
+ " TText TINYTEXT, " + " TextVal TEXT, "
+ + " MText MEDIUMTEXT, " + " LText LONGTEXT " + ");",
+
+ "insert into type (BoolVal, IntVal, LongVal, Bint, Tint, Sint, Mint,"
+ + "IntegerVal, RealVal, DoubleVal, FloatVal, DecVal,"
+ + "NumVal, charStr, dateVal, timeVal, TS,"
+ + "DT, TBlob, BlobVal, MBlob, LBlob,"
+ + "TText, TextVal, MText, LText"
+ + ") "
+ + "values (1, -1, 22, 2, 33,"
+ + "3, 1, 2, 3.9, 23.2, 33.3, 44,"
+ + "5, 'test string', '1799-05-26', '12:35:45', '2007-10-09 14:28:02.0',"
+ + "'1221-09-22 10:11:55', 1, 2, 3, 4,"
+ + "'Test text message tiny', 'Test text message', 'Test text message medium', 'Test text message long');" };
+
+ public void createTables() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i]);
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ public void clearTables() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute("drop table if exists type");
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#addBatch()
+ */
+ public void testAddBatch() throws SQLException {
+ PreparedStatement ps = null;
+ try {
+ ps = conn
+ .prepareStatement("INSERT INTO zoo VALUES (3,'Tuzik', ?);");
+ ps.addBatch("INSERT INTO zoo VALUES (?,'Burenka', ?); ");
+ ps.addBatch("INSERT INTO zoo VALUES (?,'Mashka','cat')");
+ try {
+ ps.executeBatch();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown for executeBatch()");
+ }
+ ps.setString(1, "dog");
+ Statement st = null;
+ try {
+ ps.executeBatch();
+ st = conn.createStatement();
+ st.execute("select * from zoo");
+ ResultSet rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown for executeBatch()");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps = conn
+ .prepareStatement("INSERT INTO zoo VALUES (3,'Tuzik', ?);");
+ ps.addBatch("");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps = conn
+ .prepareStatement("INSERT INTO zoo VALUES (3,'Tuzik', ?);");
+ ps.addBatch(null);
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#execute()
+ */
+
+ // TODO Crashes VM. Fix later.
+
+/* public void testExecute() {
+ Statement st = null;
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into zoo(id, family, name) values(?, ?, 'unknown animal')";
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 3);
+ ps.setString(2, "No name");
+ assertTrue(ps.execute());
+ st = conn.createStatement();
+ st.execute("select * from zoo");
+ assertEquals(3, getCount(st.getResultSet()));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ ps.close();
+ st.close();
+ } catch(Exception ee) {}
+ }
+
+ try {
+ String query = "update zoo set name='Masha', family=? where id=?;";
+ ps = conn.prepareStatement(query);
+ ps.setString(1, "cat");
+ ps.setInt(2, 2);
+ assertTrue(ps.execute());
+ assertEquals(1, ps.getUpdateCount());
+ st = conn.createStatement();
+ st.execute("select family from zoo where id=2");
+ ResultSet rs = st.getResultSet();
+ rs.next(); assertEquals("cat", rs.getString(1));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ ps.close();
+ st.close();
+ } catch(Exception ee) {}
+ }
+
+ try {
+ conn.createStatement().execute("drop table if exists hutch");
+ String query = "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));";
+ ps = conn.prepareStatement(query);
+ assertTrue(ps.execute());
+ } catch(SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+
+ try {
+ String query = "select name, family from zoo where id = ?";
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 1);
+ assertTrue(ps.execute());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee){}
+ }
+
+ try {
+ String query = "select name, family from zoo where id = ?";
+ ps = conn.prepareStatement(query);
+ ps.execute();
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
+*/
+ /*
+ * @test java.sql.PreparedStatement#executeQuery()
+ */
+
+ // TODO Crashes VM. Fix later.
+ /* public void testExecuteQuery() {
+
+ String[] queries2 = { "update zoo set name='Masha', family='cat' where id=;",
+ "insert into hutch (id, animal_id, address) values (1, ?,'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=?" };
+
+ for (int i = 0; i < queries2.length; i++) {
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(queries2[i]);
+ ps.executeQuery();
+ fail("SQLException is not thrown for query: " + queries2[i]);
+ } catch(SQLException sqle) {
+ // expected
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
+
+ String query = "select * from zoo where id = ?";
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 1);
+ ResultSet rs = ps.executeQuery();
+ rs.next();
+ assertEquals(1, rs.getInt(1));
+ assertEquals("Kesha", rs.getString(2));
+ assertEquals("parrot", rs.getString(3));
+ } catch (SQLException e) {
+ fail("SQLException is thrown for query");
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+
+ try {
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 5);
+ ResultSet rs = ps.executeQuery();
+ assertNotNull(rs);
+ assertFalse(rs.next());
+ } catch(SQLException e) {
+ fail("SQLException is thrown for query");
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
+*/
+ /**
+ * @test java.sql.PreparedStatement#executeUpdate()
+ */
+
+ // TODO Crashes VM. Fix later.
+/* public void testExecuteUpdate() {
+ String[] queries1 = { "insert into hutch (id, animal_id, address) values (1, ?, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (?, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2" };
+
+ for (int i = 0; i < queries1.length; i++) {
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(queries1[i]);
+ ps.executeUpdate();
+ fail("SQLException is not thrown for query: " + queries1[i]);
+ } catch(SQLException sqle) {
+ // expected
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
+
+ String query = "update zoo set name='Masha', family='cat' where id=?;";
+ PreparedStatement ps = null;
+ try {
+ ps = conn.prepareStatement(query);
+ ps.setInt(1, 2);
+ int updateCount = ps.executeUpdate();
+ assertEquals(1, updateCount);
+ ps.setInt(1, 1);
+ int updateCount1 = ps.executeUpdate();
+ assertEquals(1, updateCount1);
+ } catch (SQLException e) {
+ fail("SQLException is thrown for query");
+ } finally {
+ try {
+ ps.close();
+ } catch(Exception ee) {}
+ }
+ }
+ */
+ /**
+ * @test java.sql.PreparedStatement#getMetaData()
+ *
+ * TODO Doesn't pass on SQLite but according to Java docs:
+ * it is possible to invoke the method getMetaData on a
+ * PreparedStatement object rather than waiting to execute it.
+ */
+ public void testGetMetaData() {
+ PreparedStatement ps = null;
+ try {
+ String query = "update zoo set name='Masha', family='cat' where id=?;";
+ ps = conn.prepareStatement(query);
+ assertNull(ps.getMetaData());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ } catch (Exception e) {
+ fail("Exception is thrown: " + e.toString());
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ String query = "select * from zoo where id = ?";
+ ps = conn.prepareStatement(query);
+ ResultSetMetaData rsmd = ps.getMetaData();
+ assertNotNull(rsmd);
+ assertEquals(3, rsmd.getColumnCount());
+ assertEquals("id", rsmd.getColumnName(1));
+ assertEquals("id", rsmd.getColumnName(1));
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#getParameterMetaData()
+ * TODO not supported exception
+ */
+ /* public void testGetParameterMetaData() {
+ PreparedStatement ps = null;
+ try {
+ String query = "select * from zoo where id = ?";
+ ps = conn.prepareStatement(query);
+ ParameterMetaData rsmd = ps.getParameterMetaData();
+ assertNotNull(rsmd);
+ assertEquals(1, rsmd.getParameterCount());
+ ps.setInt(1, 2);
+ ps.execute();
+ ParameterMetaData rsmd1 = ps.getParameterMetaData();
+ assertNotNull(rsmd1);
+ assertEquals(1, rsmd1.getParameterCount());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.toString());
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ String query = "select * from zoo where id = ?";
+ ps = conn.prepareStatement(query);
+ ParameterMetaData rsmd = ps.getParameterMetaData();
+ assertNotNull(rsmd);
+ assertEquals(1, rsmd.getParameterCount());
+ ps.setInt(1, 2);
+ ps.execute();
+ ParameterMetaData rsmd1 = ps.getParameterMetaData();
+ assertNotNull(rsmd1);
+ assertEquals(1, rsmd1.getParameterCount());
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ String query = "select * from zoo where id = 1";
+ ps = conn.prepareStatement(query);
+ ParameterMetaData rsmd = ps.getParameterMetaData();
+ assertNotNull(rsmd);
+ assertEquals(0, rsmd.getParameterCount());
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.PreparedStatement#clearParameters()
+ */
+ /*
+ * TODO Crashes VM. Fix later.
+ * public void testClearParameters() {
+ * PreparedStatement ps = null;
+ * try {
+ * String query = "select * from zoo where id = ? and family=?";
+ * ps = conn.prepareStatement(query);
+ * ps.setInt(1, 2);
+ * ps.setString(2, "dog");
+ * ps.clearParameters();
+ * try { ps.execute();
+ * fail("SQLException is not thrown during execute method after calling clearParameters()");
+ * } catch(SQLException sqle) {
+ * // expected
+ * }
+ * ps.setInt(1, 2);
+ * ps.clearParameters();
+ * try {
+ * ps.execute();
+ * fail("SQLException is not thrown during execute method after calling clearParameters()");
+ * } catch(SQLException sqle) {
+ * // expected
+ * }
+ * ps.setInt(1, 2);
+ * ps.setString(2, "cat");
+ *
+ * try {
+ * ps.execute();
+ * } catch (SQLException sqle) {
+ * fail("SQLException is thrown during execute method after calling clearParameters() twice");
+ * }
+ * } catch (SQLException e) {
+ * fail("SQLException is thrown");
+ * } finally {
+ * try {
+ * ps.close();
+ * } catch(SQLException ee) {}
+ * }
+ * }
+ */
+ /**
+ * @test java.sql.PreparedStatement#setInt(int parameterIndex, int x)
+ */
+ public void testSetInt() throws SQLException {
+ createTables();
+ PreparedStatement ps = null;
+ Statement st = null;
+ try {
+ String query = "insert into type (IntVal) values (?);";
+ ps = conn.prepareStatement(query);
+ try {
+ ps.setInt(1, Integer.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal="
+ + Integer.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setInt(1, Integer.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal="
+ + Integer.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setInt(2, Integer.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setInt(-2, 0);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setLong(int parameterIndex, long x)
+ */
+ public void testSetLong() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (LongVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setLong(1, Long.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where LongVal="
+ + Long.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setLong(1, Long.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where LongVal="
+ + Long.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setLong(2, Long.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setLong(-2, 0);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setFloat(int parameterIndex, float x)
+ */
+ public void testSetFloat() {
+ float value1 = 12345678.12345689f;
+ float value2 = -12345678.12345689f;
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (FloatVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setFloat(1, value1);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where FloatVal=" + value1);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setFloat(1, value2);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where FloatVal=" + value2);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setFloat(2, Float.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setFloat(-2, 0);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setDouble(int parameterIndex, double x)
+ */
+ public void testSetDouble() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (DoubleVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setDouble(1, Double.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where DoubleVal="
+ + Double.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setDouble(1, Double.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where DoubleVal="
+ + Double.MIN_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setDouble(2, Double.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setDouble(-2, 0);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
+ */
+ public void testSetString_charField() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String str = "test^text$test%";
+ String query = "insert into type (charStr) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setString(1, str);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where charStr='" + str + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, "");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where charStr=''");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, " ");
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where charStr=' '");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(-2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(1, " test & text * test % text * test ^ text ");
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ ps.setString(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
+ */
+ public void testSetString_tinyTextField() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
+ String query = "insert into type (TText) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setString(1, str);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where TText='" + str + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, "");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where TText=''");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, " ");
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where TText=' '");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(-2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(
+ 1,
+ "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test*test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test-test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test+test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test?test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test#test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test ");
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ ps.setString(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
+ */
+ public void testSetString_textField() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
+ String query = "insert into type (TextVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setString(1, str);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where TextVal='" + str + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, "");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where TextVal=''");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, " ");
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where TextVal=' '");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setString(2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(-2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ String longString = " test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/";
+ for (int i = 0; i < 10; i++) {
+ longString += longString;
+ }
+ ps.setString(1, longString);
+ ps.execute();
+
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ ps.setString(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
+ */
+ public void testSetString_mediumTextField() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
+ String query = "insert into type (MText) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setString(1, str);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where MText='" + str + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, "");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where MText=''");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, " ");
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where MText=' '");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(-2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setString(int parameterIndex, String x)
+ */
+ public void testSetString_longTextField() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String str = "test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test/test^text$test%test(text)test@text5test~test^text$test%test(text)test@text5test";
+ String query = "insert into type (LText) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setString(1, str);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where LText='" + str + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, "");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where LText=''");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(1, " ");
+ ps.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where LText=' '");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setString(2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(-2, "test text");
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setString(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setShort(int parameterIndex, short x)
+ */
+ public void testSetShort() {
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ PreparedStatement ps2 = null;
+ try {
+ String query = "insert into type (Sint) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setShort(1, Short.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where Sint=" + Short.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setShort(1, Short.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where Sint=" + Short.MIN_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setShort(2, Short.MAX_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setShort(-2, Short.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ String query1 = "insert type(Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+ try {
+ ps1.setShort(1, Short.MAX_VALUE);
+ ps1.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ String query2 = "insert into type (IntVal) values (?);";
+ ps2 = conn.prepareStatement(query2);
+ try {
+ ps2.setShort(1, Short.MAX_VALUE);
+ ps2.execute();
+ st = conn.createStatement();
+ st
+ .execute("select * from type where IntVal="
+ + Short.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ ps2.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setBoolean(int parameterIndex, boolean
+ * x)
+ */
+ public void testSetBoolean() {
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (BoolVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setBoolean(1, false);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where BoolVal = 0");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setBoolean(1, true);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where BoolVal= 1");
+ ResultSet rs = st.getResultSet();
+ assertEquals(2, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setBoolean(2, true);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setBoolean(-2, false);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ String query1 = "insert into type (Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+ try {
+ ps1.setBoolean(1, true);
+ ps1.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setByte(int parameterIndex, byte x)
+ */
+ public void testSetByte() {
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (Tint) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setByte(1, Byte.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where Tint=" + Byte.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setByte(1, Byte.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where Tint=" + Byte.MIN_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setByte(2, Byte.MAX_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setByte(-2, Byte.MIN_VALUE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ String query1 = "insert into type (IntVal) values (?);";
+ ps1 = conn.prepareStatement(query1);
+ try {
+ ps1.setByte(1, Byte.MAX_VALUE);
+ ps1.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setBytes(int parameterIndex, byte[] x)
+ */
+ public void testSetBytes() {
+
+ byte[] bytesArray = {1, 0};
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (LBlob) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setBytes(1, bytesArray);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ ps.setBytes(2, bytesArray);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setBytes(-2, bytesArray);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (TBlob) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps.setBytes(1, bytesArray);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setBigDecimal(int parameterIndex,
+ * BigDecimal x)
+ */
+ public void testSetBigDecimal() {
+
+ BigDecimal bd = new BigDecimal("50");
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (DecVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setBigDecimal(1, bd);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where DecVal=" + bd);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ ps.setBigDecimal(2, bd);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setBigDecimal(-2, bd);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setBigDecimal(1, bd);
+ ps1.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setDate(int parameterIndex, Date x)
+ */
+ public void testSetDate_int_Date() {
+
+ Date[] dates = { new Date(1799, 05, 26), new Date(Integer.MAX_VALUE),
+ new Date(123456789) };
+
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (dateVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ for (int i = 0; i < dates.length; i++) {
+ Statement st = null;
+ try {
+ ps.setDate(1, dates[i]);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where dateVal='"
+ + dates[i].toString() + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ try {
+ ps.setDate(2, dates[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setDate(-2, dates[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert type(Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setDate(1, dates[0]);
+ ps1.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setDate(int parameterIndex, Date x,
+ * Calendar cal)
+ */
+ public void testSetDate_int_Date_Calendar() {
+
+ Calendar[] cals = { Calendar.getInstance(),
+ Calendar.getInstance(Locale.GERMANY),
+ Calendar.getInstance(TimeZone.getDefault()) };
+
+ Date[] dates = { new Date(1799, 05, 26), new Date(Integer.MAX_VALUE),
+ new Date(123456789) };
+
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (dateVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ for (int i = 0; i < dates.length; i++) {
+ Statement st = null;
+ try {
+ ps.setDate(1, dates[i], cals[i]);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where dateVal='"
+ + dates[i].toString() + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ try {
+ ps.setDate(2, dates[0], cals[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setDate(-2, dates[0], cals[1]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setDate(1, dates[0], cals[2]);
+ ps1.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown");
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setNull(int parameterIndex, int sqlType)
+ *
+ * this test doesn't passed on RI
+ */
+ public void testSetNull_int_int() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (BoolVal, IntVal) values ('true', ?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setNull(1, Types.INTEGER);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (BoolVal, LongVal) values (true, ?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setNull(1, Types.BIGINT);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ //expected
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (BoolVal, DecVal) values ('true', ?)";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setNull(1, Types.DECIMAL);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (BoolVal, dateVal) values (true, ?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setNull(1, Types.DATE);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ //expected
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (BoolVal, BlobVal) values (true, ?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setNull(1, Types.BLOB);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ //expected
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (BoolVal, TextVal) values (true, ?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setNull(1, Types.CHAR);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ //expected
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x)
+ *
+ * this test doesn't pass on RI
+ */
+ public void testSetObject_int_Object() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (IntVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setObject(1, Integer.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal="
+ + Integer.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (LongVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, "test text");
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where LongVal='test text';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ query = "insert into type (DecVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, new Object());
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is not thrown");
+ }
+
+ query = "insert into type (dateVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, new Date(123456789));
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where dateVal='"
+ + new Date(123456789) + "';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ // this sub test doesn't pass on RI
+ query = "insert into type (BlobVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, null);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x,
+ * int targetSqlType)
+ *
+ * this test doesn't pass on RI
+ */
+ public void testSetObject_int_Object_int() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type(IntVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setObject(1, Integer.MAX_VALUE, Types.INTEGER);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal="
+ + Integer.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (LongVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, "test text", Types.CHAR);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where LongVal='test text';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (DecVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, new Object(), Types.DECIMAL);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+
+ query = "insert into type (dateVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, new Date(123456789), Types.DATE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where dateVal='"
+ + new Date(123456789) + "';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ // this sub test doesn't pass on RI
+ query = "insert into type (BlobVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, "", Types.BLOB);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setObject(int parameterIndex, Object x,
+ * int targetSqlType, int scale)
+ *
+ * this test doesn't pass on RI
+ */
+ public void testSetObject_int_Object_int_int() {
+ createTables();
+ PreparedStatement ps = null;
+ try {
+ String query = "insert into type (IntVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ try {
+ ps.setObject(1, Integer.MAX_VALUE, Types.INTEGER,
+ Integer.MAX_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where IntVal="
+ + Integer.MAX_VALUE);
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (LongVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, "test text", Types.CHAR, Integer.MIN_VALUE);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where LongVal='test text';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ query = "insert into type (DecVal) values (?);";
+ ps = conn.prepareStatement(query);
+ BigDecimal bd2 = new BigDecimal("12.21");
+
+ try {
+ ps.setObject(1, bd2, Types.DECIMAL, 2);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+
+ query = "insert into type (dateVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, new Date(123456789), Types.DATE, -1);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where dateVal='"
+ + new Date(123456789) + "';");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ // this sub test doesn't pass on RI
+ query = "insert into type(BlobVal) values (?);";
+ ps = conn.prepareStatement(query);
+
+ try {
+ ps.setObject(1, "", Types.BLOB, 0);
+ ps.execute();
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setTime(int parameterIndex, Time x)
+ */
+ public void testSetTimeint_Time() {
+
+ Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE),
+ new Time(123456789) };
+
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (timeVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ for (int i = 0; i < times.length; i++) {
+ try {
+ ps.setTime(1, times[i]);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where timeVal='"
+ + times[i].toString() + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ try {
+ ps.setTime(2, times[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setTime(-2, times[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (Tint) values (?)";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setTime(1, times[0]);
+ ps1.execute();
+
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setTime(int parameterIndex, Time x,
+ * Calendar cal)
+ */
+ public void testSetTime_int_Time_Calendar() {
+
+ Calendar[] cals = { Calendar.getInstance(),
+ Calendar.getInstance(Locale.GERMANY),
+ Calendar.getInstance(TimeZone.getDefault()) };
+
+ Time[] times = { new Time(24, 25, 26), new Time(Integer.MAX_VALUE),
+ new Time(123456789) };
+
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (timeVal) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ for (int i = 0; i < times.length; i++) {
+ try {
+ ps.setTime(1, times[i], cals[i]);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where timeVal='"
+ + times[i].toString() + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ try {
+ ps.setTime(2, times[0], cals[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setTime(-2, times[0], cals[1]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setTime(1, times[0], cals[2]);
+ ps1.execute();
+
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.PreparedStatement#setTimestamp(int parameterIndex,
+ * Timestamp x)
+ */
+ public void testSetTimestamp_int_Timestamp() {
+
+ Timestamp[] timestamps = { new Timestamp(2007, 10, 17, 19, 06, 50, 23),
+ new Timestamp(123) };
+
+ createTables();
+ PreparedStatement ps = null;
+ PreparedStatement ps1 = null;
+ try {
+ String query = "insert into type (TS) values (?);";
+ ps = conn.prepareStatement(query);
+ Statement st = null;
+ for (int i = 0; i < timestamps.length; i++) {
+ try {
+ ps.setTimestamp(1, timestamps[i]);
+ ps.execute();
+ st = conn.createStatement();
+ st.execute("select * from type where TS='"
+ + timestamps[i].toString() + "'");
+ ResultSet rs = st.getResultSet();
+ assertEquals(1, getCount(rs));
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ try {
+ ps.setTimestamp(2, timestamps[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ try {
+ ps.setTimestamp(-2, timestamps[0]);
+ ps.execute();
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+ String query1 = "insert into type (Tint) values (?);";
+ ps1 = conn.prepareStatement(query1);
+
+ try {
+ ps1.setTimestamp(1, timestamps[0]);
+ ps1.execute();
+
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ clearTables();
+ ps.close();
+ ps1.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+}
diff --git a/sql/src/test/java/tests/sql/ResultSetMetaDataTest.java b/sql/src/test/java/tests/sql/ResultSetMetaDataTest.java
new file mode 100755
index 0000000..1f9483b
--- /dev/null
+++ b/sql/src/test/java/tests/sql/ResultSetMetaDataTest.java
@@ -0,0 +1,252 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Types;
+
+public class ResultSetMetaDataTest extends SQLTest {
+
+ ResultSetMetaData rsmd = null;
+ Statement st = null;
+ ResultSet rs = null;
+
+ public void setUp() {
+ super.setUp();
+ try {
+ String query = "select * from zoo";
+ st = conn.createStatement();
+ st.execute(query);
+ rs = st.getResultSet();
+ rsmd = rs.getMetaData();
+ } catch (SQLException e) {
+ fail("Couldn't get ResultSetMetaData object");
+ }
+ }
+
+ public void tearDown() {
+ super.tearDown();
+ try {
+ rs.close();
+ st.close();
+ } catch (SQLException e) {
+ fail("Couldn't close Statement object");
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getCatalogName(int column)
+ */
+ public void testGetCatalogName() throws SQLException {
+ try {
+ assertNull(rsmd.getCatalogName(0));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnClassName(int column)
+ */
+ public void testGetColumnClassName() {
+ try {
+ assertNotNull(rsmd);
+ assertEquals(Short.class.getName(), rsmd.getColumnClassName(1));
+ assertEquals(String.class.getName(), rsmd.getColumnClassName(2));
+ assertEquals(String.class.getName(), rsmd.getColumnClassName(3));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+
+ try {
+ String name = rsmd.getColumnClassName(-1);
+ assertNull(name);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ String name = rsmd.getColumnClassName(4);
+ assertNull(name);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnCount()
+ */
+ public void testGetColumnCount() {
+ try {
+ assertEquals(3, rsmd.getColumnCount());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnLabel(int column)
+ */
+ public void testGetColumnLabel() {
+ String[] labels = { "zoo.id", "zoo.name", "zoo.family" };
+ try {
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ String label = rsmd.getColumnLabel(i + 1);
+ assertEquals(labels[i], label);
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnName(int column)
+ */
+ public void testGetColumnName() {
+ String[] labels = { "zoo.id", "zoo.name", "zoo.family" };
+ try {
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ String label = rsmd.getColumnLabel(i + 1);
+ assertEquals(labels[i], label);
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+
+ try {
+ String label = rsmd.getColumnLabel(-1);
+ assertNull(label);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+
+ try {
+ String label = rsmd.getColumnLabel(5);
+ assertNull(label);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnType(int column)
+ */
+ public void testGetColumnType() {
+ int[] types = { Types.SMALLINT, Types.VARCHAR, Types.VARCHAR};
+ try {
+ for (int i = 0; i < rsmd.getColumnCount(); i++) {
+ int type = rsmd.getColumnType(i + 1);
+ assertEquals(types[i], type);
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+
+ try {
+ rsmd.getColumnType(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ try {
+ rsmd.getColumnType(5);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getColumnTypeName(int column)
+ */
+ public void testGetColumnTypeName() {
+ try {
+ assertEquals("smallint", rsmd.getColumnTypeName(1));
+ assertEquals("varchar", rsmd.getColumnTypeName(2));
+ assertEquals("varchar", rsmd.getColumnTypeName(3));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+
+ try {
+ rsmd.getColumnTypeName(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ try {
+ rsmd.getColumnTypeName(5);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+
+ /**
+ * @test java.sql.ResultSetMetaData#getTableName(int column)
+ */
+ public void testGetTableName() {
+ try {
+ assertEquals("zoo", rsmd.getTableName(1));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ Statement st1 = null;
+ ResultSet rs1 = null;
+ try {
+ String[] queries = {
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "select name, animal_id from hutch, zoo where zoo.id = 1" };
+ st1 = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st1.execute(queries[i]);
+ }
+ rs1 = st1.getResultSet();
+ ResultSetMetaData rsmd1 = rs1.getMetaData();
+ assertEquals("zoo", rsmd1.getTableName(1));
+ assertEquals("hutch", rsmd1.getTableName(2));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs1.close();
+ st1.execute("drop table ifexists hutch");
+ st1.close();
+
+ } catch (SQLException sqle) {
+ }
+ }
+
+ try {
+ String name = rsmd.getTableName(-1);
+ assertNull(name);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ try {
+ String name = rsmd.getTableName(5);
+ assertNull(name);
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ }
+}
diff --git a/sql/src/test/java/tests/sql/SQLTest.java b/sql/src/test/java/tests/sql/SQLTest.java
new file mode 100755
index 0000000..08ae350
--- /dev/null
+++ b/sql/src/test/java/tests/sql/SQLTest.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.Statement;
+
+import tests.support.Support_SQL;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestCase;
+import junit.framework.TestSuite;
+
+public class SQLTest extends TestCase {
+ static Connection conn;
+
+ public void setUp() {
+ getSQLiteConnection();
+ createZoo();
+ }
+
+ private final File dbFile = new File("sqliteTest2.db");
+
+ protected void getSQLiteConnection() {
+ try {
+ Class.forName("SQLite.JDBCDriver").newInstance();
+ if(dbFile.exists()) dbFile.delete();
+ conn = DriverManager.getConnection("jdbc:sqlite:/"
+ + dbFile.getName());
+ } catch (Exception e) {
+ fail("Exception: " + e.toString());
+ }
+ }
+
+ public void tearDown() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute("drop table if exists zoo");
+
+ } catch (SQLException e) {
+ fail("Couldn't drop table: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ conn.close();
+ } catch(SQLException ee) {}
+ }
+ }
+
+ public void createZoo() {
+
+ String[] queries = {
+ "create table zoo(id smallint, name varchar(10), family varchar(10))",
+ "insert into zoo values (1, 'Kesha', 'parrot')",
+ "insert into zoo values (2, 'Yasha', 'sparrow')" };
+
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i]);
+ }
+ } catch (SQLException e) {
+ e.printStackTrace();
+ fail("Unexpected exception: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {}
+ }
+ }
+
+ public void createProcedure() {
+ String proc = "CREATE PROCEDURE welcomeAnimal (IN parameter1 integer, IN parameter2 char(20), IN parameter3 char(20)) "
+ + " BEGIN "
+ + " INSERT INTO zoo(id, name, family) VALUES (parameter1, parameter2, parameter3); "
+ + "SELECT * FROM zoo;" + " END;";
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute("DROP PROCEDURE IF EXISTS welcomeAnimal");
+ st.execute(proc);
+ } catch (SQLException e) {
+ fail("Unexpected exception: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {}
+ }
+ }
+
+ public int getCount(ResultSet rs) {
+ int count = 0;
+ try {
+ while (rs.next()) {
+ count++;
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ }
+ return count;
+ }
+}
diff --git a/sql/src/test/java/tests/sql/StatementTest.java b/sql/src/test/java/tests/sql/StatementTest.java
new file mode 100755
index 0000000..fd1002e
--- /dev/null
+++ b/sql/src/test/java/tests/sql/StatementTest.java
@@ -0,0 +1,955 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.sql;
+
+import java.sql.BatchUpdateException;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.Statement;
+import java.util.Vector;
+
+public class StatementTest extends SQLTest {
+
+ /**
+ * @test java.sql.Statement#addBatch(String)
+ */
+ public void testAddBatch() throws SQLException {
+
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.addBatch("INSERT INTO zoo VALUES (3,'Tuzik','dog')");
+ st.addBatch("INSERT INTO zoo VALUES (4,'Mashka','cat')");
+
+ int[] updateCounts = st.executeBatch();
+ assertEquals(2, updateCounts.length);
+ assertEquals(1, updateCounts[0]);
+ assertEquals(1, updateCounts[1]);
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.addBatch("");
+ st.executeBatch();
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.addBatch(null);
+ st.executeBatch();
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#clearWarnings()
+ */
+ public void testClearWarnings() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute("select animals from zoo");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ try {
+ st = conn.createStatement();
+ st.clearWarnings();
+ SQLWarning w = st.getWarnings();
+ assertNull(w);
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#getWarnings()
+ *
+ * TODO getWarnings is not supported
+ */
+/* public void testGetWarnings() {
+
+ Statement st = null;
+ int errorCode1 = -1;
+ int errorCode2 = -1;
+
+ try {
+ st = conn.createStatement();
+ st.execute("select animals from zoooo");
+ } catch (SQLException e) {
+ // expected
+ errorCode1 = e.getErrorCode();
+ }
+ try {
+ SQLWarning wrs = st.getWarnings();
+ assertNull(wrs);
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+ try {
+ st.execute("select horse from zoooooo");
+ } catch (SQLException e) {
+ // expected
+ errorCode2 = e.getErrorCode();
+ }
+
+ try {
+ SQLWarning wrs = st.getWarnings();
+ assertEquals(errorCode1, wrs.getErrorCode());
+ assertNotNull(wrs.getNextWarning());
+ assertEquals(errorCode2, wrs.getErrorCode());
+ } catch (Exception e) {
+ fail("Unexpected Exception: " + e.getMessage());
+ }
+
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+
+ }
+*/
+ /**
+ * @test java.sql.Statement#clearBatch(String)
+ */
+ public void testClearBatch() throws SQLException {
+
+ Statement st = null;
+
+ try {
+ st = conn.createStatement();
+ st.addBatch("INSERT INTO zoo VALUES (3,'Tuzik','dog'); ");
+ st.addBatch("INSERT INTO zoo VALUES (4,'Mashka','cat')");
+
+ int[] updateCounts = st.executeBatch();
+ assertEquals(2, updateCounts.length);
+ assertEquals(1, updateCounts[0]);
+ assertEquals(1, updateCounts[1]);
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.addBatch("");
+ st.executeBatch();
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.addBatch(null);
+ st.executeBatch();
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#execute(String sql)
+ *
+ * TODO not pass on SQLite and RI.
+ *
+ */
+ public void testExecute() throws SQLException {
+
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "select animal_id, address from hutch where animal_id=1;",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+ boolean[] results = {true, true, true, true, true, true, true,
+ true, true};
+
+ for (int i = 0; i < queries.length; i++) {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ boolean res = st.execute(queries[i]);
+ assertEquals(results[i], res);
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ String[] inc_queries = {
+ "update zoo_zoo set name='Masha', family='cat' where id=5;",
+ "drop table hutchNO",
+ "insert into hutch (id, animal_id, address) values (1, 2, 10);",
+ "select animal_id, from hutch where animal_id=1;",
+ "drop view address;", "drop table hutch;", "", null };
+
+ for (int i = 0; i < inc_queries.length; i++) {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute(inc_queries[i]);
+ fail("SQLException is not thrown for query: " + inc_queries[i]);
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#execute(String sql, int autoGeneratedKeys)
+ * TODO not supported
+ */
+ /* public void testExecute_String_int() {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "select animal_id, address from hutch where animal_id=1;",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ for (int i = 0; i < queries.length; i++) {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.execute(queries[i], Statement.NO_GENERATED_KEYS);
+ ResultSet rs = st.getGeneratedKeys();
+ assertFalse(rs.next());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#getConnection()
+ */
+ public void testGetConnection() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ assertSame(conn, st.getConnection());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#getFetchDirection()
+ */
+ public void testGetFetchDirection() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ assertEquals(ResultSet.FETCH_UNKNOWN, st.getFetchDirection());
+ } catch (SQLException e) {
+ fail("SQLException is thrown" + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#setFetchDirection()
+ * TODO not supported
+ */
+/* public void testSetFetchDirection() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ st.setFetchDirection(ResultSet.FETCH_FORWARD);
+ assertEquals(ResultSet.FETCH_FORWARD, st.getFetchDirection());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ try {
+ st = conn.createStatement();
+ st.setFetchDirection(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.setFetchDirection(100);
+ fail("SQLException is not thrown");
+ } catch (SQLException e) {
+ // expected
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#getFetchSize()
+ */
+ public void testGetFetchSize() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ assertEquals(1, st.getFetchSize());
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#setFetchSize()
+ * TODO not supported
+ */
+/* public void testSetFetchSize() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ int rows = 100;
+ for (int i = 0; i < rows; i++) {
+ try {
+ st.setFetchSize(i);
+ assertEquals(i, st.getFetchSize());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.toString());
+ }
+ }
+ try {
+ st.setFetchSize(-1);
+ fail("SQLException is not thrown");
+ } catch (SQLException sqle) {
+ // expected
+ }
+
+ } catch (SQLException e) {
+ fail("SQLException is thrown");
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#setMaxFieldSize(int max)
+ * TODO not supported
+ */
+/* public void testSetMaxFieldSize() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < 300; i += 50) {
+ try {
+ st.setMaxFieldSize(i);
+ assertEquals(i, st.getMaxFieldSize());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ }
+ try {
+ st.setMaxFieldSize(-1);
+ fail("SQLException isn't thrown");
+ } catch (SQLException sqle) {
+ // expecteds
+ }
+ } catch (SQLException e) {
+ fail("Can't create statement, SQLException is thrown: "
+ + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#getMaxFieldSize()
+ * TODO not supported
+ */
+/* public void testGetMaxFieldSize() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 200; i < 500; i += 50) {
+ try {
+ st.setMaxFieldSize(i);
+ assertEquals(i, st.getMaxFieldSize());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ }
+ } catch (SQLException e) {
+ fail("Can't create statement, SQLException is thrown: "
+ + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#setMaxRows(int max)
+ * TODO not supported
+ */
+ /* public void testSetMaxRows() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < 300; i += 50) {
+ try {
+ st.setMaxRows(i);
+ assertEquals(i, st.getMaxRows());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ }
+ try {
+ st.setMaxRows(-1);
+ fail("SQLException isn't thrown");
+ } catch (SQLException sqle) {
+ // expecteds
+ }
+ } catch (SQLException e) {
+ fail("Can't create statement, SQLException is thrown: "
+ + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#getMaxRows()
+ * TODO not supported
+ */
+/* public void testGetMaxRows() {
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 200; i < 500; i += 50) {
+ try {
+ st.setMaxRows(i);
+ assertEquals(i, st.getMaxRows());
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown: " + sqle.getMessage());
+ }
+ }
+ } catch (SQLException e) {
+ fail("Can't create statement, SQLException is thrown: "
+ + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#close()
+ * TODO not passed but according to Java Docs
+ */
+ public void testClose() {
+ Statement st = null;
+ try {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "insert into zoo (id, name, family) values (3, 'Vorobey', 'sparrow');",
+ "insert into zoo (id, name, family) values (4, 'Slon', 'elephant');",
+ "select * from zoo" };
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i]);
+ }
+ assertNotNull(st.getResultSet());
+ st.close();
+ assertNull(st.getResultSet());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#execute(String sql, int[] columnIndexes)
+ * TODO not supported
+ */
+/* public void testExecute_String_intArray() {
+ Statement st = null;
+ try {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "insert zoo(id, name, family) values (3, 'Vorobey', 'sparrow');",
+ "insert zoo(id, name, family) values (4, 'Slon', 'elephant');",
+ "select * from zoo" };
+ Vector<int[]> array = new Vector<int[]>();
+ array.addElement(null);
+ array.addElement(new int[] { 1, 2, 3 });
+ array.addElement(new int[] { 1, 2, 10, 100 });
+ array.addElement(new int[] {});
+
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i], (int[]) array.elementAt(i));
+ }
+ assertNotNull(st.getResultSet());
+ st.close();
+ assertNull(st.getResultSet());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#execute(String sql, String[] columnNames)
+ */
+/* public void testExecute_String_StringArray() {
+ Statement st = null;
+ try {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "insert zoo(id, name, family) values (3, 'Vorobey', 'sparrow');",
+ "insert zoo(id, name, family) values (4, 'Slon', 'elephant');",
+ "select * from zoo" };
+ Vector<String[]> array = new Vector<String[]>();
+ array.addElement(null);
+ array.addElement(new String[] { "", "", "", "", "", "", "", "" });
+ array.addElement(new String[] { "field 1", "", "field2" });
+ array.addElement(new String[] { "id", "family", "name" });
+
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.execute(queries[i], (String[]) array.elementAt(i));
+ }
+ assertNotNull(st.getResultSet());
+ st.close();
+ assertNull(st.getResultSet());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#executeBatch()
+ */
+ public void testExecuteBatch() {
+
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ int[] result = { 1, 1, 1, 1, 1, 1, 1, 1 };
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ assertEquals(0, st.executeBatch().length);
+ for (int i = 0; i < queries.length; i++) {
+ st.addBatch(queries[i]);
+ }
+ int[] resArray = st.executeBatch();
+ assertTrue(java.util.Arrays.equals(result, resArray));
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ st.addBatch("select * from zoo");
+ st.executeBatch();
+ } catch (BatchUpdateException bue) {
+ fail("BatchUpdateException is thrown: " + bue.toString());
+ } catch (SQLException sqle) {
+ fail("Unknown SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#executeQuery(String sql)
+ */
+ public void testExecuteQuery_String() {
+
+ String[] queries1 = { "select * from zoo",
+ "select name, family from zoo where id = 1" };
+
+ String[] queries2 = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;", "select from zoo" };
+
+ Statement st = null;
+
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < queries1.length; i++) {
+ try {
+ ResultSet rs = st.executeQuery(queries1[i]);
+ assertNotNull(rs);
+ } catch (SQLException sqle) {
+ fail("SQLException is thrown for query: " + queries1[i]);
+ }
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < queries2.length; i++) {
+ try {
+ st.executeQuery(queries2[i]);
+ fail("SQLException is not thrown for query: " + queries2[i]);
+ } catch (SQLException sqle) {
+ // expected
+ }
+ }
+ } catch (SQLException sqle) {
+ fail("Unknown SQLException is thrown: " + sqle.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+
+ }
+
+ /**
+ * @test java.sql.Statement#executeUpdate(String sql)
+ */
+ public void testExecuteUpdate_String() {
+
+ String[] queries1 = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ String[] queries2 = { "select * from zoo",
+ "select name, family from zoo where id = 1" };
+
+ Statement st = null;
+ try {
+ st = conn.createStatement();
+ for (int i = 0; i < queries1.length; i++) {
+ try {
+ st.executeUpdate(queries1[i]);
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ }
+ }
+
+ for (int i = 0; i < queries2.length; i++) {
+ try {
+ st.executeUpdate(queries2[i]);
+ fail("SQLException is not thrown for query: " + queries2[i]);
+ } catch (SQLException e) {
+ // expected
+ }
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+
+ /**
+ * @test java.sql.Statement#executeUpdate(String sql, int[] columnIndexes)
+ *
+ * TODO executeUpdate(String sql, int[] columnIndexes) is not supported
+ */
+/* public void testExecuteUpdate_String_intArray() {
+ Statement st = null;
+ try {
+ String[] queries1 = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ Vector<int[]> array = new Vector<int[]>();
+ array.addElement(null);
+ array.addElement(new int[] { 1, 2, 3 });
+ array.addElement(new int[] { 1, 2, 10, 100 });
+ array.addElement(new int[] {});
+ array.addElement(new int[] { 100, 200 });
+ array.addElement(new int[] { -1, 0 });
+ array.addElement(new int[] { 0, 0, 0, 1, 2, 3 });
+ array.addElement(new int[] { -100, -200 });
+
+ st = conn.createStatement();
+ for (int i = 0; i < queries1.length; i++) {
+ st.executeUpdate(queries1[i], (int[]) array.elementAt(i));
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#executeUpdate(String sql, int autoGeneratedKeys)
+ *
+ * TODO executeUpdate(String sql, int autoGeneratedKeys) is not supported
+ */
+/* public void testExecuteUpdate_String_int() {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "select animal_id, address from hutch where animal_id=1;",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ for (int i = 0; i < queries.length; i++) {
+ Statement st = null;
+ ResultSet rs = null;
+ try {
+ st = conn.createStatement();
+ st.executeUpdate(queries[i], Statement.NO_GENERATED_KEYS);
+ rs = st.getGeneratedKeys();
+ assertFalse(rs.next());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ rs.close();
+ st.close();
+ } catch (Exception ee) {
+ }
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#executeUpdate(String sql, String[] columnNames)
+ *
+ * TODO executeUpdate(String sql, String[] columnNames) is not supported
+ */
+/* public void testExecuteUpdate_String_StringArray() {
+ Statement st = null;
+ try {
+ String[] queries = {
+ "update zoo set name='Masha', family='cat' where id=2;",
+ "drop table if exists hutch",
+ "create table hutch (id integer not null, animal_id integer, address char(20), primary key (id));",
+ "insert into hutch (id, animal_id, address) values (1, 2, 'Birds-house, 1');",
+ "insert into hutch (id, animal_id, address) values (2, 1, 'Horse-house, 5');",
+ "create view address as select address from hutch where animal_id=2",
+ "drop view address;", "drop table hutch;" };
+
+ Vector<String[]> array = new Vector<String[]>();
+ array.addElement(null);
+ array.addElement(new String[] { "", "", "", "", "", "", "", "" });
+ array.addElement(new String[] { "field 1", "", "field2" });
+ array.addElement(new String[] { "id", "family", "name" });
+ array
+ .addElement(new String[] { "id", null, "family", null,
+ "name" });
+ array.addElement(new String[] { "id", " ", "name" });
+ array.addElement(new String[] { null, null, null, null });
+ array.addElement(new String[] { " ", "123 21", "~!@#$%^&*()_+ ",
+ null });
+
+ st = conn.createStatement();
+ for (int i = 0; i < queries.length; i++) {
+ st.executeUpdate(queries[i], (String[]) array.elementAt(i));
+ }
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+*/
+ /**
+ * @test java.sql.Statement#getUpdateCount()
+ */
+ public void testGetUpdateCount() {
+ Statement st = null;
+ try {
+ String query = "update zoo set name='Masha', family='cat' where id=2;";
+ st = conn.createStatement();
+ assertEquals(0, st.getUpdateCount());
+ st.executeUpdate(query);
+ assertEquals(1, st.getUpdateCount());
+ query = "update zoo set name='Masha', family='cat' where id=5;";
+ st.executeUpdate(query);
+ assertEquals(0, st.getUpdateCount());
+ } catch (SQLException e) {
+ fail("SQLException is thrown: " + e.getMessage());
+ } finally {
+ try {
+ st.close();
+ } catch (SQLException ee) {
+ }
+ }
+ }
+}
diff --git a/sql/src/test/java/tests/support/DatabaseCreator.java b/sql/src/test/java/tests/support/DatabaseCreator.java
new file mode 100755
index 0000000..8d73c45
--- /dev/null
+++ b/sql/src/test/java/tests/support/DatabaseCreator.java
@@ -0,0 +1,401 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+import java.sql.Connection;
+import java.sql.Date;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.sql.Time;
+
+public class DatabaseCreator {
+ public static final int defaultInt = 2;
+
+ public static final String defaultString = "string";
+
+ public static final String defaultCharacter = "chr";
+
+ public static final double defaultDouble = 0.1;
+
+ public static final String TEST_TABLE1 = "table1";
+
+ public static final String TEST_TABLE2 = "table2";
+
+ public static final String TEST_TABLE3 = "table3";
+
+ public static final String TEST_TABLE4 = "table4";
+
+ public static final String SALESPEOPLE_TABLE = "Salespeople";
+
+ public static final String CUSTOMERS_TABLE = "Customers";
+
+ public static final String ORDERS_TABLE = "Orders";
+
+ public static final String PARENT_TABLE = "test_names";
+
+ public static final String FKSTRICT_TABLE = "test_strict";
+
+ public static final String FKCASCADE_TABLE = "test_cascade";
+
+ public static final String TEST_TABLE5 = "test";
+
+ public static final String SIMPLE_TABLE1 = "simple_table1";
+
+ public static final String SIMPLE_TABLE2 = "simple_table2";
+
+ public static final String SIMPLE_TABLE3 = "simple_table3";
+
+ public static final String CREATE_TABLE1 = "CREATE TABLE " + TEST_TABLE1
+ + " (id INTEGER NOT NULL," + " field1 CHAR(100) DEFAULT NULL,"
+ + " field2 DECIMAL " //+ defaultInt
+ + " COMMENT 'field2_rem'," + " field3 DECIMAL," + " fkey INTEGER,"
+ + " PRIMARY KEY (id) FOREIGN KEY (fkey) REFERENCES "
+ + TEST_TABLE3 + "(fk))";
+
+ public static final String CREATE_TABLE2 = "CREATE TABLE " + TEST_TABLE2
+ + " ( " + "finteger integer NOT NULL, " + "ftext text, "
+ + "fcharacter character (5), " + "fdecimal decimal (5,1), "
+ + "fnumeric numeric (4,1), " + "fsmallint smallint, "
+ + "ffloat float, " + "freal real, " + "fdouble double, "
+ + "fdate date," + " ftime time, PRIMARY KEY (finteger))";
+
+ public static final String CREATE_TABLE3 = "CREATE TABLE " + TEST_TABLE3
+ + " (fk INTEGER NOT NULL," + "" + " PRIMARY KEY (fk))";
+
+ public static final String CREATE_TABLE4 = "CREATE TABLE " + TEST_TABLE4
+ + " (fk INTEGER NOT NULL," + " field1 CHAR(100) NOT NULL,"
+ + " PRIMARY KEY (fk))";
+
+ public static final String CREATE_TABLE5 = "CREATE TABLE " + TEST_TABLE5
+ + "( testId INTEGER NOT NULL, testValue CHAR(200))";
+
+ public static final String CREATE_TABLE_SALESPEOPLE = "CREATE TABLE "
+ + SALESPEOPLE_TABLE + " (snum integer, sname character (10),"
+ + " city character (10), comm real, PRIMARY KEY (snum))";
+
+ public static final String CREATE_TABLE_CUSTOMERS = "CREATE TABLE "
+ + CUSTOMERS_TABLE
+ + " (cnum integer, cname character (10), city character (10),"
+ + " rating integer, snum integer, PRIMARY KEY (cnum))";
+
+ public static final String CREATE_TABLE_ORDERS = "CREATE TABLE "
+ + ORDERS_TABLE
+ + " (onum integer, amt real, odate date, cnum integer,"
+ + " snum integer, PRIMARY KEY (onum))";
+
+ public static final String CREATE_TABLE_PARENT = "CREATE TABLE "
+ + PARENT_TABLE + "(id INTEGER NOT NULL, "
+ + "name CHAR(200), PRIMARY KEY(id))";
+
+ public static final String CREATE_TABLE_FKSTRICT = "CREATE TABLE "
+ + FKSTRICT_TABLE + "(id INTEGER NOT NULL," + "name_id INTEGER,"
+ + "value CHAR(200), PRIMARY KEY(id), "
+ + "CONSTRAINT fk1 FOREIGN KEY (name_id) " + "REFERENCES "
+ + PARENT_TABLE + " (id) " + "ON DELETE RESTRICT "
+ + "ON UPDATE RESTRICT)";
+
+ public static final String CREATE_TABLE_FKCASCADE = "CREATE TABLE "
+ + FKCASCADE_TABLE + "(id INTEGER NOT NULL," + "name_id INTEGER,"
+ + "value CHAR(200), PRIMARY KEY(id), "
+ + "CONSTRAINT fk2 FOREIGN KEY (name_id) " + "REFERENCES "
+ + PARENT_TABLE + " (id) " + "ON DELETE CASCADE "
+ + "ON UPDATE CASCADE)";
+
+ public static final String CREATE_TABLE_SIMPLE1 = "CREATE TABLE "
+ + SIMPLE_TABLE1 + "(id INTEGER NOT NULL," + "speed INTEGER,"
+ + "size INTEGER)";
+
+ public static final String CREATE_TABLE_SIMPLE2 = "CREATE TABLE "
+ + SIMPLE_TABLE2 + "(id INTEGER NOT NULL," + "speed INTEGER,"
+ + "size INTEGER)";
+
+ public static final String CREATE_TABLE_SIMPLE3 = "CREATE TABLE "
+ + SIMPLE_TABLE3 + "(id INTEGER NOT NULL," + "speed INTEGER)";
+
+ public static final String DROP_TABLE1 = "DROP TABLE " + TEST_TABLE1;
+
+ public static final String DROP_TABLE2 = "DROP TABLE " + TEST_TABLE2;
+
+ public static final String DROP_TABLE3 = "DROP TABLE " + TEST_TABLE3;
+
+ public static final String DROP_TABLE4 = "DROP TABLE " + TEST_TABLE4;
+
+ public static final String DROP_TABLE5 = "DROP TABLE " + TEST_TABLE5;
+
+ public static final String DROP_TABLE_CUSTOMERS = "DROP TABLE "
+ + CUSTOMERS_TABLE;
+
+ public static final String DROP_TABLE_ORDERS = "DROP TABLE " + ORDERS_TABLE;
+
+ public static final String DROP_TABLE_SALESPEOPLE = "DROP TABLE "
+ + SALESPEOPLE_TABLE;
+
+ public static final String DROP_TABLE_PARENT = "DROP TABLE " + PARENT_TABLE;
+
+ public static final String DROP_TABLE_FKSTRICT = "DROP TABLE "
+ + FKSTRICT_TABLE;
+
+ public static final String DROP_TABLE_FKCASCADE = "DROP TABLE "
+ + FKCASCADE_TABLE;
+
+ public static final String DROP_TABLE_SIMPLE1 = "DROP TABLE "
+ + SIMPLE_TABLE1;
+
+ public static final String DROP_TABLE_SIMPLE2 = "DROP TABLE "
+ + SIMPLE_TABLE2;
+
+ public static final String DROP_TABLE_SIMPLE3 = "DROP TABLE "
+ + SIMPLE_TABLE3;
+
+ public static final String INSERT_SALESPEOPLE1 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1001, 'Peel', 'London', .12)";
+
+ public static final String INSERT_SALESPEOPLE2 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1002, 'Serres', 'SanJose', .13)";
+
+ public static final String INSERT_SALESPEOPLE3 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1004, 'Motika', 'London', .11)";
+
+ public static final String INSERT_SALESPEOPLE4 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1007, 'Rifkin', 'Barcelona', .15)";
+
+ public static final String INSERT_SALESPEOPLE5 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1003, 'Axelrod', 'NewYork', .10)";
+
+ public static final String INSERT_SALESPEOPLE6 = " INSERT INTO "
+ + SALESPEOPLE_TABLE + " (snum, sname, city, comm) "
+ + "VALUES (1013, 'Simpson', 'Kasan', .25)";
+
+ public static final String INSERT_CUSTOMERS1 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum)"
+ + " VALUES (2001, 'Hoffman', 'London', 100, 1001)";
+
+ public static final String INSERT_CUSTOMERS2 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2002, 'Giovanni', 'Rome', 200, 1003)";
+
+ public static final String INSERT_CUSTOMERS3 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2003, 'Liu', 'SanJose', 200, 1002)";
+
+ public static final String INSERT_CUSTOMERS4 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2004, 'Grass', 'Berlin', 300, 1002)";
+
+ public static final String INSERT_CUSTOMERS5 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2006, 'Clemens', 'London', 100, 1001)";
+
+ public static final String INSERT_CUSTOMERS6 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2008, 'Cisneros', 'SanJose', 300, 1007)";
+
+ public static final String INSERT_CUSTOMERS7 = " INSERT INTO "
+ + CUSTOMERS_TABLE + " (cnum, cname, city, rating, snum) "
+ + "VALUES (2007, 'Pereira', 'Rome', 100, 1004)";
+
+ public static final String INSERT_ORDERS1 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3001, 18.69, 10/03/1990, 2008, 1007)";
+
+ public static final String INSERT_ORDERS2 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3003, 767.19, 10/03/1990, 2001, 1001)";
+
+ public static final String INSERT_ORDERS3 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3002, 1900.10, 10/03/1990, 2007, 1004)";
+
+ public static final String INSERT_ORDERS4 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3005, 5160.45, 10/03/1990, 2003, 1002)";
+
+ public static final String INSERT_ORDERS5 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3006, 1098.16, 10/03/1990, 2008, 1007)";
+
+ public static final String INSERT_ORDERS6 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3009, 1713.23, 10/04/1990, 2002, 1003)";
+
+ public static final String INSERT_ORDERS7 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3007, 75.75, 10/04/1990, 2004, 1002)";
+
+ public static final String INSERT_ORDERS8 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3008, 4723.01, 10/05/1990, 2006, 1001)";
+
+ public static final String INSERT_ORDERS9 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3010, 1309.95, 10/06/1990, 2004, 1002)";
+
+ public static final String INSERT_ORDERS10 = " INSERT INTO " + ORDERS_TABLE
+ + " (onum, amt, odate, cnum, snum) "
+ + "VALUES (3011, 9891.88, 10/06/1990, 2006, 1001)";
+
+ public static void fillParentTable(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement
+ .execute("INSERT INTO " + PARENT_TABLE + " VALUES(1, 'test1')");
+ statement.execute("INSERT INTO " + PARENT_TABLE + " VALUES(2,'test2')");
+ statement
+ .execute("INSERT INTO " + PARENT_TABLE + " VALUES(3, 'test3')");
+ }
+
+ public static void fillFKStrictTable(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement.execute("INSERT INTO " + FKSTRICT_TABLE
+ + " VALUES(1, 1, '1')");
+ statement.execute("INSERT INTO " + FKSTRICT_TABLE
+ + " VALUES(2, 2, '2')");
+ statement.execute("INSERT INTO " + FKSTRICT_TABLE
+ + " VALUES(3, 1, '3')");
+ }
+
+ public static void fillFKCascadeTable(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement.execute("INSERT INTO " + FKCASCADE_TABLE
+ + " VALUES(1, 1, '1')");
+ statement.execute("INSERT INTO " + FKCASCADE_TABLE
+ + " VALUES(2, 2, '2')");
+ statement.execute("INSERT INTO " + FKCASCADE_TABLE
+ + " VALUES(3, 1, '3')");
+ }
+
+ public static void fillSimpleTable1(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement
+ .execute("INSERT INTO " + SIMPLE_TABLE1 + " VALUES(1, 10, 20)");
+ statement.execute("INSERT INTO " + SIMPLE_TABLE1 + " VALUES(2, 5, 7)");
+ }
+
+ public static void fillSimpleTable3(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement.execute("INSERT INTO " + SIMPLE_TABLE3 + " VALUES(1, 8)");
+ statement.execute("INSERT INTO " + SIMPLE_TABLE3 + " VALUES(2, 6)");
+ statement.execute("INSERT INTO " + SIMPLE_TABLE3 + " VALUES(3, 4)");
+ }
+
+ public static void fillSalesPeopleTable(Connection conn)
+ throws SQLException {
+ Statement statement = conn.createStatement();
+
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE1);
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE2);
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE3);
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE4);
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE5);
+ statement.execute(DatabaseCreator.INSERT_SALESPEOPLE6);
+ }
+
+ public static void fillCustomersTable(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS1);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS2);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS3);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS4);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS5);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS6);
+ statement.execute(DatabaseCreator.INSERT_CUSTOMERS7);
+ }
+
+ public static void fillOrdersTable(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+
+ statement.execute(DatabaseCreator.INSERT_ORDERS1);
+ statement.execute(DatabaseCreator.INSERT_ORDERS2);
+ statement.execute(DatabaseCreator.INSERT_ORDERS3);
+ statement.execute(DatabaseCreator.INSERT_ORDERS4);
+ statement.execute(DatabaseCreator.INSERT_ORDERS5);
+ statement.execute(DatabaseCreator.INSERT_ORDERS6);
+ statement.execute(DatabaseCreator.INSERT_ORDERS7);
+ statement.execute(DatabaseCreator.INSERT_ORDERS8);
+ statement.execute(DatabaseCreator.INSERT_ORDERS9);
+ statement.execute(DatabaseCreator.INSERT_ORDERS10);
+ }
+
+ public static void fillTestTable1(Connection conn, int numberOfRecords)
+ throws SQLException {
+ Statement statement = conn.createStatement();
+ for (int id = 0; id < numberOfRecords; id++) {
+ String value = DatabaseCreator.defaultString + id;
+ String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE1
+ + " (id, field1, field2, field3) VALUES(" + id + ", '"
+ + value + "', " + id + ", " + id + ")";
+ statement.execute(insertQuery);
+ }
+ }
+
+ public static void fillTestTable2(Connection conn, int startID, int endID,
+ long time) throws SQLException {
+ Statement statement = conn.createStatement();
+ for (int id = startID; id <= endID; id++) {
+ double value = id + DatabaseCreator.defaultDouble;
+ String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE2
+ + " (finteger, ftext, fcharacter, fdecimal, fnumeric,"
+ + " fsmallint, ffloat, freal, fdouble, fdate, ftime)"
+ + " VALUES (" + id + ", '" + DatabaseCreator.defaultString
+ + id + "'," + " '" + DatabaseCreator.defaultCharacter + id
+ + "', " + value + ", " + value + "," + value + ", " + value
+ + ", " + value + "," + value + ", '"
+ + new Date(time).toString() + "'," + " '"
+ + new Time(time).toString() + "')";
+ statement.execute(insertQuery);
+ }
+ }
+
+ public static void fillTestTable2(Connection conn, int numberOfRecords)
+ throws SQLException {
+ Statement statement = conn.createStatement();
+ for (int id = 0; id < numberOfRecords; id++) {
+ double value = id + DatabaseCreator.defaultDouble;
+ String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE2
+ + " (finteger, ftext, fcharacter, fdecimal, fnumeric,"
+ + " fsmallint, ffloat, freal, fdouble)" + " VALUES (" + id
+ + ", '" + DatabaseCreator.defaultString + id + "'," + " '"
+ + DatabaseCreator.defaultCharacter + id + "', " + value
+ + ", " + value + "," + value + ", " + value + ", " + value
+ + "," + value + ")";
+ statement.execute(insertQuery);
+ }
+ }
+
+ public static void fillTestTable4(Connection conn, int numberOfRecords)
+ throws SQLException {
+ Statement statement = conn.createStatement();
+ for (int id = 0; id < numberOfRecords; id++) {
+ String insertQuery = "INSERT INTO " + DatabaseCreator.TEST_TABLE4
+ + " (fk, field1) VALUES(" + id + ", \""
+ + DatabaseCreator.defaultString + id + "\")";
+ statement.execute(insertQuery);
+ }
+ }
+
+ public static void fillTestTable5(Connection conn) throws SQLException {
+ Statement statement = conn.createStatement();
+ statement.execute("INSERT INTO " + TEST_TABLE5 + " VALUES(1, '0')");
+ statement.execute("INSERT INTO " + TEST_TABLE5 + " VALUES(2, '3')");
+ statement.execute("INSERT INTO " + TEST_TABLE5 + " VALUES(3, '4')");
+ }
+}
diff --git a/sql/src/test/java/tests/support/Support_SQL.java b/sql/src/test/java/tests/support/Support_SQL.java
new file mode 100644
index 0000000..7c42163
--- /dev/null
+++ b/sql/src/test/java/tests/support/Support_SQL.java
@@ -0,0 +1,90 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+
+public class Support_SQL {
+
+ public static String sqlDriver = null;
+
+ public static String sqlLogin = null;
+
+ public static String sqlCatalog = null;
+
+ public static String sqlHost = null;
+
+ public static String sqlUrl = null;
+
+ public static String sqlPassword = null;
+
+ public static String sqlUser = null;
+
+ public static int sqlMaxConnections = 1;
+
+ public static int sqlMaxTasks = 0;
+
+ public static void loadDriver() {
+ try {
+ loadProperties(Class.forName("tests.support.Support_SQL")
+ .getResourceAsStream("/connection.properties"));
+ Class.forName(sqlDriver).newInstance();
+ } catch (Exception ex) {
+ System.err.println("Unexpected exception " + ex.toString());
+ }
+ }
+
+ public static Connection getConnection() throws SQLException {
+ return DriverManager.getConnection(Support_SQL.sqlUrl,
+ Support_SQL.sqlLogin, Support_SQL.sqlPassword);
+ }
+
+ public static Connection getConnection(String url, String login,
+ String password) throws SQLException {
+
+ return DriverManager.getConnection(url, login, password);
+ }
+
+ public static boolean isEqual(byte[] b1, int off1, byte[] b2, int off2,
+ int len) {
+ for (int i = 0; i < len; ++i)
+ if (b1[i + off1] != b2[i + off2])
+ return false;
+ return true;
+ }
+
+ private static void loadProperties(InputStream fileName) throws IOException {
+ Properties properties = new Properties();
+ properties.load(fileName);
+ sqlDriver = properties.getProperty("sqlDriver");
+ sqlLogin = properties.getProperty("sqlLogin");
+ sqlCatalog = properties.getProperty("sqlCatalog");
+ sqlHost = properties.getProperty("sqlHost");
+ sqlUrl = properties.getProperty("sqlUrlPrefix") + sqlHost + "/"
+ + sqlCatalog;
+ sqlPassword = properties.getProperty("sqlPassword");
+ sqlUser = properties.getProperty("sqlUser");
+ sqlMaxConnections = Integer.parseInt(properties
+ .getProperty("sqlMaxConnections"));
+ sqlMaxTasks = Integer.parseInt(properties.getProperty("sqlMaxTasks"));
+ }
+}
diff --git a/sql/src/test/java/tests/support/ThreadPool.java b/sql/src/test/java/tests/support/ThreadPool.java
new file mode 100644
index 0000000..84f22a9
--- /dev/null
+++ b/sql/src/test/java/tests/support/ThreadPool.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2007 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package tests.support;
+
+import java.util.LinkedList;
+
+public class ThreadPool extends ThreadGroup {
+
+ private boolean isAlive;
+
+ private LinkedList<Runnable> taskQueue;
+
+ private int threadID;
+
+ private static int threadPoolID;
+
+ public ThreadPool(int numThreads) {
+ super("ThreadPool-" + (threadPoolID++));
+ setDaemon(true);
+
+ isAlive = true;
+
+ taskQueue = new LinkedList<Runnable>();
+ for (int i = 0; i < numThreads; i++) {
+ new PooledThread().start();
+ }
+ }
+
+ public synchronized void runTask(Runnable task) {
+ if (!isAlive) {
+ throw new IllegalStateException();
+ }
+ if (task != null) {
+ taskQueue.add(task);
+ notify();
+ }
+ }
+
+ protected synchronized Runnable getTask() throws InterruptedException {
+ while (taskQueue.size() == 0) {
+ if (!isAlive) {
+ return null;
+ }
+ wait();
+ }
+ return (Runnable) taskQueue.removeFirst();
+ }
+
+ public synchronized void close() {
+ if (isAlive) {
+ isAlive = false;
+ taskQueue.clear();
+ interrupt();
+ }
+ }
+
+ public void join() {
+ synchronized (this) {
+ isAlive = false;
+ notifyAll();
+ }
+
+ Thread[] threads = new Thread[activeCount()];
+ int count = enumerate(threads);
+ for (int i = 0; i < count; i++) {
+ try {
+ threads[i].join();
+ } catch (InterruptedException ex) {
+ System.err.println(ex.getMessage());
+ }
+ }
+ }
+
+ private class PooledThread extends Thread {
+
+ public PooledThread() {
+ super(ThreadPool.this, "PooledThread-" + (threadID++));
+ }
+
+ public void run() {
+ while (!isInterrupted()) {
+
+ Runnable task = null;
+ try {
+ task = getTask();
+ } catch (InterruptedException ex) {
+ System.err.println(ex.getMessage());
+ }
+
+ if (task == null) {
+ return;
+ }
+
+ try {
+ task.run();
+ } catch (Throwable t) {
+ System.err.println(t.getMessage());
+ }
+ }
+ }
+ }
+}
diff --git a/sql/src/test/resources/connection.properties b/sql/src/test/resources/connection.properties
new file mode 100644
index 0000000..2e49346
--- /dev/null
+++ b/sql/src/test/resources/connection.properties
@@ -0,0 +1,9 @@
+sqlDriver = SQLite.JDBCDriver
+sqlLogin =
+sqlCatalog =sqliteTest.db
+sqlHost =
+sqlUrlPrefix = jdbc:sqlite:
+sqlPassword =
+sqlUser =
+sqlMaxConnections = 30
+sqlMaxTasks = 10000
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.golden.ser
new file mode 100644
index 0000000..d20eed1
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/BatchUpdateExceptionTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.golden.ser
new file mode 100644
index 0000000..9ecd6e1
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/DataTruncationTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.golden.ser
new file mode 100644
index 0000000..6e58660
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLExceptionTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.golden.ser
new file mode 100644
index 0000000..be37cb8
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/SQLWarningTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/TimestampTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/TimestampTest.golden.ser
new file mode 100644
index 0000000..4e51a0a
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/java/sql/TimestampTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.golden.ser
new file mode 100644
index 0000000..642e2fc
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/ConnectionEventTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/RowSetMetaDataImplTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/RowSetMetaDataImplTest.golden.ser
new file mode 100644
index 0000000..edd8bee
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/RowSetMetaDataImplTest.golden.ser
Binary files differ
diff --git a/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.golden.ser b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.golden.ser
new file mode 100644
index 0000000..71ed471
--- /dev/null
+++ b/sql/src/test/resources/serialization/org/apache/harmony/sql/tests/javax/sql/rowset/serial/SerialExceptionTest.golden.ser
Binary files differ