From 1f8c8ac8439e4586b7b570dd48ff341ccab70db7 Mon Sep 17 00:00:00 2001 From: leo Date: Mon, 19 Jan 2009 03:09:41 +0000 Subject: [PATCH] removed unnecessary sources and modified Makefiles git-svn-id: http://www.xerial.org/svn/project/XerialJ/trunk/sqlite-jdbc@2855 ae02f08e-27ec-0310-ae8c-8ba02fe2eafd --- Makefile | 4 +- sqlitejdbc/Makefile | 14 +- sqlitejdbc/Makefile.common | 10 +- sqlitejdbc/Makefile.nested | 10 +- sqlitejdbc/src/org/sqlite/Codes.java | 106 ----- sqlitejdbc/src/org/sqlite/Conn.java | 239 ---------- sqlitejdbc/src/org/sqlite/DB.java | 343 -------------- sqlitejdbc/src/org/sqlite/Function.java | 182 -------- sqlitejdbc/src/org/sqlite/JDBC.java | 56 --- sqlitejdbc/src/org/sqlite/MetaData.java | 717 ---------------------------- sqlitejdbc/src/org/sqlite/NativeDB.c | 780 ------------------------------- sqlitejdbc/src/org/sqlite/NativeDB.java | 123 ----- sqlitejdbc/src/org/sqlite/NestedDB.c | 78 ---- sqlitejdbc/src/org/sqlite/NestedDB.java | 442 ------------------ sqlitejdbc/src/org/sqlite/PrepStmt.java | 213 --------- sqlitejdbc/src/org/sqlite/RS.java | 347 -------------- sqlitejdbc/src/org/sqlite/Stmt.java | 242 ---------- sqlitejdbc/src/org/sqlite/Unused.java | 250 ---------- sqlitejdbc/src/test/ConnectionTest.java | 45 -- sqlitejdbc/src/test/DBMetaDataTest.java | 413 ---------------- sqlitejdbc/src/test/PrepStmtTest.java | 487 ------------------- sqlitejdbc/src/test/RSMetaDataTest.java | 76 --- sqlitejdbc/src/test/StatementTest.java | 306 ------------ sqlitejdbc/src/test/TransactionTest.java | 226 --------- sqlitejdbc/src/test/UDFTest.java | 313 ------------- 25 files changed, 20 insertions(+), 6002 deletions(-) delete mode 100644 sqlitejdbc/src/org/sqlite/Codes.java delete mode 100644 sqlitejdbc/src/org/sqlite/Conn.java delete mode 100644 sqlitejdbc/src/org/sqlite/DB.java delete mode 100644 sqlitejdbc/src/org/sqlite/Function.java delete mode 100644 sqlitejdbc/src/org/sqlite/JDBC.java delete mode 100644 sqlitejdbc/src/org/sqlite/MetaData.java delete mode 100644 sqlitejdbc/src/org/sqlite/NativeDB.c delete mode 100644 sqlitejdbc/src/org/sqlite/NativeDB.java delete mode 100644 sqlitejdbc/src/org/sqlite/NestedDB.c delete mode 100644 sqlitejdbc/src/org/sqlite/NestedDB.java delete mode 100644 sqlitejdbc/src/org/sqlite/PrepStmt.java delete mode 100644 sqlitejdbc/src/org/sqlite/RS.java delete mode 100644 sqlitejdbc/src/org/sqlite/Stmt.java delete mode 100644 sqlitejdbc/src/org/sqlite/Unused.java delete mode 100644 sqlitejdbc/src/test/ConnectionTest.java delete mode 100644 sqlitejdbc/src/test/DBMetaDataTest.java delete mode 100644 sqlitejdbc/src/test/PrepStmtTest.java delete mode 100644 sqlitejdbc/src/test/RSMetaDataTest.java delete mode 100644 sqlitejdbc/src/test/StatementTest.java delete mode 100644 sqlitejdbc/src/test/TransactionTest.java delete mode 100644 sqlitejdbc/src/test/UDFTest.java diff --git a/Makefile b/Makefile index 177a2f2..21c23c9 100644 --- a/Makefile +++ b/Makefile @@ -41,7 +41,7 @@ deploy: mvn deploy -OSInfoClass=org/xerial/db/sql/sqlite/OSInfo +OSInfoClass=org/sqlite/OSInfo OSINFO_PROG=target/sqlitejdbc/$(OSInfoClass).class SQLITE_DLL=sqlitejdbc/build/$(target)/$(LIBNAME) SQLITE_BUILD_DIR=sqlitejdbc/build/$(sqlite)-$(target) @@ -57,7 +57,7 @@ $(OSINFO_PROG): src/main/java/$(OSInfoClass).java $(SQLITE_DLL): $(SQLITE_BUILD_DIR) $(SQLITE_BUILD_DIR): Makefile sqlitejdbc/Makefile - cd sqlitejdbc && make native + cd sqlitejdbc && make native #$(NATIVE_DLL): $(OSINFO_PROG) $(SQLITE_DLL) # mkdir -p $(WORK_DIR)/$(LIB_FOLDER) diff --git a/sqlitejdbc/Makefile b/sqlitejdbc/Makefile index fa7f0e9..920a9a1 100644 --- a/sqlitejdbc/Makefile +++ b/sqlitejdbc/Makefile @@ -17,6 +17,8 @@ include Makefile.common +SRC_FOLDER=../src/main/java/org/sqlite/ + default: test test: native $(test_classes) @@ -33,7 +35,7 @@ build/$(target)/$(LIBNAME): build/$(sqlite)-$(target)/sqlite3.o build/org/sqlite @mkdir -p build/$(target) $(JAVAH) -classpath build -jni -o build/NativeDB.h org.sqlite.NativeDB $(CC) $(CFLAGS) -c -o build/$(target)/NativeDB.o \ - src/org/sqlite/NativeDB.c + ../src/main/java/org/sqlite/NativeDB.c $(CC) $(CFLAGS) $(LINKFLAGS) -o build/$(target)/$(LIBNAME) \ build/$(target)/NativeDB.o build/$(sqlite)-$(target)/*.o $(STRIP) build/$(target)/$(LIBNAME) @@ -51,14 +53,14 @@ build/$(sqlite)-%/sqlite3.o: dl/$(sqlite)-amal.zip -DSQLITE_ENABLE_RTREE \ -DSQLITE_OMIT_LOAD_EXTENSION sqlite3.c) -build/org/%.class: src/org/%.java +build/org/sqlite/%.class: ../src/main/java/org/sqlite/%.java @mkdir -p build - $(JAVAC) -source 1.2 -target 1.2 -sourcepath src -d build $< + $(JAVAC) -source 1.2 -target 1.2 -sourcepath ../src/main/java -d build $< -build/test/%.class: src/test/%.java - @mkdir -p build +build/test/org/sqlite/%.class: ../src/test/java/org/sqlite/%.java + @mkdir -p build/test $(JAVAC) -target 1.5 -classpath "build$(sep)$(libjunit)" \ - -sourcepath src/test -d build $< + -sourcepath ../src/test/java -d build/test $< dl/$(sqlite)-amal.zip: @mkdir -p dl diff --git a/sqlitejdbc/Makefile.common b/sqlitejdbc/Makefile.common index 8d8151b..b926361 100644 --- a/sqlitejdbc/Makefile.common +++ b/sqlitejdbc/Makefile.common @@ -46,13 +46,13 @@ JAVA := "$$JAVA_HOME/bin/java" JAVAC := "$$JAVA_HOME/bin/javac" -Xbootclasspath/p:$(libjdbc) JAVAH := "$$JAVA_HOME/bin/javah" -java_sources = $(wildcard src/org/sqlite/*.java) -java_classes = $(java_sources:src/%.java=build/%.class) +java_sources = $(wildcard ../src/main/java/org/sqlite/*.java) +java_classes = $(java_sources:../src/main/java/org/sqlite/%.java=build/org/sqlite/%.class) native_classes = $(filter-out %NestedDB.class,$(java_classes)) java_classlist = $(subst $$,\$$,$(patsubst build/%, %, $(wildcard $(java_classes:%.class=%*)))) -test_sources = $(wildcard src/test/*.java) -test_classes = $(test_sources:src/%.java=build/%.class) -tests = $(subst /,.,$(patsubst build/%.class,%,$(test_classes))) +test_sources = $(wildcard ../src/test/java/org/sqlite/*.java) +test_classes = $(test_sources:../src/test/java/org/sqlite/%.java=build/test/org/sqlite/%.class) +tests = $(subst /,.,$(patsubst build/test/org/sqlite/%.class,org/sqlite/%,$(test_classes))) target := $(os)-$(arch) diff --git a/sqlitejdbc/Makefile.nested b/sqlitejdbc/Makefile.nested index d69a509..e7e2244 100644 --- a/sqlitejdbc/Makefile.nested +++ b/sqlitejdbc/Makefile.nested @@ -15,15 +15,15 @@ dist/$(sqlitejdbc)-pure.jar: build/org/sqlite/SQLite.class $(java_classes) org/sqlite/SQLite.class $(java_classlist) \ -C ../$(nestedvm)/build org/ibex -build/org/%.class: ../src/main/java/org/sqlite/%.java +build/org/sqlite/%.class: ../src/main/java/org/sqlite/%.java @mkdir -p build $(JAVAC) -source 1.2 -target 1.2 -classpath "$(nestedvm)/build" \ - -sourcepath src -d build $< + -sourcepath ../src/main/java -d build $< -build/test/%.class: src/test/%.java +build/test/org/sqlite/%.class: ../src/test/java/org/sqlite/%.java @mkdir -p build $(JAVAC) -target 1.5 -classpath "build$(sep)$(libjunit)" \ - -sourcepath src/test -d build $< + -sourcepath ../src/test/java -d build/test $< $(nestedvm)/%: $(MAKE) -C $(nestedvm) $* @@ -46,7 +46,7 @@ build/SQLite.mips: $(nestedvm)/Makefile $(nestedvm)/env.sh dl/$(sqlite)-amal.zip @mkdir -p build @mkdir -p build/$(sqlite)-nestedvm unzip -qo dl/$(sqlite)-amal.zip -d build/$(sqlite)-nestedvm - cp src/org/sqlite/Nested*.c build/$(sqlite)-nestedvm + cp ../src/main/java/org/sqlite/Nested*.c build/$(sqlite)-nestedvm perl -pi -e "s/sqlite3_api;/sqlite3_api = 0;/g" \ build/$(sqlite)-nestedvm/sqlite3ext.h diff --git a/sqlitejdbc/src/org/sqlite/Codes.java b/sqlitejdbc/src/org/sqlite/Codes.java deleted file mode 100644 index ab78411..0000000 --- a/sqlitejdbc/src/org/sqlite/Codes.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -interface Codes -{ - /** Successful result */ - public static final int SQLITE_OK = 0; - - /** SQL error or missing database */ - public static final int SQLITE_ERROR = 1; - - /** An internal logic error in SQLite */ - public static final int SQLITE_INTERNAL = 2; - - /** Access permission denied */ - public static final int SQLITE_PERM = 3; - - /** Callback routine requested an abort */ - public static final int SQLITE_ABORT = 4; - - /** The database file is locked */ - public static final int SQLITE_BUSY = 5; - - /** A table in the database is locked */ - public static final int SQLITE_LOCKED = 6; - - /** A malloc() failed */ - public static final int SQLITE_NOMEM = 7; - - /** Attempt to write a readonly database */ - public static final int SQLITE_READONLY = 8; - - /** Operation terminated by sqlite_interrupt() */ - public static final int SQLITE_INTERRUPT = 9; - - /** Some kind of disk I/O error occurred */ - public static final int SQLITE_IOERR = 10; - - /** The database disk image is malformed */ - public static final int SQLITE_CORRUPT = 11; - - /** (Internal Only) Table or record not found */ - public static final int SQLITE_NOTFOUND = 12; - - /** Insertion failed because database is full */ - public static final int SQLITE_FULL = 13; - - /** Unable to open the database file */ - public static final int SQLITE_CANTOPEN = 14; - - /** Database lock protocol error */ - public static final int SQLITE_PROTOCOL = 15; - - /** (Internal Only) Database table is empty */ - public static final int SQLITE_EMPTY = 16; - - /** The database schema changed */ - public static final int SQLITE_SCHEMA = 17; - - /** Too much data for one row of a table */ - public static final int SQLITE_TOOBIG = 18; - - /** Abort due to constraint violation */ - public static final int SQLITE_CONSTRAINT = 19; - - /** Data type mismatch */ - public static final int SQLITE_MISMATCH = 20; - - /** Library used incorrectly */ - public static final int SQLITE_MISUSE = 21; - - /** Uses OS features not supported on host */ - public static final int SQLITE_NOLFS = 22; - - /** Authorization denied */ - public static final int SQLITE_AUTH = 23; - - /** sqlite_step() has another row ready */ - public static final int SQLITE_ROW = 100; - - /** sqlite_step() has finished executing */ - public static final int SQLITE_DONE = 101; - - - // types returned by sqlite3_column_type() - - public static final int SQLITE_INTEGER = 1; - public static final int SQLITE_FLOAT = 2; - public static final int SQLITE_TEXT = 3; - public static final int SQLITE_BLOB = 4; - public static final int SQLITE_NULL = 5; -} diff --git a/sqlitejdbc/src/org/sqlite/Conn.java b/sqlitejdbc/src/org/sqlite/Conn.java deleted file mode 100644 index b0e8ec9..0000000 --- a/sqlitejdbc/src/org/sqlite/Conn.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import java.sql.*; -import java.util.*; -import java.io.File; -import java.lang.ref.WeakReference; - -class Conn implements Connection -{ - private final String url; - private DB db = null; - private MetaData meta = null; - private boolean autoCommit = true; - private int timeout = 0; - - public Conn(String url, String filename) throws SQLException { - // check the path to the file exists - if (!":memory:".equals(filename)) { - File file = new File(filename).getAbsoluteFile(); - File parent = file.getParentFile(); - if (parent != null && !parent.exists()) { - for (File up = parent; up != null && !up.exists();) { - parent = up; - up = up.getParentFile(); - } - throw new SQLException("path to '" + filename + "': '" - + parent + "' does not exist"); - } - - // check write access if file does not exist - try { - /* - * The extra check to exists() is necessary as createNewFile() does - * not follow the JavaDoc when used on read-only shares. Pointed out - * by armesschwein@googlemail.com. - */ - if (!file.exists() && file.createNewFile()) file.delete(); - } catch (Exception e) { - throw new SQLException( - "opening db: '" + filename + "': " +e.getMessage()); - } - filename = file.getAbsolutePath(); - } - - // TODO: library variable to explicitly control load type - // attempt to use the Native library first - try { - Class nativedb = Class.forName("org.sqlite.NativeDB"); - if (((Boolean)nativedb.getDeclaredMethod("load", null) - .invoke(null, null)).booleanValue()) - db = (DB)nativedb.newInstance(); - } catch (Exception e) { } // fall through to nested library - - // load nested library - if (db == null) { - try { - db = (DB)Class.forName("org.sqlite.NestedDB").newInstance(); - } catch (Exception e) { - throw new SQLException("no SQLite library found"); - } - } - - this.url = url; - db.open(this, filename); - setTimeout(3000); - } - - int getTimeout() { return timeout; } - void setTimeout(int ms) throws SQLException { - timeout = ms; - db.busy_timeout(ms); - } - String url() { return url; } - String libversion() throws SQLException { return db.libversion(); } - DB db() { return db; } - - private void checkOpen() throws SQLException { - if (db == null) throw new SQLException("database connection closed"); - } - - private void checkCursor(int rst, int rsc, int rsh) throws SQLException { - if (rst != ResultSet.TYPE_FORWARD_ONLY) throw new SQLException( - "SQLite only supports TYPE_FORWARD_ONLY cursors"); - if (rsc != ResultSet.CONCUR_READ_ONLY) throw new SQLException( - "SQLite only supports CONCUR_READ_ONLY cursors"); - if (rsh != ResultSet.CLOSE_CURSORS_AT_COMMIT) throw new SQLException( - "SQLite only supports closing cursors at commit"); - } - - public void finalize() throws SQLException { close(); } - public void close() throws SQLException { - if (db == null) return; - if (meta != null) meta.close(); - - db.close(); - db = null; - } - - public boolean isClosed() throws SQLException { return db == null; } - - public String getCatalog() throws SQLException { checkOpen(); return null; } - public void setCatalog(String catalog) throws SQLException { checkOpen(); } - - public int getHoldability() throws SQLException { - checkOpen(); return ResultSet.CLOSE_CURSORS_AT_COMMIT; } - public void setHoldability(int h) throws SQLException { - checkOpen(); - if (h != ResultSet.CLOSE_CURSORS_AT_COMMIT) throw new SQLException( - "SQLite only supports CLOSE_CURSORS_AT_COMMIT"); - } - - public int getTransactionIsolation() { return TRANSACTION_SERIALIZABLE; } - public void setTransactionIsolation(int level) throws SQLException { - if (level != TRANSACTION_SERIALIZABLE) throw new SQLException( - "SQLite supports only TRANSACTION_SERIALIZABLE"); - } - - public Map getTypeMap() throws SQLException - { throw new SQLException("not yet implemented");} - public void setTypeMap(Map map) throws SQLException - { throw new SQLException("not yet implemented");} - - public boolean isReadOnly() throws SQLException { return false; } // FIXME - public void setReadOnly(boolean ro) throws SQLException {} - - public DatabaseMetaData getMetaData() { - if (meta == null) meta = new MetaData(this); - return meta; - } - - public String nativeSQL(String sql) { return sql; } - - public void clearWarnings() throws SQLException { } - public SQLWarning getWarnings() throws SQLException { return null; } - - public boolean getAutoCommit() throws SQLException { - checkOpen(); return autoCommit; } - public void setAutoCommit(boolean ac) throws SQLException { - checkOpen(); - if (autoCommit == ac) return; - autoCommit = ac; - db.exec(autoCommit ? "commit;" : "begin;"); - } - - public void commit() throws SQLException { - checkOpen(); - if (autoCommit) throw new SQLException("database in auto-commit mode"); - db.exec("commit;"); - db.exec("begin;"); - } - - public void rollback() throws SQLException { - checkOpen(); - if (autoCommit) throw new SQLException("database in auto-commit mode"); - db.exec("rollback;"); - db.exec("begin;"); - } - - public Statement createStatement() throws SQLException { - return createStatement(ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - public Statement createStatement(int rsType, int rsConcurr) - throws SQLException { return createStatement(rsType, rsConcurr, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - public Statement createStatement(int rst, int rsc, int rsh) - throws SQLException { - checkCursor(rst, rsc, rsh); - return new Stmt(this); - } - - public CallableStatement prepareCall(String sql) throws SQLException { - return prepareCall(sql, ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - public CallableStatement prepareCall(String sql, int rst, int rsc) - throws SQLException { - return prepareCall(sql, rst, rsc, ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - public CallableStatement prepareCall(String sql, int rst, int rsc, int rsh) - throws SQLException { - throw new SQLException("SQLite does not support Stored Procedures"); - } - - public PreparedStatement prepareStatement(String sql) throws SQLException { - return prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, - ResultSet.CONCUR_READ_ONLY); - } - public PreparedStatement prepareStatement(String sql, int autoC) - throws SQLException { throw new SQLException("NYI"); } - public PreparedStatement prepareStatement(String sql, int[] colInds) - throws SQLException { throw new SQLException("NYI"); } - public PreparedStatement prepareStatement(String sql, String[] colNames) - throws SQLException { throw new SQLException("NYI"); } - public PreparedStatement prepareStatement(String sql, int rst, int rsc) - throws SQLException { - return prepareStatement(sql, rst, rsc, - ResultSet.CLOSE_CURSORS_AT_COMMIT); - } - - public PreparedStatement prepareStatement( - String sql, int rst, int rsc, int rsh) throws SQLException { - checkCursor(rst, rsc, rsh); - return new PrepStmt(this, sql); - } - - - // UNUSED FUNCTIONS ///////////////////////////////////////////// - - public Savepoint setSavepoint() throws SQLException { - throw new SQLException("unsupported by SQLite: savepoints"); } - public Savepoint setSavepoint(String name) throws SQLException { - throw new SQLException("unsupported by SQLite: savepoints"); } - public void releaseSavepoint(Savepoint savepoint) throws SQLException { - throw new SQLException("unsupported by SQLite: savepoints"); } - public void rollback(Savepoint savepoint) throws SQLException { - throw new SQLException("unsupported by SQLite: savepoints"); } - - public Struct createStruct(String t, Object[] attr) throws SQLException { - throw new SQLException("unsupported by SQLite"); } -} diff --git a/sqlitejdbc/src/org/sqlite/DB.java b/sqlitejdbc/src/org/sqlite/DB.java deleted file mode 100644 index 41d25a6..0000000 --- a/sqlitejdbc/src/org/sqlite/DB.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import java.lang.ref.*; -import java.io.File; -import java.sql.*; -import java.util.*; - -/* - * This class is the interface to SQLite. It provides some helper functions - * used by other parts of the driver. The goal of the helper functions here - * are not only to provide functionality, but to handle contractual - * differences between the JDBC specification and the SQLite C API. - * - * The process of moving SQLite weirdness into this class is incomplete. - * You'll still find lots of code in Stmt and PrepStmt that are doing - * implicit contract conversions. Sorry. - * - * The two subclasses, NativeDB and NestedDB, provide the actual access to - * SQLite functions. - */ -abstract class DB implements Codes -{ - /** The JDBC Connection that 'owns' this database instance. */ - Conn conn = null; - - /** The "begin;"and "commit;" statement handles. */ - long begin = 0; - long commit = 0; - - /** Tracer for statements to avoid unfinalized statements on db close. */ - private Map stmts = new Hashtable(); - - // WRAPPER FUNCTIONS //////////////////////////////////////////// - - abstract void interrupt() throws SQLException; - abstract void busy_timeout(int ms) throws SQLException; - abstract String errmsg() throws SQLException; - abstract String libversion() throws SQLException; - abstract int changes() throws SQLException; - - final synchronized void exec(String sql) throws SQLException { - long pointer = 0; - try { - pointer = prepare(sql); - switch (step(pointer)) { - case SQLITE_DONE: - ensureAutoCommit(); - return; - case SQLITE_ROW: - return; - default: - throwex(); - } - } finally { - finalize(pointer); - } - } - - final synchronized void open(Conn conn, String file) throws SQLException { - this.conn = conn; - _open(file); - } - - final synchronized void close() throws SQLException { - // finalize any remaining statements before closing db - synchronized (stmts) { - Iterator i = stmts.entrySet().iterator(); - while (i.hasNext()) { - Map.Entry entry = (Map.Entry)i.next(); - Stmt stmt = (Stmt)entry.getValue(); - finalize(((Long)entry.getKey()).longValue()); - if (stmt != null) { - stmt.pointer = 0; - } - i.remove(); - } - } - - // remove memory used by user-defined functions - free_functions(); - - // clean up commit object - if (begin != 0) { - finalize(begin); - begin = 0; - } - if (commit != 0) { - finalize(commit); - commit = 0; - } - - _close(); - } - - final synchronized void prepare(Stmt stmt) throws SQLException { - if (stmt.pointer != 0) - finalize(stmt); - stmt.pointer = prepare(stmt.sql); - stmts.put(new Long(stmt.pointer), stmt); - } - - final synchronized int finalize(Stmt stmt) throws SQLException { - if (stmt.pointer == 0) return 0; - int rc = SQLITE_ERROR; - try { - rc = finalize(stmt.pointer); - } finally { - stmts.remove(new Long(stmt.pointer)); - stmt.pointer = 0; - } - return rc; - } - - protected abstract void _open(String filename) throws SQLException; - protected abstract void _close() throws SQLException; - protected abstract long prepare(String sql) throws SQLException; - protected abstract int finalize(long stmt) throws SQLException; - protected abstract int step(long stmt) throws SQLException; - protected abstract int reset(long stmt) throws SQLException; - - abstract int clear_bindings(long stmt) throws SQLException; // TODO remove? - abstract int bind_parameter_count(long stmt) throws SQLException; - - abstract int column_count (long stmt) throws SQLException; - abstract int column_type (long stmt, int col) throws SQLException; - abstract String column_decltype (long stmt, int col) throws SQLException; - abstract String column_table_name (long stmt, int col) throws SQLException; - abstract String column_name (long stmt, int col) throws SQLException; - abstract String column_text (long stmt, int col) throws SQLException; - abstract byte[] column_blob (long stmt, int col) throws SQLException; - abstract double column_double (long stmt, int col) throws SQLException; - abstract long column_long (long stmt, int col) throws SQLException; - abstract int column_int (long stmt, int col) throws SQLException; - - abstract int bind_null (long stmt, int pos) throws SQLException; - abstract int bind_int (long stmt, int pos, int v) throws SQLException; - abstract int bind_long (long stmt, int pos, long v) throws SQLException; - abstract int bind_double(long stmt, int pos, double v) throws SQLException; - abstract int bind_text (long stmt, int pos, String v) throws SQLException; - abstract int bind_blob (long stmt, int pos, byte[] v) throws SQLException; - - abstract void result_null (long context) throws SQLException; - abstract void result_text (long context, String val) throws SQLException; - abstract void result_blob (long context, byte[] val) throws SQLException; - abstract void result_double(long context, double val) throws SQLException; - abstract void result_long (long context, long val) throws SQLException; - abstract void result_int (long context, int val) throws SQLException; - abstract void result_error (long context, String err) throws SQLException; - - abstract int value_bytes (Function f, int arg) throws SQLException; - abstract String value_text (Function f, int arg) throws SQLException; - abstract byte[] value_blob (Function f, int arg) throws SQLException; - abstract double value_double(Function f, int arg) throws SQLException; - abstract long value_long (Function f, int arg) throws SQLException; - abstract int value_int (Function f, int arg) throws SQLException; - abstract int value_type (Function f, int arg) throws SQLException; - - abstract int create_function(String name, Function f) throws SQLException; - abstract int destroy_function(String name) throws SQLException; - abstract void free_functions() throws SQLException; - - /** Provides metadata for the columns of a statement. Returns: - * res[col][0] = true if column constrained NOT NULL - * res[col][1] = true if column is part of the primary key - * res[col][2] = true if column is auto-increment - */ - abstract boolean[][] column_metadata(long stmt) throws SQLException; - - - // COMPOUND FUNCTIONS //////////////////////////////////////////// - - final synchronized String[] column_names(long stmt) throws SQLException { - String[] names = new String[column_count(stmt)]; - for (int i=0; i < names.length; i++) - names[i] = column_name(stmt, i); - return names; - } - - final synchronized int sqlbind(long stmt, int pos, Object v) - throws SQLException { - pos++; - if (v == null) { - return bind_null(stmt, pos); - } else if (v instanceof Integer) { - return bind_int(stmt, pos, ((Integer)v).intValue()); - } else if (v instanceof Long) { - return bind_long(stmt, pos, ((Long)v).longValue()); - } else if (v instanceof Double) { - return bind_double(stmt, pos, ((Double)v).doubleValue()); - } else if (v instanceof String) { - return bind_text(stmt, pos, (String)v); - } else if (v instanceof byte[]) { - return bind_blob(stmt, pos, (byte[])v); - } else { - throw new SQLException("unexpected param type: "+v.getClass()); - } - } - - final synchronized int[] executeBatch(long stmt, int count, Object[] vals) - throws SQLException { - if (count < 1) throw new SQLException("count (" + count + ") < 1"); - - final int params = bind_parameter_count(stmt); - - int rc; - int[] changes = new int[count]; - - try { - for (int i=0; i < count; i++) { - reset(stmt); - for (int j=0; j < params; j++) - if (sqlbind(stmt, j, vals[(i * params) + j]) != SQLITE_OK) - throwex(); - - rc = step(stmt); - if (rc != SQLITE_DONE) { - reset(stmt); - if (rc == SQLITE_ROW) throw new BatchUpdateException( - "batch entry "+i+": query returns results", changes); - throwex(); - } - - changes[i] = changes(); - } - } finally { - ensureAutoCommit(); - } - - reset(stmt); - return changes; - } - - final synchronized boolean execute(Stmt stmt, Object[] vals) - throws SQLException { - if (vals != null) { - final int params = bind_parameter_count(stmt.pointer); - if (params != vals.length) - throw new SQLException("assertion failure: param count (" - + params + ") != value count (" + vals.length + ")"); - - for (int i=0; i < params; i++) - if (sqlbind(stmt.pointer, i, vals[i]) != SQLITE_OK) throwex(); - } - - switch (step(stmt.pointer)) { - case SQLITE_DONE: - reset(stmt.pointer); - ensureAutoCommit(); - return false; - case SQLITE_ROW: - return true; - case SQLITE_BUSY: - case SQLITE_LOCKED: - throw new SQLException("database locked"); - case SQLITE_MISUSE: - throw new SQLException(errmsg()); - default: - finalize(stmt); - throw new SQLException(errmsg()); - } - } - - final synchronized int executeUpdate(Stmt stmt, Object[] vals) - throws SQLException { - if (execute(stmt, vals)) - throw new SQLException("query returns results"); - reset(stmt.pointer); - return changes(); - } - - final void throwex() throws SQLException { - throw new SQLException(errmsg()); - } - - /* - * SQLite and the JDBC API have very different ideas about the meaning - * of auto-commit. Under JDBC, when executeUpdate() returns in - * auto-commit mode (the default), the programmer assumes the data has - * been written to disk. In SQLite however, a call to sqlite3_step() - * with an INSERT statement can return SQLITE_OK, and yet the data is - * still in limbo. - * - * This limbo appears when another statement on the database is active, - * e.g. a SELECT. SQLite auto-commit waits until the final read - * statement finishes, and then writes whatever updates have already - * been OKed. So if a program crashes before the reads are complete, - * data is lost. E.g: - * - * select begins - * insert - * select continues - * select finishes - * - * Works as expected, however - * - * select beings - * insert - * select continues - * crash - * - * Results in the data never being written to disk. - * - * As a solution, we call "commit" after every statement in auto-commit - * mode. - */ - final void ensureAutoCommit() throws SQLException { - if (!conn.getAutoCommit()) - return; - - if (begin == 0) - begin = prepare("begin;"); - if (commit == 0) - commit = prepare("commit;"); - - try { - if (step(begin) != SQLITE_DONE) - return; // assume we are in a transaction - if (step(commit) != SQLITE_DONE) { - reset(commit); - throwex(); - } - //throw new SQLException("unable to auto-commit"); - } finally { - reset(begin); - reset(commit); - } - } -} diff --git a/sqlitejdbc/src/org/sqlite/Function.java b/sqlitejdbc/src/org/sqlite/Function.java deleted file mode 100644 index 8faa757..0000000 --- a/sqlitejdbc/src/org/sqlite/Function.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import java.sql.*; - -/** Provides an interface for creating SQLite user-defined functions. - * - *

A subclass of org.sqlite.Function can be registered with - * Function.create() and called by the name it was given. All - * functions must implement xFunc(), which is called when SQLite - * runs the custom function.

- * - * Eg. - * - *
- *      Class.forName("org.sqlite.JDBC");
- *      Connection conn = DriverManager.getConnection("jdbc:sqlite:");
- *
- *      Function.create(conn, "myFunc", new Function() {
- *          protected void xFunc() {
- *              System.out.println("myFunc called!");
- *          }
- *      });
- *
- *      conn.createStatement().execute("select myFunc();");
- *  
- * - *

Arguments passed to a custom function can be accessed using the - * protected functions provided. args() returns - * the number of arguments passed, while - * value_<type>(int) returns the value of the specific - * argument. Similarly a function can return a value using the - * result(<type>) function.

- * - *

Aggregate functions are not yet supported, but coming soon.

- * - */ -public abstract class Function -{ - private Conn conn; - private DB db; - - long context = 0; // pointer sqlite3_context* - long value = 0; // pointer sqlite3_value** - int args = 0; - - /** Registers the given function with the Connection using the - * provided name. */ - public static final void create(Connection conn, String name, Function f) - throws SQLException { - if (conn == null || !(conn instanceof Conn)) - throw new SQLException("connection must be to an SQLite db"); - if (conn.isClosed()) - throw new SQLException("connection closed"); - - f.conn = (Conn)conn; - f.db = f.conn.db(); - - if (name == null || name.length() > 255) - throw new SQLException("invalid function name: '"+name+"'"); - - if (f.db.create_function(name, f) != Codes.SQLITE_OK) - throw new SQLException("error creating function"); - } - - /** Removes the named function form the Connection. */ - public static final void destroy(Connection conn, String name) - throws SQLException { - if (conn == null || !(conn instanceof Conn)) - throw new SQLException("connection must be to an SQLite db"); - ((Conn)conn).db().destroy_function(name); - } - - - /** Called by SQLite as a custom function. Should access arguments - * through value_*(int), return results with - * result(*) and throw errors with error(String). */ - protected abstract void xFunc() throws SQLException; - - - /** Returns the number of arguments passed to the function. - * Can only be called from xFunc(). */ - protected synchronized final int args() - throws SQLException { checkContext(); return args; } - - /** Called by xFunc to return a value. */ - protected synchronized final void result(byte[] value) - throws SQLException { checkContext(); db.result_blob(context, value); } - - /** Called by xFunc to return a value. */ - protected synchronized final void result(double value) - throws SQLException { checkContext(); db.result_double(context,value);} - - /** Called by xFunc to return a value. */ - protected synchronized final void result(int value) - throws SQLException { checkContext(); db.result_int(context, value); } - - /** Called by xFunc to return a value. */ - protected synchronized final void result(long value) - throws SQLException { checkContext(); db.result_long(context, value); } - - /** Called by xFunc to return a value. */ - protected synchronized final void result() - throws SQLException { checkContext(); db.result_null(context); } - - /** Called by xFunc to return a value. */ - protected synchronized final void result(String value) - throws SQLException { checkContext(); db.result_text(context, value); } - - /** Called by xFunc to throw an error. */ - protected synchronized final void error(String err) - throws SQLException { checkContext(); db.result_error(context, err); } - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final int value_bytes(int arg) - throws SQLException {checkValue(arg); return db.value_bytes(this,arg);} - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final String value_text(int arg) - throws SQLException {checkValue(arg); return db.value_text(this,arg);} - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final byte[] value_blob(int arg) - throws SQLException {checkValue(arg); return db.value_blob(this,arg); } - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final double value_double(int arg) - throws SQLException {checkValue(arg); return db.value_double(this,arg);} - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final int value_int(int arg) - throws SQLException {checkValue(arg); return db.value_int(this, arg); } - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final long value_long(int arg) - throws SQLException { checkValue(arg); return db.value_long(this,arg); } - - /** Called by xFunc to access the value of an argument. */ - protected synchronized final int value_type(int arg) - throws SQLException {checkValue(arg); return db.value_type(this,arg); } - - - private void checkContext() throws SQLException { - if (conn == null || conn.db() == null || context == 0) - throw new SQLException("no context, not allowed to read value"); - } - - private void checkValue(int arg) throws SQLException { - if (conn == null || conn.db() == null || value == 0) - throw new SQLException("not in value access state"); - if (arg >= args) - throw new SQLException("arg "+arg+" out bounds [0,"+args+")"); - } - - - public static abstract class Aggregate - extends Function - implements Cloneable - { - protected final void xFunc() {} - protected abstract void xStep() throws SQLException; - protected abstract void xFinal() throws SQLException; - - public Object clone() throws CloneNotSupportedException { - return super.clone(); - } - } -} diff --git a/sqlitejdbc/src/org/sqlite/JDBC.java b/sqlitejdbc/src/org/sqlite/JDBC.java deleted file mode 100644 index 34cf091..0000000 --- a/sqlitejdbc/src/org/sqlite/JDBC.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package org.sqlite; - -import java.sql.*; -import java.util.*; - -public class JDBC implements Driver -{ - private static final String PREFIX = "jdbc:sqlite:"; - - static { - try { - DriverManager.registerDriver(new JDBC()); - } catch (SQLException e) { - e.printStackTrace(); - } - } - - public int getMajorVersion() { return 1; } - public int getMinorVersion() { return 1; } - - public boolean jdbcCompliant() { return false; } - - public boolean acceptsURL(String url) { - return url != null && url.toLowerCase().startsWith(PREFIX); - } - - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) - throws SQLException { - return new DriverPropertyInfo[] {}; - } - - public Connection connect(String url, Properties info) throws SQLException { - if (!acceptsURL(url)) return null; - url = url.trim(); - - // if no file name is given use a memory database - return new Conn(url, PREFIX.equalsIgnoreCase(url) ? - ":memory:" : url.substring(PREFIX.length())); - } -} diff --git a/sqlitejdbc/src/org/sqlite/MetaData.java b/sqlitejdbc/src/org/sqlite/MetaData.java deleted file mode 100644 index 19b93da..0000000 --- a/sqlitejdbc/src/org/sqlite/MetaData.java +++ /dev/null @@ -1,717 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package org.sqlite; - -import java.sql.*; - -class MetaData implements DatabaseMetaData -{ - private Conn conn; - private PreparedStatement - getTables = null, - getTableTypes = null, - getTypeInfo = null, - getCrossReference = null, - getCatalogs = null, - getSchemas = null, - getUDTs = null, - getColumnsTblName = null, - getSuperTypes = null, - getSuperTables = null, - getTablePrivileges = null, - getExportedKeys = null, - getProcedures = null, - getProcedureColumns = null, - getAttributes = null, - getBestRowIdentifier = null, - getVersionColumns = null, - getColumnPrivileges = null; - - /** Used by PrepStmt to save generating a new statement every call. */ - private PreparedStatement getGeneratedKeys = null; - - MetaData(Conn conn) { this.conn = conn; } - - void checkOpen() throws SQLException { - if (conn == null) throw new SQLException("connection closed"); } - - synchronized void close() throws SQLException { - if (conn == null) return; - - try { - if (getTables != null) getTables.close(); - if (getTableTypes != null) getTableTypes.close(); - if (getTypeInfo != null) getTypeInfo.close(); - if (getCrossReference != null) getCrossReference.close(); - if (getCatalogs != null) getCatalogs.close(); - if (getSchemas != null) getSchemas.close(); - if (getUDTs != null) getUDTs.close(); - if (getColumnsTblName != null) getColumnsTblName.close(); - if (getSuperTypes != null) getSuperTypes.close(); - if (getSuperTables != null) getSuperTables.close(); - if (getTablePrivileges != null) getTablePrivileges.close(); - if (getExportedKeys != null) getExportedKeys.close(); - if (getProcedures != null) getProcedures.close(); - if (getProcedureColumns != null) getProcedureColumns.close(); - if (getAttributes != null) getAttributes.close(); - if (getBestRowIdentifier != null) getBestRowIdentifier.close(); - if (getVersionColumns != null) getVersionColumns.close(); - if (getColumnPrivileges != null) getColumnPrivileges.close(); - if (getGeneratedKeys != null) getGeneratedKeys.close(); - - getTables = null; - getTableTypes = null; - getTypeInfo = null; - getCrossReference = null; - getCatalogs = null; - getSchemas = null; - getUDTs = null; - getColumnsTblName = null; - getSuperTypes = null; - getSuperTables = null; - getTablePrivileges = null; - getExportedKeys = null; - getProcedures = null; - getProcedureColumns = null; - getAttributes = null; - getBestRowIdentifier = null; - getVersionColumns = null; - getColumnPrivileges = null; - getGeneratedKeys = null; - } finally { - conn = null; - } - } - - public Connection getConnection() { return conn; } - public int getDatabaseMajorVersion() { return 3; } - public int getDatabaseMinorVersion() { return 0; } - public int getDriverMajorVersion() { return 1; } - public int getDriverMinorVersion() { return 1; } - public int getJDBCMajorVersion() { return 2; } - public int getJDBCMinorVersion() { return 1; } - public int getDefaultTransactionIsolation() - { return Connection.TRANSACTION_SERIALIZABLE; } - public int getMaxBinaryLiteralLength() { return 0; } - public int getMaxCatalogNameLength() { return 0; } - public int getMaxCharLiteralLength() { return 0; } - public int getMaxColumnNameLength() { return 0; } - public int getMaxColumnsInGroupBy() { return 0; } - public int getMaxColumnsInIndex() { return 0; } - public int getMaxColumnsInOrderBy() { return 0; } - public int getMaxColumnsInSelect() { return 0; } - public int getMaxColumnsInTable() { return 0; } - public int getMaxConnections() { return 0; } - public int getMaxCursorNameLength() { return 0; } - public int getMaxIndexLength() { return 0; } - public int getMaxProcedureNameLength() { return 0; } - public int getMaxRowSize() { return 0; } - public int getMaxSchemaNameLength() { return 0; } - public int getMaxStatementLength() { return 0; } - public int getMaxStatements() { return 0; } - public int getMaxTableNameLength() { return 0; } - public int getMaxTablesInSelect() { return 0; } - public int getMaxUserNameLength() { return 0; } - public int getResultSetHoldability() - { return ResultSet.CLOSE_CURSORS_AT_COMMIT; } - public int getSQLStateType() { return sqlStateSQL99; } - - public String getDatabaseProductName() { return "SQLite"; } - public String getDatabaseProductVersion() throws SQLException { - return conn.libversion(); } - public String getDriverName() { return "SQLiteJDBC"; } - public String getDriverVersion() { return "1"; } - public String getExtraNameCharacters() { return ""; } - public String getCatalogSeparator() { return "."; } - public String getCatalogTerm() { return "catalog"; } - public String getSchemaTerm() { return "schema"; } - public String getProcedureTerm() { return "not_implemented"; } - public String getSearchStringEscape() { return null; } - public String getIdentifierQuoteString() { return " "; } - public String getSQLKeywords() { return ""; } - public String getNumericFunctions() { return ""; } - public String getStringFunctions() { return ""; } - public String getSystemFunctions() { return ""; } - public String getTimeDateFunctions() { return ""; } - - public String getURL() { return conn.url(); } - public String getUserName() { return null; } - - public boolean allProceduresAreCallable() { return false; } - public boolean allTablesAreSelectable() { return true; } - public boolean dataDefinitionCausesTransactionCommit() { return false; } - public boolean dataDefinitionIgnoredInTransactions() { return false; } - public boolean doesMaxRowSizeIncludeBlobs() { return false; } - public boolean deletesAreDetected(int type) { return false; } - public boolean insertsAreDetected(int type) { return false; } - public boolean isCatalogAtStart() { return true; } - public boolean locatorsUpdateCopy() { return false; } - public boolean nullPlusNonNullIsNull() { return true; } - public boolean nullsAreSortedAtEnd() { return !nullsAreSortedAtStart(); } - public boolean nullsAreSortedAtStart() { return true; } - public boolean nullsAreSortedHigh() { return true; } - public boolean nullsAreSortedLow() { return !nullsAreSortedHigh(); } - public boolean othersDeletesAreVisible(int type) { return false; } - public boolean othersInsertsAreVisible(int type) { return false; } - public boolean othersUpdatesAreVisible(int type) { return false; } - public boolean ownDeletesAreVisible(int type) { return false; } - public boolean ownInsertsAreVisible(int type) { return false; } - public boolean ownUpdatesAreVisible(int type) { return false; } - public boolean storesLowerCaseIdentifiers() { return false; } - public boolean storesLowerCaseQuotedIdentifiers() { return false; } - public boolean storesMixedCaseIdentifiers() { return true; } - public boolean storesMixedCaseQuotedIdentifiers() { return false; } - public boolean storesUpperCaseIdentifiers() { return false; } - public boolean storesUpperCaseQuotedIdentifiers() { return false; } - public boolean supportsAlterTableWithAddColumn() { return false; } - public boolean supportsAlterTableWithDropColumn() { return false; } - public boolean supportsANSI92EntryLevelSQL() { return false; } - public boolean supportsANSI92FullSQL() { return false; } - public boolean supportsANSI92IntermediateSQL() { return false; } - public boolean supportsBatchUpdates() { return true; } - public boolean supportsCatalogsInDataManipulation() { return false; } - public boolean supportsCatalogsInIndexDefinitions() { return false; } - public boolean supportsCatalogsInPrivilegeDefinitions() { return false; } - public boolean supportsCatalogsInProcedureCalls() { return false; } - public boolean supportsCatalogsInTableDefinitions() { return false; } - public boolean supportsColumnAliasing() { return true; } - public boolean supportsConvert() { return false; } - public boolean supportsConvert(int fromType, int toType) { return false; } - public boolean supportsCorrelatedSubqueries() { return false; } - public boolean supportsDataDefinitionAndDataManipulationTransactions() - { return true; } - public boolean supportsDataManipulationTransactionsOnly() { return false; } - public boolean supportsDifferentTableCorrelationNames() { return false; } - public boolean supportsExpressionsInOrderBy() { return true; } - public boolean supportsMinimumSQLGrammar() { return true; } - public boolean supportsCoreSQLGrammar() { return true; } - public boolean supportsExtendedSQLGrammar() { return false; } - public boolean supportsLimitedOuterJoins() { return true; } - public boolean supportsFullOuterJoins() { return false; } - public boolean supportsGetGeneratedKeys() { return false; } - public boolean supportsGroupBy() { return true; } - public boolean supportsGroupByBeyondSelect() { return false; } - public boolean supportsGroupByUnrelated() { return false; } - public boolean supportsIntegrityEnhancementFacility() { return false; } - public boolean supportsLikeEscapeClause() { return false; } - public boolean supportsMixedCaseIdentifiers() { return true; } - public boolean supportsMixedCaseQuotedIdentifiers() { return false; } - public boolean supportsMultipleOpenResults() { return false; } - public boolean supportsMultipleResultSets() { return false; } - public boolean supportsMultipleTransactions() { return true; } - public boolean supportsNamedParameters() { return true; } - public boolean supportsNonNullableColumns() { return true; } - public boolean supportsOpenCursorsAcrossCommit() { return false; } - public boolean supportsOpenCursorsAcrossRollback() { return false; } - public boolean supportsOpenStatementsAcrossCommit() { return false; } - public boolean supportsOpenStatementsAcrossRollback() { return false; } - public boolean supportsOrderByUnrelated() { return false; } - public boolean supportsOuterJoins() { return true; } - public boolean supportsPositionedDelete() { return false; } - public boolean supportsPositionedUpdate() { return false; } - public boolean supportsResultSetConcurrency(int t, int c) - { return t == ResultSet.TYPE_FORWARD_ONLY - && c == ResultSet.CONCUR_READ_ONLY; } - public boolean supportsResultSetHoldability(int h) - { return h == ResultSet.CLOSE_CURSORS_AT_COMMIT; } - public boolean supportsResultSetType(int t) - { return t == ResultSet.TYPE_FORWARD_ONLY; } - public boolean supportsSavepoints() { return false; } - public boolean supportsSchemasInDataManipulation() { return false; } - public boolean supportsSchemasInIndexDefinitions() { return false; } - public boolean supportsSchemasInPrivilegeDefinitions() { return false; } - public boolean supportsSchemasInProcedureCalls() { return false; } - public boolean supportsSchemasInTableDefinitions() { return false; } - public boolean supportsSelectForUpdate() { return false; } - public boolean supportsStatementPooling() { return false; } - public boolean supportsStoredProcedures() { return false; } - public boolean supportsSubqueriesInComparisons() { return false; } - public boolean supportsSubqueriesInExists() { return true; } // TODO: check - public boolean supportsSubqueriesInIns() { return true; } // TODO: check - public boolean supportsSubqueriesInQuantifieds() { return false; } - public boolean supportsTableCorrelationNames() { return false; } - public boolean supportsTransactionIsolationLevel(int level) - { return level == Connection.TRANSACTION_SERIALIZABLE; } - public boolean supportsTransactions() { return true; } - public boolean supportsUnion() { return true; } - public boolean supportsUnionAll() { return true; } - public boolean updatesAreDetected(int type) { return false; } - public boolean usesLocalFilePerTable() { return false; } - public boolean usesLocalFiles() { return true; } - public boolean isReadOnly() throws SQLException - { return conn.isReadOnly(); } - - public ResultSet getAttributes(String c, String s, String t, String a) - throws SQLException { - if (getAttributes == null) getAttributes = conn.prepareStatement( - "select " - + "null as TYPE_CAT, " - + "null as TYPE_SCHEM, " - + "null as TYPE_NAME, " - + "null as ATTR_NAME, " - + "null as DATA_TYPE, " - + "null as ATTR_TYPE_NAME, " - + "null as ATTR_SIZE, " - + "null as DECIMAL_DIGITS, " - + "null as NUM_PREC_RADIX, " - + "null as NULLABLE, " - + "null as REMARKS, " - + "null as ATTR_DEF, " - + "null as SQL_DATA_TYPE, " - + "null as SQL_DATETIME_SUB, " - + "null as CHAR_OCTET_LENGTH, " - + "null as ORDINAL_POSITION, " - + "null as IS_NULLABLE, " - + "null as SCOPE_CATALOG, " - + "null as SCOPE_SCHEMA, " - + "null as SCOPE_TABLE, " - + "null as SOURCE_DATA_TYPE limit 0;"); - return getAttributes.executeQuery(); - } - - public ResultSet getBestRowIdentifier(String c, String s, String t, - int scope, boolean n) throws SQLException { - if (getBestRowIdentifier == null) - getBestRowIdentifier = conn.prepareStatement( - "select " - + "null as SCOPE, " - + "null as COLUMN_NAME, " - + "null as DATA_TYPE, " - + "null as TYPE_NAME, " - + "null as COLUMN_SIZE, " - + "null as BUFFER_LENGTH, " - + "null as DECIMAL_DIGITS, " - + "null as PSEUDO_COLUMN limit 0;"); - return getBestRowIdentifier.executeQuery(); - } - - public ResultSet getColumnPrivileges(String c, String s, String t, - String colPat) - throws SQLException { - if (getColumnPrivileges == null) - getColumnPrivileges = conn.prepareStatement( - "select " - + "null as TABLE_CAT, " - + "null as TABLE_SCHEM, " - + "null as TABLE_NAME, " - + "null as COLUMN_NAME, " - + "null as GRANTOR, " - + "null as GRANTEE, " - + "null as PRIVILEGE, " - + "null as IS_GRANTABLE limit 0;"); - return getColumnPrivileges.executeQuery(); - } - - public ResultSet getColumns(String c, String s, String tbl, String colPat) - throws SQLException { - Statement stat = conn.createStatement(); - ResultSet rs; - String sql; - - checkOpen(); - - if (getColumnsTblName == null) - getColumnsTblName = conn.prepareStatement( - "select tbl_name from sqlite_master where tbl_name like ?;"); - - // determine exact table name - getColumnsTblName.setString(1, tbl); - rs = getColumnsTblName.executeQuery(); - if (!rs.next()) - return rs; - tbl = rs.getString(1); - rs.close(); - - sql = "select " - + "null as TABLE_CAT, " - + "null as TABLE_SCHEM, " - + "'" + escape(tbl) + "' as TABLE_NAME, " - + "cn as COLUMN_NAME, " - + "ct as DATA_TYPE, " - + "tn as TYPE_NAME, " - + "2000000000 as COLUMN_SIZE, " - + "2000000000 as BUFFER_LENGTH, " - + "10 as DECIMAL_DIGITS, " - + "10 as NUM_PREC_RADIX, " - + "colnullable as NULLABLE, " - + "null as REMARKS, " - + "null as COLUMN_DEF, " - + "0 as SQL_DATA_TYPE, " - + "0 as SQL_DATETIME_SUB, " - + "2000000000 as CHAR_OCTET_LENGTH, " - + "ordpos as ORDINAL_POSITION, " - + "(case colnullable when 0 then 'N' when 1 then 'Y' else '' end)" - + " as IS_NULLABLE, " - + "null as SCOPE_CATLOG, " - + "null as SCOPE_SCHEMA, " - + "null as SCOPE_TABLE, " - + "null as SOURCE_DATA_TYPE from ("; - - // the command "pragma table_info('tablename')" does not embed - // like a normal select statement so we must extract the information - // and then build a resultset from unioned select statements - rs = stat.executeQuery("pragma table_info ('"+escape(tbl)+"');"); - - boolean colFound = false; - for (int i=0; rs.next(); i++) { - String colName = rs.getString(2); - String colType = rs.getString(3); - String colNotNull = rs.getString(4); - - int colNullable = 2; - if (colNotNull != null) colNullable = colNotNull.equals("0") ? 1:0; - if (colFound) sql += " union all "; - colFound = true; - - colType = colType == null ? "TEXT" : colType.toUpperCase(); - int colJavaType = -1; - if (colType == "INT" || colType == "INTEGER") - colJavaType = Types.INTEGER; - else if (colType == "TEXT") - colJavaType = Types.VARCHAR; - else if (colType == "FLOAT") - colJavaType = Types.FLOAT; - else - colJavaType = Types.VARCHAR; - - sql += "select " - + i + " as ordpos, " - + colNullable + " as colnullable, '" - + colJavaType + "' as ct, '" - + escape(colName) + "' as cn, '" - + escape(colType) + "' as tn"; - - if (colPat != null) - sql += " where upper(cn) like upper('" + escape(colPat) + "')"; - } - sql += colFound ? ");" : - "select null as ordpos, null as colnullable, " - + "null as cn, null as tn) limit 0;"; - rs.close(); - - return stat.executeQuery(sql); - } - - public ResultSet getCrossReference(String pc, String ps, String pt, - String fc, String fs, String ft) - throws SQLException { - if (getCrossReference == null) - getCrossReference = conn.prepareStatement("select " - + "null as PKTABLE_CAT, " - + "null as PKTABLE_SCHEM, " - + "null as PKTABLE_NAME, " - + "null as PKCOLUMN_NAME, " - + "null as FKTABLE_CAT, " - + "null as FKTABLE_SCHEM, " - + "null as FKTABLE_NAME, " - + "null as FKCOLUMN_NAME, " - + "null as KEY_SEQ, " - + "null as UPDATE_RULE, " - + "null as DELETE_RULE, " - + "null as FK_NAME, " - + "null as PK_NAME, " - + "null as DEFERRABILITY " - + "limit 0;"); - getCrossReference.clearParameters(); - return getCrossReference.executeQuery(); - } - - public ResultSet getSchemas() throws SQLException { - if (getSchemas == null) getSchemas = conn.prepareStatement("select " - + "null as TABLE_SCHEM, " - + "null as TABLE_CATALOG " - + "limit 0;"); - getSchemas.clearParameters(); - return getSchemas.executeQuery(); - } - - public ResultSet getCatalogs() throws SQLException { - if (getCatalogs == null) getCatalogs = conn.prepareStatement( - "select null as TABLE_CAT limit 0;"); - getCatalogs.clearParameters(); - return getCatalogs.executeQuery(); - } - - public ResultSet getPrimaryKeys(String c, String s, String table) - throws SQLException { - String sql; - ResultSet rs; - Statement stat = conn.createStatement(); - - rs = stat.executeQuery("pragma table_info('"+escape(table)+"');"); - - sql = "select " - + "null as TABLE_CAT, " - + "null as TABLE_SCHEM, " - + "'" + escape(table) + "' as TABLE_NAME, " - + "cn as COLUMN_NAME, " - + "0 as KEY_SEQ, " - + "null as PK_NAME from ("; - - int i; - for (i=0; rs.next(); i++) { - String colName = rs.getString(2); - - if (!rs.getBoolean(6)) { i--; continue; } - if (i > 0) sql += " union all "; - - sql += "select '" + escape(colName) + "' as cn"; - } - sql += i == 0 ? "select null as cn) limit 0;" : ");"; - rs.close(); - - return stat.executeQuery(sql); - } - - public ResultSet getExportedKeys(String c, String s, String t) - throws SQLException { - if (getExportedKeys == null) getExportedKeys = conn.prepareStatement( - "select " - + "null as PKTABLE_CAT, " - + "null as PKTABLE_SCHEM, " - + "null as PKTABLE_NAME, " - + "null as PKCOLUMN_NAME, " - + "null as FKTABLE_CAT, " - + "null as FKTABLE_SCHEM, " - + "null as FKTABLE_NAME, " - + "null as FKCOLUMN_NAME, " - + "null as KEY_SEQ, " - + "null as UPDATE_RULE, " - + "null as DELETE_RULE, " - + "null as FK_NAME, " - + "null as PK_NAME, " - + "null as DEFERRABILITY limit 0;"); - return getExportedKeys.executeQuery(); - } - - public ResultSet getImportedKeys(String c, String s, String t) - throws SQLException { throw new SQLException("not yet implemented"); } - public ResultSet getIndexInfo(String c, String s, String t, - boolean u, boolean approximate) - throws SQLException { throw new SQLException("not yet implemented"); } - public ResultSet getProcedureColumns(String c, String s, String p, - String colPat) - throws SQLException { - if (getProcedures == null) getProcedureColumns = conn.prepareStatement( - "select " - + "null as PROCEDURE_CAT, " - + "null as PROCEDURE_SCHEM, " - + "null as PROCEDURE_NAME, " - + "null as COLUMN_NAME, " - + "null as COLUMN_TYPE, " - + "null as DATA_TYPE, " - + "null as TYPE_NAME, " - + "null as PRECISION, " - + "null as LENGTH, " - + "null as SCALE, " - + "null as RADIX, " - + "null as NULLABLE, " - + "null as REMARKS limit 0;"); - return getProcedureColumns.executeQuery(); - - } - - public ResultSet getProcedures(String c, String s, String p) - throws SQLException { - if (getProcedures == null) getProcedures = conn.prepareStatement( - "select " - + "null as PROCEDURE_CAT, " - + "null as PROCEDURE_SCHEM, " - + "null as PROCEDURE_NAME, " - + "null as UNDEF1, " - + "null as UNDEF2, " - + "null as UNDEF3, " - + "null as REMARKS, " - + "null as PROCEDURE_TYPE limit 0;"); - return getProcedures.executeQuery(); - } - - public ResultSet getSuperTables(String c, String s, String t) - throws SQLException { - if (getSuperTables == null) getSuperTables = conn.prepareStatement( - "select " - + "null as TABLE_CAT, " - + "null as TABLE_SCHEM, " - + "null as TABLE_NAME, " - + "null as SUPERTABLE_NAME limit 0;"); - return getSuperTables.executeQuery(); - } - - public ResultSet getSuperTypes(String c, String s, String t) - throws SQLException { - if (getSuperTypes == null) getSuperTypes = conn.prepareStatement( - "select " - + "null as TYPE_CAT, " - + "null as TYPE_SCHEM, " - + "null as TYPE_NAME, " - + "null as SUPERTYPE_CAT, " - + "null as SUPERTYPE_SCHEM, " - + "null as SUPERTYPE_NAME limit 0;"); - return getSuperTypes.executeQuery(); - } - - public ResultSet getTablePrivileges(String c, String s, String t) - throws SQLException { - if (getTablePrivileges == null) - getTablePrivileges = conn.prepareStatement( - "select " - + "null as TABLE_CAT, " - + "null as TABLE_SCHEM, " - + "null as TABLE_NAME, " - + "null as GRANTOR, " - + "null as GRANTEE, " - + "null as PRIVILEGE, " - + "null as IS_GRANTABLE limit 0;"); - return getTablePrivileges.executeQuery(); - } - - public synchronized ResultSet getTables(String c, String s, - String t, String[] types) throws SQLException { - checkOpen(); - - t = (t == null || "".equals(t)) ? "%" : t.toUpperCase(); - - String sql = "select" - + " null as TABLE_CAT," - + " null as TABLE_SCHEM," - + " upper(name) as TABLE_NAME," - + " upper(type) as TABLE_TYPE," - + " null as REMARKS," - + " null as TYPE_CAT," - + " null as TYPE_SCHEM," - + " null as TYPE_NAME," - + " null as SELF_REFERENCING_COL_NAME," - + " null as REF_GENERATION" - + " from (select name, type from sqlite_master union all" - + " select name, type from sqlite_temp_master)" - + " where TABLE_NAME like '" + escape(t) + "'"; - - if (types != null) { - sql += " and TABLE_TYPE in ("; - for (int i=0; i < types.length; i++) { - if (i > 0) sql += ", "; - sql += "'" + types[i].toUpperCase() + "'"; - } - sql += ")"; - } - - sql += ";"; - - return conn.createStatement().executeQuery(sql); - } - - public ResultSet getTableTypes() throws SQLException { - checkOpen(); - if (getTableTypes == null) getTableTypes = conn.prepareStatement( - "select 'TABLE' as TABLE_TYPE" - + " union select 'VIEW' as TABLE_TYPE;"); - getTableTypes.clearParameters(); - return getTableTypes.executeQuery(); - } - - public ResultSet getTypeInfo() throws SQLException { - if (getTypeInfo == null) { - getTypeInfo = conn.prepareStatement( - "select " - + "tn as TYPE_NAME, " - + "dt as DATA_TYPE, " - + "0 as PRECISION, " - + "null as LITERAL_PREFIX, " - + "null as LITERAL_SUFFIX, " - + "null as CREATE_PARAMS, " - + typeNullable + " as NULLABLE, " - + "1 as CASE_SENSITIVE, " - + typeSearchable + " as SEARCHABLE, " - + "0 as UNSIGNED_ATTRIBUTE, " - + "0 as FIXED_PREC_SCALE, " - + "0 as AUTO_INCREMENT, " - + "null as LOCAL_TYPE_NAME, " - + "0 as MINIMUM_SCALE, " - + "0 as MAXIMUM_SCALE, " - + "0 as SQL_DATA_TYPE, " - + "0 as SQL_DATETIME_SUB, " - + "10 as NUM_PREC_RADIX from (" - + " select 'BLOB' as tn, " + Types.BLOB + " as dt union" - + " select 'NULL' as tn, " + Types.NULL + " as dt union" - + " select 'REAL' as tn, " + Types.REAL+ " as dt union" - + " select 'TEXT' as tn, " + Types.VARCHAR + " as dt union" - + " select 'INTEGER' as tn, "+ Types.INTEGER +" as dt" - + ") order by TYPE_NAME;" - ); - } - - getTypeInfo.clearParameters(); - return getTypeInfo.executeQuery(); - } - - public ResultSet getUDTs(String c, String s, String t, int[] types) - throws SQLException { - if (getUDTs == null) getUDTs = conn.prepareStatement("select " - + "null as TYPE_CAT, " - + "null as TYPE_SCHEM, " - + "null as TYPE_NAME, " - + "null as CLASS_NAME, " - + "null as DATA_TYPE, " - + "null as REMARKS, " - + "null as BASE_TYPE " - + "limit 0;"); - - getUDTs.clearParameters(); - return getUDTs.executeQuery(); - } - public ResultSet getVersionColumns(String c, String s, String t) - throws SQLException { - if (getVersionColumns == null) - getVersionColumns = conn.prepareStatement( - "select " - + "null as SCOPE, " - + "null as COLUMN_NAME, " - + "null as DATA_TYPE, " - + "null as TYPE_NAME, " - + "null as COLUMN_SIZE, " - + "null as BUFFER_LENGTH, " - + "null as DECIMAL_DIGITS, " - + "null as PSEUDO_COLUMN limit 0;"); - return getVersionColumns.executeQuery(); - } - - ResultSet getGeneratedKeys() throws SQLException { - if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement( - "select last_insert_rowid();"); - return getGeneratedKeys.executeQuery(); - } - - /** Replace all instances of ' with '' */ - private String escape(final String val) { - // TODO: this function is ugly, pass this work off to SQLite, then we - // don't have to worry about Unicode 4, other characters needing - // escaping, etc. - int len = val.length(); - StringBuffer buf = new StringBuffer(len); - for (int i=0; i < len; i++) { - if (val.charAt(i) == '\'') buf.append('\''); - buf.append(val.charAt(i)); - } - return buf.toString(); - } - - public Struct createStruct(String t, Object[] attr) throws SQLException { - throw new SQLException("Not yet implemented by SQLite JDBC driver"); } - public ResultSet getFunctionColumns(String a, String b, String c, - String d) throws SQLException { - throw new SQLException("Not yet implemented by SQLite JDBC driver"); } -} diff --git a/sqlitejdbc/src/org/sqlite/NativeDB.c b/sqlitejdbc/src/org/sqlite/NativeDB.c deleted file mode 100644 index 4edc2aa..0000000 --- a/sqlitejdbc/src/org/sqlite/NativeDB.c +++ /dev/null @@ -1,780 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include -#include -#include -#include "NativeDB.h" -#include "sqlite3.h" - -static jclass dbclass = 0; -static jclass fclass = 0; -static jclass aclass = 0; - -static void * toref(jlong value) -{ - jvalue ret; - ret.j = value; - return (void *) ret.l; -} - -static jlong fromref(void * value) -{ - jvalue ret; - ret.l = value; - return ret.j; -} - -static void throwex(JNIEnv *env, jobject this) -{ - static jmethodID mth_throwex = 0; - - if (!mth_throwex) - mth_throwex = (*env)->GetMethodID(env, dbclass, "throwex", "()V"); - - (*env)->CallVoidMethod(env, this, mth_throwex); -} - -static void throwexmsg(JNIEnv *env, const char *str) -{ - static jmethodID mth_throwexmsg = 0; - - if (!mth_throwexmsg) mth_throwexmsg = (*env)->GetStaticMethodID( - env, dbclass, "throwex", "(Ljava/lang/String;)V"); - - (*env)->CallStaticVoidMethod(env, dbclass, mth_throwexmsg, - (*env)->NewStringUTF(env, str)); -} - -static sqlite3 * gethandle(JNIEnv *env, jobject this) -{ - static jfieldID pointer = 0; - if (!pointer) pointer = (*env)->GetFieldID(env, dbclass, "pointer", "J"); - - return (sqlite3 *)toref((*env)->GetLongField(env, this, pointer)); -} - -static void sethandle(JNIEnv *env, jobject this, sqlite3 * ref) -{ - static jfieldID pointer = 0; - if (!pointer) pointer = (*env)->GetFieldID(env, dbclass, "pointer", "J"); - - (*env)->SetLongField(env, this, pointer, fromref(ref)); -} - -/* Returns number of 16-bit blocks in UTF-16 string, not including null. */ -static jsize jstrlen(const jchar *str) -{ - const jchar *s; - for (s = str; *s; s++); - return (jsize)(s - str); -} - - -// User Defined Function SUPPORT //////////////////////////////////// - -struct UDFData { - JavaVM *vm; - jobject func; - struct UDFData *next; // linked list of all UDFData instances -}; - -/* Returns the sqlite3_value for the given arg of the given function. - * If 0 is returned, an exception has been thrown to report the reason. */ -static sqlite3_value * tovalue(JNIEnv *env, jobject function, jint arg) -{ - jlong value_pntr = 0; - jint numArgs = 0; - static jfieldID func_value = 0, - func_args = 0; - - if (!func_value || !func_args) { - func_value = (*env)->GetFieldID(env, fclass, "value", "J"); - func_args = (*env)->GetFieldID(env, fclass, "args", "I"); - } - - // check we have any business being here - if (arg < 0) { throwexmsg(env, "negative arg out of range"); return 0; } - if (!function) { throwexmsg(env, "inconstent function"); return 0; } - - value_pntr = (*env)->GetLongField(env, function, func_value); - numArgs = (*env)->GetIntField(env, function, func_args); - - if (value_pntr == 0) { throwexmsg(env, "no current value"); return 0; } - if (arg >= numArgs) { throwexmsg(env, "arg out of range"); return 0; } - - return ((sqlite3_value**)toref(value_pntr))[arg]; -} - -/* called if an exception occured processing xFunc */ -static void xFunc_error(sqlite3_context *context, JNIEnv *env) -{ - const char *strmsg = 0; - jstring msg = 0; - jint msgsize = 0; - - jclass exclass = 0; - static jmethodID exp_msg = 0; - jthrowable ex = (*env)->ExceptionOccurred(env); - - (*env)->ExceptionClear(env); - - if (!exp_msg) { - exclass = (*env)->FindClass(env, "java/lang/Throwable"); - exp_msg = (*env)->GetMethodID( - env, exclass, "toString", "()Ljava/lang/String;"); - } - - msg = (jstring)(*env)->CallObjectMethod(env, ex, exp_msg); - if (!msg) { sqlite3_result_error(context, "unknown error", 13); return; } - - msgsize = (*env)->GetStringUTFLength(env, msg); - strmsg = (*env)->GetStringUTFChars(env, msg, 0); - assert(strmsg); // out-of-memory - - sqlite3_result_error(context, strmsg, msgsize); - - (*env)->ReleaseStringUTFChars(env, msg, strmsg); -} - -/* used to call xFunc, xStep and xFinal */ -static xCall( - sqlite3_context *context, - int args, - sqlite3_value** value, - jobject func, - jmethodID method) -{ - static jfieldID fld_context = 0, - fld_value = 0, - fld_args = 0; - JNIEnv *env = 0; - struct UDFData *udf = 0; - - udf = (struct UDFData*)sqlite3_user_data(context); - assert(udf); - (*udf->vm)->AttachCurrentThread(udf->vm, (void **)&env, 0); - if (!func) func = udf->func; - - if (!fld_context || !fld_value || !fld_args) { - fld_context = (*env)->GetFieldID(env, fclass, "context", "J"); - fld_value = (*env)->GetFieldID(env, fclass, "value", "J"); - fld_args = (*env)->GetFieldID(env, fclass, "args", "I"); - } - - (*env)->SetLongField(env, func, fld_context, fromref(context)); - (*env)->SetLongField(env, func, fld_value, value ? fromref(value) : 0); - (*env)->SetIntField(env, func, fld_args, args); - - (*env)->CallVoidMethod(env, func, method); - - (*env)->SetLongField(env, func, fld_context, 0); - (*env)->SetLongField(env, func, fld_value, 0); - (*env)->SetIntField(env, func, fld_args, 0); - - // check if xFunc threw an Exception - if ((*env)->ExceptionCheck(env)) xFunc_error(context, env); -} - - -void xFunc(sqlite3_context *context, int args, sqlite3_value** value) -{ - static jmethodID mth = 0; - if (!mth) { - JNIEnv *env; - struct UDFData *udf = (struct UDFData*)sqlite3_user_data(context); - (*udf->vm)->AttachCurrentThread(udf->vm, (void **)&env, 0); - mth = (*env)->GetMethodID(env, fclass, "xFunc", "()V"); - } - xCall(context, args, value, 0, mth); -} - -void xStep(sqlite3_context *context, int args, sqlite3_value** value) -{ - JNIEnv *env; - struct UDFData *udf; - jobject *func = 0; - static jmethodID mth = 0; - static jmethodID clone = 0; - - if (!mth || !clone) { - udf = (struct UDFData*)sqlite3_user_data(context); - (*udf->vm)->AttachCurrentThread(udf->vm, (void **)&env, 0); - - mth = (*env)->GetMethodID(env, aclass, "xStep", "()V"); - clone = (*env)->GetMethodID(env, aclass, "clone", - "()Ljava/lang/Object;"); - } - - // clone the Function.Aggregate instance and store a pointer - // in SQLite's aggregate_context (clean up in xFinal) - func = sqlite3_aggregate_context(context, sizeof(jobject)); - if (!*func) { - udf = (struct UDFData*)sqlite3_user_data(context); - (*udf->vm)->AttachCurrentThread(udf->vm, (void **)&env, 0); - - *func = (*env)->CallObjectMethod(env, udf->func, clone); - *func = (*env)->NewGlobalRef(env, *func); - } - - xCall(context, args, value, *func, mth); -} - -void xFinal(sqlite3_context *context) -{ - JNIEnv *env = 0; - struct UDFData *udf = 0; - jobject *func = 0; - static jmethodID mth = 0; - - udf = (struct UDFData*)sqlite3_user_data(context); - (*udf->vm)->AttachCurrentThread(udf->vm, (void **)&env, 0); - - if (!mth) mth = (*env)->GetMethodID(env, aclass, "xFinal", "()V"); - - func = sqlite3_aggregate_context(context, sizeof(jobject)); - assert(*func); // disaster - - xCall(context, 0, 0, *func, mth); - - // clean up Function.Aggregate instance - (*env)->DeleteGlobalRef(env, *func); -} - - -// INITIALISATION /////////////////////////////////////////////////// - -JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) -{ - JNIEnv* env = 0; - - if (JNI_OK != (*vm)->GetEnv(vm, (void **)&env, JNI_VERSION_1_2)) - return JNI_ERR; - - dbclass = (*env)->FindClass(env, "org/sqlite/NativeDB"); - if (!dbclass) return JNI_ERR; - dbclass = (*env)->NewGlobalRef(env, dbclass); - - fclass = (*env)->FindClass(env, "org/sqlite/Function"); - if (!fclass) return JNI_ERR; - fclass = (*env)->NewGlobalRef(env, fclass); - - aclass = (*env)->FindClass(env, "org/sqlite/Function$Aggregate"); - if (!aclass) return JNI_ERR; - aclass = (*env)->NewGlobalRef(env, aclass); - - return JNI_VERSION_1_2; -} - - -// WRAPPERS for sqlite_* functions ////////////////////////////////// - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_shared_1cache( - JNIEnv *env, jobject this, jboolean enable) -{ - return sqlite3_enable_shared_cache(enable ? 1 : 0); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB__1open( - JNIEnv *env, jobject this, jstring file) -{ - int ret; - sqlite3 *db = gethandle(env, this); - const char *str; - - if (db) { - throwexmsg(env, "DB already open"); - sqlite3_close(db); - return; - } - - str = (*env)->GetStringUTFChars(env, file, 0); - if (sqlite3_open(str, &db)) { - throwex(env, this); - sqlite3_close(db); - return; - } - (*env)->ReleaseStringUTFChars(env, file, str); - - sethandle(env, this, db); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB__1close( - JNIEnv *env, jobject this) -{ - if (sqlite3_close(gethandle(env, this)) != SQLITE_OK) - throwex(env, this); - sethandle(env, this, 0); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_interrupt(JNIEnv *env, jobject this) -{ - sqlite3_interrupt(gethandle(env, this)); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_busy_1timeout( - JNIEnv *env, jobject this, jint ms) -{ - sqlite3_busy_timeout(gethandle(env, this), ms); -} - -JNIEXPORT jlong JNICALL Java_org_sqlite_NativeDB_prepare( - JNIEnv *env, jobject this, jstring sql) -{ - sqlite3* db = gethandle(env, this); - sqlite3_stmt* stmt; - - const char *strsql = (*env)->GetStringUTFChars(env, sql, 0); - int status = sqlite3_prepare_v2(db, strsql, -1, &stmt, 0); - (*env)->ReleaseStringUTFChars(env, sql, strsql); - - if (status != SQLITE_OK) { - throwex(env, this); - return fromref(0); - } - return fromref(stmt); -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_errmsg(JNIEnv *env, jobject this) -{ - return (*env)->NewStringUTF(env, sqlite3_errmsg(gethandle(env, this))); -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_libversion( - JNIEnv *env, jobject this) -{ - return (*env)->NewStringUTF(env, sqlite3_libversion()); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_changes( - JNIEnv *env, jobject this) -{ - return sqlite3_changes(gethandle(env, this)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_finalize( - JNIEnv *env, jobject this, jlong stmt) -{ - return sqlite3_finalize(toref(stmt)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_step( - JNIEnv *env, jobject this, jlong stmt) -{ - return sqlite3_step(toref(stmt)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_reset( - JNIEnv *env, jobject this, jlong stmt) -{ - return sqlite3_reset(toref(stmt)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_clear_1bindings( - JNIEnv *env, jobject this, jlong stmt) -{ - int i; - int count = sqlite3_bind_parameter_count(toref(stmt)); - jint rc = SQLITE_OK; - for(i=1; rc==SQLITE_OK && i <= count; i++) { - rc = sqlite3_bind_null(toref(stmt), i); - } - return rc; -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1parameter_1count( - JNIEnv *env, jobject this, jlong stmt) -{ - return sqlite3_bind_parameter_count(toref(stmt)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_column_1count( - JNIEnv *env, jobject this, jlong stmt) -{ - return sqlite3_column_count(toref(stmt)); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_column_1type( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - return sqlite3_column_type(toref(stmt), col); -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_column_1decltype( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - const char *str = sqlite3_column_decltype(toref(stmt), col); - return (*env)->NewStringUTF(env, str); -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_column_1table_1name( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - const void *str = sqlite3_column_table_name16(toref(stmt), col); - return str ? (*env)->NewString(env, str, jstrlen(str)) : NULL; -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_column_1name( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - const void *str = sqlite3_column_name16(toref(stmt), col); - return str ? (*env)->NewString(env, str, jstrlen(str)) : NULL; -} - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_column_1text( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - return (*env)->NewStringUTF( - env, (const char*)sqlite3_column_text(toref(stmt), col)); -} - -JNIEXPORT jbyteArray JNICALL Java_org_sqlite_NativeDB_column_1blob( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - jsize length; - jbyteArray jBlob; - jbyte *a; - const void *blob = sqlite3_column_blob(toref(stmt), col); - if (!blob) return NULL; - - length = sqlite3_column_bytes(toref(stmt), col); - jBlob = (*env)->NewByteArray(env, length); - assert(jBlob); // out-of-memory - - a = (*env)->GetPrimitiveArrayCritical(env, jBlob, 0); - memcpy(a, blob, length); - (*env)->ReleasePrimitiveArrayCritical(env, jBlob, a, 0); - - return jBlob; -} - -JNIEXPORT jdouble JNICALL Java_org_sqlite_NativeDB_column_1double( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - return sqlite3_column_double(toref(stmt), col); -} - -JNIEXPORT jlong JNICALL Java_org_sqlite_NativeDB_column_1long( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - return sqlite3_column_int64(toref(stmt), col); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_column_1int( - JNIEnv *env, jobject this, jlong stmt, jint col) -{ - return sqlite3_column_int(toref(stmt), col); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1null( - JNIEnv *env, jobject this, jlong stmt, jint pos) -{ - return sqlite3_bind_null(toref(stmt), pos); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1int( - JNIEnv *env, jobject this, jlong stmt, jint pos, jint v) -{ - return sqlite3_bind_int(toref(stmt), pos, v); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1long( - JNIEnv *env, jobject this, jlong stmt, jint pos, jlong v) -{ - return sqlite3_bind_int64(toref(stmt), pos, v); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1double( - JNIEnv *env, jobject this, jlong stmt, jint pos, jdouble v) -{ - return sqlite3_bind_double(toref(stmt), pos, v); -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1text( - JNIEnv *env, jobject this, jlong stmt, jint pos, jstring v) -{ - const char *chars = (*env)->GetStringUTFChars(env, v, 0); - int rc = sqlite3_bind_text(toref(stmt), pos, chars, -1, SQLITE_TRANSIENT); - (*env)->ReleaseStringUTFChars(env, v, chars); - return rc; -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_bind_1blob( - JNIEnv *env, jobject this, jlong stmt, jint pos, jbyteArray v) -{ - jint rc; - void *a; - jsize size = (*env)->GetArrayLength(env, v); - assert(a = (*env)->GetPrimitiveArrayCritical(env, v, 0)); - rc = sqlite3_bind_blob(toref(stmt), pos, a, size, SQLITE_TRANSIENT); - (*env)->ReleasePrimitiveArrayCritical(env, v, a, JNI_ABORT); - return rc; -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1null( - JNIEnv *env, jobject this, jlong context) -{ - sqlite3_result_null(toref(context)); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1text( - JNIEnv *env, jobject this, jlong context, jstring value) -{ - const jchar *str; - jsize size; - - if (value == NULL) { sqlite3_result_null(toref(context)); return; } - size = (*env)->GetStringLength(env, value) * 2; - - str = (*env)->GetStringCritical(env, value, 0); - assert(str); // out-of-memory - sqlite3_result_text16(toref(context), str, size, SQLITE_TRANSIENT); - (*env)->ReleaseStringCritical(env, value, str); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1blob( - JNIEnv *env, jobject this, jlong context, jobject value) -{ - jbyte *bytes; - jsize size; - - if (value == NULL) { sqlite3_result_null(toref(context)); return; } - size = (*env)->GetArrayLength(env, value); - - // be careful with *Critical - bytes = (*env)->GetPrimitiveArrayCritical(env, value, 0); - assert(bytes); // out-of-memory - sqlite3_result_blob(toref(context), bytes, size, SQLITE_TRANSIENT); - (*env)->ReleasePrimitiveArrayCritical(env, value, bytes, JNI_ABORT); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1double( - JNIEnv *env, jobject this, jlong context, jdouble value) -{ - sqlite3_result_double(toref(context), value); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1long( - JNIEnv *env, jobject this, jlong context, jlong value) -{ - sqlite3_result_int64(toref(context), value); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_result_1int( - JNIEnv *env, jobject this, jlong context, jint value) -{ - sqlite3_result_int(toref(context), value); -} - - - - -JNIEXPORT jstring JNICALL Java_org_sqlite_NativeDB_value_1text( - JNIEnv *env, jobject this, jobject f, jint arg) -{ - jint length = 0; - const void *str = 0; - sqlite3_value *value = tovalue(env, f, arg); - if (!value) return NULL; - - length = sqlite3_value_bytes16(value) / 2; // in jchars - str = sqlite3_value_text16(value); - return str ? (*env)->NewString(env, str, length) : NULL; -} - -JNIEXPORT jbyteArray JNICALL Java_org_sqlite_NativeDB_value_1blob( - JNIEnv *env, jobject this, jobject f, jint arg) -{ - jsize length; - jbyteArray jBlob; - jbyte *a; - const void *blob; - sqlite3_value *value = tovalue(env, f, arg); - if (!value) return NULL; - - blob = sqlite3_value_blob(value); - if (!blob) return NULL; - - length = sqlite3_value_bytes(value); - jBlob = (*env)->NewByteArray(env, length); - assert(jBlob); // out-of-memory - - a = (*env)->GetPrimitiveArrayCritical(env, jBlob, 0); - memcpy(a, blob, length); - (*env)->ReleasePrimitiveArrayCritical(env, jBlob, a, 0); - - return jBlob; -} - -JNIEXPORT jdouble JNICALL Java_org_sqlite_NativeDB_value_1double( - JNIEnv *env, jobject this, jobject f, jint arg) -{ - sqlite3_value *value = tovalue(env, f, arg); - return value ? sqlite3_value_double(value) : 0; -} - -JNIEXPORT jlong JNICALL Java_org_sqlite_NativeDB_value_1long( - JNIEnv *env, jobject this, jobject f, jint arg) -{ - sqlite3_value *value = tovalue(env, f, arg); - return value ? sqlite3_value_int64(value) : 0; -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_value_1int( - JNIEnv *env, jobject this, jobject f, jint arg) -{ - sqlite3_value *value = tovalue(env, f, arg); - return value ? sqlite3_value_int(value) : 0; -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_value_1type( - JNIEnv *env, jobject this, jobject func, jint arg) -{ - return sqlite3_value_type(tovalue(env, func, arg)); -} - - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_create_1function( - JNIEnv *env, jobject this, jstring name, jobject func) -{ - jint ret = 0; - const char *strname = 0; - int isAgg = 0; - - static jfieldID udfdatalist = 0; - struct UDFData *udf = malloc(sizeof(struct UDFData)); - - assert(udf); // out-of-memory - - if (!udfdatalist) - udfdatalist = (*env)->GetFieldID(env, dbclass, "udfdatalist", "J"); - - isAgg = (*env)->IsInstanceOf(env, func, aclass); - udf->func = (*env)->NewGlobalRef(env, func); - (*env)->GetJavaVM(env, &udf->vm); - - // add new function def to linked list - udf->next = toref((*env)->GetLongField(env, this, udfdatalist)); - (*env)->SetLongField(env, this, udfdatalist, fromref(udf)); - - strname = (*env)->GetStringUTFChars(env, name, 0); - assert(strname); // out-of-memory - - ret = sqlite3_create_function( - gethandle(env, this), - strname, // function name - -1, // number of args - SQLITE_UTF16, // preferred chars - udf, - isAgg ? 0 :&xFunc, - isAgg ? &xStep : 0, - isAgg ? &xFinal : 0 - ); - - (*env)->ReleaseStringUTFChars(env, name, strname); - - return ret; -} - -JNIEXPORT jint JNICALL Java_org_sqlite_NativeDB_destroy_1function( - JNIEnv *env, jobject this, jstring name) -{ - const char* strname = (*env)->GetStringUTFChars(env, name, 0); - sqlite3_create_function( - gethandle(env, this), strname, -1, SQLITE_UTF16, 0, 0, 0, 0 - ); - (*env)->ReleaseStringUTFChars(env, name, strname); -} - -JNIEXPORT void JNICALL Java_org_sqlite_NativeDB_free_1functions( - JNIEnv *env, jobject this) -{ - // clean up all the malloc()ed UDFData instances using the - // linked list stored in DB.udfdatalist - jfieldID udfdatalist; - struct UDFData *udf, *udfpass; - - udfdatalist = (*env)->GetFieldID(env, dbclass, "udfdatalist", "J"); - udf = toref((*env)->GetLongField(env, this, udfdatalist)); - (*env)->SetLongField(env, this, udfdatalist, 0); - - while (udf) { - udfpass = udf->next; - (*env)->DeleteGlobalRef(env, udf->func); - free(udf); - udf = udfpass; - } -} - - -// COMPOUND FUNCTIONS /////////////////////////////////////////////// - -JNIEXPORT jobjectArray JNICALL Java_org_sqlite_NativeDB_column_1metadata( - JNIEnv *env, jobject this, jlong stmt) -{ - const char *zTableName, *zColumnName; - int pNotNull, pPrimaryKey, pAutoinc, i, colCount; - jobjectArray array; - jbooleanArray colData; - jboolean* colDataRaw; - sqlite3 *db; - sqlite3_stmt *dbstmt; - - db = gethandle(env, this); - dbstmt = toref(stmt); - - colCount = sqlite3_column_count(dbstmt); - array = (*env)->NewObjectArray( - env, colCount, (*env)->FindClass(env, "[Z"), NULL) ; - assert(array); // out-of-memory - - colDataRaw = (jboolean*)malloc(3 * sizeof(jboolean)); - assert(colDataRaw); // out-of-memory - - for (i = 0; i < colCount; i++) { - // load passed column name and table name - zColumnName = sqlite3_column_name(dbstmt, i); - zTableName = sqlite3_column_table_name(dbstmt, i); - - pNotNull = 0; - pPrimaryKey = 0; - pAutoinc = 0; - - // request metadata for column and load into output variables - if (zTableName && zColumnName) { - sqlite3_table_column_metadata( - db, 0, zTableName, zColumnName, - 0, 0, &pNotNull, &pPrimaryKey, &pAutoinc - ); - } - - // load relevant metadata into 2nd dimension of return results - colDataRaw[0] = pNotNull; - colDataRaw[1] = pPrimaryKey; - colDataRaw[2] = pAutoinc; - - colData = (*env)->NewBooleanArray(env, 3); - assert(colData); // out-of-memory - - (*env)->SetBooleanArrayRegion(env, colData, 0, 3, colDataRaw); - (*env)->SetObjectArrayElement(env, array, i, colData); - } - - free(colDataRaw); - - return array; -} - diff --git a/sqlitejdbc/src/org/sqlite/NativeDB.java b/sqlitejdbc/src/org/sqlite/NativeDB.java deleted file mode 100644 index eb7ea1b..0000000 --- a/sqlitejdbc/src/org/sqlite/NativeDB.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package org.sqlite; - -import java.io.File; -import java.sql.SQLException; - -/** This class provides a thin JNI layer over the SQLite3 C API. */ -final class NativeDB extends DB -{ - /** SQLite connection handle. */ - long pointer = 0; - - private static Boolean loaded = null; - - static boolean load() { - if (loaded != null) return loaded == Boolean.TRUE; - - String libpath = System.getProperty("org.sqlite.lib.path"); - String libname = System.getProperty("org.sqlite.lib.name"); - if (libname == null) libname = System.mapLibraryName("sqlitejdbc"); - - try { - if (libpath == null) System.loadLibrary("sqlitejdbc"); - else System.load(new File(libpath, libname).getAbsolutePath()); - } catch (UnsatisfiedLinkError e) { - loaded = Boolean.FALSE; - return false; - } - - loaded = Boolean.TRUE; - return true; - } - - - /** linked list of all instanced UDFDatas */ - private long udfdatalist = 0; - - - // WRAPPER FUNCTIONS //////////////////////////////////////////// - - protected native synchronized void _open(String file) throws SQLException; - protected native synchronized void _close() throws SQLException; - native synchronized void interrupt(); - native synchronized void busy_timeout(int ms); - //native synchronized void exec(String sql) throws SQLException; - protected native synchronized long prepare(String sql) throws SQLException; - native synchronized String errmsg(); - native synchronized String libversion(); - native synchronized int changes(); - - protected native synchronized int finalize(long stmt); - protected native synchronized int step(long stmt); - protected native synchronized int reset(long stmt); - native synchronized int clear_bindings(long stmt); - - native synchronized int bind_parameter_count(long stmt); - - native synchronized int column_count (long stmt); - native synchronized int column_type (long stmt, int col); - native synchronized String column_decltype (long stmt, int col); - native synchronized String column_table_name (long stmt, int col); - native synchronized String column_name (long stmt, int col); - native synchronized String column_text (long stmt, int col); - native synchronized byte[] column_blob (long stmt, int col); - native synchronized double column_double (long stmt, int col); - native synchronized long column_long (long stmt, int col); - native synchronized int column_int (long stmt, int col); - - native synchronized int bind_null (long stmt, int pos); - native synchronized int bind_int (long stmt, int pos, int v); - native synchronized int bind_long (long stmt, int pos, long v); - native synchronized int bind_double(long stmt, int pos, double v); - native synchronized int bind_text (long stmt, int pos, String v); - native synchronized int bind_blob (long stmt, int pos, byte[] v); - - native synchronized void result_null (long context); - native synchronized void result_text (long context, String val); - native synchronized void result_blob (long context, byte[] val); - native synchronized void result_double(long context, double val); - native synchronized void result_long (long context, long val); - native synchronized void result_int (long context, int val); - native synchronized void result_error (long context, String err); - - native synchronized int value_bytes (Function f, int arg); - native synchronized String value_text (Function f, int arg); - native synchronized byte[] value_blob (Function f, int arg); - native synchronized double value_double(Function f, int arg); - native synchronized long value_long (Function f, int arg); - native synchronized int value_int (Function f, int arg); - native synchronized int value_type (Function f, int arg); - - native synchronized int create_function(String name, Function func); - native synchronized int destroy_function(String name); - native synchronized void free_functions(); - - // COMPOUND FUNCTIONS (for optimisation) ///////////////////////// - - /** Provides metadata for the columns of a statement. Returns: - * res[col][0] = true if column constrained NOT NULL - * res[col][1] = true if column is part of the primary key - * res[col][2] = true if column is auto-increment - */ - native synchronized boolean[][] column_metadata(long stmt); - - static void throwex(String msg) throws SQLException { - throw new SQLException(msg); - } -} diff --git a/sqlitejdbc/src/org/sqlite/NestedDB.c b/sqlitejdbc/src/org/sqlite/NestedDB.c deleted file mode 100644 index bb8a4b8..0000000 --- a/sqlitejdbc/src/org/sqlite/NestedDB.c +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -#include -#include "sqlite3.h" - -/* Provides access to metadata across NestedVM 7-argument limit on functions.*/ -struct metadata { - int pNotNull; - int pPrimaryKey; - int pAutoinc; -}; - -int column_metadata_helper( - sqlite3 *db, - sqlite3_stmt *stmt, - int col, - struct metadata *p -){ - const char *zTableName, *zColumnName; - int rc = 0; - - p->pNotNull = 0; - p->pPrimaryKey = 0; - p->pAutoinc = 0; - - zTableName = sqlite3_column_table_name(stmt, col); - zColumnName = sqlite3_column_name(stmt, col); - - if (zTableName && zColumnName) { - rc = sqlite3_table_column_metadata( - db, 0, zTableName, zColumnName, 0, 0, - &p->pNotNull, &p->pPrimaryKey, &p->pAutoinc - ); - } - - return rc; -} - - -extern int _call_java(int xType, int context, int args, int value); - -void xFunc_helper(sqlite3_context *context, int args, sqlite3_value** value) -{ - _call_java(1, (int)context, args, (int)value); -} - -void xStep_helper(sqlite3_context *context, int args, sqlite3_value** value) -{ - _call_java(2, (int)context, args, (int)value); -} - -void xFinal_helper(sqlite3_context *context) -{ - _call_java(3, (int)context, 0, 0); -} - -/* create function if pos is non-negative, aggregate if agg is true */ -int create_function_helper(sqlite3 *db, const char *name, int pos, int agg) -{ - return sqlite3_create_function(db, name, -1, SQLITE_ANY, (void*)pos, - pos>=0 && !agg ? &xFunc_helper : 0, - pos>=0 && agg ? &xStep_helper : 0, - pos>=0 && agg ? &xFinal_helper : 0); -} diff --git a/sqlitejdbc/src/org/sqlite/NestedDB.java b/sqlitejdbc/src/org/sqlite/NestedDB.java deleted file mode 100644 index a0d0314..0000000 --- a/sqlitejdbc/src/org/sqlite/NestedDB.java +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import org.ibex.nestedvm.Runtime; - -import java.io.File; -import java.io.PrintWriter; -import java.sql.*; - -// FEATURE: strdup is wasteful, SQLite interface will take unterminated char* - -/** Communicates with the Java version of SQLite provided by NestedVM. */ -final class NestedDB extends DB implements Runtime.CallJavaCB -{ - /** database pointer */ - int handle = 0; - - /** sqlite binary embedded in nestedvm */ - private Runtime rt = null; - - /** user defined functions referenced by position (stored in used data) */ - private Function[] functions = null; - private String[] funcNames = null; - - - // WRAPPER FUNCTIONS //////////////////////////////////////////// - - protected synchronized void _open(String filename) throws SQLException { - if (handle != 0) throw new SQLException("DB already open"); - - // handle silly windows drive letter mapping - if (filename.length() > 2) { - char drive = Character.toLowerCase(filename.charAt(0)); - if (filename.charAt(1) == ':' && drive >= 'a' && drive <= 'z') { - - // convert to nestedvm's "/c:/file" format - filename = filename.substring(2); - filename = filename.replace('\\', '/'); - filename = "/" + drive + ":" + filename; - } - } - - // start the nestedvm runtime - try { - rt = (Runtime)Class.forName("org.sqlite.SQLite") - .newInstance(); - rt.start(); - } catch (Exception e) { - throw new CausedSQLException(e); - } - - // callback for user defined functions - rt.setCallJavaCB(this); - - // open the db and retrieve sqlite3_db* pointer - int passback = rt.xmalloc(4); - int str = rt.strdup(filename); - if (call("sqlite3_open", str, passback) != SQLITE_OK) - throwex(); - handle = deref(passback); - rt.free(str); - rt.free(passback); - } - - /* callback for Runtime.CallJavaCB above */ - public int call(int xType, int context, int args, int value) { - xUDF(xType, context, args, value); - return 0; - } - - protected synchronized void _close() throws SQLException { - if (handle == 0) return; - try { - if (call("sqlite3_close", handle) != SQLITE_OK) - throwex(); - } finally { - handle = 0; - rt.stop(); - rt = null; - } - } - - synchronized void interrupt() throws SQLException { - call("sqlite3_interrupt", handle); - } - synchronized void busy_timeout(int ms) throws SQLException { - call("sqlite3_busy_timeout", handle, ms); - } - protected synchronized long prepare(String sql) throws SQLException { - int passback = rt.xmalloc(4); - int str = rt.strdup(sql); - int ret = call("sqlite3_prepare_v2", handle, str, -1, passback, 0); - rt.free(str); - if (ret != SQLITE_OK) { - rt.free(passback); - throwex(); - } - int pointer = deref(passback); - rt.free(passback); - return pointer; - } - synchronized String errmsg() throws SQLException { - return cstring(call("sqlite3_errmsg", handle)); - } - synchronized String libversion() throws SQLException { - return cstring(call("sqlite3_libversion", handle)); - } - synchronized int changes() throws SQLException { - return call("sqlite3_changes", handle); } - - protected synchronized int finalize(long stmt) throws SQLException { - return call("sqlite3_finalize", (int)stmt); } - protected synchronized int step(long stmt) throws SQLException { - return call("sqlite3_step", (int)stmt); } - protected synchronized int reset(long stmt) throws SQLException { - return call("sqlite3_reset", (int)stmt); } - synchronized int clear_bindings(long stmt) throws SQLException { - return call("sqlite3_clear_bindings", (int)stmt); } - - synchronized int bind_parameter_count(long stmt) throws SQLException { - return call("sqlite3_bind_parameter_count", (int)stmt); } - - synchronized int column_count(long stmt) throws SQLException { - return call("sqlite3_column_count", (int)stmt); } - synchronized int column_type(long stmt, int col) throws SQLException { - return call("sqlite3_column_type", (int)stmt, col); } - synchronized String column_name(long stmt, int col) throws SQLException { - return utfstring(call("sqlite3_column_name", (int)stmt, col)); - } - synchronized String column_text(long stmt, int col) throws SQLException { - return utfstring(call("sqlite3_column_text", (int)stmt, col)); - } - synchronized byte[] column_blob(long stmt, int col) throws SQLException { - int addr = call("sqlite3_column_blob", (int)stmt, col); - if (addr == 0) return null; - byte[] blob = new byte[call("sqlite3_column_bytes", (int)stmt, col)]; - copyin(addr, blob, blob.length); - return blob; - } - synchronized double column_double(long stmt, int col) throws SQLException { - try { return Double.parseDouble(column_text(stmt, col)); } - catch (NumberFormatException e) { return Double.NaN; } // TODO - } - synchronized long column_long(long stmt, int col) throws SQLException { - try { return Long.parseLong(column_text(stmt, col)); } - catch (NumberFormatException e) { return 0; } // TODO - } - synchronized int column_int(long stmt, int col) throws SQLException { - return call("sqlite3_column_int", (int)stmt, col); } - synchronized String column_decltype(long stmt, int col) - throws SQLException { - return utfstring(call("sqlite3_column_decltype", (int)stmt, col)); - } - synchronized String column_table_name(long stmt, int col) - throws SQLException { - return utfstring(call("sqlite3_column_table_name", (int)stmt, col)); - } - - synchronized int bind_null(long stmt, int pos) throws SQLException { - return call("sqlite3_bind_null", (int)stmt, pos); - } - synchronized int bind_int(long stmt, int pos, int v) throws SQLException { - return call("sqlite3_bind_int", (int)stmt, pos, v); - } - synchronized int bind_long(long stmt, int pos, long v) throws SQLException { - return bind_text(stmt, pos, Long.toString(v)); // TODO - } - synchronized int bind_double(long stmt, int pos, double v) - throws SQLException { - return bind_text(stmt, pos, Double.toString(v)); // TODO - } - synchronized int bind_text(long stmt, int pos, String v) - throws SQLException { - if (v == null) return bind_null(stmt, pos); - return call("sqlite3_bind_text", (int)stmt, pos, rt.strdup(v), - -1, rt.lookupSymbol("free")); - } - synchronized int bind_blob(long stmt, int pos, byte[] buf) - throws SQLException { - if (buf == null || buf.length < 1) return bind_null(stmt, pos); - int len = buf.length; - int blob = rt.xmalloc(len); // free()ed by sqlite3_bind_blob - copyout(buf, blob, len); - return call("sqlite3_bind_blob", (int)stmt, pos, blob, len, - rt.lookupSymbol("free")); - } - - synchronized void result_null(long cxt) throws SQLException { - call("sqlite3_result_null", (int)cxt); } - synchronized void result_text(long cxt, String val) throws SQLException { - call("sqlite3_result_text", (int)cxt, rt.strdup(val), -1, - rt.lookupSymbol("free")); - } - synchronized void result_blob(long cxt, byte[] val) throws SQLException { - if (val == null || val.length == 0) { result_null(cxt); return; } - int blob = rt.xmalloc(val.length); - copyout(val, blob, val.length); - call("sqlite3_result_blob", (int)cxt, blob, - val.length, rt.lookupSymbol("free")); - } - synchronized void result_double(long cxt, double val) throws SQLException { - result_text(cxt, Double.toString(val)); } // TODO - synchronized void result_long(long cxt, long val) throws SQLException { - result_text(cxt, Long.toString(val)); } // TODO - synchronized void result_int(long cxt, int val) throws SQLException { - call("sqlite3_result_int", (int)cxt, val); } - synchronized void result_error(long cxt, String err) throws SQLException { - int str = rt.strdup(err); - call("sqlite3_result_error", (int)cxt, str, -1); - rt.free(str); - } - - synchronized int value_bytes(Function f, int arg) throws SQLException { - return call("sqlite3_value_bytes", value(f, arg)); - } - synchronized String value_text(Function f, int arg) throws SQLException { - return utfstring(call("sqlite3_value_text", value(f, arg))); - } - synchronized byte[] value_blob(Function f, int arg) throws SQLException { - int addr = call("sqlite3_value_blob", value(f, arg)); - if (addr == 0) return null; - byte[] blob = new byte[value_bytes(f, arg)]; - copyin(addr, blob, blob.length); - return blob; - } - synchronized double value_double(Function f, int arg) throws SQLException { - return Double.parseDouble(value_text(f, arg)); // TODO - } - synchronized long value_long(Function f, int arg) throws SQLException { - return Long.parseLong(value_text(f, arg)); // TODO - } - synchronized int value_int(Function f, int arg) throws SQLException { - return call("sqlite3_value_int", value(f, arg)); - } - synchronized int value_type(Function f, int arg) throws SQLException { - return call("sqlite3_value_type", value(f, arg)); - } - - private int value(Function f, int arg) throws SQLException { - return deref((int)f.value + (arg*4)); - } - - - synchronized int create_function(String name, Function func) - throws SQLException { - if (functions == null) { - functions = new Function[10]; - funcNames = new String[10]; - } - - // find a position - int pos; - for (pos=0; pos < functions.length; pos++) - if (functions[pos] == null) break; - - if (pos == functions.length) { // expand function arrays - Function[] fnew = new Function[functions.length * 2]; - String[] nnew = new String[funcNames.length * 2]; - System.arraycopy(functions, 0, fnew, 0, functions.length); - System.arraycopy(funcNames, 0, nnew, 0, funcNames.length); - functions = fnew; - funcNames = nnew; - } - - // register function - functions[pos] = func; - funcNames[pos] = name; - int rc; - int str = rt.strdup(name); - rc = call("create_function_helper", handle, str, pos, - func instanceof Function.Aggregate ? 1 : 0); - rt.free(str); - return rc; - } - - synchronized int destroy_function(String name) throws SQLException { - if (name == null) return 0; - - // find function position number - int pos; - for (pos = 0; pos < funcNames.length; pos++) - if (name.equals(funcNames[pos])) break; - if (pos == funcNames.length) return 0; - - functions[pos] = null; - funcNames[pos] = null; - - // deregister function - int rc; - int str = rt.strdup(name); - rc = call("create_function_helper", handle, str, -1, 0); - rt.free(str); - return rc; - } - - /* unused as we use the user_data pointer to store a single word */ - synchronized void free_functions() {} - - /** Callback used by xFunc (1), xStep (2) and xFinal (3). */ - synchronized void xUDF(int xType, int context, int args, int value) { - Function func = null; - - try { - int pos = call("sqlite3_user_data", context); - func = functions[pos]; - if (func == null) - throw new SQLException("function state inconsistent"); - - func.context = context; - func.value = value; - func.args = args; - - switch (xType) { - case 1: func.xFunc(); break; - case 2: ((Function.Aggregate)func).xStep(); break; - case 3: ((Function.Aggregate)func).xFinal(); break; - } - } catch (SQLException e) { - try { - String err = e.toString(); - if (err == null) err = "unknown error"; - int str = rt.strdup(err); - call("sqlite3_result_error", context, str, -1); - rt.free(str); - } catch (SQLException exp) { - exp.printStackTrace();//TODO - } - } finally { - if (func != null) { - func.context = 0; - func.value = 0; - func.args = 0; - } - } - } - - - /** Calls support function found in upstream/sqlite-metadata.patch */ - synchronized boolean[][] column_metadata(long stmt) throws SQLException { - int colCount = call("sqlite3_column_count", (int)stmt); - boolean[][] meta = new boolean[colCount][3]; - int pass; - - pass = rt.xmalloc(12); // struct metadata - - for (int i=0; i < colCount; i++) { - call("column_metadata_helper", handle, (int)stmt, i, pass); - meta[i][0] = deref(pass) == 1; - meta[i][1] = deref(pass + 4) == 1; - meta[i][2] = deref(pass + 8) == 1; - } - - rt.free(pass); - return meta; - } - - - // HELPER FUNCTIONS ///////////////////////////////////////////// - - /** safe to reuse parameter arrays as all functions are syncrhonized */ - private final int[] - p0 = new int[] {}, - p1 = new int[] { 0 }, - p2 = new int[] { 0, 0 }, - p3 = new int[] { 0, 0, 0 }, - p4 = new int[] { 0, 0, 0, 0 }, - p5 = new int[] { 0, 0, 0, 0, 0 }; - - private int call(String addr, int a0) throws SQLException { - p1[0] = a0; return call(addr, p1); } - private int call(String addr, int a0, int a1) throws SQLException { - p2[0] = a0; p2[1] = a1; return call(addr, p2); } - private int call(String addr, int a0, int a1, int a2) throws SQLException { - p3[0] = a0; p3[1] = a1; p3[2] = a2; return call(addr, p3); } - private int call(String addr, int a0, int a1, int a2, int a3) - throws SQLException { - p4[0] = a0; p4[1] = a1; p4[2] = a2; p4[3] = a3; - return call(addr, p4); - } - private int call(String addr, int a0, int a1, int a2, int a3, int a4) - throws SQLException { - p5[0] = a0; p5[1] = a1; p5[2] = a2; p5[3] = a3; p5[4] = a4; - return call(addr, p5); - } - private int call(String func, int[] args) throws SQLException { - try { - return rt.call(func, args); - } catch (Runtime.CallException e) { throw new CausedSQLException(e); } - } - - /** Dereferences a pointer, returning the word it points to. */ - private int deref(int pointer) throws SQLException { - try { return rt.memRead(pointer); } - catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);} - } - private String utfstring(int str) throws SQLException { - try { return rt.utfstring(str); } - catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);} - } - private String cstring(int str) throws SQLException { - try { return rt.cstring(str); } - catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);} - } - private void copyin(int addr, byte[] buf, int count) throws SQLException { - try { rt.copyin(addr, buf, count); } - catch (Runtime.ReadFaultException e) { throw new CausedSQLException(e);} - } - private void copyout(byte[] buf, int addr, int count) throws SQLException { - try { rt.copyout(buf, addr, count); } - catch (Runtime.FaultException e) { throw new CausedSQLException(e);} - } - - /** Maps any exception onto an SQLException. */ - private static final class CausedSQLException extends SQLException { - private final Exception cause; - CausedSQLException(Exception e) { - if (e == null) throw new RuntimeException("null exception cause"); - cause = e; - } - public Throwable getCause() { return cause; } - public void printStackTrace() { cause.printStackTrace(); } - public void printStackTrace(PrintWriter s) { cause.printStackTrace(s); } - public Throwable fillInStackTrace() { return cause.fillInStackTrace(); } - public StackTraceElement[] getStackTrace() { - return cause.getStackTrace(); } - public String getMessage() { return cause.getMessage(); } - } -} diff --git a/sqlitejdbc/src/org/sqlite/PrepStmt.java b/sqlitejdbc/src/org/sqlite/PrepStmt.java deleted file mode 100644 index 28b37dd..0000000 --- a/sqlitejdbc/src/org/sqlite/PrepStmt.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package org.sqlite; - -import java.io.Reader; -import java.io.InputStream; -import java.net.URL; -import java.sql.*; -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.Calendar; - -final class PrepStmt extends Stmt - implements PreparedStatement, ParameterMetaData, Codes -{ - private int columnCount; - private int paramCount; - - PrepStmt(Conn conn, String sql) throws SQLException { - super(conn); - - this.sql = sql; - db.prepare(this); - rs.colsMeta = db.column_names(pointer); - columnCount = db.column_count(pointer); - paramCount = db.bind_parameter_count(pointer); - batch = new Object[paramCount]; - batchPos = 0; - } - - public void close() throws SQLException { - batch = null; - clearParameters(); - super.close(); - } - - public void clearParameters() throws SQLException { - checkOpen(); - db.reset(pointer); - clearBatch(); - } - - protected void finalize() throws SQLException { close(); } - - public boolean execute() throws SQLException { - checkOpen(); - rs.close(); - db.reset(pointer); - resultsWaiting = db.execute(this, batch); - return columnCount != 0; - } - - public ResultSet executeQuery() throws SQLException { - checkOpen(); - if (columnCount == 0) - throw new SQLException("query does not return results"); - rs.close(); - db.reset(pointer); - resultsWaiting = db.execute(this, batch); - return getResultSet(); - } - - public int executeUpdate() throws SQLException { - checkOpen(); - if (columnCount != 0) - throw new SQLException("query returns results"); - rs.close(); - db.reset(pointer); - return db.executeUpdate(this, batch); - } - - public int[] executeBatch() throws SQLException { - if (batchPos == 0) return new int[] {}; - return db.executeBatch(pointer, batchPos / paramCount, batch); - } - - public int getUpdateCount() throws SQLException { - checkOpen(); - if (pointer == 0 || resultsWaiting) return -1; - return db.changes(); - } - - public void addBatch() throws SQLException { - checkOpen(); - batchPos += paramCount; - if (batchPos + paramCount > batch.length) { - Object[] nb = new Object[batch.length * 2]; - System.arraycopy(batch, 0, nb, 0, batch.length); - batch = nb; - } - } - - - // ParameterMetaData FUNCTIONS ////////////////////////////////// - - public ParameterMetaData getParameterMetaData() { return this; } - - public int getParameterCount() throws SQLException { - checkOpen(); return paramCount; } - public String getParameterClassName(int param) throws SQLException { - checkOpen(); return "java.lang.String"; } - public String getParameterTypeName(int pos) { return "VARCHAR"; } - public int getParameterType(int pos) { return Types.VARCHAR; } - public int getParameterMode(int pos) { return parameterModeIn; } - public int getPrecision(int pos) { return 0; } - public int getScale(int pos) { return 0; } - public int isNullable(int pos) { return parameterNullable; } - public boolean isSigned(int pos) { return true; } - public Statement getStatement() { return this; } - - - // PARAMETER FUNCTIONS ////////////////////////////////////////// - - private void batch(int pos, Object value) throws SQLException { - checkOpen(); - if (batch == null) batch = new Object[paramCount]; - batch[batchPos + pos - 1] = value; - } - - public void setBoolean(int pos, boolean value) throws SQLException { - setInt(pos, value ? 1 : 0); - } - public void setByte(int pos, byte value) throws SQLException { - setInt(pos, (int)value); - } - public void setBytes(int pos, byte[] value) throws SQLException { - batch(pos, value); - } - public void setDouble(int pos, double value) throws SQLException { - batch(pos, new Double(value)); - } - public void setFloat(int pos, float value) throws SQLException { - setDouble(pos, value); - } - public void setInt(int pos, int value) throws SQLException { - batch(pos, new Integer(value)); - } - public void setLong(int pos, long value) throws SQLException { - batch(pos, new Long(value)); - } - public void setNull(int pos, int u1) throws SQLException { - setNull(pos, u1, null); - } - public void setNull(int pos, int u1, String u2) throws SQLException { - batch(pos, null); - } - public void setObject(int pos , Object value) throws SQLException { - if (value == null) - batch(pos, null); - else if (value instanceof java.util.Date) - batch(pos, new Long(((java.util.Date)value).getTime())); - else if (value instanceof Long) batch(pos, value); - else if (value instanceof Integer) batch(pos, value); - else if (value instanceof Float) batch(pos, value); - else if (value instanceof Double) batch(pos, value); - else - batch(pos, value.toString()); - } - public void setObject(int p, Object v, int t) throws SQLException { - setObject(p, v); } - public void setObject(int p, Object v, int t, int s) throws SQLException { - setObject(p, v); } - public void setShort(int pos, short value) throws SQLException { - setInt(pos, (int)value); } - public void setString(int pos, String value) throws SQLException { - batch(pos, value); - } - public void setDate(int pos, Date x) throws SQLException { - setLong(pos, x.getTime()); } - public void setDate(int pos, Date x, Calendar cal) throws SQLException { - setLong(pos, x.getTime()); } - public void setTime(int pos, Time x) throws SQLException { - setLong(pos, x.getTime()); } - public void setTime(int pos, Time x, Calendar cal) throws SQLException { - setLong(pos, x.getTime()); } - public void setTimestamp(int pos, Timestamp x) throws SQLException { - setLong(pos, x.getTime()); } - public void setTimestamp(int pos, Timestamp x, Calendar cal) - throws SQLException { setLong(pos, x.getTime()); } - - public ResultSetMetaData getMetaData() throws SQLException { - checkOpen(); return rs; } - - - // UNUSED /////////////////////////////////////////////////////// - - public boolean execute(String sql) - throws SQLException { throw unused(); } - public int executeUpdate(String sql) - throws SQLException { throw unused(); } - public ResultSet executeQuery(String sql) - throws SQLException { throw unused(); } - public void addBatch(String sql) - throws SQLException { throw unused(); } - - private SQLException unused() { - return new SQLException("not supported by PreparedStatment"); - } -} diff --git a/sqlitejdbc/src/org/sqlite/RS.java b/sqlitejdbc/src/org/sqlite/RS.java deleted file mode 100644 index 055676b..0000000 --- a/sqlitejdbc/src/org/sqlite/RS.java +++ /dev/null @@ -1,347 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import java.sql.*; - -import java.io.InputStream; -import java.io.Reader; -import java.math.BigDecimal; -import java.net.URL; -import java.util.Calendar; -import java.util.Map; - -/** - * Implements a JDBC ResultSet. - */ -final class RS extends Unused implements ResultSet, ResultSetMetaData, Codes -{ - private final Stmt stmt; - private final DB db; - - boolean open = false ; // true means have results and can iterate them - int maxRows; // max. number of rows as set by a Statement - String[] cols = null; // if null, the RS is closed() - String[] colsMeta = null; // same as cols, but used by Meta interface - boolean[][] meta = null; - - private int limitRows; // 0 means no limit, must check against maxRows - private int row = 1; // number of current row, starts at 1 - private int lastCol; // last column accessed, for wasNull(). -1 if none - - RS(Stmt stmt) { - this.stmt = stmt; - this.db = stmt.db; - } - - - // INTERNAL FUNCTIONS /////////////////////////////////////////// - - boolean isOpen() { return open; } - - /* Throws SQLException if ResultSet is not open. */ - void checkOpen() throws SQLException { - if (!open) throw new SQLException("ResultSet closed"); - } - - // takes col in [1,x] form, returns in [0,x-1] form - private int checkCol(int col) throws SQLException { - if (colsMeta == null) throw new IllegalStateException( - "SQLite JDBC: inconsistent internal state"); - if (col < 1 || col > colsMeta.length) throw new SQLException( - "column " + col + " out of bounds [1," + colsMeta.length + "]"); - return --col; - } - - // takes col in [1,x] form, marks it as last accessed and returns [0,x-1] - private int markCol(int col) throws SQLException { - checkOpen(); checkCol(col); lastCol = col; return --col; - } - - private void checkMeta() throws SQLException { - checkCol(1); - if (meta == null) meta = db.column_metadata(stmt.pointer); - } - - - // ResultSet Functions ////////////////////////////////////////// - - public void close() throws SQLException { - cols = null; - colsMeta = null; - meta = null; - open = false; - limitRows = 0; - row = 1; - lastCol = -1; - - if (stmt == null) - return; - if (stmt != null && stmt.pointer != 0) - db.reset(stmt.pointer); - } - - // returns col in [1,x] form - public int findColumn(String col) throws SQLException { - checkOpen(); - for (int i=0; i < cols.length; i++) - if (col.equalsIgnoreCase(cols[i])) return i+1; - throw new SQLException("no such column: '"+col+"'"); - } - - public boolean next() throws SQLException { - //XXX System.out.println("next(): open="+open+", row="+row+", maxRows="+maxRows+", limitRows="+limitRows); - if (!open) return false; // finished ResultSet - lastCol = -1; - - // first row is loaded by execute(), so do not step() again - if (row == 1) { row++; return true; } - - // check if we are row limited by the statement or the ResultSet - if (maxRows != 0 && row > maxRows) return false; - if (limitRows != 0 && row >= limitRows) return false; - - // do the real work - switch (db.step(stmt.pointer)) { - case SQLITE_DONE: - close(); // agressive closing to avoid writer starvation - return false; - case SQLITE_ROW: row++; return true; - case SQLITE_BUSY: - throw new SQLException("database locked"); - default: - db.throwex(); return false; - } - } - - public int getType() throws SQLException { return TYPE_FORWARD_ONLY; } - - public int getFetchSize() throws SQLException { return limitRows; } - public void setFetchSize(int rows) throws SQLException { - if (0 > rows || (maxRows != 0 && rows > maxRows)) - throw new SQLException("fetch size " + rows - + " out of bounds " + maxRows); - limitRows = rows; - } - - public int getFetchDirection() throws SQLException { - checkOpen(); return ResultSet.FETCH_FORWARD; } - public void setFetchDirection(int d) throws SQLException { - checkOpen(); - if (d != ResultSet.FETCH_FORWARD) - throw new SQLException("only FETCH_FORWARD direction supported"); - } - - public boolean isAfterLast() throws SQLException { return !open; } - public boolean isBeforeFirst() throws SQLException { - return open && row == 1; } - public boolean isFirst() throws SQLException { return row == 2; } - public boolean isLast() throws SQLException { // FIXME - throw new SQLException("function not yet implemented for SQLite"); } - - protected void finalize() throws SQLException { close(); } - - public int getRow() throws SQLException { return row; } - - public boolean wasNull() throws SQLException { - return db.column_type(stmt.pointer, markCol(lastCol)) == SQLITE_NULL; - } - - - // DATA ACCESS FUNCTIONS //////////////////////////////////////// - - public boolean getBoolean(int col) throws SQLException { - return getInt(col) == 0 ? false : true; } - public boolean getBoolean(String col) throws SQLException { - return getBoolean(findColumn(col)); } - - public byte getByte(int col) throws SQLException { - return (byte)getInt(col); } - public byte getByte(String col) throws SQLException { - return getByte(findColumn(col)); } - - public byte[] getBytes(int col) throws SQLException { - return db.column_blob(stmt.pointer, markCol(col)); } - public byte[] getBytes(String col) throws SQLException { - return getBytes(findColumn(col)); } - - public Date getDate(int col) throws SQLException { - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return null; - return new Date(db.column_long(stmt.pointer, markCol(col))); - } - public Date getDate(int col, Calendar cal) throws SQLException { - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return null; - if (cal == null) return getDate(col); - cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col))); - return new Date(cal.getTime().getTime()); - } - public Date getDate(String col) throws SQLException { - return getDate(findColumn(col), Calendar.getInstance()); } - public Date getDate(String col, Calendar cal) throws SQLException { - return getDate(findColumn(col), cal); } - - public double getDouble(int col) throws SQLException { - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return 0; - return db.column_double(stmt.pointer, markCol(col)); - } - public double getDouble(String col) throws SQLException { - return getDouble(findColumn(col)); } - - public float getFloat(int col) throws SQLException { - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return 0; - return (float)db.column_double(stmt.pointer, markCol(col)); - } - public float getFloat(String col) throws SQLException { - return getFloat(findColumn(col)); } - - public int getInt(int col) throws SQLException { - return db.column_int(stmt.pointer, markCol(col)); } - public int getInt(String col) throws SQLException { - return getInt(findColumn(col)); } - - public long getLong(int col) throws SQLException { - return db.column_long(stmt.pointer, markCol(col)); } - public long getLong(String col) throws SQLException { - return getLong(findColumn(col)); } - - public short getShort(int col) throws SQLException { - return (short)getInt(col); } - public short getShort(String col) throws SQLException { - return getShort(findColumn(col)); } - - public String getString(int col) throws SQLException { - return db.column_text(stmt.pointer, markCol(col)); } - public String getString(String col) throws SQLException { - return getString(findColumn(col)); } - - public Time getTime(int col) throws SQLException { - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return null; - return new Time(db.column_long(stmt.pointer, markCol(col))); } - public Time getTime(int col, Calendar cal) throws SQLException { - if (cal == null) return getTime(col); - if (db.column_type(stmt.pointer, markCol(col)) == SQLITE_NULL) - return null; - cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col))); - return new Time(cal.getTime().getTime()); - } - public Time getTime(String col) throws SQLException { - return getTime(findColumn(col)); } - public Time getTime(String col, Calendar cal) throws SQLException { - return getTime(findColumn(col), cal); } - - public Timestamp getTimestamp(int col) throws SQLException { - return new Timestamp(db.column_long(stmt.pointer, markCol(col))); } - public Timestamp getTimestamp(int col, Calendar cal) throws SQLException { - if (cal == null) return getTimestamp(col); - cal.setTimeInMillis(db.column_long(stmt.pointer, markCol(col))); - return new Timestamp(cal.getTime().getTime()); - } - public Timestamp getTimestamp(String col) throws SQLException { - return getTimestamp(findColumn(col)); } - public Timestamp getTimestamp(String c, Calendar ca) throws SQLException { - return getTimestamp(findColumn(c), ca); } - - public Object getObject(int col) throws SQLException { - switch (db.column_type(stmt.pointer, checkCol(col))) { - case SQLITE_INTEGER: - long val = getLong(col); - if (val > (long)Integer.MAX_VALUE - || val < (long)Integer.MIN_VALUE) - return new Long(val); - else - return new Integer((int)val); - case SQLITE_FLOAT: return new Double(getDouble(col)); - case SQLITE_BLOB: return getBytes(col); - case SQLITE_NULL: return null; - case SQLITE_TEXT: - default: - return getString(col); - } - } - public Object getObject(String col) throws SQLException { - return getObject(findColumn(col)); } - - public Statement getStatement() { return stmt; } - public String getCursorName() throws SQLException { return null; } - public SQLWarning getWarnings() throws SQLException { return null; } - public void clearWarnings() throws SQLException {} - - // ResultSetMetaData Functions ////////////////////////////////// - - // we do not need to check the RS is open, only that colsMeta - // is not null, done with checkCol(int). - - public ResultSetMetaData getMetaData() throws SQLException { - return this; } - - public String getCatalogName(int col) throws SQLException { - return db.column_table_name(stmt.pointer, checkCol(col)); } - public String getColumnClassName(int col) throws SQLException { - checkCol(col); return "java.lang.Object"; } - public int getColumnCount() throws SQLException { - checkCol(1); return colsMeta.length; - } - public int getColumnDisplaySize(int col) throws SQLException { - return Integer.MAX_VALUE; } - public String getColumnLabel(int col) throws SQLException { - return getColumnName(col); } - public String getColumnName(int col) throws SQLException { - return db.column_name(stmt.pointer, checkCol(col)); } - public int getColumnType(int col) throws SQLException { - switch (db.column_type(stmt.pointer, checkCol(col))) { - case SQLITE_INTEGER: return Types.INTEGER; - case SQLITE_FLOAT: return Types.FLOAT; - case SQLITE_BLOB: return Types.BLOB; - case SQLITE_NULL: return Types.NULL; - case SQLITE_TEXT: - default: - return Types.VARCHAR; - } - } - public String getColumnTypeName(int col) throws SQLException { - return db.column_decltype(stmt.pointer, checkCol(col)); - } - public int getPrecision(int col) throws SQLException { return 0; } // FIXME - public int getScale(int col) throws SQLException { return 0; } - public String getSchemaName(int col) throws SQLException { return ""; } - public String getTableName(int col) throws SQLException { - return db.column_table_name(stmt.pointer, checkCol(col)); } - public int isNullable(int col) throws SQLException { - checkMeta(); - return meta[checkCol(col)][1] ? columnNoNulls: columnNullable; - } - public boolean isAutoIncrement(int col) throws SQLException { - checkMeta(); return meta[checkCol(col)][2]; } - public boolean isCaseSensitive(int col) throws SQLException { return true; } - public boolean isCurrency(int col) throws SQLException { return false; } - public boolean isDefinitelyWritable(int col) throws SQLException { - return true; } // FIXME: check db file constraints? - public boolean isReadOnly(int col) throws SQLException { return false; } - public boolean isSearchable(int col) throws SQLException { return true; } - public boolean isSigned(int col) throws SQLException { return false; } - public boolean isWritable(int col) throws SQLException { return true; } - - public int getConcurrency() throws SQLException { return CONCUR_READ_ONLY; } - - public boolean rowDeleted() throws SQLException { return false; } - public boolean rowInserted() throws SQLException { return false; } - public boolean rowUpdated() throws SQLException { return false; } -} diff --git a/sqlitejdbc/src/org/sqlite/Stmt.java b/sqlitejdbc/src/org/sqlite/Stmt.java deleted file mode 100644 index c5980b8..0000000 --- a/sqlitejdbc/src/org/sqlite/Stmt.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ -package org.sqlite; - -import java.sql.*; -import java.util.ArrayList; - -class Stmt extends Unused implements Statement, Codes -{ - final Conn conn; - final DB db; - final RS rs; - - long pointer; - String sql = null; - - int batchPos; - Object[] batch = null; - boolean resultsWaiting = false; - - Stmt(Conn c) { - conn = c; - db = conn.db(); - rs = new RS(this); - } - - protected final void checkOpen() throws SQLException { - if (pointer == 0) throw new SQLException("statement is not executing"); - } - boolean isOpen() throws SQLException { - return (pointer != 0); - } - - /** Calls sqlite3_step() and sets up results. Expects a clean stmt. */ - protected boolean exec() throws SQLException { - if (sql == null) throw new SQLException( - "SQLiteJDBC internal error: sql==null"); - if (rs.isOpen()) throw new SQLException( - "SQLite JDBC internal error: rs.isOpen() on exec."); - - boolean rc = false; - try { - rc = db.execute(this, null); - } finally { - resultsWaiting = rc; - } - - return db.column_count(pointer) != 0; - } - - - // PUBLIC INTERFACE ///////////////////////////////////////////// - - public void close() throws SQLException { - if (pointer == 0) return; - rs.close(); - batch = null; - batchPos = 0; - int resp = db.finalize(this); - if (resp != SQLITE_OK && resp != SQLITE_MISUSE) - db.throwex(); - } - - protected void finalize() throws SQLException { close(); } - - public boolean execute(String sql) throws SQLException { - close(); - this.sql = sql; - db.prepare(this); - return exec(); - } - - public ResultSet executeQuery(String sql) throws SQLException { - close(); - this.sql = sql; - db.prepare(this); - if (!exec()) { - close(); - throw new SQLException("query does not return ResultSet"); - } - return getResultSet(); - } - - public int executeUpdate(String sql) throws SQLException { - close(); - this.sql = sql; - int changes = 0; - try { - db.prepare(this); - changes = db.executeUpdate(this, null); - } finally { close(); } - return changes; - } - - public ResultSet getResultSet() throws SQLException { - checkOpen(); - if (rs.isOpen()) throw new SQLException("ResultSet already requested"); - if (db.column_count(pointer) == 0) throw new SQLException( - "no ResultSet available"); - if (rs.colsMeta == null) - rs.colsMeta = db.column_names(pointer); - rs.cols = rs.colsMeta; - - rs.open = resultsWaiting; - resultsWaiting = false; - return rs; - } - - /* - * This function has a complex behaviour best understood by carefully - * reading the JavaDoc for getMoreResults() and considering the test - * StatementTest.execute(). - */ - public int getUpdateCount() throws SQLException { - if (pointer != 0 - && !rs.isOpen() - && !resultsWaiting - && db.column_count(pointer) == 0) - return db.changes(); - return -1; - } - - public void addBatch(String sql) throws SQLException { - close(); - if (batch == null || batchPos + 1 >= batch.length) - batch = new Object[Math.max(10, batchPos * 2)]; - batch[batchPos++] = sql; - } - - public void clearBatch() throws SQLException { - batchPos = 0; - if (batch != null) - for (int i=0; i < batch.length; i++) - batch[i] = null; - } - - public int[] executeBatch() throws SQLException { - // TODO: optimise - close(); - if (batch == null || batchPos == 0) return new int[] {}; - - int[] changes = new int[batchPos]; - - synchronized (db) { try { - for (int i=0; i < changes.length; i++) { - try { - this.sql = (String)batch[i]; - db.prepare(this); - changes[i] = db.executeUpdate(this, null); - } catch (SQLException e) { - throw new BatchUpdateException( - "batch entry " + i + ": " + e.getMessage(), changes); - } finally { - db.finalize(this); - } - } - } finally { - clearBatch(); - } } - - return changes; - } - - public void setCursorName(String name) {} - - public SQLWarning getWarnings() throws SQLException { return null; } - public void clearWarnings() throws SQLException {} - - public Connection getConnection() throws SQLException { - return conn; } - - public void cancel() throws SQLException { rs.checkOpen(); db.interrupt(); } - public int getQueryTimeout() throws SQLException { - return conn.getTimeout(); } - public void setQueryTimeout(int seconds) throws SQLException { - if (seconds < 0) throw new SQLException("query timeout must be >= 0"); - conn.setTimeout(1000 * seconds); - } - - // TODO: write test - public int getMaxRows() throws SQLException { - checkOpen(); - return rs.maxRows; - } - public void setMaxRows(int max) throws SQLException { - checkOpen(); - if (max < 0) throw new SQLException("max row count must be >= 0"); - rs.maxRows = max; - } - - public int getMaxFieldSize() throws SQLException { return 0; } - public void setMaxFieldSize(int max) throws SQLException { - if (max < 0) throw new SQLException( - "max field size "+max+" cannot be negative"); - } - - public int getFetchSize() throws SQLException { return rs.getFetchSize(); } - public void setFetchSize(int r) throws SQLException { rs.setFetchSize(r); } - public int getFetchDirection() throws SQLException { - return rs.getFetchDirection(); - } - public void setFetchDirection(int d) throws SQLException { - rs.setFetchDirection(d); - } - - /** As SQLite's last_insert_rowid() function is DB-specific not - * statement specific, this function introduces a race condition - * if the same connection is used by two threads and both insert. */ - public ResultSet getGeneratedKeys() throws SQLException { - return ((MetaData)conn.getMetaData()).getGeneratedKeys(); - } - - /** SQLite does not support multiple results from execute(). */ - public boolean getMoreResults() throws SQLException { - return getMoreResults(0); - } - public boolean getMoreResults(int c) throws SQLException { - checkOpen(); - close(); // as we never have another result, clean up pointer - return false; - } - - public int getResultSetConcurrency() throws SQLException { - return ResultSet.CONCUR_READ_ONLY; } - public int getResultSetHoldability() throws SQLException { - return ResultSet.CLOSE_CURSORS_AT_COMMIT; } - public int getResultSetType() throws SQLException { - return ResultSet.TYPE_FORWARD_ONLY; } -} diff --git a/sqlitejdbc/src/org/sqlite/Unused.java b/sqlitejdbc/src/org/sqlite/Unused.java deleted file mode 100644 index 1957699..0000000 --- a/sqlitejdbc/src/org/sqlite/Unused.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * Copyright (c) 2007 David Crawshaw - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package org.sqlite; - -import java.io.*; -import java.math.*; -import java.net.*; -import java.sql.*; -import java.util.Map; - -/** Unused JDBC functions from Statement, PreparedStatement and ResultSet. */ -abstract class Unused -{ - private SQLException unused() { - return new SQLException("not implemented by SQLite JDBC driver"); - } - - - // Statement //////////////////////////////////////////////////// - - public void setEscapeProcessing(boolean enable) - throws SQLException { throw unused(); } - public boolean execute(String sql, int[] colinds) - throws SQLException { throw unused(); } - public boolean execute(String sql, String[] colnames) - throws SQLException { throw unused(); } - public int executeUpdate(String sql, int autoKeys) - throws SQLException { throw unused(); } - public int executeUpdate(String sql, int[] colinds) - throws SQLException { throw unused(); } - public int executeUpdate(String sql, String[] cols) - throws SQLException { throw unused(); } - public boolean execute(String sql, int autokeys) - throws SQLException { throw unused(); } - - - // PreparedStatement //////////////////////////////////////////// - - public void setArray(int i, Array x) - throws SQLException { throw unused(); } - public void setAsciiStream(int parameterIndex, InputStream x, int length) - throws SQLException { throw unused(); } - public void setBigDecimal(int parameterIndex, BigDecimal x) - throws SQLException { throw unused(); } - public void setBinaryStream(int parameterIndex, InputStream x, int length) - throws SQLException { throw unused(); } - public void setBlob(int i, Blob x) - throws SQLException { throw unused(); } - public void setCharacterStream(int pos, Reader reader, int length) - throws SQLException { throw unused(); } - public void setClob(int i, Clob x) - throws SQLException { throw unused(); } - public void setRef(int i, Ref x) - throws SQLException { throw unused(); } - public void setUnicodeStream(int pos, InputStream x, int length) - throws SQLException { throw unused(); } - public void setURL(int pos, URL x) - throws SQLException { throw unused(); } - - - // ResultSet //////////////////////////////////////////////////// - - public Array getArray(int i) - throws SQLException { throw unused(); } - public Array getArray(String col) - throws SQLException { throw unused(); } - public InputStream getAsciiStream(int col) - throws SQLException { throw unused(); } - public InputStream getAsciiStream(String col) - throws SQLException { throw unused(); } - public BigDecimal getBigDecimal(int col) - throws SQLException { throw unused(); } - public BigDecimal getBigDecimal(int col, int s) - throws SQLException { throw unused(); } - public BigDecimal getBigDecimal(String col) - throws SQLException { throw unused(); } - public BigDecimal getBigDecimal(String col, int s) - throws SQLException { throw unused(); } - public InputStream getBinaryStream(int col) - throws SQLException { throw unused(); } - public InputStream getBinaryStream(String col) - throws SQLException { throw unused(); } - public Blob getBlob(int col) - throws SQLException { throw unused(); } - public Blob getBlob(String col) - throws SQLException { throw unused(); } - public Reader getCharacterStream(int col) - throws SQLException { throw unused(); } - public Reader getCharacterStream(String col) - throws SQLException { throw unused(); } - public Clob getClob(int col) - throws SQLException { throw unused(); } - public Clob getClob(String col) - throws SQLException { throw unused(); } - public Object getObject(int col, Map map) - throws SQLException { throw unused(); } - public Object getObject(String col, Map map) - throws SQLException { throw unused(); } - public Ref getRef(int i) - throws SQLException { throw unused(); } - public Ref getRef(String col) - throws SQLException { throw unused(); } - - public InputStream getUnicodeStream(int col) - throws SQLException { throw unused(); } - public InputStream getUnicodeStream(String col) - throws SQLException { throw unused(); } - public URL getURL(int col) - throws SQLException { throw unused(); } - public URL getURL(String col) - throws SQLException { throw unused(); } - - public void insertRow() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public void moveToCurrentRow() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public void moveToInsertRow() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public boolean last() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public boolean previous() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public boolean relative(int rows) throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public boolean absolute(int row) throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public void afterLast() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public void beforeFirst() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - public boolean first() throws SQLException { - throw new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } - - public void cancelRowUpdates() - throws SQLException { throw unused(); } - public void deleteRow() - throws SQLException { throw unused(); } - - public void updateArray(int col, Array x) - throws SQLException { throw unused(); } - public void updateArray(String col, Array x) - throws SQLException { throw unused(); } - public void updateAsciiStream(int col, InputStream x, int l) - throws SQLException { throw unused(); } - public void updateAsciiStream(String col, InputStream x, int l) - throws SQLException { throw unused(); } - public void updateBigDecimal(int col, BigDecimal x) - throws SQLException { throw unused(); } - public void updateBigDecimal(String col, BigDecimal x) - throws SQLException { throw unused(); } - public void updateBinaryStream(int c, InputStream x, int l) - throws SQLException { throw unused(); } - public void updateBinaryStream(String c, InputStream x, int l) - throws SQLException { throw unused(); } - public void updateBlob(int col, Blob x) - throws SQLException { throw unused(); } - public void updateBlob(String col, Blob x) - throws SQLException { throw unused(); } - public void updateBoolean(int col, boolean x) - throws SQLException { throw unused(); } - public void updateBoolean(String col, boolean x) - throws SQLException { throw unused(); } - public void updateByte(int col, byte x) - throws SQLException { throw unused(); } - public void updateByte(String col, byte x) - throws SQLException { throw unused(); } - public void updateBytes(int col, byte[] x) - throws SQLException { throw unused(); } - public void updateBytes(String col, byte[] x) - throws SQLException { throw unused(); } - public void updateCharacterStream(int c, Reader x, int l) - throws SQLException { throw unused(); } - public void updateCharacterStream(String c, Reader r, int l) - throws SQLException { throw unused(); } - public void updateClob(int col, Clob x) - throws SQLException { throw unused(); } - public void updateClob(String col, Clob x) - throws SQLException { throw unused(); } - public void updateDate(int col, Date x) - throws SQLException { throw unused(); } - public void updateDate(String col, Date x) - throws SQLException { throw unused(); } - public void updateDouble(int col, double x) - throws SQLException { throw unused(); } - public void updateDouble(String col, double x) - throws SQLException { throw unused(); } - public void updateFloat(int col, float x) - throws SQLException { throw unused(); } - public void updateFloat(String col, float x) - throws SQLException { throw unused(); } - public void updateInt(int col, int x) - throws SQLException { throw unused(); } - public void updateInt(String col, int x) - throws SQLException { throw unused(); } - public void updateLong(int col, long x) - throws SQLException { throw unused(); } - public void updateLong(String col, long x) - throws SQLException { throw unused(); } - public void updateNull(int col) - throws SQLException { throw unused(); } - public void updateNull(String col) - throws SQLException { throw unused(); } - public void updateObject(int c, Object x) - throws SQLException { throw unused(); } - public void updateObject(int c, Object x, int s) - throws SQLException { throw unused(); } - public void updateObject(String col, Object x) - throws SQLException { throw unused(); } - public void updateObject(String c, Object x, int s) - throws SQLException { throw unused(); } - public void updateRef(int col, Ref x) - throws SQLException { throw unused(); } - public void updateRef(String c, Ref x) - throws SQLException { throw unused(); } - public void updateRow() - throws SQLException { throw unused(); } - public void updateShort(int c, short x) - throws SQLException { throw unused(); } - public void updateShort(String c, short x) - throws SQLException { throw unused(); } - public void updateString(int c, String x) - throws SQLException { throw unused(); } - public void updateString(String c, String x) - throws SQLException { throw unused(); } - public void updateTime(int c, Time x) - throws SQLException { throw unused(); } - public void updateTime(String c, Time x) - throws SQLException { throw unused(); } - public void updateTimestamp(int c, Timestamp x) - throws SQLException { throw unused(); } - public void updateTimestamp(String c, Timestamp x) - throws SQLException { throw unused(); } - - public void refreshRow() - throws SQLException { throw unused(); } -} diff --git a/sqlitejdbc/src/test/ConnectionTest.java b/sqlitejdbc/src/test/ConnectionTest.java deleted file mode 100644 index e78f9ea..0000000 --- a/sqlitejdbc/src/test/ConnectionTest.java +++ /dev/null @@ -1,45 +0,0 @@ -package test; - -import java.io.File; -import java.sql.*; -import org.junit.*; -import static org.junit.Assert.*; - -/** These tests check whether access to files is woring correctly and - * some Connection.close() cases. */ -public class ConnectionTest -{ - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Test public void openMemory() throws SQLException { - Connection conn = DriverManager.getConnection("jdbc:sqlite:"); - conn.close(); - } - - @Test public void isClosed() throws SQLException { - Connection conn = DriverManager.getConnection("jdbc:sqlite:"); - conn.close(); - assertTrue(conn.isClosed()); - } - - @Test public void openFile() throws SQLException { - File testdb = new File("test.db"); - if (testdb.exists()) testdb.delete(); - assertFalse(testdb.exists()); - Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db"); - conn.close(); - assertTrue(testdb.exists()); - testdb.delete(); - } - - @Test(expected= SQLException.class) - public void closeTest() throws SQLException { - Connection conn = DriverManager.getConnection("jdbc:sqlite:"); - PreparedStatement prep = conn.prepareStatement("select null;"); - ResultSet rs = prep.executeQuery(); - conn.close(); - prep.clearParameters(); - } -} diff --git a/sqlitejdbc/src/test/DBMetaDataTest.java b/sqlitejdbc/src/test/DBMetaDataTest.java deleted file mode 100644 index e6f7992..0000000 --- a/sqlitejdbc/src/test/DBMetaDataTest.java +++ /dev/null @@ -1,413 +0,0 @@ -package test; - -import java.sql.*; -import org.junit.*; -import static org.junit.Assert.*; - -/** These tests are designed to stress Statements on memory databases. */ -public class DBMetaDataTest -{ - private Connection conn; - private Statement stat; - private DatabaseMetaData meta; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - conn = DriverManager.getConnection("jdbc:sqlite:"); - stat = conn.createStatement(); - stat.executeUpdate( - "create table test (id integer primary key, fn, sn);"); - stat.executeUpdate("create view testView as select * from test;"); - meta = conn.getMetaData(); - } - - @After public void close() throws SQLException { - meta = null; - stat.close(); - conn.close(); - } - - @Test public void getTables() throws SQLException { - ResultSet rs = meta.getTables(null, null, null, null); - assertNotNull(rs); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "TEST"); // 3 - assertEquals(rs.getString("TABLE_TYPE"), "TABLE"); // 4 - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "TESTVIEW"); - assertEquals(rs.getString("TABLE_TYPE"), "VIEW"); - rs.close(); - - rs = meta.getTables(null, null, "bob", null); - assertFalse(rs.next()); - rs.close(); - rs = meta.getTables(null, null, "test", null); - assertTrue(rs.next()); - assertFalse(rs.next()); - rs.close(); - rs = meta.getTables(null, null, "test%", null); - assertTrue(rs.next()); - assertTrue(rs.next()); - rs.close(); - - rs = meta.getTables(null, null, null, new String[] { "table" }); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "TEST"); - assertFalse(rs.next()); - rs.close(); - - rs = meta.getTables(null, null, null, new String[] { "view" }); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "TESTVIEW"); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void getTableTypes() throws SQLException { - ResultSet rs = meta.getTableTypes(); - assertNotNull(rs); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_TYPE"), "TABLE"); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_TYPE"), "VIEW"); - assertFalse(rs.next()); - } - - @Test public void getTypeInfo() throws SQLException { - ResultSet rs = meta.getTypeInfo(); - assertNotNull(rs); - assertTrue(rs.next()); - assertEquals(rs.getString("TYPE_NAME"), "BLOB"); - assertTrue(rs.next()); - assertEquals(rs.getString("TYPE_NAME"), "INTEGER"); - assertTrue(rs.next()); - assertEquals(rs.getString("TYPE_NAME"), "NULL"); - assertTrue(rs.next()); - assertEquals(rs.getString("TYPE_NAME"), "REAL"); - assertTrue(rs.next()); - assertEquals(rs.getString("TYPE_NAME"), "TEXT"); - assertFalse(rs.next()); - } - - @Test public void getColumns() throws SQLException { - ResultSet rs = meta.getColumns(null, null, "test", "id"); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "test"); - assertEquals(rs.getString("COLUMN_NAME"), "id"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "test", "fn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "fn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "test", "sn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "sn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "test", "%"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "id"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "fn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "sn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "test", "%n"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "fn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "sn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "test%", "%"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "id"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "fn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "sn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "%", "%"); - assertTrue(rs.next()); - assertEquals(rs.getString("TABLE_NAME"), "test"); - assertEquals(rs.getString("COLUMN_NAME"), "id"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "fn"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "sn"); - assertFalse(rs.next()); - - rs = meta.getColumns(null, null, "doesnotexist", "%"); - assertFalse(rs.next()); - } - - @Test public void columnOrderOfgetTables() throws SQLException { - ResultSet rs = meta.getTables(null, null, null, null); - assertTrue(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 10); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TABLE_NAME"); - assertEquals(rsmeta.getColumnName(4), "TABLE_TYPE"); - assertEquals(rsmeta.getColumnName(5), "REMARKS"); - assertEquals(rsmeta.getColumnName(6), "TYPE_CAT"); - assertEquals(rsmeta.getColumnName(7), "TYPE_SCHEM"); - assertEquals(rsmeta.getColumnName(8), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(9), "SELF_REFERENCING_COL_NAME"); - assertEquals(rsmeta.getColumnName(10), "REF_GENERATION"); - } - - @Test public void columnOrderOfgetTableTypes() throws SQLException { - ResultSet rs = meta.getTableTypes(); - assertTrue(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 1); - assertEquals(rsmeta.getColumnName(1), "TABLE_TYPE"); - } - - @Test public void columnOrderOfgetTypeInfo() throws SQLException { - ResultSet rs = meta.getTypeInfo(); - assertTrue(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 18); - assertEquals(rsmeta.getColumnName(1), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(2), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(3), "PRECISION"); - assertEquals(rsmeta.getColumnName(4), "LITERAL_PREFIX"); - assertEquals(rsmeta.getColumnName(5), "LITERAL_SUFFIX"); - assertEquals(rsmeta.getColumnName(6), "CREATE_PARAMS"); - assertEquals(rsmeta.getColumnName(7), "NULLABLE"); - assertEquals(rsmeta.getColumnName(8), "CASE_SENSITIVE"); - assertEquals(rsmeta.getColumnName(9), "SEARCHABLE"); - assertEquals(rsmeta.getColumnName(10), "UNSIGNED_ATTRIBUTE"); - assertEquals(rsmeta.getColumnName(11), "FIXED_PREC_SCALE"); - assertEquals(rsmeta.getColumnName(12), "AUTO_INCREMENT"); - assertEquals(rsmeta.getColumnName(13), "LOCAL_TYPE_NAME"); - assertEquals(rsmeta.getColumnName(14), "MINIMUM_SCALE"); - assertEquals(rsmeta.getColumnName(15), "MAXIMUM_SCALE"); - assertEquals(rsmeta.getColumnName(16), "SQL_DATA_TYPE"); - assertEquals(rsmeta.getColumnName(17), "SQL_DATETIME_SUB"); - assertEquals(rsmeta.getColumnName(18), "NUM_PREC_RADIX"); - } - - @Test public void columnOrderOfgetColumns() throws SQLException { - ResultSet rs = meta.getColumns(null, null, "test", null); - assertTrue(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 22); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TABLE_NAME"); - assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(5), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(6), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(7), "COLUMN_SIZE"); - assertEquals(rsmeta.getColumnName(8), "BUFFER_LENGTH"); - assertEquals(rsmeta.getColumnName(9), "DECIMAL_DIGITS"); - assertEquals(rsmeta.getColumnName(10), "NUM_PREC_RADIX"); - assertEquals(rsmeta.getColumnName(11), "NULLABLE"); - assertEquals(rsmeta.getColumnName(12), "REMARKS"); - assertEquals(rsmeta.getColumnName(13), "COLUMN_DEF"); - assertEquals(rsmeta.getColumnName(14), "SQL_DATA_TYPE"); - assertEquals(rsmeta.getColumnName(15), "SQL_DATETIME_SUB"); - assertEquals(rsmeta.getColumnName(16), "CHAR_OCTET_LENGTH"); - assertEquals(rsmeta.getColumnName(17), "ORDINAL_POSITION"); - assertEquals(rsmeta.getColumnName(18), "IS_NULLABLE"); - // should be SCOPE_CATALOG, but misspelt in the standard - assertEquals(rsmeta.getColumnName(19), "SCOPE_CATLOG"); - assertEquals(rsmeta.getColumnName(20), "SCOPE_SCHEMA"); - assertEquals(rsmeta.getColumnName(21), "SCOPE_TABLE"); - assertEquals(rsmeta.getColumnName(22), "SOURCE_DATA_TYPE"); - } - - // the following functions always return an empty resultset, so - // do not bother testing their parameters, only the column types - - @Test public void columnOrderOfgetProcedures() throws SQLException { - ResultSet rs = meta.getProcedures(null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 8); - assertEquals(rsmeta.getColumnName(1), "PROCEDURE_CAT"); - assertEquals(rsmeta.getColumnName(2), "PROCEDURE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "PROCEDURE_NAME"); - // currently (Java 1.5), cols 4,5,6 are undefined - assertEquals(rsmeta.getColumnName(7), "REMARKS"); - assertEquals(rsmeta.getColumnName(8), "PROCEDURE_TYPE"); - } - - @Test public void columnOrderOfgetProcedurColumns() throws SQLException { - ResultSet rs = meta.getProcedureColumns(null, null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 13); - assertEquals(rsmeta.getColumnName(1), "PROCEDURE_CAT"); - assertEquals(rsmeta.getColumnName(2), "PROCEDURE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "PROCEDURE_NAME"); - assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(5), "COLUMN_TYPE"); - assertEquals(rsmeta.getColumnName(6), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(7), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(8), "PRECISION"); - assertEquals(rsmeta.getColumnName(9), "LENGTH"); - assertEquals(rsmeta.getColumnName(10), "SCALE"); - assertEquals(rsmeta.getColumnName(11), "RADIX"); - assertEquals(rsmeta.getColumnName(12), "NULLABLE"); - assertEquals(rsmeta.getColumnName(13), "REMARKS"); - } - - @Test public void columnOrderOfgetSchemas() throws SQLException { - ResultSet rs = meta.getSchemas(); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 2); - assertEquals(rsmeta.getColumnName(1), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(2), "TABLE_CATALOG"); - } - - @Test public void columnOrderOfgetCatalogs() throws SQLException { - ResultSet rs = meta.getCatalogs(); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 1); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - } - - @Test public void columnOrderOfgetColumnPrivileges() throws SQLException { - ResultSet rs = meta.getColumnPrivileges(null, null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 8); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TABLE_NAME"); - assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(5), "GRANTOR"); - assertEquals(rsmeta.getColumnName(6), "GRANTEE"); - assertEquals(rsmeta.getColumnName(7), "PRIVILEGE"); - assertEquals(rsmeta.getColumnName(8), "IS_GRANTABLE"); - } - - @Test public void columnOrderOfgetTablePrivileges() throws SQLException { - ResultSet rs = meta.getTablePrivileges(null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 7); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TABLE_NAME"); - assertEquals(rsmeta.getColumnName(4), "GRANTOR"); - assertEquals(rsmeta.getColumnName(5), "GRANTEE"); - assertEquals(rsmeta.getColumnName(6), "PRIVILEGE"); - assertEquals(rsmeta.getColumnName(7), "IS_GRANTABLE"); - } - - @Test public void columnOrderOfgetBestRowIdentifier() throws SQLException { - ResultSet rs = meta.getBestRowIdentifier(null, null, null, 0, false); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 8); - assertEquals(rsmeta.getColumnName(1), "SCOPE"); - assertEquals(rsmeta.getColumnName(2), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(3), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(4), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(5), "COLUMN_SIZE"); - assertEquals(rsmeta.getColumnName(6), "BUFFER_LENGTH"); - assertEquals(rsmeta.getColumnName(7), "DECIMAL_DIGITS"); - assertEquals(rsmeta.getColumnName(8), "PSEUDO_COLUMN"); - } - - @Test public void columnOrderOfgetVersionColumns() throws SQLException { - ResultSet rs = meta.getVersionColumns(null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 8); - assertEquals(rsmeta.getColumnName(1), "SCOPE"); - assertEquals(rsmeta.getColumnName(2), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(3), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(4), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(5), "COLUMN_SIZE"); - assertEquals(rsmeta.getColumnName(6), "BUFFER_LENGTH"); - assertEquals(rsmeta.getColumnName(7), "DECIMAL_DIGITS"); - assertEquals(rsmeta.getColumnName(8), "PSEUDO_COLUMN"); - } - - @Test public void columnOrderOfgetPrimaryKeys() throws SQLException { - ResultSet rs; - ResultSetMetaData rsmeta; - - stat.executeUpdate("create table nopk (c1, c2, c3, c4);"); - stat.executeUpdate("create table pk1 (col1 primary key, col2, col3);"); - stat.executeUpdate("create table pk2 (col1, col2 primary key, col3);"); - stat.executeUpdate("create table pk3 (col1, col2, col3, col4, " - + "primary key (col2, col3));"); - - rs = meta.getPrimaryKeys(null, null, "nopk"); - assertFalse(rs.next()); - rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 6); - assertEquals(rsmeta.getColumnName(1), "TABLE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TABLE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TABLE_NAME"); - assertEquals(rsmeta.getColumnName(4), "COLUMN_NAME"); - assertEquals(rsmeta.getColumnName(5), "KEY_SEQ"); - assertEquals(rsmeta.getColumnName(6), "PK_NAME"); - rs.close(); - - rs = meta.getPrimaryKeys(null, null, "pk1"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "col1"); - assertFalse(rs.next()); - rs.close(); - - rs = meta.getPrimaryKeys(null, null, "pk2"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "col2"); - assertFalse(rs.next()); - rs.close(); - - rs = meta.getPrimaryKeys(null, null, "pk3"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "col2"); - assertTrue(rs.next()); - assertEquals(rs.getString("COLUMN_NAME"), "col3"); - assertFalse(rs.next()); - rs.close(); - } - - /* TODO - @Test public void columnOrderOfgetImportedKeys() throws SQLException { - @Test public void columnOrderOfgetExportedKeys() throws SQLException { - @Test public void columnOrderOfgetCrossReference() throws SQLException { - @Test public void columnOrderOfgetTypeInfo() throws SQLException { - @Test public void columnOrderOfgetIndexInfo() throws SQLException { - @Test public void columnOrderOfgetSuperTypes() throws SQLException { - @Test public void columnOrderOfgetSuperTables() throws SQLException { - @Test public void columnOrderOfgetAttributes() throws SQLException {*/ - - @Test public void columnOrderOfgetUDTs() throws SQLException { - ResultSet rs = meta.getUDTs(null, null, null, null); - assertFalse(rs.next()); - ResultSetMetaData rsmeta = rs.getMetaData(); - assertEquals(rsmeta.getColumnCount(), 7); - assertEquals(rsmeta.getColumnName(1), "TYPE_CAT"); - assertEquals(rsmeta.getColumnName(2), "TYPE_SCHEM"); - assertEquals(rsmeta.getColumnName(3), "TYPE_NAME"); - assertEquals(rsmeta.getColumnName(4), "CLASS_NAME"); - assertEquals(rsmeta.getColumnName(5), "DATA_TYPE"); - assertEquals(rsmeta.getColumnName(6), "REMARKS"); - assertEquals(rsmeta.getColumnName(7), "BASE_TYPE"); - } - - @Test public void version() throws SQLException { - assertNotNull(meta.getDatabaseProductVersion()); - } -} diff --git a/sqlitejdbc/src/test/PrepStmtTest.java b/sqlitejdbc/src/test/PrepStmtTest.java deleted file mode 100644 index 5229da6..0000000 --- a/sqlitejdbc/src/test/PrepStmtTest.java +++ /dev/null @@ -1,487 +0,0 @@ -package test; - -import java.sql.*; -import java.util.StringTokenizer; -import org.junit.*; -import static org.junit.Assert.*; - -/** These tests are designed to stress PreparedStatements on memory dbs. */ -public class PrepStmtTest -{ - static byte[] b1 = new byte[] { 1,2,7,4,2,6,2,8,5,2,3,1,5,3,6,3,3,6,2,5 }; - static byte[] b2 = "To be or not to be.".getBytes(); - static byte[] b3 = "Question!#$%".getBytes(); - static String utf01 = "\uD840\uDC40"; - static String utf02 = "\uD840\uDC47 "; - static String utf03 = " \uD840\uDC43"; - static String utf04 = " \uD840\uDC42 "; - static String utf05 = "\uD840\uDC40\uD840\uDC44"; - static String utf06 = "Hello World, \uD840\uDC40 \uD880\uDC99"; - static String utf07 = "\uD840\uDC41 testing \uD880\uDC99"; - static String utf08 = "\uD840\uDC40\uD840\uDC44 testing"; - - private Connection conn; - private Statement stat; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - conn = DriverManager.getConnection("jdbc:sqlite:"); - stat = conn.createStatement(); - } - - @After public void close() throws SQLException { - stat.close(); - conn.close(); - } - - @Test public void update() throws SQLException { - assertEquals(conn.prepareStatement( - "create table s1 (c1);").executeUpdate(), 0); - PreparedStatement prep = conn.prepareStatement( - "insert into s1 values (?);"); - prep.setInt(1, 3); assertEquals(prep.executeUpdate(), 1); - prep.setInt(1, 5); assertEquals(prep.executeUpdate(), 1); - prep.setInt(1, 7); assertEquals(prep.executeUpdate(), 1); - prep.close(); - - // check results with normal statement - ResultSet rs = stat.executeQuery("select sum(c1) from s1;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 15); - rs.close(); - } - - @Test public void multiUpdate() throws SQLException { - stat.executeUpdate("create table test (c1);"); - PreparedStatement prep = conn.prepareStatement( - "insert into test values (?);"); - - for (int i=0; i < 10; i++) { - prep.setInt(1, i); - prep.executeUpdate(); - prep.execute(); - } - - prep.close(); - stat.executeUpdate("drop table test;"); - } - - @Test public void emptyRS() throws SQLException { - PreparedStatement prep = conn.prepareStatement("select null limit 0;"); - ResultSet rs = prep.executeQuery(); - assertFalse(rs.next()); - rs.close(); - prep.close(); - } - - @Test public void singleRowRS() throws SQLException { - PreparedStatement prep = conn.prepareStatement("select ?;"); - prep.setInt(1, Integer.MAX_VALUE); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), Integer.MAX_VALUE); - assertEquals(rs.getString(1), Integer.toString(Integer.MAX_VALUE)); - assertEquals(rs.getDouble(1), - new Integer(Integer.MAX_VALUE).doubleValue()); - assertFalse(rs.next()); - rs.close(); - prep.close(); - } - - @Test public void twoRowRS() throws SQLException { - PreparedStatement prep = conn.prepareStatement( - "select ? union all select ?;"); - prep.setDouble(1, Double.MAX_VALUE); - prep.setDouble(2, Double.MIN_VALUE); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getDouble(1), Double.MAX_VALUE); - assertTrue(rs.next()); - assertEquals(rs.getDouble(1), Double.MIN_VALUE); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void stringRS() throws SQLException { - String name = "Gandhi"; - PreparedStatement prep = conn.prepareStatement("select ?;"); - prep.setString(1, name); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), name); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void finalizePrep() throws SQLException { - conn.prepareStatement("select null;"); - System.gc(); - } - - @Test public void set() throws SQLException { - ResultSet rs; - PreparedStatement prep = conn.prepareStatement("select ?, ?, ?;"); - - // integers - prep.setInt(1, Integer.MIN_VALUE); - prep.setInt(2, Integer.MAX_VALUE); - prep.setInt(3, 0); - rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), Integer.MIN_VALUE); - assertEquals(rs.getInt(2), Integer.MAX_VALUE); - assertEquals(rs.getInt(3), 0); - - // strings - String name = "Winston Leonard Churchill"; - String fn = name.substring(0, 7), - mn = name.substring(8, 15), - sn = name.substring(16, 25); - prep.clearParameters(); - prep.setString(1, fn); - prep.setString(2, mn); - prep.setString(3, sn); - prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), fn); - assertEquals(rs.getString(2), mn); - assertEquals(rs.getString(3), sn); - - // mixed - prep.setString(1, name); - prep.setString(2, null); - prep.setLong(3, Long.MAX_VALUE); - prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), name); - assertNull(rs.getString(2)); - assertTrue(rs.wasNull()); - assertEquals(rs.getLong(3), Long.MAX_VALUE); - - // bytes - prep.setBytes(1, b1); - prep.setBytes(2, b2); - prep.setBytes(3, b3); - prep.executeQuery(); - assertTrue(rs.next()); - assertArrayEq(rs.getBytes(1), b1); - assertArrayEq(rs.getBytes(2), b2); - assertArrayEq(rs.getBytes(3), b3); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void colNameAccess() throws SQLException { - PreparedStatement prep = conn.prepareStatement( - "select ? as col1, ? as col2, ? as bingo;"); - prep.setNull(1, 0); - prep.setFloat(2, Float.MIN_VALUE); - prep.setShort(3, Short.MIN_VALUE); - prep.executeQuery(); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertNull(rs.getString("col1")); - assertTrue(rs.wasNull()); - assertEquals(rs.getFloat("col2"), Float.MIN_VALUE); - assertEquals(rs.getShort("bingo"), Short.MIN_VALUE); - rs.close(); - prep.close(); - } - - @Test public void insert1000() throws SQLException { - stat.executeUpdate("create table in1000 (a);"); - PreparedStatement prep = conn.prepareStatement( - "insert into in1000 values (?);"); - conn.setAutoCommit(false); - for (int i=0; i < 1000; i++) { - prep.setInt(1, i); - prep.executeUpdate(); - } - conn.commit(); - - ResultSet rs = stat.executeQuery("select count(a) from in1000;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1000); - rs.close(); - } - - @Ignore - @Test public void getObject() throws SQLException { - stat.executeUpdate("create table testobj (" - + "c1 integer, c2 float, c3, c4 varchar, c5 bit, c6, c7);"); - PreparedStatement prep = conn.prepareStatement( - "insert into testobj values (?,?,?,?,?,?,?);"); - - prep.setInt (1, Integer.MAX_VALUE); - prep.setFloat (2, Float.MAX_VALUE); - prep.setDouble (3, Double.MAX_VALUE); - prep.setLong (4, Long.MAX_VALUE); - prep.setBoolean(5, false); - prep.setByte (6, (byte)7); - prep.setBytes (7, b1); - prep.executeUpdate(); - - ResultSet rs = stat.executeQuery( - "select c1,c2,c3,c4,c5,c6,c7 from testobj;"); - assertTrue(rs.next()); - - assertEquals(rs.getInt(1), Integer.MAX_VALUE); - assertEquals((int)rs.getLong(1), Integer.MAX_VALUE); - assertEquals(rs.getFloat(2), Float.MAX_VALUE); - assertEquals(rs.getDouble(3), Double.MAX_VALUE); - assertEquals(rs.getLong(4), Long.MAX_VALUE); - assertFalse(rs.getBoolean(5)); - assertEquals(rs.getByte(6), (byte)7); - assertArrayEq(rs.getBytes(7), b1); - - assertNotNull(rs.getObject(1)); - assertNotNull(rs.getObject(2)); - assertNotNull(rs.getObject(3)); - assertNotNull(rs.getObject(4)); - assertNotNull(rs.getObject(5)); - assertNotNull(rs.getObject(6)); - assertNotNull(rs.getObject(7)); - assertTrue(rs.getObject(1) instanceof Integer); - assertTrue(rs.getObject(2) instanceof Double); - assertTrue(rs.getObject(3) instanceof Double); - assertTrue(rs.getObject(4) instanceof String); - assertTrue(rs.getObject(5) instanceof Integer); - assertTrue(rs.getObject(6) instanceof Integer); - assertTrue(rs.getObject(7) instanceof byte[]); - rs.close(); - } - - @Test public void tokens() throws SQLException { - /* checks for a bug where a substring is read by the driver as the - * full original string, caused by my idiocyin assuming the - * pascal-style string was null terminated. Thanks Oliver Randschau. */ - StringTokenizer st = new StringTokenizer("one two three"); - st.nextToken(); - String substr = st.nextToken(); - - PreparedStatement prep = conn.prepareStatement("select ?;"); - prep.setString(1, substr); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), substr); - } - - @Test public void utf() throws SQLException { - ResultSet rs = stat.executeQuery("select '" - +utf01+"','"+utf02+"','"+utf03+"','"+utf04+"','" - +utf05+"','"+utf06+"','"+utf07+"','"+utf08+"';"); - assertEquals(rs.getString(1), utf01); - assertEquals(rs.getString(2), utf02); - assertEquals(rs.getString(3), utf03); - assertEquals(rs.getString(4), utf04); - assertEquals(rs.getString(5), utf05); - assertEquals(rs.getString(6), utf06); - assertEquals(rs.getString(7), utf07); - assertEquals(rs.getString(8), utf08); - rs.close(); - - PreparedStatement prep = conn.prepareStatement( - "select ?,?,?,?,?,?,?,?;"); - prep.setString(1, utf01); prep.setString(2, utf02); - prep.setString(3, utf03); prep.setString(4, utf04); - prep.setString(5, utf05); prep.setString(6, utf06); - prep.setString(7, utf07); prep.setString(8, utf08); - rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), utf01); - assertEquals(rs.getString(2), utf02); - assertEquals(rs.getString(3), utf03); - assertEquals(rs.getString(4), utf04); - assertEquals(rs.getString(5), utf05); - assertEquals(rs.getString(6), utf06); - assertEquals(rs.getString(7), utf07); - assertEquals(rs.getString(8), utf08); - rs.close(); - } - - @Test public void batch() throws SQLException { - ResultSet rs; - - stat.executeUpdate("create table test (c1, c2, c3, c4);"); - PreparedStatement prep = conn.prepareStatement( - "insert into test values (?,?,?,?);"); - for (int i=0; i < 10; i++) { - prep.setInt(1, Integer.MIN_VALUE + i); - prep.setFloat(2, Float.MIN_VALUE + i); - prep.setString(3, "Hello " + i); - prep.setDouble(4, Double.MAX_VALUE + i); - prep.addBatch(); - } - assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 }); - prep.close(); - - rs = stat.executeQuery("select * from test;"); - for (int i=0; i < 10; i++) { - assertTrue(rs.next()); - assertEquals(rs.getInt(1), Integer.MIN_VALUE + i); - assertEquals(rs.getFloat(2), Float.MIN_VALUE + i); - assertEquals(rs.getString(3), "Hello " + i); - assertEquals(rs.getDouble(4), Double.MAX_VALUE + i); - } - rs.close(); - stat.executeUpdate("drop table test;"); - } - - @Test public void dblock() throws SQLException { - stat.executeUpdate("create table test (c1);"); - stat.executeUpdate("insert into test values (1);"); - conn.prepareStatement("select * from test;").executeQuery().close(); - stat.executeUpdate("drop table test;"); - - } - - @Test public void dbclose() throws SQLException { - conn.prepareStatement("select ?;").setString(1, "Hello World"); - conn.prepareStatement("select null;").close(); - conn.prepareStatement("select null;").executeQuery().close(); - conn.prepareStatement("create table t (c);").executeUpdate(); - conn.prepareStatement("select null;"); - } - - @Test public void batchOneParam() throws SQLException { - stat.executeUpdate("create table test (c1);"); - PreparedStatement prep = conn.prepareStatement( - "insert into test values (?);"); - for (int i=0; i < 10; i++) { - prep.setInt(1, Integer.MIN_VALUE + i); - prep.addBatch(); - } - assertArrayEq(prep.executeBatch(), new int[] { 1,1,1,1,1,1,1,1,1,1 }); - prep.close(); - ResultSet rs = stat.executeQuery("select count(*) from test;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 10); - rs.close(); - } - - @Test public void paramMetaData() throws SQLException { - PreparedStatement prep = conn.prepareStatement("select ?,?,?,?;"); - assertEquals(prep.getParameterMetaData().getParameterCount(), 4); - } - - @Test public void metaData() throws SQLException { - PreparedStatement prep = conn.prepareStatement( - "select ? as col1, ? as col2, ? as delta;"); - ResultSetMetaData meta = prep.getMetaData(); - assertEquals(meta.getColumnCount(), 3); - assertEquals(meta.getColumnName(1), "col1"); - assertEquals(meta.getColumnName(2), "col2"); - assertEquals(meta.getColumnName(3), "delta"); - /*assertEquals(meta.getColumnType(1), Types.INTEGER); - assertEquals(meta.getColumnType(2), Types.INTEGER); - assertEquals(meta.getColumnType(3), Types.INTEGER);*/ - - meta = prep.executeQuery().getMetaData(); - assertEquals(meta.getColumnCount(), 3); - prep.close(); - } - - @Test public void date1() throws SQLException { - Date d1 = new Date(987654321); - - stat.execute("create table t (c1);"); - PreparedStatement prep = conn.prepareStatement( - "insert into t values(?);"); - prep.setDate(1, d1); - prep.executeUpdate(); - - ResultSet rs = stat.executeQuery("select c1 from t;"); - assertTrue(rs.next()); - assertEquals(rs.getLong(1), d1.getTime()); - assertTrue(rs.getDate(1).equals(d1)); - rs.close(); - } - - @Test public void date2() throws SQLException { - Date d1 = new Date(1092941466000L); - stat.execute("create table t (c1);"); - PreparedStatement prep = conn.prepareStatement( - "insert into t values (datetime(?/1000, 'unixepoch'));"); - prep.setDate(1, d1); - prep.executeUpdate(); - - ResultSet rs = stat.executeQuery( - "select strftime('%s', c1) * 1000 from t;"); - assertTrue(rs.next()); - assertEquals(rs.getLong(1), d1.getTime()); - assertTrue(rs.getDate(1).equals(d1)); - } - - @Test public void changeSchema() throws SQLException { - stat.execute("create table t (c1);"); - PreparedStatement prep = conn.prepareStatement( - "insert into t values (?);"); - conn.createStatement().execute("create table t2 (c2);"); - prep.setInt(1, 1000); - prep.execute(); - prep.executeUpdate(); - } - - @Test public void reusingSetValues() throws SQLException { - PreparedStatement prep = conn.prepareStatement("select ?,?;"); - prep.setInt(1, 9); - - for (int i=0; i < 10; i++) { - prep.setInt(2, i); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 9); - assertEquals(rs.getInt(2), i); - } - - for (int i=0; i < 10; i++) { - prep.setInt(2, i); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 9); - assertEquals(rs.getInt(2), i); - rs.close(); - } - - prep.close(); - } - - @Test(expected= SQLException.class) - public void noSuchTable() throws SQLException { - PreparedStatement prep = - conn.prepareStatement("select * from doesnotexist;"); - prep.executeQuery(); - } - - @Test(expected= SQLException.class) - public void noSuchCol() throws SQLException { - PreparedStatement prep = - conn.prepareStatement("select notacol from (select 1);"); - prep.executeQuery(); - } - - @Test(expected= SQLException.class) - public void noSuchColName() throws SQLException { - ResultSet rs = conn.prepareStatement("select 1;").executeQuery(); - assertTrue(rs.next()); - rs.getInt("noSuchColName"); - } - - private void assertArrayEq(byte[] a, byte[] b) { - assertNotNull(a); - assertNotNull(b); - assertEquals(a.length, b.length); - for (int i=0; i < a.length; i++) - assertEquals(a[i], b[i]); - } - private void assertArrayEq(int[] a, int[] b) { - assertNotNull(a); - assertNotNull(b); - assertEquals(a.length, b.length); - for (int i=0; i < a.length; i++) - assertEquals(a[i], b[i]); - } -} diff --git a/sqlitejdbc/src/test/RSMetaDataTest.java b/sqlitejdbc/src/test/RSMetaDataTest.java deleted file mode 100644 index 8ff621c..0000000 --- a/sqlitejdbc/src/test/RSMetaDataTest.java +++ /dev/null @@ -1,76 +0,0 @@ -package test; - -import java.sql.*; -import org.junit.*; -import static org.junit.Assert.*; - -public class RSMetaDataTest -{ - private Connection conn; - private Statement stat; - private ResultSetMetaData meta; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - conn = DriverManager.getConnection("jdbc:sqlite:"); - stat = conn.createStatement(); - stat.executeUpdate( - "create table People (pid integer primary key autoincrement, " - + " firstname string, surname string, dob date);"); - stat.executeUpdate( - "insert into people values (null, 'Mohandas', 'Gandhi', " - + " '1869-10-02');"); - meta = stat.executeQuery( - "select pid, firstname, surname from people;").getMetaData(); - } - - @After public void close() throws SQLException { - stat.executeUpdate("drop table people;"); - stat.close(); - conn.close(); - } - - @Test public void catalogName() throws SQLException { - assertEquals(meta.getCatalogName(1), "People"); - } - - @Test public void columns() throws SQLException { - assertEquals(meta.getColumnCount(), 3); - assertEquals(meta.getColumnName(1), "pid"); - assertEquals(meta.getColumnName(2), "firstname"); - assertEquals(meta.getColumnName(3), "surname"); - assertEquals(meta.getColumnType(1), Types.INTEGER); - assertEquals(meta.getColumnType(2), Types.VARCHAR); - assertEquals(meta.getColumnType(3), Types.VARCHAR); - assertTrue(meta.isAutoIncrement(1)); - assertFalse(meta.isAutoIncrement(2)); - assertFalse(meta.isAutoIncrement(3)); - assertEquals(meta.isNullable(1), meta.columnNoNulls); - assertEquals(meta.isNullable(2), meta.columnNullable); - assertEquals(meta.isNullable(3), meta.columnNullable); - } - - @Test public void differentRS() throws SQLException { - meta = stat.executeQuery("select * from people;").getMetaData(); - assertEquals(meta.getColumnCount(), 4); - assertEquals(meta.getColumnName(1), "pid"); - assertEquals(meta.getColumnName(2), "firstname"); - assertEquals(meta.getColumnName(3), "surname"); - assertEquals(meta.getColumnName(4), "dob"); - } - - @Test public void nullable() throws SQLException { - meta = stat.executeQuery("select null;").getMetaData(); - assertEquals(meta.isNullable(1), ResultSetMetaData.columnNullable); - } - - @Test(expected= SQLException.class) - public void badCatalogIndex() throws SQLException { meta.getCatalogName(4);} - - @Test(expected= SQLException.class) - public void badColumnIndex() throws SQLException { meta.getColumnName(4); } - -} diff --git a/sqlitejdbc/src/test/StatementTest.java b/sqlitejdbc/src/test/StatementTest.java deleted file mode 100644 index 69ed0ae..0000000 --- a/sqlitejdbc/src/test/StatementTest.java +++ /dev/null @@ -1,306 +0,0 @@ -package test; - -import java.sql.*; -import org.junit.*; -import static org.junit.Assert.*; - -/** These tests are designed to stress Statements on memory databases. */ -public class StatementTest -{ - private Connection conn; - private Statement stat; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - conn = DriverManager.getConnection("jdbc:sqlite:"); - stat = conn.createStatement(); - } - - @After public void close() throws SQLException { - stat.close(); - conn.close(); - } - - @Test public void stmtUpdate() throws SQLException { - assertEquals(stat.executeUpdate("create table s1 (c1);"), 0); - assertEquals(stat.executeUpdate("insert into s1 values (0);"), 1); - assertEquals(stat.executeUpdate("insert into s1 values (1);"), 1); - assertEquals(stat.executeUpdate("insert into s1 values (2);"), 1); - assertEquals(stat.executeUpdate("update s1 set c1 = 5;"), 3); - // count_changes_pgrama. truncate_optimization - assertEquals(stat.executeUpdate("delete from s1;"), 3); - assertEquals(stat.executeUpdate("drop table s1;"), 3); - } - - @Test public void emptyRS() throws SQLException { - ResultSet rs = stat.executeQuery("select null limit 0;"); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void singleRowRS() throws SQLException { - ResultSet rs = stat.executeQuery("select " + Integer.MAX_VALUE + ";"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), Integer.MAX_VALUE); - assertEquals(rs.getString(1), Integer.toString(Integer.MAX_VALUE)); - assertEquals(rs.getDouble(1), - new Integer(Integer.MAX_VALUE).doubleValue()); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void twoRowRS() throws SQLException { - ResultSet rs = stat.executeQuery("select 9 union all select 7;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 9); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 7); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void autoClose() throws SQLException { - conn.createStatement().executeQuery("select 1;"); - } - - @Test public void stringRS() throws SQLException { - ResultSet rs = stat.executeQuery("select \"Russell\";"); - assertTrue(rs.next()); - assertEquals(rs.getString(1), "Russell"); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void execute() throws SQLException { - assertTrue(stat.execute("select null;")); - ResultSet rs = stat.getResultSet(); - assertNotNull(rs); - assertTrue(rs.next()); - assertNull(rs.getString(1)); - assertTrue(rs.wasNull()); - assertFalse(stat.getMoreResults()); - assertEquals(stat.getUpdateCount(), -1); - - assertTrue(stat.execute("select null;")); - assertFalse(stat.getMoreResults()); - assertEquals(stat.getUpdateCount(), -1); - - assertFalse(stat.execute("create table test (c1);")); - assertEquals(stat.getUpdateCount(), 0); - assertFalse(stat.getMoreResults()); - assertEquals(stat.getUpdateCount(), -1); - } - - @Test public void colNameAccess() throws SQLException { - assertEquals(stat.executeUpdate( - "create table tab (id, firstname, surname);"), 0); - assertEquals(stat.executeUpdate( - "insert into tab values (0, 'Bob', 'Builder');"), 1); - assertEquals(stat.executeUpdate( - "insert into tab values (1, 'Fred', 'Blogs');"), 1); - assertEquals(stat.executeUpdate( - "insert into tab values (2, 'John', 'Smith');"), 1); - ResultSet rs = stat.executeQuery("select * from tab;"); - assertTrue(rs.next()); - assertEquals(rs.getInt("id"), 0); - assertEquals(rs.getString("firstname"), "Bob"); - assertEquals(rs.getString("surname"), "Builder"); - assertTrue(rs.next()); - assertEquals(rs.getInt("id"), 1); - assertEquals(rs.getString("firstname"), "Fred"); - assertEquals(rs.getString("surname"), "Blogs"); - assertTrue(rs.next()); - assertEquals(rs.getInt("id"), 2); - assertEquals( rs.getString("id"), "2"); - assertEquals(rs.getString("firstname"), "John"); - assertEquals(rs.getString("surname"), "Smith"); - assertFalse(rs.next()); - rs.close(); - assertEquals(stat.executeUpdate("drop table tab;"), 1); - } - - @Test public void nulls() throws SQLException { - ResultSet rs = stat.executeQuery("select null union all select null;"); - assertTrue(rs.next()); - assertNull(rs.getString(1)); - assertTrue(rs.wasNull()); - assertTrue(rs.next()); - assertNull(rs.getString(1)); - assertTrue(rs.wasNull()); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void tempTable() throws SQLException { - assertEquals(stat.executeUpdate("create temp table myTemp (a);"), 0); - assertEquals(stat.executeUpdate("insert into myTemp values (2);"), 1); - } - - @Test public void insert1000() throws SQLException { - assertEquals(stat.executeUpdate("create table in1000 (a);"), 0); - conn.setAutoCommit(false); - for (int i=0; i < 1000; i++) - assertEquals(stat.executeUpdate( - "insert into in1000 values ("+i+");"), 1); - conn.commit(); - - ResultSet rs = stat.executeQuery("select count(a) from in1000;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1000); - rs.close(); - - assertEquals(stat.executeUpdate("drop table in1000;"), 1); - } - - private void assertArrayEq(int[] a, int[] b) { - assertNotNull(a); - assertNotNull(b); - assertEquals(a.length, b.length); - for (int i=0; i < a.length; i++) - assertEquals(a[i], b[i]); - } - - @Test public void batch() throws SQLException { - stat.addBatch("create table batch (c1);"); - stat.addBatch("insert into batch values (1);"); - stat.addBatch("insert into batch values (1);"); - stat.addBatch("insert into batch values (2);"); - stat.addBatch("insert into batch values (3);"); - stat.addBatch("insert into batch values (4);"); - assertArrayEq(new int[] { 0, 1, 1, 1, 1, 1 }, stat.executeBatch()); - assertArrayEq(new int[] { }, stat.executeBatch()); - stat.clearBatch(); - stat.addBatch("insert into batch values (9);"); - assertArrayEq(new int[] { 1 }, stat.executeBatch()); - assertArrayEq(new int[] {}, stat.executeBatch()); - stat.clearBatch(); - stat.addBatch("insert into batch values (7);"); - stat.addBatch("insert into batch values (7);"); - assertArrayEq(new int[] { 1, 1 }, stat.executeBatch()); - stat.clearBatch(); - - ResultSet rs = stat.executeQuery("select count(*) from batch;"); - assertTrue(rs.next()); - assertEquals(8, rs.getInt(1)); - rs.close(); - } - - @Test public void closeOnFalseNext() throws SQLException { - stat.executeUpdate("create table t1 (c1);"); - conn.createStatement().executeQuery("select * from t1;").next(); - stat.executeUpdate("drop table t1;"); - } - - @Test public void getGeneratedKeys() throws SQLException { - ResultSet rs; - stat.executeUpdate("create table t1 (c1 integer primary key, v);"); - stat.executeUpdate("insert into t1 (v) values ('red');"); - rs = stat.getGeneratedKeys(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1); - rs.close(); - stat.executeUpdate("insert into t1 (v) values ('blue');"); - rs = stat.getGeneratedKeys(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 2); - rs.close(); - } - - @Test public void isBeforeFirst() throws SQLException { - ResultSet rs = stat.executeQuery("select 1 union all select 2;"); - assertTrue(rs.isBeforeFirst()); - assertTrue(rs.next()); - assertTrue(rs.isFirst()); - assertEquals(rs.getInt(1), 1); - assertTrue(rs.next()); - assertFalse(rs.isBeforeFirst()); - assertFalse(rs.isFirst()); - assertEquals(rs.getInt(1), 2); - assertFalse(rs.next()); - assertFalse(rs.isBeforeFirst()); - rs.close(); - } - - @Test public void columnNaming() throws SQLException { - stat.executeUpdate("create table t1 (c1 integer);"); - stat.executeUpdate("create table t2 (c1 integer);"); - stat.executeUpdate("insert into t1 values (1);"); - stat.executeUpdate("insert into t2 values (1);"); - ResultSet rs = stat.executeQuery( - "select a.c1 AS c1 from t1 a, t2 where a.c1=t2.c1;"); - assertTrue(rs.next()); - assertEquals(rs.getInt("c1"), 1); - rs.close(); - } - - @Test public void nullDate() throws SQLException { - ResultSet rs = stat.executeQuery("select null;"); - assertTrue(rs.next()); - assertEquals(rs.getDate(1), null); - assertEquals(rs.getTime(1), null); - rs.close(); - } - - @Ignore - @Test(expected= SQLException.class) - public void ambiguousColumnNaming() throws SQLException { - stat.executeUpdate("create table t1 (c1 int);"); - stat.executeUpdate("create table t2 (c1 int, c2 int);"); - stat.executeUpdate("insert into t1 values (1);"); - stat.executeUpdate("insert into t2 values (2, 1);"); - ResultSet rs = stat.executeQuery( - "select a.c1, b.c1 from t1 a, t2 b where a.c1=b.c2;"); - assertTrue(rs.next()); - assertEquals(rs.getInt("c1"), 1); - rs.close(); - } - - @Test(expected= SQLException.class) - public void failToDropWhenRSOpen() throws SQLException { - stat.executeUpdate("create table t1 (c1);"); - stat.executeUpdate("insert into t1 values (4);"); - stat.executeUpdate("insert into t1 values (4);"); - conn.createStatement().executeQuery("select * from t1;").next(); - stat.executeUpdate("drop table t1;"); - } - - @Test(expected= SQLException.class) - public void executeNoRS() throws SQLException { - assertFalse(stat.execute("insert into test values (8);")); - stat.getResultSet(); - } - - @Test(expected= SQLException.class) - public void executeClearRS() throws SQLException { - assertTrue(stat.execute("select null;")); - assertNotNull(stat.getResultSet()); - assertFalse(stat.getMoreResults()); - stat.getResultSet(); - } - - @Test(expected= BatchUpdateException.class) - public void batchReturnsResults() throws SQLException { - stat.addBatch("select null;"); - stat.executeBatch(); - } - - @Test(expected= SQLException.class) - public void noSuchTable() throws SQLException { - stat.executeQuery("select * from doesnotexist;"); - } - - @Test(expected= SQLException.class) - public void noSuchCol() throws SQLException { - stat.executeQuery("select notacol from (select 1);"); - } - - @Test(expected= SQLException.class) - public void noSuchColName() throws SQLException { - ResultSet rs = stat.executeQuery("select 1;"); - assertTrue(rs.next()); - rs.getInt("noSuchColName"); - } -} diff --git a/sqlitejdbc/src/test/TransactionTest.java b/sqlitejdbc/src/test/TransactionTest.java deleted file mode 100644 index 479413b..0000000 --- a/sqlitejdbc/src/test/TransactionTest.java +++ /dev/null @@ -1,226 +0,0 @@ -package test; - -import java.io.File; -import java.sql.*; -import org.junit.*; -import static org.junit.Assert.*; - -/** These tests assume that Statements and PreparedStatements are working - * as per normal and test the interactions of commit(), rollback() and - * setAutoCommit(boolean) with multiple connections to the same db. */ -public class TransactionTest -{ - private Connection conn1, conn2, conn3; - private Statement stat1, stat2, stat3; - - boolean done = false; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - new File("test-trans.db").delete(); - conn1 = DriverManager.getConnection("jdbc:sqlite:test-trans.db"); - conn2 = DriverManager.getConnection("jdbc:sqlite:test-trans.db"); - conn3 = DriverManager.getConnection("jdbc:sqlite:test-trans.db"); - stat1 = conn1.createStatement(); - stat2 = conn2.createStatement(); - stat3 = conn3.createStatement(); - } - - @After public void close() throws Exception { - stat1.close(); stat2.close(); stat3.close(); - conn1.close(); conn2.close(); conn3.close(); - new File("test-trans.db").delete(); - } - - @Test public void multiConn() throws SQLException { - stat1.executeUpdate("create table test (c1);"); - stat1.executeUpdate("insert into test values (1);"); - stat2.executeUpdate("insert into test values (2);"); - stat3.executeUpdate("insert into test values (3);"); - - ResultSet rs = stat1.executeQuery("select sum(c1) from test;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 6); - rs.close(); - - rs = stat3.executeQuery("select sum(c1) from test;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 6); - rs.close(); - } - - @Test public void locking() throws SQLException { - stat1.executeUpdate("create table test (c1);"); - stat1.executeUpdate("begin immediate;"); - stat2.executeUpdate("select * from test;"); - } - - @Test public void insert() throws SQLException { - ResultSet rs; - String countSql = "select count(*) from trans;"; - - stat1.executeUpdate("create table trans (c1);"); - conn1.setAutoCommit(false); - - assertEquals(1, stat1.executeUpdate("insert into trans values (4);")); - - // transaction not yet commited, conn1 can see, conn2 can not - rs = stat1.executeQuery(countSql); - assertTrue(rs.next()); - assertEquals(1, rs.getInt(1)); - rs.close(); - rs = stat2.executeQuery(countSql); - assertTrue(rs.next()); - assertEquals(0, rs.getInt(1)); - rs.close(); - - conn1.commit(); - - // all connects can see data - rs = stat2.executeQuery(countSql); - assertTrue(rs.next()); - assertEquals(1, rs.getInt(1)); - rs.close(); - } - - @Test public void rollback() throws SQLException { - String select = "select * from trans;"; - ResultSet rs; - - stat1.executeUpdate("create table trans (c1);"); - conn1.setAutoCommit(false); - stat1.executeUpdate("insert into trans values (3);"); - - rs = stat1.executeQuery(select); - assertTrue(rs.next()); - rs.close(); - - conn1.rollback(); - - rs = stat1.executeQuery(select); - assertFalse(rs.next()); - rs.close(); - } - - @Test public void multiRollback() throws SQLException { - ResultSet rs; - - stat1.executeUpdate("create table t (c1);"); - conn1.setAutoCommit(false); - stat1.executeUpdate("insert into t values (1);"); - conn1.commit(); - stat1.executeUpdate("insert into t values (1);"); - conn1.rollback(); - stat1.addBatch("insert into t values (2);"); - stat1.addBatch("insert into t values (3);"); - stat1.executeBatch(); - conn1.commit(); - stat1.addBatch("insert into t values (7);"); - stat1.executeBatch(); - conn1.rollback(); - stat1.executeUpdate("insert into t values (4);"); - conn1.setAutoCommit(true); - stat1.executeUpdate("insert into t values (5);"); - conn1.setAutoCommit(false); - PreparedStatement p = conn1.prepareStatement( - "insert into t values (?);"); - p.setInt(1, 6); - p.executeUpdate(); - p.setInt(1, 7); - p.executeUpdate(); - - // conn1 can see (1+...+7), conn2 can see (1+...+5) - rs = stat1.executeQuery("select sum(c1) from t;"); - assertTrue(rs.next()); - assertEquals(1+2+3+4+5+6+7, rs.getInt(1)); - rs.close(); - rs = stat2.executeQuery("select sum(c1) from t;"); - assertTrue(rs.next()); - assertEquals(1+2+3+4+5, rs.getInt(1)); - rs.close(); - } - - @Test - public void transactionsDontMindReads() throws SQLException { - stat1.executeUpdate("create table t (c1);"); - stat1.executeUpdate("insert into t values (1);"); - stat1.executeUpdate("insert into t values (2);"); - ResultSet rs = stat1.executeQuery("select * from t;"); - assertTrue(rs.next()); // select is open - - conn2.setAutoCommit(false); - stat1.executeUpdate("insert into t values (2);"); - - rs.close(); - conn2.commit(); - } - - @Test - public void secondConnWillWait() throws Exception { - stat1.executeUpdate("create table t (c1);"); - stat1.executeUpdate("insert into t values (1);"); - stat1.executeUpdate("insert into t values (2);"); - ResultSet rs = stat1.executeQuery("select * from t;"); - assertTrue(rs.next()); - - final TransactionTest lock = this; - lock.done = false; - new Thread() { public void run() { - try { - stat2.executeUpdate("insert into t values (3);"); - } catch (SQLException e) { - e.printStackTrace(); - return; - } - - synchronized (lock) { - lock.done = true; - lock.notify(); - } - } }.start(); - - Thread.sleep(100); - rs.close(); - - synchronized (lock) { - lock.wait(5000); - if (!lock.done) - throw new Exception("should be done"); - } - } - - @Test(expected= SQLException.class) - public void secondConnMustTimeout() throws SQLException { - stat1.setQueryTimeout(1); - stat1.executeUpdate("create table t (c1);"); - stat1.executeUpdate("insert into t values (1);"); - stat1.executeUpdate("insert into t values (2);"); - ResultSet rs = stat1.executeQuery("select * from t;"); - assertTrue(rs.next()); - - stat2.executeUpdate("insert into t values (3);"); // can't be done - } - -// @Test(expected= SQLException.class) - @Test - public void cantUpdateWhileReading() throws SQLException { - stat1.executeUpdate("create table t (c1);"); - stat1.executeUpdate("insert into t values (1);"); - stat1.executeUpdate("insert into t values (2);"); - ResultSet rs = conn1.createStatement().executeQuery("select * from t;"); - assertTrue(rs.next()); - - // commit now succeeds since sqlite 3.6.5 - stat1.executeUpdate("insert into t values (3);"); // can't be done - } - - @Test(expected= SQLException.class) - public void cantCommit() throws SQLException { conn1.commit(); } - - @Test(expected= SQLException.class) - public void cantRollback() throws SQLException { conn1.rollback(); } - -} diff --git a/sqlitejdbc/src/test/UDFTest.java b/sqlitejdbc/src/test/UDFTest.java deleted file mode 100644 index 18a3245..0000000 --- a/sqlitejdbc/src/test/UDFTest.java +++ /dev/null @@ -1,313 +0,0 @@ -package test; - -import java.io.File; -import java.sql.*; -import java.util.*; -import org.sqlite.Function; -import org.junit.*; -import static org.junit.Assert.*; - -/** Tests User Defined Functions. */ -public class UDFTest -{ - private static int val = 0; - private static byte[] b1 = new byte[] { 2, 5, -4, 8, -1, 3, -5 }; - private static int gotTrigger = 0; - - private Connection conn; - private Statement stat; - - @BeforeClass public static void forName() throws Exception { - Class.forName("org.sqlite.JDBC"); - } - - @Before public void connect() throws Exception { - conn = DriverManager.getConnection("jdbc:sqlite:"); - stat = conn.createStatement(); - } - - @After public void close() throws SQLException { - stat.close(); - conn.close(); - } - - @Test public void calling() throws SQLException { - Function.create(conn, "f1", new Function() { - public void xFunc() throws SQLException { val = 4; } - }); - stat.executeQuery("select f1();").close(); - assertEquals(val, 4); - } - - @Test public void returning() throws SQLException { - Function.create(conn, "f2", new Function() { - public void xFunc() throws SQLException { result(4); } - }); - ResultSet rs = stat.executeQuery("select f2();"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 4); - rs.close(); - - for (int i=0; i < 20; i++) { - rs = stat.executeQuery("select (f2() + " + i + ");"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 4 + i); - rs.close(); - } - } - - @Test public void accessArgs() throws SQLException { - Function.create(conn, "f3", new Function() { - public void xFunc() throws SQLException { result(value_int(0)); } - }); - for (int i=0; i < 15; i++) { - ResultSet rs = stat.executeQuery("select f3("+i+");"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), i); - rs.close(); - } - } - - @Test public void multipleArgs() throws SQLException { - Function.create(conn, "f4", new Function() { - public void xFunc() throws SQLException { - int ret = 0; - for (int i=0; i < args(); i++) ret += value_int(i); - result(ret); - } - }); - ResultSet rs = stat.executeQuery("select f4(2, 3, 9, -5);"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 9); - rs.close(); - rs = stat.executeQuery("select f4(2);"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 2); - rs.close(); - rs = stat.executeQuery("select f4(-3, -4, -5);"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), -12); - } - - @Test public void returnTypes() throws SQLException { - Function.create(conn, "f5", new Function() { - public void xFunc() throws SQLException { result("Hello World"); } - }); - ResultSet rs = stat.executeQuery("select f5();"); - assertTrue(rs.next()); - assertEquals(rs.getString(1), "Hello World"); - - Function.create(conn, "f6", new Function() { - public void xFunc() throws SQLException { result(Long.MAX_VALUE); } - }); - rs.close(); rs = stat.executeQuery("select f6();"); - assertTrue(rs.next()); - assertEquals(rs.getLong(1), Long.MAX_VALUE); - - Function.create(conn, "f7", new Function() { - public void xFunc() throws SQLException {result(Double.MAX_VALUE);} - }); - rs.close(); rs = stat.executeQuery("select f7();"); - assertTrue(rs.next()); - assertEquals(rs.getDouble(1), Double.MAX_VALUE); - - Function.create(conn, "f8", new Function() { - public void xFunc() throws SQLException { result(b1); } - }); - rs.close(); rs = stat.executeQuery("select f8();"); - assertTrue(rs.next()); - assertArrayEq(rs.getBytes(1), b1); - } - - @Test public void returnArgInt() throws SQLException { - Function.create(conn, "farg_int", new Function() { - public void xFunc() throws SQLException { result(value_int(0)); } - }); - PreparedStatement prep = conn.prepareStatement("select farg_int(?);"); - prep.setInt(1, Integer.MAX_VALUE); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), Integer.MAX_VALUE); - prep.close(); - } - - @Test public void returnArgLong() throws SQLException { - Function.create(conn, "farg_long", new Function() { - public void xFunc() throws SQLException { result(value_long(0)); } - }); - PreparedStatement prep = conn.prepareStatement("select farg_long(?);"); - prep.setLong(1, Long.MAX_VALUE); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getLong(1), Long.MAX_VALUE); - prep.close(); - } - - @Test public void returnArgDouble() throws SQLException { - Function.create(conn, "farg_doub", new Function() { - public void xFunc() throws SQLException { result(value_double(0)); } - }); - PreparedStatement prep = conn.prepareStatement("select farg_doub(?);"); - prep.setDouble(1, Double.MAX_VALUE); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getDouble(1), Double.MAX_VALUE); - prep.close(); - } - - @Test public void returnArgBlob() throws SQLException { - Function.create(conn, "farg_blob", new Function() { - public void xFunc() throws SQLException { result(value_blob(0)); } - }); - PreparedStatement prep = conn.prepareStatement("select farg_blob(?);"); - prep.setBytes(1, b1); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertArrayEq(rs.getBytes(1), b1); - prep.close(); - } - - @Test public void returnArgString() throws SQLException { - Function.create(conn, "farg_str", new Function() { - public void xFunc() throws SQLException { result(value_text(0)); } - }); - PreparedStatement prep = conn.prepareStatement("select farg_str(?);"); - prep.setString(1, "Hello"); - ResultSet rs = prep.executeQuery(); - assertTrue(rs.next()); - assertEquals(rs.getString(1), "Hello"); - prep.close(); - } - - @Test(expected= SQLException.class) - public void customErr() throws SQLException { - Function.create(conn, "f9", new Function() { - public void xFunc() throws SQLException { - throw new SQLException("myErr"); } - }); - stat.executeQuery("select f9();"); - } - - @Test public void trigger() throws SQLException { - Function.create(conn, "inform", new Function() { - protected void xFunc() throws SQLException { - gotTrigger = value_int(0); } - }); - stat.executeUpdate("create table trigtest (c1);"); - stat.executeUpdate( - "create trigger trigt after insert on trigtest" - + " begin select inform(new.c1); end;" - ); - stat.executeUpdate("insert into trigtest values (5);"); - assertEquals(gotTrigger, 5); - } - - @Test public void aggregate() throws SQLException { - Function.create(conn, "mySum", new Function.Aggregate() { - private int val = 0; - protected void xStep() throws SQLException { - for (int i=0; i < args(); i++) val += value_int(i); - } - protected void xFinal() throws SQLException { - result(val); - } - }); - stat.executeUpdate("create table t (c1);"); - stat.executeUpdate("insert into t values (5);"); - stat.executeUpdate("insert into t values (3);"); - stat.executeUpdate("insert into t values (8);"); - stat.executeUpdate("insert into t values (2);"); - stat.executeUpdate("insert into t values (7);"); - ResultSet rs = stat.executeQuery("select mySum(c1), sum(c1) from t;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), rs.getInt(2)); - } - - @Test public void destroy() throws SQLException { - Function.create(conn, "f1", new Function() { - public void xFunc() throws SQLException { val = 9; } - }); - stat.executeQuery("select f1();").close(); - assertEquals(val, 9); - - Function.destroy(conn, "f1"); - Function.destroy(conn, "f1"); - } - - @Test public void manyfunctions() throws SQLException { - Function.create(conn, "f1", new Function() { - public void xFunc() throws SQLException { result(1); } }); - Function.create(conn, "f2", new Function() { - public void xFunc() throws SQLException { result(2); } }); - Function.create(conn, "f3", new Function() { - public void xFunc() throws SQLException { result(3); } }); - Function.create(conn, "f4", new Function() { - public void xFunc() throws SQLException { result(4); } }); - Function.create(conn, "f5", new Function() { - public void xFunc() throws SQLException { result(5); } }); - Function.create(conn, "f6", new Function() { - public void xFunc() throws SQLException { result(6); } }); - Function.create(conn, "f7", new Function() { - public void xFunc() throws SQLException { result(7); } }); - Function.create(conn, "f8", new Function() { - public void xFunc() throws SQLException { result(8); } }); - Function.create(conn, "f9", new Function() { - public void xFunc() throws SQLException { result(9); } }); - Function.create(conn, "f10", new Function() { - public void xFunc() throws SQLException { result(10); } }); - Function.create(conn, "f11", new Function() { - public void xFunc() throws SQLException { result(11); } }); - - ResultSet rs = stat.executeQuery( - "select f1() + f2() + f3() + f4() + f5() + f6()" - + " + f7() + f8() + f9() + f10() + f11();"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), 1+2+3+4+5+6+7+8+9+10+11); - rs.close(); - } - - @Test public void multipleThreads() throws Exception { - Function func = new Function() { - int sum = 0; - protected void xFunc() { try { - sum += value_int(1); - } catch (SQLException e) { e.printStackTrace(); } } - public String toString() { return String.valueOf(sum); } - }; - Function.create(conn, "func", func); - stat.executeUpdate("create table foo (col integer);"); - stat.executeUpdate( - "create trigger foo_trigger after insert on foo begin" - + " select func(new.rowid, new.col); end;"); - int times = 1000; - List threads = new LinkedList(); - for (int tn=0; tn < times; tn++) { - threads.add(new Thread("func thread " + tn) { - public void run() { try { - Statement s = conn.createStatement(); - s.executeUpdate("insert into foo values (1);"); - s.close(); - } catch (SQLException e) { e.printStackTrace(); } } - }); - } - for (Thread thread: threads) thread.start(); - for (Thread thread: threads) thread.join(); - - // check that all of the threads successfully executed - ResultSet rs = stat.executeQuery("select sum(col) from foo;"); - assertTrue(rs.next()); - assertEquals(rs.getInt(1), times); - rs.close(); - - // check that custom function was executed each time - assertEquals(Integer.parseInt(func.toString()), times); - } - - private void assertArrayEq(byte[] a, byte[] b) { - assertNotNull(a); - assertNotNull(b); - assertEquals(a.length, b.length); - for (int i=0; i < a.length; i++) - assertEquals(a[i], b[i]); - } -} -- 2.11.0