diff options
author | Neil Fuller <nfuller@google.com> | 2014-06-19 10:43:41 +0000 |
---|---|---|
committer | Android Git Automerger <android-git-automerger@android.com> | 2014-06-19 10:43:41 +0000 |
commit | 11ae35efd8d3ec9dd7668f9a324304eda42a9d76 (patch) | |
tree | 2c6daec1ed81f1edc170abab7c2c1429fd1e370b /luni/src/test/java | |
parent | 8192a4ef251310a92b20c590e1186736c2c48263 (diff) | |
parent | bfbc1b512b2c31907dd9a90dace17a4346912d03 (diff) | |
download | libcore-11ae35efd8d3ec9dd7668f9a324304eda42a9d76.zip libcore-11ae35efd8d3ec9dd7668f9a324304eda42a9d76.tar.gz libcore-11ae35efd8d3ec9dd7668f9a324304eda42a9d76.tar.bz2 |
am bfbc1b51: am 0be12357: Merge "Removing tests that test the SqlLite API directly."
* commit 'bfbc1b512b2c31907dd9a90dace17a4346912d03':
Removing tests that test the SqlLite API directly.
Diffstat (limited to 'luni/src/test/java')
12 files changed, 145 insertions, 3152 deletions
diff --git a/luni/src/test/java/libcore/java/sql/ConnectionTest.java b/luni/src/test/java/libcore/java/sql/ConnectionTest.java new file mode 100644 index 0000000..02046fc --- /dev/null +++ b/luni/src/test/java/libcore/java/sql/ConnectionTest.java @@ -0,0 +1,69 @@ +package libcore.java.sql; + +import junit.framework.TestCase; + +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.Driver; +import java.sql.DriverManager; + +public class ConnectionTest extends TestCase { + + private File dbFile = null; + private String connectionURL = null; + + @Override + public void setUp() throws Exception { + super.setUp(); + + // Trigger the static initializer that will cause the driver to register itself with + // DriverManager. + Class.forName("SQLite.JDBCDriver"); + } + + @Override + protected void tearDown() throws Exception { + super.tearDown(); + if (dbFile != null) { + dbFile.delete(); + } + } + + public void testDriverManager_getConnection() throws Exception { + Connection c = DriverManager.getConnection(getConnectionURL()); + assertFalse(c.isClosed()); + c.close(); + assertTrue(c.isClosed()); + } + + public void testConnect() throws Exception { + Driver driver = DriverManager.getDriver(getConnectionURL()); + assertNotNull(driver); + Connection c = driver.connect(getConnectionURL(), null); + assertFalse(c.isClosed()); + c.close(); + assertTrue(c.isClosed()); + } + + private String getConnectionURL() { + if (connectionURL == null) { + String tmp = System.getProperty("java.io.tmpdir"); + File tmpDir = new File(tmp); + if (tmpDir.isDirectory()) { + try { + dbFile = File.createTempFile("OldJDBCDriverTest", ".db", tmpDir); + } catch (IOException e) { + System.err.println("error creating temporary DB file."); + } + dbFile.deleteOnExit(); + } else { + System.err.println("java.io.tmpdir does not exist"); + } + + connectionURL = "jdbc:sqlite:/" + dbFile.getPath(); + } + + return connectionURL; + } +} diff --git a/luni/src/test/java/libcore/java/sql/DriverTest.java b/luni/src/test/java/libcore/java/sql/DriverTest.java new file mode 100644 index 0000000..59d13bd --- /dev/null +++ b/luni/src/test/java/libcore/java/sql/DriverTest.java @@ -0,0 +1,76 @@ +/* + * Copyright (C) 2008 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 libcore.java.sql; + +import junit.framework.TestCase; + +import SQLite.JDBCDriver; + +import java.sql.Driver; +import java.sql.DriverManager; +import java.sql.DriverPropertyInfo; +import java.sql.SQLException; + +public final class DriverTest extends TestCase { + + public static final String SQLITE_JDBC_URL = "jdbc:sqlite:/only_used_at_connect_time"; + + @Override + public void setUp() throws Exception { + super.setUp(); + + // Trigger the static initializer that will cause the driver to register itself with + // DriverManager. + Class.forName("SQLite.JDBCDriver"); + } + + public void testDriverImplementation() throws Exception { + Driver driver = getDriver(); + assertTrue(driver instanceof JDBCDriver); + } + + public void testAcceptsURL() throws Exception { + Driver driver = getDriver(); + assertTrue(driver.acceptsURL(SQLITE_JDBC_URL)); + } + + public void testGetMajorVersion() throws Exception { + assertTrue(getDriver().getMajorVersion() > 0); + } + + public void testGetMinorVersion() throws Exception { + assertTrue(getDriver().getMinorVersion() > 0); + } + + public void testGetPropertyInfo() throws Exception { + Driver driver = getDriver(); + DriverPropertyInfo[] info = driver.getPropertyInfo(SQLITE_JDBC_URL, null); + assertNotNull(info); + assertTrue(info.length > 0); + } + + public void testJdbcCompliant() throws Exception { + // The SQLite JDBC driver used by these tests is not actually JDBC compliant. + assertFalse(getDriver().jdbcCompliant()); + } + + private Driver getDriver() throws SQLException { + Driver driver = DriverManager.getDriver(SQLITE_JDBC_URL); + assertNotNull(driver); + return driver; + } +} diff --git a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java b/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java deleted file mode 100644 index d194548..0000000 --- a/luni/src/test/java/libcore/sqlite/AbstractSqlTest.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * 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 libcore.sqlite; - -import SQLite.Exception; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import junit.framework.TestCase; - - -/** - * This class provides SQL unit test, which can be used by subclasses eg. to - * test JDBC drivers. - */ -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() { - super(); - 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 - * @throws Exception - * @exception Exception may be thrown by subclasses - */ - @Override - protected void setUp() throws java.lang.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/luni/src/test/java/libcore/sqlite/OldBlobTest.java b/luni/src/test/java/libcore/sqlite/OldBlobTest.java deleted file mode 100644 index 3289d38..0000000 --- a/luni/src/test/java/libcore/sqlite/OldBlobTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.Blob; -import SQLite.Database; -import SQLite.Exception; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import tests.support.Support_SQL; - -public final class OldBlobTest extends OldSQLiteTest { - - private static Blob testBlob = null; - - private static Database db = null; - - public void setUp() throws java.lang.Exception { - super.setUp(); - testBlob = new Blob(); - - super.setUp(); - Support_SQL.loadDriver(); - db = new Database(); - db.open(dbFile.getPath(), 0); - - db.exec("create table B(id integer primary key, val blob)",null); - db.exec("insert into B values(1, zeroblob(128))", null); - db.exec("insert into B values(2, zeroblob(128))", null); - db.exec("insert into B values(3, zeroblob(128))", null); - - // can not fill Blob with data at this point... - /* - File resources = Support_Resources.createTempFolder(); - BufferedReader r = null; - try { - Class c = Class.forName(this.getClass().getName()); - assertNotNull(c); - file = Class.forName(this.getClass().getName()) - .getResourceAsStream("/blob.c"); - r = new BufferedReader(new InputStreamReader(file)); - } catch (NullPointerException e) { - fail("Should not throw NullPointerException reading file" - + e.getMessage()); - } - OutputStream out = testBlob.getOutputStream(); - String s = null; - while ((s = r.readLine()) != null) { - out.write(r.readLine().getBytes()); - } - out.flush(); - out.close(); - testBlob.close(); - */ - } - - @Override public void tearDown() throws java.lang.Exception { - testBlob.close(); - super.tearDown(); - } - - /** - * db.open_blob is not supported. - */ - public void testBlob() throws Exception, IOException { - byte[] b = new byte[4]; - byte[] b128 = new byte[128]; - for (int i = 0; i < b128.length; i++) { - b128[i] = (byte) i; - } - Blob blob = db.open_blob(dbFile.getPath(), "B", "val", 1, true); - try { - - OutputStream os = blob.getOutputStream(); - os.write(b128); - os.close(); - - InputStream is = blob.getInputStream(); - is.skip(96); - assertEquals(4,is.read(b)); - is.close(); - } finally { - blob.close(); - } - } - - public void testGetInputStream() { - InputStream in = testBlob.getInputStream(); - try { - in.read(); - fail("Exception not thrown for invalid Blob."); - } catch (Throwable e) { - //ok - } - } - - public void testGetOutputStream() { - OutputStream out = testBlob.getOutputStream(); - - try { - out.write(null); - fail("Write operation unsupported"); - } catch (Throwable e) { - assertEquals("Write operation unsupported", e.getMessage()); - } - } - - public void testClose() { - assertNotNull(testBlob); - - testBlob.close(); - // inputStream either null or some error occurs - try { - // TODO This does look a bit weird. Revisit later. - assertNull(testBlob.getInputStream()); - } catch (Throwable e) { - //ok - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java b/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java deleted file mode 100644 index f2cbc57..0000000 --- a/luni/src/test/java/libcore/sqlite/OldDatabaseTest.java +++ /dev/null @@ -1,1224 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.Authorizer; -import SQLite.Blob; -import SQLite.BusyHandler; -import SQLite.Callback; -import SQLite.Constants; -import SQLite.Database; -import SQLite.Exception; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.ProgressHandler; -import SQLite.Stmt; -import SQLite.TableResult; -import SQLite.Trace; -import SQLite.Vm; -import java.io.File; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.logging.Logger; -import tests.support.DatabaseCreator; -import tests.support.MockFunction; -import tests.support.ThreadPool; - -public final class OldDatabaseTest extends OldSQLiteTest { - - private static ErrorTracker tracker = null; - - private Statement statement; - - private Database db = null; - - private static final int numThreads = 10; - - private static final int numOfRecords = 30; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - assertNotNull("Could not establish DB connection",conn); - tracker = new ErrorTracker(); - - statement = conn.createStatement(); - - // Cleanup tables if necessary - - DatabaseMetaData meta = conn.getMetaData(); - assertNotNull(meta); - ResultSet userTab = meta.getTables(null, null, null, null); - while (userTab.next()) { - String tableName = userTab.getString("TABLE_NAME"); - this.statement.execute("drop table " + tableName); - } - - // Create default test table - statement.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); - statement.close(); - - db = new Database(); - db.open(dbFile.getPath(), 0); - db.busy_handler(null); - } - - public void tearDown() throws java.lang.Exception { - try { - db.close(); - } catch (Exception e) { - if (!(e.getMessage().equals("database already closed"))) { - System.err.println("Error closing DB " + dbFile.getPath()); - } - } - tracker.reset(); - super.tearDown(); - } - - public void testDatabase() throws Exception { - // db closed - Database db2 = new Database(); - db.close(); - db2 = new Database(); - db2.open(dbFile.getPath(), 0); - db2.close(); - db.open(dbFile.getPath(), 0); - //db is open - db2.open(dbFile.getPath(), 0); - db2.close(); - } - - public void testOpen() throws Exception { - db.close(); - db.open(dbFile.getPath(), 0); - // open second db while db1 still open - Database db2 = new Database(); - db2.open(dbFile.getPath(), 0); - db2.open(dbFile.getPath(), 0); - db2.close(); - // open non db file - try { - URL file = OldDatabaseTest.class.getResource("/blob.c"); - db2.open(file.getPath(), 0); - fail("Should not be able to open non db file"); - } catch (SQLite.Exception e) { - assertEquals("unknown error in open", e.getMessage()); - } - } - - public void testOpen_aux_file() { - File temp = null; - try { - db.open_aux_file(""); - fail("open should fail"); - } catch (Exception e) { - assertEquals("unsupported", e.getMessage()); - } - - /* - try { - temp = File.createTempFile("openAuxMethod", ".db"); - db.open_aux_file(""); - db.exec("create table AUX_TABLE", null); - db.close(); - } catch (Exception e) { - temp.delete(); - fail("Error handling temporary file "+e.getMessage()); - e.printStackTrace(); - } catch (IOException e) { - temp.delete(); - fail("Could not create temporary File"); - e.printStackTrace(); - } - try { - db.open(dbFile.getPath(),0); - db.exec("select * from AUX_TABLE", null); - fail("Statement should fail"); - } catch (Exception e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - temp.delete(); - */ - } - - public void testClose() throws Exception { - try { - db.close(); - db.get_table("test"); - fail(); - } catch (Exception e) { - assertTrue(e.getMessage().equals("database already closed")); - try { - db.open(dbFile.getPath(), 0); - } catch (Exception e1) { - fail("Database object could not be reopened after 'close': " - + e.getMessage()); - e1.printStackTrace(); - } - } - - try { - db.close(); - db.close(); - fail(); - } catch (Exception e) { - assertTrue(e.getMessage().equals("database already closed")); - db.open(dbFile.getPath(), 0); - } - } - - public void testExecStringCallback() throws Exception { - TableResult res = new TableResult(); - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(1, 10, 20)", null); - db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res); - db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 + " where 1", null); - String row[] = (String[]) res.rows.elementAt(0); - assertEquals(Integer.parseInt(row[0]), 1); - assertEquals(Integer.parseInt(row[1]), 10); - assertEquals(Integer.parseInt(row[2]), 20); - } - - public void testExecStringCallbackStringArray() throws Exception { - TableResult res = new TableResult(); - String args[] = new String[1]; - args[0] = "table"; - db.exec("select name from sqlite_master where type = '%q';", res, args); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - - try { - db.exec("select name from sqlite_master where type = ", res, args); - fail("Testmethod should fail"); - } catch (Exception e) { - // Ok - } - } - - public void testLast_insert_rowid() throws Exception { - assertEquals(0, db.last_insert_rowid()); - db.exec("create table TEST5(id integer, firstname text, lastname text);", null); - db.exec("insert into TEST5 values (1,'James','Bond');", null); - db.exec("insert into TEST5 values (2,'Fiona','Apple');", null); - assertEquals(2, db.last_insert_rowid()); - assertEquals(db.last_insert_rowid(), db.last_insert_rowid()); - - db.exec("drop table TEST5;", null); - assertEquals(2, db.last_insert_rowid()); - } - - /** - * Reason for failure unknown: Database should be locked. Specification - * of interrupt is scarce. - */ - public void testInterrupt() throws Exception, SQLException { - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs; - userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - // should not be able to do any other insertions since task 1 holds lock - int id2 = numOfRecords + 3; - threadPool - .runTask(createTask2Interrupt(id2, dbFile.getPath(), tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - System.out.println("Last error: " + db.error_message()); - if (errors.size() > 0) { - assertEquals(errors.get(0), db.error_string(Constants.SQLITE_LOCKED)); - for (String s : errors) { - Logger.global.info("INTERRUPT Error: " + s); - } - - } else { - fail("Should have one exception: database should be locked."); - } - - // reset - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", null); - } - - /** - * Returns wrong number for updates: returns value > 1 for select. - */ - public void testChanges() throws Exception { - TableResult res = new TableResult(); - assertTrue(db.changes() == 0); - db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(2, 5, 7);", null); - int rows = (int) db.changes(); - assertEquals(1,db.changes()); - db.exec("update " + DatabaseCreator.SIMPLE_TABLE1 - + " set speed = 7, size= 5 where id = 2;", null); - assertEquals(1,db.changes()); - db.exec("select * from " + DatabaseCreator.SIMPLE_TABLE1, res); - assertEquals(0,db.changes()); - db.exec("INSERT INTO " + DatabaseCreator.SIMPLE_TABLE1 - + " VALUES(8, 5, 7);", null); - db.exec("Update "+DatabaseCreator.SIMPLE_TABLE1+" set speed = 10;",null); - assertTrue(db.changes() > 2); - } - - /** - * method test fails once in a while. Cannot be sure that exception is - * thrown in every test execution. - */ - public void testBusy_handler() throws SQLException, Exception { - TestBusyHandler bh = new TestBusyHandler(); - db.busy_handler(bh); - int counter = 0; - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs; - userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - - try { - conn.setAutoCommit(false); - int id1 = numOfRecords - 3; - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - int id2 = numOfRecords + 3; - threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); - int oldID = 5; - int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID, - tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - if (errors.size() > 0) { -// assertEquals(errors.get(0), -// db.error_string(Constants.SQLITE_LOCKED)); - for (String s: errors) { - System.out.println("Round 2 Error: "+s); - } - } else { - fail("No error happened"); - } - - // reset - - - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", - null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", - null); -// -// // increase timeout for retry -// db.busy_timeout(1000); -// db.busy_handler(bh); -// tracker.reset(); - -// threadPool = new ThreadPool(numThreads); -// -// threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); -// threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); -// -// threadPool.join(); -// -// errors = tracker.getErrors(); -// if (errors.size() > 0) { -// // assertEquals(errors.get(0), -// // db.error_string(Constants.SQLITE_LOCKED)); -// for (String s: errors) { -// System.out.println("Round 2 Error"+s); -// } -// } else { -// // ok -// System.out.println("BUSY: No Error!"); -// } -// -// - } finally { - conn.setAutoCommit(true); - db.exec(DatabaseCreator.DROP_TABLE1, null); - db.exec(DatabaseCreator.DROP_TABLE3, null); - } - } - - /** - * test fails. Cannot be sure that exception is thrown every time. - * Database does not lock values. - */ - public void testBusy_timeout() throws Exception, SQLException { - int counter = 0; - ThreadPool threadPool = new ThreadPool(numThreads); - - // initialization - ResultSet userTabs = conn.getMetaData().getTables(null, null, null, null); - while (userTabs.next()) { - String tableName = userTabs.getString("TABLE_NAME"); - if (tableName.equals(DatabaseCreator.TEST_TABLE1)) { - statement.execute(DatabaseCreator.DROP_TABLE1); - } - } - db.exec(DatabaseCreator.CREATE_TABLE3, null); - db.exec(DatabaseCreator.CREATE_TABLE1, null); - - // test run - try { - conn.setAutoCommit(false); - -// DatabaseCreator.fillTestTable1(conn, numOfRecords); - // set to fail immediately if table is locked. - db.busy_handler(null); - db.busy_timeout(0); - int id1 = numOfRecords - 3; - - threadPool.runTask(createTask2(id1, dbFile.getPath(), tracker)); - int id2 = numOfRecords + 3; - threadPool.runTask(createTask1(id2, dbFile.getPath(), tracker)); - int oldID = 5; - int newID = 100; - threadPool.runTask(createTask3(oldID, dbFile.getPath(), newID, - tracker)); - - threadPool.join(); - - List<String> errors = tracker.getErrors(); - assertTrue("No error occurred on DB but should have",errors.size() > 0); - - assertEquals(errors.get(0), - db.error_string(Constants.SQLITE_LOCKED)); - assertEquals(errors.get(0), "database is locked"); - - // reset - - db.exec("delete from " + DatabaseCreator.TEST_TABLE1 + " where 1", - null); - db.exec("delete from " + DatabaseCreator.TEST_TABLE3 + " where 1", - null); - - // increase timeout for retry - db.busy_timeout(10000); - db.busy_handler(null); - tracker.reset(); - threadPool = new ThreadPool(numThreads); - - threadPool.runTask(createTask1(id1, dbFile.getPath(), tracker)); - threadPool.runTask(createTask2(id2, dbFile.getPath(), tracker)); - - threadPool.join(); - - errors = tracker.getErrors(); - if (errors.size() > 0) { - fail("busy timeout should prevent from lock exception!"); - for (String s: errors) { - System.out.println("Round 2 Error"+s); - } - } else { - // ok - } - } finally { - conn.setAutoCommit(true); - // cleanup - db.exec(DatabaseCreator.DROP_TABLE1, null); - db.exec(DatabaseCreator.DROP_TABLE3, null); - } - } - - public void testGet_tableString() throws Exception { - TableResult emptyTable = new TableResult(); - //select from empty table - TableResult res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertEquals(res.toString(), emptyTable.toString()); - //fill table-> t -// DatabaseCreator.fillSimpleTable1(conn); -// res = db.get_table("select * from " -// + DatabaseCreator.SIMPLE_TABLE1); -// assertFalse(emptyTable.toString().equals(res.toString())); - - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 + " VALUES(1, 10, 20)", null); - res = db.get_table("select * from " + DatabaseCreator.SIMPLE_TABLE1); - db.exec("delete from " + DatabaseCreator.SIMPLE_TABLE1 - + " where 1", null); - String row[] = (String[]) res.rows.elementAt(0); - assertEquals(Integer.parseInt(row[0]), 1); - assertEquals(Integer.parseInt(row[1]), 10); - assertEquals(Integer.parseInt(row[2]), 20); - } - - public void testGet_tableStringStringArray() throws Exception { - String args[] = new String[1]; - args[0] = "table"; - String argsFail[] = new String[1]; - try { - db.get_table("select name from sqlite_master where type = ", argsFail); - fail("Testmethod should fail"); - } catch (Exception e) { - } - - TableResult res = db.get_table( - "select name from sqlite_master where type = '%q'", - args); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - } - - public void testGet_tableStringStringArrayTableResult() throws Exception { - String args[] = new String[1]; - String argsFail[] = new String[1]; - TableResult res = new TableResult(); - TableResult defaultTableRes = new TableResult(); - args[0] = "table"; - - try { - db.get_table("select name from sqlite_master where type = '%q'", argsFail, res); - assertEquals(defaultTableRes.toString(), res.toString()); - } catch (Exception e) { - db.get_table("select name from sqlite_master where type = '%q'", args, res); - String[] s = (String[]) res.rows.elementAt(0); - assertEquals(s[0], DatabaseCreator.SIMPLE_TABLE1); - System.out.println("DatabaseTest.testGet_tableStringStringArrayTableResult() " - + Arrays.toString(res.types)); - } - } - - public void testComplete() { - assertFalse(db.complete("create")); - assertTrue(db.complete("create table TEST (res double);")); - } - - public void testVersion() { - String version = db.version(); - if (version != null) { - assertTrue(Integer.parseInt(db.version().substring(0, 1)) > 0); - assertEquals(db.version(), db.version()); - } else { - fail("DB version info missing"); - } - } - - public void testDbversion() throws Exception { - String verNo = ""; - try { - verNo = db.dbversion(); - db.close(); - assertEquals(db.dbversion(),"unknown"); - db.open(dbFile.getPath(), 0); - assertEquals(verNo, db.dbversion()); - } catch (Exception e) { - db.open(dbFile.getPath(), 0); - } - - assertTrue(Integer.parseInt(verNo.substring(0, 1))>= 3 ); - - } - - public void testCreate_function() throws Exception { - double input = 1.0; - db.exec("create table TEST (res double)", null); - db.exec("insert into TEST values (" + Double.toString(input) + ")", - null); - TableResult res = new TableResult(); - Function sinFunc = (Function) new SinFunc(); - db.create_function("sin", 1, sinFunc); - db.exec("select sin(res) from TEST WHERE res = " - + Double.toString(input), res); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - double sinusVal = Double.parseDouble(val); - double funcVal = Math.sin(input); - - assertTrue(Math.round(funcVal) == Math.round(sinusVal)); - } - - /** - * Aggregation function not called. - */ - public void testCreate_aggregate() throws Exception { - TestTrace t = new TestTrace(); - MockFunction aggFunction = new MockFunction(); - db.exec("create table TEST(id integer, firstname text, lastname text)", null); - db.exec("insert into TEST values(3, 'James', 'Bond'); ", null); - db.exec("insert into TEST values(4, 'Fiona', 'Apple'); ", null); - db.trace((Trace) t); - db.create_aggregate("myaggfunc", 1, aggFunction); - db.function_type("myaggfunc", Constants.SQLITE3_TEXT); - db.exec("PRAGMA show_datatypes = on", null); - - assertFalse(aggFunction.functionCalled); - assertFalse(aggFunction.stepCalled); - assertFalse(aggFunction.lastStepCalled); - db.exec("select myaggfunc(TEST.firstname) from TEST", t); - assertTrue(aggFunction.stepCalled); - assertTrue(aggFunction.lastStepCalled); - assertTrue(aggFunction.functionCalled); - - assertEquals("James Fiona ",aggFunction.getAggValue()); - db.exec("drop table TEST", null); - - try { - db.create_aggregate("myaggfunc", 0, null); - } catch (Throwable e) { - assertEquals("null SQLite.Function not allowed",e.getMessage()); - } - - try { - db.create_aggregate("myaggfunc", 0, aggFunction); - } catch (Throwable e) { - assertEquals("wrong number of arguments to function myaggfunc()",e.getMessage()); - } - } - - public void testFunction_type() throws Exception { - double input = 1.0; - TableResult res = new TableResult(); - Function sinFunc = (Function) new SinFunc(); - - db.exec("PRAGMA show_datatypes = on", null); - db.exec("create table TEST (res double)", null); - db.exec("insert into TEST values (" + Double.toString(input) + ")", - null); - - db.create_function("sin", 1, sinFunc); - db.function_type("sin", Constants.SQLITE_FLOAT); - res = db.get_table("select sin(res) from TEST WHERE res = " - + Double.toString(input)); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - assertTrue("double".equalsIgnoreCase(res.types[0])); - assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); - - // function determines return type: test that Double type is returned. - db.function_type("sin", Constants.SQLITE_BLOB); - Stmt s = db.prepare("select sin(res) from TEST WHERE res = ?"); - s.bind(1, input); - s.step(); - - res = db.get_table("select sin(res) from TEST WHERE res = " - + Double.toString(input)); - assertTrue("double".equalsIgnoreCase(res.types[0])); - row = (String[]) res.rows.elementAt(0); - val = row[0]; - assertSame(Math.round(Math.sin(input)), Math.round(Double.parseDouble(val))); - } - - public void testLast_error() { - assertEquals(db.last_error(), Constants.SQLITE_OK); - try { - db.exec("create table TEST (res double)",null); - db.exec("create table TEST (res double)",null); - fail("Error should have happened"); - } catch (Exception e) { - assertEquals(db.last_error(),db.last_error()); - assertEquals(db.last_error(),Constants.SQLITE_ERROR); - } - } - - public void testSet_last_error() { - assertEquals(db.last_error(), Constants.SQLITE_OK); - try { - db.exec("sel from test;", null); - } catch (Exception e) { - assertEquals(Constants.SQLITE_ERROR,db.last_error()); - } - } - - public void testError_message() { - String statement = "create table TEST (res double)"; - try { - db.exec(statement,null); - db.exec(statement,null); - fail("DB Error expected"); - } catch (Exception e) { - String dbError = db.error_message(); - assertTrue(e.getMessage().equals(dbError)); - - } - } - - public void testError_string() { - TestTrace t = new TestTrace(); - assertEquals(db.last_error(), Constants.SQLITE_OK); - String errorString = db.error_string(Constants.SQLITE_ERROR); - try { - db.trace((Trace) t); - db.exec("create table TEST (res double)", t); - db.exec("create table TEST (res double)", t); - } catch (Exception e) { - assertEquals(db.last_error(), Constants.SQLITE_ERROR); - if (db.is3()) { - assertEquals("Unsupported Method (sqlite 3): error_string", db - .error_string(db.last_error()), errorString); - } - } - } - - /** - * ASCII encoding does not work: a UTF encoded val is returned. Spec is not - * sufficient. Might be that test impl is wrong or String constructor for - * the ASCII encoding. - */ - public void testSet_encoding() throws UnsupportedEncodingException, Exception { - String input = "\u00bfMa\u00f1ana\u003f"; // ?Manana? - TableResult res = new TableResult(); - String refOutput = null; - Stmt stat = null; - - // DB setup - db.exec("create table encodingTest (encoded text DEFAULT NULL);", - null); - stat = db - .prepare("insert into encodingTest(encoded) values(:one);"); - stat.bind(1, input); - stat.step(); - // stat.close(); - db.exec("select * from encodingTest;", res); - String[] encInput = (String[]) res.rows.elementAt(0); - String output = encInput[0]; - assertEquals(input, output); - // db.exec("delete from encodingTest where 1", null); - - // tests for different encoding schemes - String[] charsetNames = {"UTF-8", "UTF-16", "UTF-16BE", "UTF-16LE"}; - for (int i = 0; i < charsetNames.length; i++) { - byte[] encInputBytes = input.getBytes(charsetNames[i]); - db.set_encoding(charsetNames[i]); - db.exec("select * from encodingTest;", res); - String[] encOutput = (String[]) res.rows.elementAt(0); - String inputAsString = new String(encInputBytes,charsetNames[i]); - assertEquals(inputAsString, encOutput[0]); - } - - // Default tests - db.set_encoding("UTF-16"); - db.exec("select * from encodingTest;", res); - String[] encOutput1 = (String[]) res.rows.elementAt(0); - assertEquals("Got "+encOutput1[0]+" as UTF-16",input,encOutput1[0]); - - db.set_encoding("US-ASCII"); - db.exec("select * from encodingTest;", res); - String[] encOutput2 = (String[]) res.rows.elementAt(0); - assertEquals(new String(input.getBytes(),"US-ASCII"),encOutput2[0]); - - // DB teardown - stat.close(); - db.exec("delete from encodingTest", null); - - // Default tests - try { - db.set_encoding(""); - fail("invalid input should fail"); - } catch (Exception e) { - //ok - } - } - - /** - * Callback never made for authorization. Results of private table are - * returned withouth furhter checks. - * - * Test fails -> implemented correctly? - */ - public void testSet_authorizer() throws Exception { - TableResult resPriv = null; - TableResult resPub = null; - TableResult emptyTable = new TableResult(); - String insertPublic = "insert into public_table values(1,2)"; - String insertPrivate = "insert into private_table values(1,2)"; - // prepare, authorizer is not activated yet - db.exec("create table public_table(c1 integer, c2 integer);", null); - db.exec("create table private_table(c1 integer, c2 integer);", null); - // inserts - db.exec(insertPublic, null); - db.exec(insertPrivate, null); - // selects - resPriv = db.get_table("select * from private_table"); - resPub = db.get_table("select * from public_table"); - -// db.exec("delete from public_table where 1", null); -// TableResult emptyPubTable = db.exec("select * from public"); - - // set Authorizer (positive case): denies private table - AuthorizerCallback cb = new AuthorizerCallback(); - db.set_authorizer(cb); - //select - - db.exec("select * from private_table", cb); - assertTrue(cb.wasCalled()); - - /* - TableResult res = db.get_table("select * from private_table"); - assertEquals(emptyTable.toString(),res.toString()); - assertFalse(emptyTable.equals(resPriv)); - - res = db.get_table("select * from public_table"); - assertEquals(resPub,res); - */ - - // Try insert - try { - db.exec(insertPublic, null); - fail("authorization failed"); - } catch (Exception e) { - } - - try { - db.exec(insertPrivate, null); - fail("authorization failed"); - } catch (Exception e1) { - // ok - } - } - - public void testTrace() throws Exception { - String stmt = "create table TEST (res double);"; - TestTrace t = new TestTrace(); - assertFalse(t.traceCalled); - assertEquals(db.last_error(),Constants.SQLITE_OK); - db.trace((Trace) t); - db.exec(stmt,t); - assertTrue(t.traceCalled); - assertEquals(t.getTrace(),stmt); - - try { - db.close(); - db.exec(stmt,t); - fail("Exception Expected"); - } catch (Exception e) { - //ok - } - } - - public void testCompileString() throws Exception { - db.compile("select name from sqlite_master;"); - try { - db.compile("test"); - fail("Compiling of inaccurate statement does not fail."); - } catch (Exception e) { - } - } - - public void testCompileStringStringArray() throws Exception { - String args[] = new String[1]; - args[0] = "table"; - db.compile("select name from sqlite_master where type = '%q';",args); - - try { - db.compile("test",null); - fail("Compiling of inaccurate statement does not fail."); - } catch (Exception e) { - } - } - - public void testPrepare() throws Exception { - Stmt st = null; - Stmt st2 = null; - // test empty statement - try { - st = db.prepare(""); - assertEquals(0, st.bind_parameter_count()); - st.step(); - fail("stmt should not be prepared"); - } catch (Exception e) { - assertEquals("stmt already closed", e.getMessage()); - } - - // test statement with unbound arguments - try { - st2 = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st2.bind_parameter_count()); - assertEquals(3, st2.bind_parameter_index(":three")); - assertEquals(":two", st2.bind_parameter_name(2)); - } finally { - st2.close(); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(:one,:two,:three,:four);"); - } catch (Exception e) { - assertEquals("table " + DatabaseCreator.SIMPLE_TABLE1 - + " has 3 columns but 4 values were supplied", e - .getMessage()); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(5, '10, 20);"); - } catch (Exception e) { - assertEquals("unrecognized token: \"'10, 20);\"", e.getMessage()); - } - - try { - db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values(5, 10 20);"); - } catch (Exception e) { - assertEquals("near \"20\": syntax error", e.getMessage()); - } - - } - - /** - * Not supported. - */ - public void testOpen_blob() throws Exception, java.lang.Exception { - Stmt statement2; - Blob blobInput = new Blob(); - - // Create test input Blob - InputStream inStream = null; - byte[] in = {(byte) 1, (byte) 2, (byte) 3, (byte) 4}; - - // setup test input - db.exec("create table TEST (res blob)",null); - inStream = Class.forName(this.getClass().getName()).getResourceAsStream("/blob.c"); - assertNotNull(inStream); - - // insert byte array in db - statement2 = db.prepare("insert into TEST(res) values (?)"); - statement2.bind(1, in); - statement2.step(); - statement2.close(); - - // read from db - Blob blob = db.open_blob(dbFile.getPath(), "TEST", "res", 1, true); - if (blob == null) { - fail("Blob could not be retrieved"); - } - //read from blob and compare values (positive case) - InputStream is = blob.getInputStream(); - - int i = 0; - int outByte = 0; - byte[] out = new byte[4]; - while ((outByte = is.read()) > -1) { - out[i] = (byte) outByte; - i++; - } - is.close(); - - blob.close(); - - assertTrue(Arrays.equals(in, out)); - - //read from blob and compare values (default blob) - db.exec("insert into TEST values(zeroblob(128))", null); - Blob blob2 = db.open_blob(dbFile.getPath(), "TEST", "res", 2, true); - is = blob2.getInputStream(); - for (i = 0; i < 128; i++) { - assertEquals(0, is.read()); - } - is.close(); - } - - public void testIs3() { - int ver = Integer.parseInt(db.version().substring(0,1)); - if (db.is3()) { - assertTrue( ver == 3); - } else { - assertTrue(ver != 3); - } - } - - public void testProgress_handler() throws Exception { - int inputVal = 3; - TestProgressHandler prog = new TestProgressHandler(); - db.exec("create table TEST5(id integer, firstname text, lastname text)",null); - Vm vm = db.compile("select * from TEST5; " - + "insert into TEST5 values(3, 'James', 'Bond'); " - + "delete from TEST5 where id = 3; " - + "select * from TEST5"); - int stmt = 0; - do { - ++stmt; - if (stmt > inputVal) { - db.progress_handler(inputVal, prog); - } else { - assertEquals(0, prog.getCounts()); - } - while (vm.step(prog)) { - } - } while (vm.compile()); - assertEquals(inputVal,prog.getCounts()); - - // Boundary value test - inputVal = 0; - TestProgressHandler progBoundary = new TestProgressHandler(); - db.progress_handler(inputVal, progBoundary); - Vm vm2 = db.compile("select * from TEST5; " - + "insert into TEST5 values(3, 'James', 'Bond'); " - + "delete from TEST5 where id = 3; " - + "select * from TEST5"); - do { - vm2.step(progBoundary); - } while (vm2.compile()); - assertEquals(inputVal, progBoundary.getCounts()); - - try { - db.exec("drop table TEST5",null); - } catch (Exception e) { - System.out.println(e.getMessage()); - e.printStackTrace(); - } - } - - class SinFunc implements Function { - public void function(FunctionContext fc, String args[]) { - Double d = new Double(args[0]); - fc.set_result(Math.sin(d.doubleValue())); - } - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestTrace implements Trace,Callback { - - private StringBuffer buf = new StringBuffer(); - - public boolean traceCalled = false; - - public String getTrace() { - return buf.toString(); - } - - public void trace(String stmt) { - traceCalled = true; - buf.append(stmt); - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - class AuthorizerCallback implements Authorizer, Callback { - - private boolean isAuthorizing = false; - - public boolean wasCalled() { - return isAuthorizing; - } - - public int authorize(int action, String arg1, String arg2, String arg3, - String arg4) { - Logger.global.info("DB authorization callback " + action + " " + arg1 + " " + arg2 + " " - + arg3 + " " + arg4 + " "); - this.isAuthorizing = true; - if (action != Constants.SQLITE_SELECT || arg1.contains("private_table")) { - return Constants.SQLITE_DENY; - } else { - return Constants.SQLITE_OK; - } - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - - } - - class TestBusyHandler implements BusyHandler, Callback { - - public boolean busy(String table, int count) { - return true; - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - class TestProgressHandler implements ProgressHandler, Callback { - - private boolean progressed = false; - - private int counter = 0; - - public int getCounts() { - return counter; - } - - public boolean progress() { - this.progressed = true; - counter++; - return true; - } - - public void columns(String[] coldata) {} - - public boolean newrow(String[] rowdata) { - return false; - } - - public void types(String[] types) {} - } - - /** - * This method creates a Runnable that executes insert operation for the first table - */ - private static Runnable createTask2Interrupt(final int id, - final String dbName, final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - Database db = new Database(); - try { - String value = DatabaseCreator.defaultString + id; - - db.open(dbName, 0); - String insertQuery = "INSERT INTO " - + DatabaseCreator.TEST_TABLE1 - + " (id, field1, field2, field3) VALUES(" + id - + ", '" + value + "', " + id + ", " + id + ")"; - db.exec(insertQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - try { - db.interrupt(); - db.exec("DELETE FROM " + DatabaseCreator.SIMPLE_TABLE1 - + " WHERE id=" + id, null); - } catch (Exception e1) { - errorTracker.registerException(this, e1); - } - } - } - }; - } - - /** - * This method creates a Runnable that executes delete operation for the first table - */ - private static Runnable createTask1(final int id, final String dbName, - final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - try { - Database db = new Database(); - db.open(dbName, 0); - db.exec("DELETE FROM " - + DatabaseCreator.SIMPLE_TABLE1 + " WHERE id=" + id, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - } - } - }; - } - - /** - * This method creates a Runnable that executes insert operation for the first table - */ - private static Runnable createTask2(final int id, final String dbName, - final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - try { - String value = DatabaseCreator.defaultString + id; - Database db = new Database(); - db.open(dbName, 0); - String insertQuery = "INSERT INTO " - + DatabaseCreator.TEST_TABLE1 - + " (id, field1, field2, field3) VALUES(" + id - + ", '" + value + "', " + id + ", " + id + ")"; - db.exec(insertQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - - } - } - }; - } - - /** - * This method creates a Runnable that executes update operation for the one record of the first - * table - */ - private static Runnable createTask3(final int oldID, final String dbName, - final int newID, final ErrorTracker errorTracker) { - return new Runnable() { - public void run() { - Database db = new Database(); - try { - db.open(dbName, 0); - String value = DatabaseCreator.defaultString + newID; - String updateQuery = "UPDATE " - + DatabaseCreator.TEST_TABLE1 + " SET id=" + newID - + ", field1='" + value + "', field2=" + newID - + ", field3=" + newID + " WHERE id=" + oldID; - db.exec(updateQuery, null); - } catch (Exception e) { - errorTracker.registerException(this, e); - } - } - }; - } - - private class ErrorTracker { - - private List<String> errors = new ArrayList<String>(); - - public void registerException(Runnable runnable, Exception e) { - System.out.println("Registered: " + e.getMessage()); - errors.add(e.getMessage()); - } - - public List<String> getErrors() { - return errors; - } - - public void reset() { - errors.clear(); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java b/luni/src/test/java/libcore/sqlite/OldExceptionTest.java deleted file mode 100644 index dddfd6b..0000000 --- a/luni/src/test/java/libcore/sqlite/OldExceptionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.Database; -import SQLite.Exception; - -public final class OldExceptionTest extends OldSQLiteTest { - - private Database db = null; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - db = new Database(); - } - - public void testException() { - try { - db.open(dbFile.getName(), 0); - } catch (Exception e) { - assertNotNull(e); - assertNotNull(e.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java b/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java deleted file mode 100644 index 0924317..0000000 --- a/luni/src/test/java/libcore/sqlite/OldFunctionContextTest.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.Database; -import SQLite.Exception; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.Stmt; -import SQLite.TableResult; -import java.io.UnsupportedEncodingException; -import java.sql.SQLException; -import java.sql.Statement; -import tests.support.DatabaseCreator; - -public final class OldFunctionContextTest extends OldSQLiteTest { - - private Database db = null; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - db = new Database(); - db.open(dbFile.getPath(), 0); - Statement st = conn.createStatement(); - st.execute(DatabaseCreator.CREATE_TABLE2); - st.execute(DatabaseCreator.CREATE_TABLE_SIMPLE1); - st.close(); - } - - public void testSet_resultString() throws Exception { - TestFCString testString = new TestFCString(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (ftext) values ('TestInput')", null); - db.create_function("test", 1, testString); - TableResult res = db.get_table("select test(ftext) from " - + DatabaseCreator.TEST_TABLE2); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals("TestInput", val); - } - - public void testSet_resultInt() throws Exception { - TestFCInt testInt = new TestFCInt(); - db.exec("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (1,'" + testInt.intVal + "',3)", null); - db.create_function("testInt", 1, testInt); - TableResult res = db.get_table("select testInt(speed) from " - + DatabaseCreator.SIMPLE_TABLE1); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals(testInt.intVal, Integer.parseInt(val)); - } - - public void testSet_resultDouble() throws Exception { - SinFunc testD = new SinFunc(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (fdouble) values (" + testD.testDouble + ")", null); - db.create_function("testDouble", 1, testD); - TableResult res = db.get_table("select testDouble(fdouble) from " - + DatabaseCreator.TEST_TABLE2); - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertEquals(testD.testDouble, Double.parseDouble(val)); - - assertTrue(testD.functionCalled); - } - - public void testSet_error() throws Exception { - TestFCError testError = new TestFCError(); - SinFunc testD = new SinFunc(); - db.exec("insert into " + DatabaseCreator.TEST_TABLE2 - + " (fdouble) values (" + testD.testDouble + ")", null); - db.create_function("testError", 1, testError); - - try { - TableResult res = db.get_table("select testError(fdouble) from " - + DatabaseCreator.TEST_TABLE2); - fail("Should get Exception"); - } catch (Exception e) { - assertEquals("error in step", e.getMessage()); - } - - assertFalse(testD.functionCalled); - } - - public void testSet_resultByteArray() throws Exception, UnsupportedEncodingException { - Stmt st = null; - TestFCByteArray testBinArrayFnc = new TestFCByteArray(); - String expected = ""; - expected = "X'" + getHexString(testBinArrayFnc.byteVal) + "'"; - - // setup - db.exec("create table testBinaryData (binVal BINARY) ;", null); - - try { - st = db.prepare("insert into testBinaryData values (?)"); - st.bind(1, testBinArrayFnc.byteVal); - st.step(); - - - db.create_function("testBinArray", 1, testBinArrayFnc); - TableResult res = db - .get_table("select testBinArray(binVal) from testBinaryData"); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertTrue(expected.equalsIgnoreCase(val)); - - assertTrue(testBinArrayFnc.functionCalled); - - } finally { - //teardown - db.exec("drop table testBinaryData;", null); - } - } - - /** - * ZeroBlob not supported - */ - public void testSet_result_zeroblob() throws Exception, - UnsupportedEncodingException { - Stmt st = null; - TestFCZeroBlob testZeroBlobFnc = new TestFCZeroBlob(); - byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; - - - // setup - db.exec("create table testBinaryData (binVal BINARY) ;", null); - - try { - st = db.prepare("insert into testBinaryData values (?)"); - st.bind(1, byteVal); - st.step(); - - - db.create_function("testZeroBlob", 0, testZeroBlobFnc); - TableResult res = db - .get_table("select testZeroBlob() from testBinaryData"); - TableResult res2 = db.get_table("select zeroblob(" - + testZeroBlobFnc.numBytes + ") from testBinaryData"); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertNotNull(val); - - assertEquals(((String[]) res2.rows.elementAt(0))[0], val); - assertTrue(testZeroBlobFnc.functionCalled); - - } finally { - // teardown - db.exec("drop table if exists testBinaryData;", null); - } - } - - /** - * Test Method results in a segmentation fault - */ - public void testCount() throws SQLException, Exception { - TestFCCount countTest = new TestFCCount(); - int inputCount = 10; - - assertFalse(countTest.functionCalled); - - DatabaseCreator.fillTestTable2(conn, inputCount); - db.create_function("testCount", 0, countTest); - // the invokation of testCount leads to a Segmentation fault - /* - TableResult res = db - .get_table("select testCount() from "+DatabaseCreator.TEST_TABLE2); - - String row[] = (String[]) res.rows.elementAt(0); - String val = row[0]; - - assertTrue(countTest.functionCalled); - assertEquals(inputCount,Integer.parseInt(val)); - */ - - } - - class TestFCError implements Function { - public boolean functionCalled = false; - public String errorMsg = "FunctionError"; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - fc.set_error(errorMsg); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCCount implements Function { - public boolean functionCalled = false; - public int noOfRows = 0; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - noOfRows = fc.count(); - fc.set_result(noOfRows); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCZeroBlob implements Function { - public int numBytes = 16; - public boolean functionCalled = false; - - public void function(FunctionContext fc, String args[]) { - functionCalled = true; - fc.set_result_zeroblob(numBytes); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCString implements Function { - public String testString = "TestString"; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(args[0]); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCInt implements Function { - public int intVal = Integer.MAX_VALUE; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(Integer.parseInt(args[0])); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class TestFCByteArray implements Function { - public byte[] byteVal = {(byte) 1, (byte) 2, (byte) 3}; - public boolean functionCalled; - - public void function(FunctionContext fc, String args[]) { - assertNotNull(args); - functionCalled = true; - fc.set_result(args[0].getBytes()); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - class SinFunc implements Function { - public Double testDouble = 3.0; - public boolean functionCalled = false; - - public void function(FunctionContext fc, String args[]) { - Double d = new Double(args[0]); - functionCalled = true; - fc.set_result(d.doubleValue()); - } - - public void last_step(FunctionContext fc) {} - public void step(FunctionContext fc, String[] args) {} - } - - static final byte[] HEX_CHAR_TABLE = { - (byte)'0', (byte)'1', (byte)'2', (byte)'3', - (byte)'4', (byte)'5', (byte)'6', (byte)'7', - (byte)'8', (byte)'9', (byte)'a', (byte)'b', - (byte)'c', (byte)'d', (byte)'e', (byte)'f' - }; - - public static String getHexString(byte[] raw) - throws UnsupportedEncodingException { - byte[] hex = new byte[2 * raw.length]; - int index = 0; - - for (byte b : raw) { - int v = b & 0xFF; - hex[index++] = HEX_CHAR_TABLE[v >>> 4]; - hex[index++] = HEX_CHAR_TABLE[v & 0xF]; - } - return new String(hex, "ASCII"); - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java deleted file mode 100644 index 48eeab1..0000000 --- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverFunctionalTest.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * 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 libcore.sqlite; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.SQLException; - -/** - * Tests the SQLite.JDBCDriver. - */ -public class OldJDBCDriverFunctionalTest extends AbstractSqlTest { - private File dbFile = null; - private String connectionURL = "empty"; - - @Override protected void tearDown() throws SQLException { - super.tearDown(); - dbFile.delete(); - } - - @Override protected String getConnectionURL() { - if (connectionURL.equals("empty")) { - String tmp = System.getProperty("java.io.tmpdir"); - File tmpDir = new File(tmp); - if (tmpDir.isDirectory()) { - try { - dbFile = File.createTempFile("JDBCDriverFunctionalTest", ".db", tmpDir); - } catch (IOException e) { - System.err.println("error creating temporary DB file."); - } - dbFile.deleteOnExit(); - } else { - System.err.println("java.io.tmpdir does not exist"); - } - - connectionURL = "jdbc:sqlite:/" + dbFile.getPath(); - } - - return connectionURL; - } - - @Override protected String getDriverClassName() { - return "SQLite.JDBCDriver"; - } - - @Override protected int getTransactionIsolation() { - return Connection.TRANSACTION_SERIALIZABLE; - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java b/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java deleted file mode 100644 index ae06dc6..0000000 --- a/luni/src/test/java/libcore/sqlite/OldJDBCDriverTest.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.JDBCDriver; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverManager; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; - - -public final class OldJDBCDriverTest extends OldJDBCDriverFunctionalTest { - - /** - * The SQLite db file. - */ - private JDBCDriver jDriver; - - private Driver returnedDriver; - - @Override public void setUp() throws java.lang.Exception { - super.setUp(); - returnedDriver = DriverManager.getDriver(getConnectionURL()); - if (returnedDriver instanceof JDBCDriver) { - this.jDriver = (JDBCDriver) returnedDriver; - } - } - - public void testJDBCDriver() { - assertTrue(returnedDriver instanceof JDBCDriver); - } - - public void testAcceptsURL() { - try { - if (this.jDriver != null) { - assertTrue(jDriver.acceptsURL(getConnectionURL())); - } else { - fail("no Driver available"); - } - } catch (SQLException e) { - fail("Driver does not accept URL"); - e.printStackTrace(); - } - } - - public void testConnect() { - try { - if (this.jDriver != null) { - Connection c = jDriver.connect(getConnectionURL(), null); - assertFalse(c.isClosed()); - DriverManager.getConnection(getConnectionURL()); - } else { - fail("no Driver available"); - } - } catch (SQLException e) { - fail("Driver does not connect"); - e.printStackTrace(); - } - } - - public void testGetMajorVersion() { - if (this.jDriver != null) { - assertTrue(jDriver.getMajorVersion() > 0); - } else { - fail("no Driver available"); - } - } - - public void testGetMinorVersion() { - if (this.jDriver != null) { - assertTrue(jDriver.getMinorVersion() > 0); - } else { - fail("no version information available"); - } - } - - public void testGetPropertyInfo() throws SQLException { - DriverPropertyInfo[] info = null; - if (this.jDriver != null) { - info = jDriver.getPropertyInfo(getConnectionURL(), null); - assertNotNull(info); - assertTrue(info.length > 0); - } else { - fail("no Driver available"); - } - - assertNotNull(info); - - } - - public void testJdbcCompliant() { - if (this.jDriver != null) { - assertFalse(jDriver.jdbcCompliant()); - } else { - fail("no version information available"); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java b/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java deleted file mode 100644 index e6b7f22..0000000 --- a/luni/src/test/java/libcore/sqlite/OldSQLiteTest.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.DriverManager; -import java.util.logging.Logger; -import junit.framework.TestCase; - -public abstract class OldSQLiteTest extends TestCase { - - public static Connection conn; - - public static File dbFile = null; - - @Override public void setUp() throws Exception { - String tmp = System.getProperty("java.io.tmpdir"); - File tmpDir = new File(tmp); - try { - if (tmpDir.isDirectory()) { - dbFile = File.createTempFile("sqliteTest", ".db", tmpDir); - dbFile.deleteOnExit(); - } else { - System.out.println("ctsdir does not exist"); - } - - Class.forName("SQLite.JDBCDriver").newInstance(); - - if (!dbFile.exists()) { - Logger.global.severe("DB file could not be created. Tests can not be executed."); - } else { - conn = DriverManager.getConnection("jdbc:sqlite:/" + dbFile.getPath()); - } - assertNotNull("Error creating connection", conn); - } catch (IOException e) { - System.out.println("Problem creating test file in " + tmp); - } - } - - @Override public void tearDown() throws java.lang.Exception { - if (!conn.isClosed()) { - conn.close(); - } - super.tearDown(); - } -} diff --git a/luni/src/test/java/libcore/sqlite/OldStmtTest.java b/luni/src/test/java/libcore/sqlite/OldStmtTest.java deleted file mode 100644 index 4d379ed..0000000 --- a/luni/src/test/java/libcore/sqlite/OldStmtTest.java +++ /dev/null @@ -1,823 +0,0 @@ -/* - * Copyright (C) 2008 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 libcore.sqlite; - -import SQLite.Constants; -import SQLite.Database; -import SQLite.Stmt; -import SQLite.TableResult; -import java.sql.Connection; -import tests.support.DatabaseCreator; -import tests.support.Support_SQL; - -public class OldStmtTest extends OldSQLiteTest { - - private Database db; - private Stmt st; - - private static final String CREATE_ALL_TYPES = "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," - + " MaxLongVal BIGINT," - + " MinLongVal BIGINT," - + " validURL URL," - + " invalidURL URL);"; - - static final String INSERT_ALL_TYPES = "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, MaxLongVal, MinLongVal, validURL, invalidURL) " - + "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', 'Test text message medium'," - + "'Test text message long', " + Long.MAX_VALUE + ", " + Long.MIN_VALUE + "," - + "null, null);"; - - static final String ALL_TYPES_TABLE = "type"; - - @Override public void setUp() throws Exception { - super.setUp(); - Support_SQL.loadDriver(); - db = new Database(); - db.open(dbFile.getPath(), 0); - db.exec(DatabaseCreator.CREATE_TABLE_SIMPLE1, null); - DatabaseCreator.fillSimpleTable1(conn); - - st = new Stmt(); - } - - @Override public void tearDown() throws Exception { - if (st != null) { - try { - st.close(); - } catch (Exception e) { - } - } - db.close(); - Connection con = Support_SQL.getConnection(); - con.close(); - super.tearDown(); - } - - public void testStmt() throws Exception { - db.prepare(""); - - try { - st.step(); - fail("Cannot execute non prepared Stmt"); - } catch (SQLite.Exception expected) { - } - } - - public void testPrepare() throws Exception { - try { - st = db.prepare(""); - st.prepare(); - fail("statement is closed"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = new Stmt(); - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertFalse(st.prepare()); - st = new Stmt(); - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertFalse(st.prepare()); - st = new Stmt(); - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.bind(1, 1); - st.bind(2, 10); - st.bind(3, 30); - assertFalse(st.prepare()); - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1 - + "; " + "delete from " + DatabaseCreator.SIMPLE_TABLE1 - + " where id = 5; " + "insert into " - + DatabaseCreator.SIMPLE_TABLE1 + " values(5, 10, 20); " - + "select * from " + DatabaseCreator.SIMPLE_TABLE1 + ";"); - assertTrue(st.prepare()); - assertTrue(st.prepare()); - assertTrue(st.prepare()); - assertFalse(st.prepare()); - } - - public void testStep() throws Exception { - try { - st.step(); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = new Stmt(); - st = db.prepare("select name from sqlite_master where type = 'table'"); - st.step(); - } - - public void testClose() throws Exception { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.close(); - - try { - st.step(); - fail("Test fails"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - } - - public void testReset() throws Exception { - db.exec("create table TEST (res integer not null)", null); - - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, 1); - st.step(); - - // verify that parameter is still bound - st.reset(); - assertEquals(1,st.bind_parameter_count()); - st.step(); - - TableResult count = db.get_table("select count(*) from TEST where res=1", null); - - String[] row0 = (String[]) count.rows.elementAt(0); - assertEquals(2, Integer.parseInt(row0[0])); - } - - public void testClear_bindings() { - try { - st.clear_bindings(); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testBindIntInt() throws Exception { - int input = 0; - int maxVal = Integer.MAX_VALUE; - int minVal = Integer.MIN_VALUE; - - db.exec("create table TEST (res integer)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1,maxVal); - st.step(); - - st.reset(); - st.bind(1,minVal); - st.step(); - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertEquals(input,Integer.parseInt(row0[0])); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertEquals(maxVal,Integer.parseInt(row1[0])); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertEquals(minVal,Integer.parseInt(row2[0])); - - try { - st.close(); - st.bind(1,Integer.MIN_VALUE); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntLong() throws Exception { - long input = 0; - long maxVal = Long.MAX_VALUE; - long minVal = Long.MIN_VALUE; - - db.exec("create table TEST (res long)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1,maxVal); - st.step(); - - st.reset(); - st.bind(1,minVal); - st.step(); - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertEquals(input,Long.parseLong(row0[0])); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertEquals(maxVal,Long.parseLong(row1[0])); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertEquals(minVal,Long.parseLong(row2[0])); - - try { - st.close(); - st.bind(1,Long.MIN_VALUE); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntDouble() throws Exception { - double input = 0.0; - double maxVal = Double.MAX_VALUE; - double minVal = Double.MIN_VALUE; - double negInf = Double.NEGATIVE_INFINITY; - double posInf = Double.POSITIVE_INFINITY; - double nan = Double.NaN; - - db.exec("create table TEST (res double)", null); - st = db.prepare("insert into TEST values (:one);"); - st.bind(1, input); - st.step(); - - st.reset(); - st.bind(1, maxVal); - st.step(); - - st.reset(); - st.bind(1, minVal); - st.step(); - - st.reset(); - st.bind(1, negInf); - st.step(); - - st.reset(); - st.bind(1, posInf); - st.step(); - - st.reset(); - st.bind(1, nan); - st.step(); - - - TableResult r = db.get_table("select * from TEST"); - - String[] row0 = (String[]) r.rows.elementAt(0); - assertTrue(Double.compare(input, Double.parseDouble(row0[0])) == 0); - - String[] row1 = (String[]) r.rows.elementAt(1); - assertFalse(Double.compare(maxVal, Double.parseDouble(row1[0])) == 0); - assertTrue(Double.compare(maxVal, Double.parseDouble(row1[0])) < 0); - assertTrue(Double.isInfinite(Double.parseDouble(row1[0]))); - - String[] row2 = (String[]) r.rows.elementAt(2); - assertTrue(Double.compare(minVal, Double.parseDouble(row2[0])) == 0); - - String[] row3 = (String[]) r.rows.elementAt(3); - assertEquals("Double.NEGATIVE_INFINITY SQLite representation", - "-Inf", row3[0]); - - String[] row4 = (String[]) r.rows.elementAt(4); - assertEquals("Double.POSITIVE_INFINITY SQLite representation", - "Inf", row4[0]); - - String[] row5 = (String[]) r.rows.elementAt(4); - assertEquals("Double.Nan SQLite representation", "Inf", row5[0]); - - try { - st.close(); - st.bind(1,0.0); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntByteArray() throws Exception { - String name = "Hello World"; - byte[] b = name.getBytes(); - String stringInHex = ""; - - db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null); - st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE - + " values (:one, :two);"); - st.bind(1, 2); - st.bind(2, b); - st.step(); - - //compare what was stored with input based on Hex representation - // since type of column is CHAR - TableResult r = db.get_table("select * from " - + DatabaseCreator.PARENT_TABLE); - String[] row = (String[]) r.rows.elementAt(0); - - for (byte aByte : b) { - stringInHex += Integer.toHexString(aByte); - } - stringInHex = "X'" + stringInHex + "'"; - assertTrue(stringInHex.equalsIgnoreCase(row[1])); - - try { - st.close(); - st.bind(1,name.getBytes()); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindIntString() throws Exception { - String name = "Hello World"; - db.exec(DatabaseCreator.CREATE_TABLE_PARENT, null); - st = db.prepare("insert into " + DatabaseCreator.PARENT_TABLE - + " values (:one, :two);"); - st.bind(1, 2); - st.bind(2, name); - st.step(); - - TableResult r = db.get_table("select * from " - + DatabaseCreator.PARENT_TABLE); - String[] row = (String[]) r.rows.elementAt(0); - assertEquals(name,row[1]); - - try { - st.close(); - st.bind(1,name); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - } - - public void testBindInt() throws Exception { - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.bind(4); - st.bind(1, 4); - st.bind(2, 10); - st.bind(3, 30); - st.step(); - fail(); - } catch (SQLite.Exception expected) { - // What happens if null is bound to non existing variable position - assertEquals("parameter position out of bounds", expected.getMessage()); - } - - // functional tests - - try { - st.reset(); - st.bind(1); - st.bind(2, 10); - st.bind(3, 30); - st.step(); - fail(); - } catch (SQLite.Exception expected) { - // What happens if null is bound to NON NULL field - assertEquals("SQL logic error or missing database", expected.getMessage()); - } - - st.reset(); - st.bind(1, 3); - st.bind(2); - st.bind(3, 30); - st.step(); - } - - public void testBind_zeroblob() { - try { - st.bind_zeroblob(1, 128); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testBind_parameter_count() throws Exception { - try { - st.bind_parameter_count(); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st.bind_parameter_count()); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (?, ?, ?)"); - assertEquals(3, st.bind_parameter_count()); - - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - assertEquals(0, st.bind_parameter_count()); - - try { - st.close(); - st.bind_parameter_count(); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - } - - } - - public void testBind_parameter_name() { - try { - st.bind_parameter_name(1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(":one", st.bind_parameter_name(1)); - assertEquals(":two", st.bind_parameter_name(2)); - assertEquals(":three", st.bind_parameter_name(3)); - st.bind_parameter_name(4); - fail(); - } catch (SQLite.Exception expected) { - assertEquals("parameter position out of bounds", expected.getMessage()); - } - } - - public void testBind_parameter_index() throws Exception { - try { - st.bind_parameter_index(""); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("stmt already closed", expected.getMessage()); - } - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(3, st.bind_parameter_index(":three")); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - assertEquals(0, st.bind_parameter_index(":t")); - - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (?, ?, ?)"); - assertEquals(0, st.bind_parameter_index("?")); - } - - public void testColumn_int() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - Object columnObject; - int intColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - - st = db.prepare(selectStmt); - st.step(); - // select 'speed' value - columnObject = st.column(1); - intColumn = st.column_int(1); - assertNotNull(intColumn); - - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( intColumn, stSpeed); - assertEquals(10,stSpeed); - - selectStmt = "select TextVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - st.column_int(0); - } - - public void testColumn_long() throws Exception { - Object columnObject; - long longColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - st.step(); - columnObject = st.column(1); - longColumn = st.column_long(1); - assertNotNull(longColumn); - // column declared as integer - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( longColumn, stSpeed); - - try { - st.column_long(4); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - - try { - st.column_long(-1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - } - - public void testColumn_double() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - double doubleColumn; - double actualVal = 23.2; - String selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select double value - doubleColumn = st.column_double(0); - assertNotNull(doubleColumn); - - assertTrue("DOUBLE".equalsIgnoreCase(st.column_decltype(0))); - assertNotNull(doubleColumn); - assertEquals( actualVal, doubleColumn); - - // Exception test - selectStmt = "select dateVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select double value - st.column_double(0); - } - - public void testColumn_bytes() throws Exception { - db.exec("create table B(id integer primary key, val blob)",null); - db.exec("insert into B values(1, zeroblob(128))", null); - st = db.prepare("select val from B where id = 1"); - assertTrue(st.step()); - st.column_bytes(0); - } - - public void testColumn_string() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - - String stringColumn; - String actualVal = "test string"; - String selectStmt = "select charStr from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - // select string value - stringColumn = st.column_string(0); - assertNotNull(stringColumn); - - assertTrue("CHAR(20)".equalsIgnoreCase(st.column_decltype(0))); - assertNotNull(stringColumn); - assertEquals( actualVal, stringColumn); - - // Exception test - selectStmt = "select DoubleVal from "+ ALL_TYPES_TABLE; - - st = db.prepare(selectStmt); - st.step(); - st.column_string(0); - } - - public void testColumn_type() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - st = db.prepare("select * from " + ALL_TYPES_TABLE); - st.step(); - - // Exception test - try { - st.column_type(100); - fail(); - } catch (SQLite.Exception expected) { - } - - /* - Dictionary - - public static final int SQLITE_INTEGER = 1; - public static final int SQLITE_FLOAT = 2; - public static final int SQLITE_BLOB = 4; - public static final int SQLITE_NULL = 5; - public static final int SQLITE3_TEXT = 3; - public static final int SQLITE_NUMERIC = -1; - */ - - assertEquals(Constants.SQLITE3_TEXT, st.column_type(23)); // ok TEXT - assertEquals(Constants.SQLITE3_TEXT, st.column_type(13)); // CHAR(20) - - assertEquals(Constants.SQLITE_FLOAT, st.column_type(8)); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(9)); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(10)); // FLOAT - - for (int i = 0; i < 8; i++) { - assertEquals("Expected Integer at position " + i, - Constants.SQLITE_INTEGER, st.column_type(i)); - } - - assertEquals(Constants.SQLITE_NULL, st.column_type(28)); - assertEquals(Constants.SQLITE_NULL, st.column_type(29)); - - // Failing tests - assertTrue("INTEGER".equalsIgnoreCase(st.column_decltype(12))); - assertEquals(Constants.SQLITE_INTEGER, st.column_type(12)); - - assertTrue("FLOAT".equalsIgnoreCase(st.column_decltype(11))); - assertEquals(Constants.SQLITE_FLOAT, st.column_type(11)); // FLOAT -> - // got INTEGER - assertTrue("BLOB".equalsIgnoreCase(st.column_decltype(19))); - assertEquals(Constants.SQLITE_BLOB, st.column_type(19)); // Blob got - // INTEGER - - } - - /** - * Wrong value is returned in case of a prepared statement to which a '*' bound - */ - public void testColumn_count() throws Exception { - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - - assertEquals(3, st.column_count()); - - st.step(); - int columnCount = st.column_count(); - assertNotNull(columnCount); - assertEquals( 3, columnCount); - - // actual prepared statement - selectStmt = "select ? from "+DatabaseCreator.SIMPLE_TABLE1; - st = db.prepare(selectStmt); - - assertEquals(3, st.column_count()); - - st.bind(1, "*"); - st.step(); - columnCount = st.column_count(); - assertNotNull(columnCount); - assertEquals( 3, columnCount); - } - - public void testColumn() throws Exception { - Object columnObject; - int intColumn; - String selectStmt = "select * from "+DatabaseCreator.SIMPLE_TABLE1; - db.get_table(selectStmt); - st = db.prepare(selectStmt); - st.step(); - columnObject = st.column(1); - intColumn = st.column_int(1); - assertNotNull(intColumn); - assertTrue("Integer".equalsIgnoreCase(st.column_decltype(1))); - int stSpeed = Integer.parseInt(columnObject.toString()); - assertNotNull(stSpeed); - assertEquals( intColumn, stSpeed); - - try { - assertNotNull(columnObject); - ((Integer) columnObject).intValue(); - fail("Cast to Integer should fail"); - } catch (ClassCastException expected) { - } - - try { - st.column(4); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - - try { - st.column(-1); - fail("Exception expected"); - } catch (SQLite.Exception expected) { - assertEquals("column out of bounds", expected.getMessage()); - } - } - - public void testColumn_table_name() { - try { - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - st.column_table_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testColumn_database_name() { - try { - st = db.prepare("insert into " + DatabaseCreator.SIMPLE_TABLE1 - + " values (:one,:two,:three)"); - st.column_database_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } - - public void testColumn_decltype() throws Exception { - db.exec(CREATE_ALL_TYPES, null); - db.exec(INSERT_ALL_TYPES, null); - st = db.prepare("select * from " + ALL_TYPES_TABLE); - st.step(); - - // Exception test - try { - st.column_decltype(100); - fail(); - } catch (SQLite.Exception expected) { - } - - assertTrue(st.column_decltype(0), "BOOLEAN".equalsIgnoreCase(st - .column_decltype(0))); - assertTrue(st.column_decltype(1), "INT".equalsIgnoreCase(st - .column_decltype(1))); - assertTrue(st.column_decltype(2), "LONG".equalsIgnoreCase(st - .column_decltype(2))); - assertTrue(st.column_decltype(3), "BIGINT".equalsIgnoreCase(st - .column_decltype(3))); - assertTrue(st.column_decltype(4), "TINYINT".equalsIgnoreCase(st - .column_decltype(4))); - assertTrue(st.column_decltype(5), "SMALLINT".equalsIgnoreCase(st - .column_decltype(5))); - assertTrue(st.column_decltype(6), "MEDIUMINT".equalsIgnoreCase(st - .column_decltype(6))); - assertTrue(st.column_decltype(7), "INTEGER".equalsIgnoreCase(st - .column_decltype(7))); - assertTrue(st.column_decltype(8), "REAL".equalsIgnoreCase(st - .column_decltype(8))); - assertTrue(st.column_decltype(9), "DOUBLE".equalsIgnoreCase(st - .column_decltype(9))); - assertTrue(st.column_decltype(10), "FLOAT".equalsIgnoreCase(st - .column_decltype(10))); - assertTrue(st.column_decltype(11), "DECIMAL".equalsIgnoreCase(st - .column_decltype(11))); - assertTrue(st.column_decltype(12), "NUMERIC".equalsIgnoreCase(st - .column_decltype(12))); - assertTrue(st.column_decltype(13), "CHAR(20)".equalsIgnoreCase(st - .column_decltype(13))); - - assertTrue(st.column_decltype(19), "BLOB".equalsIgnoreCase(st - .column_decltype(19))); - - assertTrue(st.column_decltype(23), "TEXT".equalsIgnoreCase(st - .column_decltype(23))); - assertTrue(st.column_decltype(28), "URL".equalsIgnoreCase(st - .column_decltype(28))); - assertTrue(st.column_decltype(29), "URL".equalsIgnoreCase(st - .column_decltype(29))); - } - - public void testColumn_origin_name() { - try { - st = db.prepare("select * from " + DatabaseCreator.SIMPLE_TABLE1); - st.column_origin_name(1); - fail("Function is now supported."); - } catch (SQLite.Exception expected) { - assertEquals("unsupported", expected.getMessage()); - } - } -} diff --git a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java b/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java deleted file mode 100644 index 8febfff..0000000 --- a/luni/src/test/java/libcore/sqlite/QueryTimeoutTest.java +++ /dev/null @@ -1,165 +0,0 @@ -/* - * 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 libcore.sqlite; - -import SQLite.Database; -import SQLite.Function; -import SQLite.FunctionContext; -import SQLite.JDBC2z.JDBCConnection; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import junit.framework.TestCase; -import tests.support.Support_SQL; - - -/** - * Test that statements honor their timeout. - */ -public final class QueryTimeoutTest extends TestCase { - - private static final String EXEC_QUERY - = "insert into t_copy select a from t_orig where DELAY(2,1)=1"; - - private static final String FETCH_QUERY = "select a from t_orig where DELAY(2,1)=1"; - - private Connection connection; - - @Override public void setUp() throws Exception { - Support_SQL.loadDriver(); - connection = Support_SQL.getConnection(); - - exec("drop table if exists t_orig;"); - exec("drop table if exists t_copy;"); - exec("create table t_orig (a int)"); - exec("create table t_copy (a int)"); - - for (int i = 0; i < 7; i++) { - exec("insert into t_orig values (" + i + ");"); - } - - Database database = ((JDBCConnection) connection).getSQLiteDatabase(); - database.create_function("DELAY", 2, new Function() { - @Override public void function(FunctionContext functionContext, String[] args) { - try { - int seconds = Integer.parseInt(args[0]); - Thread.sleep(seconds * 1000); - } catch (InterruptedException ignored) { - } - functionContext.set_result(Integer.parseInt(args[1])); - } - @Override public void last_step(FunctionContext functionContext) { - } - @Override public void step(FunctionContext functionContext, String[] args) { - } - }); - - connection.setAutoCommit(true); - } - - @Override public void tearDown() throws Exception { - connection.close(); - } - - private void exec(String queryString) throws Exception { - System.out.println("Executing " + queryString); - Statement statement = null; - try { - statement = connection.createStatement(); - statement.execute(queryString); - } finally { - if (statement != null) { - statement.close(); - } - } - } - - public void testPreparedStatementFetch() throws Exception { - PreparedStatement statement = connection.prepareStatement(FETCH_QUERY); - statement.setQueryTimeout(1); - ResultSet resultSet = null; - try { - resultSet = statement.executeQuery(); - while (resultSet.next()) { - } - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - if (resultSet != null) { - resultSet.close(); - } - } - } - - public void testPreparedStatementUpdate() throws Exception { - PreparedStatement statement = connection.prepareStatement(EXEC_QUERY); - try { - statement.setQueryTimeout(1); - statement.execute(); - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - } - } - - public void testInvalidTimeout() throws Exception { - connection.setAutoCommit(true); - PreparedStatement statement = connection.prepareStatement("select 'hello'"); - - try { - statement.setQueryTimeout(-1); - fail(); - } catch (SQLException expected) { - } - - ResultSet resultSet = statement.executeQuery(); - resultSet.close(); - statement.close(); - } - - public void testExecuteUpdate() throws Exception { - Statement statement = connection.createStatement(); - try { - statement.setQueryTimeout(1); - statement.executeUpdate(EXEC_QUERY); - fail(); - } catch (SQLException expected) { - } finally { - statement.close(); - } - } - - public void testTimeoutAndStatementReuse() throws Exception { - Statement statement = connection.createStatement(); - statement.setQueryTimeout(1); - for (int i = 0; i < 3; i++) { - try { - ResultSet resultSet = statement.executeQuery(FETCH_QUERY); - while (resultSet.next()) { - } - fail(); - } catch (SQLException expected) { - } - } - statement.close(); - } -} |