├── .gitignore ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── sqlite4a ├── CMakeLists.txt ├── build.gradle ├── proguard.pro └── src ├── androidTest └── java │ └── sqlite4a │ ├── SQLiteCollationTest.java │ ├── SQLiteCustomFuncTest.java │ ├── SQLiteDbTest.java │ ├── SQLiteStmtTest.java │ └── SQLiteTest.java └── main ├── AndroidManifest.xml ├── cpp ├── sqlite3.c ├── sqlite3.h └── sqlite3_jni.cc └── java └── sqlite4a ├── JniFunc.java ├── RowIterator.java ├── SQLite.java ├── SQLiteContext.java ├── SQLiteDb.java ├── SQLiteException.java ├── SQLiteIterator.java ├── SQLiteRow.java ├── SQLiteStmt.java └── SQLiteValue.java /.gitignore: -------------------------------------------------------------------------------- 1 | **/build/ 2 | **/.gradle/ 3 | .gradletasknamecache 4 | **/.externalNativeBuild/ 5 | local.properties 6 | gradle.properties 7 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SQLite4a [![Apache License](https://img.shields.io/badge/license-Apache%20v2-blue.svg)](https://github.com/DanielSerdyukov/sqlite4a/blob/master/LICENSE) [![Build Status](https://gitlab.exzogeni.com/android/sqlite4a/badges/master/build.svg)](https://github.com/DanielSerdyukov/sqlite4a) 2 | 3 | Simple jni wrapper for SQLite. 4 | 5 | ---- 6 | 7 | ### Gradle 8 | ```groovy 9 | compile 'sqlite4a:sqlite4a:3.18.0' 10 | ``` 11 | 12 | ### Some examples 13 | 14 | #### Open database 15 | ```java 16 | SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 17 | ``` 18 | or 19 | ```java 20 | SQLiteDb db = SQLite.open("/absolute/path", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 21 | ``` 22 | 23 | #### Simple query 24 | ```java 25 | db.exec("PRAGMA case_sensitive_like = true;"); 26 | ``` 27 | 28 | #### Prepared query 29 | ```java 30 | SQLiteStmt stmt = db.prepare("INSERT INTO users(name, age) VALUES(?, ?);"); 31 | stmt.bindString(1, "John"); 32 | stmt.bindLong(2, 25); 33 | long johnId = stmt.insert(); 34 | 35 | stmt.clearBindings(); 36 | 37 | stmt.bindString(1, "Jane"); 38 | stmt.bindLong(2, 20); 39 | long janeId = stmt.insert(); 40 | 41 | stmt.close(); 42 | ``` 43 | 44 | #### Query tracing 45 | ```java 46 | db.trace(sql -> { Log.i("SQLITE", sql); }); 47 | db.exec("CREATE TABLE IF NOT EXISTS foo(a INTEGER PRIMARY KEY, b REAL, c TEXT, d BLOB, e TEXT);"); 48 | SQLite stmt = db.prepare("INSERT INTO foo(a, b, c, d, e) VALUES(?, ?, ?, ?, ?);"); 49 | // ... bind args 50 | stmt.insert(); 51 | stmt.close(); 52 | ``` 53 | LogCat: 54 | ``` 55 | D/SQLITE: CREATE TABLE IF NOT EXISTS foo(a INTEGER PRIMARY KEY, b REAL, c TEXT, d BLOB, e TEXT); 56 | D/SQLITE: INSERT INTO foo(a, b, c, d, e) VALUES(1000, 1.23, 'test1', x'010203', NULL); 57 | ``` 58 | 59 | #### Custom collation 60 | ```java 61 | mDb.exec("CREATE TABLE test(name TEXT);"); 62 | mDb.exec("INSERT INTO test VALUES('lorem ipsum');"); 63 | mDb.createCollation("JAVA_NOCASE", new Comparator() { 64 | @Override 65 | public int compare(String lhs, String rhs) { 66 | return lhs.compareToIgnoreCase(rhs); 67 | } 68 | }); 69 | final SQLiteStmt stmt = mDb.prepare("SELECT * FROM test WHERE name = ? COLLATE JAVA_NOCASE;"); 70 | stmt.bindString(1, "LOREM ipsum"); 71 | try (final SQLiteIterator iterator = stmt.select()) { 72 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 73 | Assert.assertThat(iterator.next().getColumnString(0), Is.is("lorem ipsum")); 74 | } 75 | ``` 76 | 77 | #### Custom functions 78 | ```java 79 | db.exec("CREATE TABLE test(first_name TEXT, last_name INTEGER);"); 80 | db.exec("INSERT INTO test VALUES('John', 'Smith');"); 81 | db.createFunction("join_name", 2, (context, values) -> { 82 | context.resultString(values[0].stringValue() + " " + values[1].stringValue()); 83 | }); 84 | try (final SQLiteIterator iterator = mDb.prepare("SELECT join_name(first_name, last_name) FROM test;").select()) { 85 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 86 | Assert.assertThat(iterator.next().getColumnString(0), IsEqual.equalTo("John Smith")); 87 | } 88 | ``` 89 | 90 | License 91 | ------- 92 | 93 | Copyright 2016-2017 exzogeni.com 94 | 95 | Licensed under the Apache License, Version 2.0 (the "License"); 96 | you may not use this file except in compliance with the License. 97 | You may obtain a copy of the License at 98 | 99 | http://www.apache.org/licenses/LICENSE-2.0 100 | 101 | Unless required by applicable law or agreed to in writing, software 102 | distributed under the License is distributed on an "AS IS" BASIS, 103 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 104 | See the License for the specific language governing permissions and 105 | limitations under the License. 106 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import com.jfrog.bintray.gradle.BintrayUploadTask 2 | 3 | buildscript { 4 | repositories { 5 | jcenter() 6 | } 7 | dependencies { 8 | classpath 'com.android.tools.build:gradle:2.4.0-alpha6' 9 | classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.7.3' 10 | } 11 | } 12 | 13 | allprojects { 14 | repositories { 15 | jcenter() 16 | } 17 | group 'sqlite4a' 18 | version '3.18.0' 19 | } 20 | 21 | configure([project(':sqlite4a')]) { 22 | apply plugin: 'com.jfrog.bintray' 23 | 24 | bintray { 25 | user = rootProject.properties.get('bintray.user') 26 | key = rootProject.properties.get('bintray.apikey') 27 | publications = ['maven'] 28 | override = true 29 | pkg { 30 | repo = 'sqlite4a' 31 | name = 'sqlite4a' 32 | licenses = ['Apache-2.0'] 33 | vcsUrl = 'https://github.com/DanielSerdyukov/sqlite4a.git' 34 | version { 35 | name = rootProject.version 36 | released = new Date() 37 | } 38 | } 39 | } 40 | 41 | ext { 42 | pomXml = { 43 | name project.name 44 | resolveStrategy = DELEGATE_FIRST 45 | url 'https://github.com/DanielSerdyukov/sqlite4a' 46 | scm { 47 | url 'https://github.com/DanielSerdyukov/sqlite4a.git' 48 | connection 'scm:git:git://github.com/DanielSerdyukov/sqlite4a.git' 49 | developerConnection 'scm:git:git@github.com/DanielSerdyukov/sqlite4a.git' 50 | } 51 | licenses { 52 | license { 53 | name 'The Apache Software License, Version 2.0' 54 | url 'http://www.apache.org/license/LICENSE-2.0.txt' 55 | distribution 'repo' 56 | } 57 | } 58 | developers { 59 | developer { 60 | name 'Daniel Serdyukov' 61 | } 62 | } 63 | } 64 | } 65 | 66 | project.tasks.withType(BintrayUploadTask).all { it.dependsOn 'publishToMavenLocal' } 67 | } 68 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DanielSerdyukov/sqlite4a/98d52e4a7c2406bc32d8854ac692b09c60ee7d39/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Mar 02 13:28:33 MSK 2017 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'sqlite4a-parent' 2 | include 'sqlite4a' 3 | -------------------------------------------------------------------------------- /sqlite4a/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.4.1) 2 | 3 | set(PROJECT_NAME sqlite3_jni) 4 | 5 | set(SOURCES 6 | src/main/cpp/sqlite3.h 7 | src/main/cpp/sqlite3.c 8 | src/main/cpp/sqlite3_jni.cc) 9 | 10 | add_definitions( 11 | -D__ANDROID__ 12 | -DHAVE_USLEEP=1 13 | -DSQLITE_HAVE_ISNAN 14 | -DSQLITE_DEFAULT_JOURNAL_SIZE_LIMIT=1048576 15 | -DSQLITE_THREADSAFE=2 16 | -DSQLITE_TEMP_STORE=3 17 | -DSQLITE_POWERSAFE_OVERWRITE=1 18 | -DSQLITE_DEFAULT_AUTOVACUUM=1 19 | -DSQLITE_ENABLE_MEMORY_MANAGEMENT=1 20 | -DSQLITE_ENABLE_FTS5 21 | -DSQLITE_ENABLE_JSON1 22 | -DSQLITE_OMIT_BUILTIN_TEST 23 | -DSQLITE_OMIT_COMPILEOPTION_DIAGS 24 | -DSQLITE_DEFAULT_FILE_PERMISSIONS=0600 25 | -DSQLITE_DEFAULT_FOREIGN_KEYS=1 26 | ) 27 | 28 | add_library(${PROJECT_NAME} SHARED ${SOURCES}) 29 | 30 | find_library(LIB_m m) 31 | find_library(LIB_log log) 32 | 33 | target_link_libraries(${PROJECT_NAME} ${LIB_m} ${LIB_log}) -------------------------------------------------------------------------------- /sqlite4a/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | 7 | defaultConfig { 8 | minSdkVersion 15 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName rootProject.version 12 | 13 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 14 | 15 | externalNativeBuild { 16 | cmake { 17 | cppFlags "-std=c++11", "-fno-rtti", "-fno-exceptions", "-fvisibility=hidden" 18 | abiFilters "armeabi-v7a", "arm64-v8a", "x86" 19 | } 20 | } 21 | } 22 | 23 | buildTypes { 24 | release { 25 | minifyEnabled true 26 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard.pro' 27 | } 28 | } 29 | 30 | externalNativeBuild { 31 | cmake { 32 | path "CMakeLists.txt" 33 | } 34 | } 35 | 36 | libraryVariants.all { variant -> 37 | int versionCode = 0 38 | (rootProject.version =~ /(\d+)/).collect { 39 | Integer.parseInt(it[0] as String) 40 | }.take(3).eachWithIndex { num, index -> 41 | versionCode += (num * Math.max(1, (1000000 / Math.pow(1000, index)))) 42 | } 43 | variant.mergedFlavor.versionCode = versionCode 44 | } 45 | } 46 | 47 | configurations { 48 | androidTestCompile.exclude group: 'org.hamcrest', module: 'hamcrest-core' 49 | } 50 | 51 | dependencies { 52 | compile 'com.android.support:support-annotations:25.3.1' 53 | androidTestCompile 'com.getkeepsafe.relinker:relinker:1.2.1' 54 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 55 | exclude group: 'com.android.support', module: 'support-annotations' 56 | exclude group: 'org.hamcrest' 57 | }) 58 | androidTestCompile 'junit:junit:4.12' 59 | androidTestCompile 'org.hamcrest:java-hamcrest:2.0.0.0' 60 | } 61 | 62 | apply plugin: 'maven-publish' 63 | 64 | task sourcesJar(type: Jar) { 65 | classifier = 'sources' 66 | from android.sourceSets.main.java.srcDirs 67 | } 68 | 69 | publishing { 70 | publications { 71 | maven(MavenPublication) { 72 | groupId project.group 73 | artifactId project.name 74 | version project.version 75 | artifact "${project.buildDir}/outputs/aar/${project.name}-release.aar" 76 | artifact sourcesJar 77 | pom.withXml { 78 | asNode().children().last() + project.pomXml 79 | def dependencies = asNode().appendNode('dependencies') 80 | configurations.compile.allDependencies.each { 81 | def dependency = dependencies.appendNode('dependency') 82 | dependency.appendNode('groupId', it.group) 83 | dependency.appendNode('artifactId', it.name) 84 | dependency.appendNode('version', it.version) 85 | dependency.appendNode('scope', 'compile') 86 | } 87 | } 88 | } 89 | } 90 | } 91 | 92 | project.tasks.withType(PublishToMavenLocal).all { it.dependsOn 'assembleRelease' } 93 | -------------------------------------------------------------------------------- /sqlite4a/proguard.pro: -------------------------------------------------------------------------------- 1 | -keepattributes Signature,Exceptions,InnerClasses,EnclosingMethod,*Annotation* 2 | 3 | -keep public interface alchemy.** { *; } 4 | 5 | -keep class sqlite4a.JniFunc { 6 | void call(long, long[]); 7 | } 8 | 9 | -keep public class sqlite4a.** { 10 | public static ; 11 | public ; 12 | } -------------------------------------------------------------------------------- /sqlite4a/src/androidTest/java/sqlite4a/SQLiteCollationTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.test.InstrumentationRegistry; 20 | import android.support.test.runner.AndroidJUnit4; 21 | 22 | import com.getkeepsafe.relinker.ReLinker; 23 | 24 | import org.hamcrest.core.Is; 25 | import org.hamcrest.core.IsEqual; 26 | import org.junit.After; 27 | import org.junit.Assert; 28 | import org.junit.Before; 29 | import org.junit.BeforeClass; 30 | import org.junit.Test; 31 | import org.junit.runner.RunWith; 32 | 33 | import java.util.Comparator; 34 | 35 | @RunWith(AndroidJUnit4.class) 36 | public class SQLiteCollationTest { 37 | 38 | private SQLiteDb mDb; 39 | 40 | @BeforeClass 41 | public static void loadLibrary() { 42 | ReLinker.loadLibrary(InstrumentationRegistry.getContext(), SQLite.JNI_LIB); 43 | } 44 | 45 | @Before 46 | public void setUp() throws Exception { 47 | mDb = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 48 | mDb.createCollation("JAVA_NOCASE", new Comparator() { 49 | @Override 50 | public int compare(String lhs, String rhs) { 51 | return lhs.compareToIgnoreCase(rhs); 52 | } 53 | }); 54 | mDb.exec("CREATE TABLE test(foo TEXT COLLATE JAVA_NOCASE, bar TEXT);"); 55 | mDb.exec("INSERT INTO test VALUES('test', 'test');"); 56 | } 57 | 58 | @Test 59 | public void tableCollation_Case_Insensitive_Column() throws Exception { 60 | final SQLiteIterator iterator = mDb.prepare("SELECT * FROM test WHERE foo = 'TEST';").select(); 61 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 62 | Assert.assertThat(iterator.next().getColumnString(0), IsEqual.equalTo("test")); 63 | iterator.close(); 64 | } 65 | 66 | @Test 67 | public void tableCollation_Case_Sensitive_Column() throws Exception { 68 | final SQLiteIterator iterator = mDb.prepare("SELECT * FROM test WHERE bar = 'TEST';").select(); 69 | Assert.assertThat(iterator.hasNext(), Is.is(false)); 70 | iterator.close(); 71 | } 72 | 73 | @Test 74 | public void queryCollation() throws Exception { 75 | final SQLiteIterator iterator = mDb.prepare("SELECT * FROM test " + 76 | "WHERE bar = 'TEST' COLLATE JAVA_NOCASE;").select(); 77 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 78 | Assert.assertThat(iterator.next().getColumnString(0), IsEqual.equalTo("test")); 79 | iterator.close(); 80 | } 81 | 82 | @After 83 | public void tearDown() throws Exception { 84 | mDb.close(); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /sqlite4a/src/androidTest/java/sqlite4a/SQLiteCustomFuncTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.NonNull; 20 | import android.support.test.InstrumentationRegistry; 21 | import android.support.test.runner.AndroidJUnit4; 22 | 23 | import com.getkeepsafe.relinker.ReLinker; 24 | 25 | import org.hamcrest.core.Is; 26 | import org.hamcrest.core.IsEqual; 27 | import org.junit.After; 28 | import org.junit.Assert; 29 | import org.junit.Before; 30 | import org.junit.BeforeClass; 31 | import org.junit.Test; 32 | import org.junit.runner.RunWith; 33 | 34 | @RunWith(AndroidJUnit4.class) 35 | public class SQLiteCustomFuncTest { 36 | 37 | private SQLiteDb mDb; 38 | 39 | @BeforeClass 40 | public static void loadLibrary() { 41 | ReLinker.loadLibrary(InstrumentationRegistry.getContext(), SQLite.JNI_LIB); 42 | } 43 | 44 | @Before 45 | public void setUp() throws Exception { 46 | mDb = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 47 | mDb.exec("CREATE TABLE test(foo TEXT, bar TEXT, baz TEXT);"); 48 | mDb.exec("INSERT INTO test VALUES('тест', 'capitalize', NULL);"); 49 | } 50 | 51 | @Test 52 | public void override_upper() throws Exception { 53 | mDb.createFunction("upper", 1, new SQLiteDb.Func() { 54 | @Override 55 | public void call(@NonNull SQLiteContext context, @NonNull SQLiteValue[] values) { 56 | final String value = values[0].stringValue(); 57 | if (value != null) { 58 | context.resultString(value.toUpperCase()); 59 | } 60 | } 61 | }); 62 | final SQLiteIterator iterator = mDb.prepare("SELECT upper(foo) FROM test;").select(); 63 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 64 | Assert.assertThat(iterator.next().getColumnString(0), IsEqual.equalTo("ТЕСТ")); 65 | iterator.close(); 66 | } 67 | 68 | @Test 69 | public void custom_join() throws Exception { 70 | mDb.createFunction("custom_join", 2, new SQLiteDb.Func() { 71 | @Override 72 | public void call(@NonNull SQLiteContext context, @NonNull SQLiteValue[] values) { 73 | context.resultString(values[0].stringValue() + " " + values[1].stringValue()); 74 | } 75 | }); 76 | final SQLiteStmt stmt = mDb.prepare("UPDATE test SET baz = custom_join(?, ?);"); 77 | stmt.bindString(1, "join"); 78 | stmt.bindString(2, "us"); 79 | stmt.execute(); 80 | stmt.close(); 81 | final SQLiteIterator iterator = mDb.prepare("SELECT baz FROM test;").select(); 82 | Assert.assertThat(iterator.hasNext(), Is.is(true)); 83 | Assert.assertThat(iterator.next().getColumnString(0), IsEqual.equalTo("join us")); 84 | iterator.close(); 85 | } 86 | 87 | @After 88 | public void tearDown() throws Exception { 89 | mDb.close(); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /sqlite4a/src/androidTest/java/sqlite4a/SQLiteDbTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.test.InstrumentationRegistry; 20 | import android.support.test.runner.AndroidJUnit4; 21 | 22 | import com.getkeepsafe.relinker.ReLinker; 23 | 24 | import org.hamcrest.collection.IsIterableContainingInOrder; 25 | import org.hamcrest.core.Is; 26 | import org.junit.Assert; 27 | import org.junit.BeforeClass; 28 | import org.junit.Test; 29 | import org.junit.runner.RunWith; 30 | 31 | import java.util.ArrayList; 32 | import java.util.List; 33 | 34 | @RunWith(AndroidJUnit4.class) 35 | public class SQLiteDbTest { 36 | 37 | @BeforeClass 38 | public static void loadLibrary() { 39 | ReLinker.loadLibrary(InstrumentationRegistry.getContext(), SQLite.JNI_LIB); 40 | } 41 | 42 | @Test 43 | public void openReadOnly() throws Exception { 44 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READONLY); 45 | Assert.assertThat(db.isReadOnly(), Is.is(true)); 46 | db.close(); 47 | } 48 | 49 | @Test 50 | public void openReadWrite() throws Exception { 51 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE); 52 | Assert.assertThat(db.isReadOnly(), Is.is(false)); 53 | db.close(); 54 | } 55 | 56 | @Test 57 | public void inTransaction_Begin_Commit() throws Exception { 58 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE); 59 | Assert.assertThat(db.inTransaction(), Is.is(false)); 60 | db.exec("BEGIN;"); 61 | Assert.assertThat(db.inTransaction(), Is.is(true)); 62 | db.exec("COMMIT;"); 63 | Assert.assertThat(db.inTransaction(), Is.is(false)); 64 | db.close(); 65 | } 66 | 67 | @Test 68 | public void inTransaction_Begin_Rollback() throws Exception { 69 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE); 70 | Assert.assertThat(db.inTransaction(), Is.is(false)); 71 | db.exec("BEGIN;"); 72 | Assert.assertThat(db.inTransaction(), Is.is(true)); 73 | db.exec("ROLLBACK;"); 74 | Assert.assertThat(db.inTransaction(), Is.is(false)); 75 | db.close(); 76 | } 77 | 78 | @Test 79 | public void trace() throws Exception { 80 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 81 | final List traceLog = new ArrayList<>(); 82 | db.trace(new SQLiteDb.Trace() { 83 | @Override 84 | public void trace(String sql) { 85 | traceLog.add(sql); 86 | } 87 | }); 88 | db.exec("BEGIN;"); 89 | db.exec("CREATE TABLE IF NOT EXISTS foo(text TEXT PRIMARY KEY);"); 90 | db.exec("CREATE TABLE IF NOT EXISTS bar(text TEXT REFERENCES foo(text) ON DELETE CASCADE);"); 91 | db.exec("INSERT INTO foo VALUES('test');"); 92 | db.exec("INSERT INTO bar VALUES('test');"); 93 | db.exec("INSERT INTO bar VALUES('test');"); 94 | db.exec("COMMIT;"); 95 | db.exec("DELETE FROM foo;"); 96 | Assert.assertThat(traceLog, IsIterableContainingInOrder.contains( 97 | "BEGIN;", 98 | "CREATE TABLE IF NOT EXISTS foo(text TEXT PRIMARY KEY);", 99 | "CREATE TABLE IF NOT EXISTS bar(text TEXT REFERENCES foo(text) ON DELETE CASCADE);", 100 | "INSERT INTO foo VALUES('test');", 101 | "INSERT INTO bar VALUES('test');", 102 | "INSERT INTO bar VALUES('test');", 103 | "COMMIT;", 104 | "DELETE FROM foo;", 105 | "-- TRIGGER " 106 | )); 107 | db.close(); 108 | } 109 | 110 | @Test 111 | public void execForNumber() throws Exception { 112 | final SQLiteDb db = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 113 | db.exec("PRAGMA user_version = 123;"); 114 | Assert.assertThat(db.execForNumber("PRAGMA user_version;").longValue(), Is.is(123L)); 115 | db.close(); 116 | } 117 | 118 | } -------------------------------------------------------------------------------- /sqlite4a/src/androidTest/java/sqlite4a/SQLiteStmtTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.test.InstrumentationRegistry; 20 | import android.support.test.runner.AndroidJUnit4; 21 | 22 | import com.getkeepsafe.relinker.ReLinker; 23 | 24 | import org.hamcrest.Matchers; 25 | import org.hamcrest.core.Is; 26 | import org.hamcrest.core.IsEqual; 27 | import org.hamcrest.core.IsNot; 28 | import org.junit.After; 29 | import org.junit.Assert; 30 | import org.junit.Before; 31 | import org.junit.BeforeClass; 32 | import org.junit.Test; 33 | import org.junit.runner.RunWith; 34 | 35 | import java.security.SecureRandom; 36 | import java.util.ArrayList; 37 | import java.util.Arrays; 38 | import java.util.Iterator; 39 | import java.util.List; 40 | import java.util.Random; 41 | import java.util.UUID; 42 | 43 | @RunWith(AndroidJUnit4.class) 44 | public class SQLiteStmtTest { 45 | 46 | private SQLiteDb mDb; 47 | 48 | private List mEntries; 49 | 50 | @BeforeClass 51 | public static void loadLibrary() { 52 | ReLinker.loadLibrary(InstrumentationRegistry.getContext(), SQLite.JNI_LIB); 53 | } 54 | 55 | @Before 56 | public void setUp() throws Exception { 57 | mDb = SQLite.open(":memory:", SQLite.OPEN_READWRITE | SQLite.OPEN_CREATE); 58 | mDb.exec("CREATE TABLE test(_id INTEGER PRIMARY KEY, " + 59 | "int INTEGER, " + 60 | "text TEXT, " + 61 | "real REAL, " + 62 | "blob BLOB);"); 63 | mEntries = new ArrayList<>(); 64 | final Random random = new SecureRandom(); 65 | final SQLiteStmt stmt = mDb.prepare("INSERT INTO test(_id, int, text, real, blob) VALUES(?, ?, ?, ?, ?);"); 66 | final long[] ids = new long[10]; 67 | for (int i = 0; i < ids.length; ++i) { 68 | final Entry entry = Entry.generate(random); 69 | stmt.bindLong(2, entry.mInt); 70 | stmt.bindString(3, entry.mText); 71 | stmt.bindDouble(4, entry.mReal); 72 | stmt.bindBlob(5, entry.mBlob); 73 | ids[i] = stmt.insert(); 74 | stmt.clearBindings(); 75 | mEntries.add(entry); 76 | } 77 | stmt.close(); 78 | Assert.assertThat(ids, IsEqual.equalTo(new long[]{ 79 | 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 80 | })); 81 | } 82 | 83 | @Test 84 | public void select() throws Exception { 85 | final SQLiteIterator actual = mDb.prepare("SELECT * FROM test;").select(); 86 | final Iterator expected = mEntries.iterator(); 87 | while (actual.hasNext() && expected.hasNext()) { 88 | final Entry entry = Entry.map(actual.next()); 89 | Assert.assertThat(entry, IsEqual.equalTo(expected.next())); 90 | Assert.assertThat(entry.mId, Matchers.greaterThan(0L)); 91 | } 92 | Assert.assertThat(actual.hasNext(), Is.is(false)); 93 | Assert.assertThat(expected.hasNext(), Is.is(false)); 94 | actual.close(); 95 | } 96 | 97 | @Test 98 | public void execute_delete() throws Exception { 99 | final Entry removed = mEntries.remove(5); 100 | final SQLiteStmt stmt = mDb.prepare("DELETE FROM test WHERE text = ?;"); 101 | stmt.bindString(1, removed.mText); 102 | Assert.assertThat(stmt.execute(), Is.is(1)); 103 | stmt.close(); 104 | final SQLiteIterator actual = mDb.prepare("SELECT * FROM test;").select(); 105 | while (actual.hasNext()) { 106 | Assert.assertThat(Entry.map(actual.next()), IsNot.not(IsEqual.equalTo(removed))); 107 | } 108 | actual.close(); 109 | } 110 | 111 | @After 112 | public void tearDown() throws Exception { 113 | mDb.close(); 114 | } 115 | 116 | private static class Entry { 117 | 118 | long mId; 119 | 120 | int mInt; 121 | 122 | String mText; 123 | 124 | double mReal; 125 | 126 | byte[] mBlob; 127 | 128 | static Entry generate(Random random) { 129 | final Entry entry = new Entry(); 130 | entry.mInt = random.nextInt(); 131 | entry.mText = UUID.randomUUID().toString(); 132 | entry.mReal = random.nextDouble(); 133 | entry.mBlob = new byte[16]; 134 | random.nextBytes(entry.mBlob); 135 | return entry; 136 | } 137 | 138 | static Entry map(SQLiteRow row) { 139 | final Entry entry = new Entry(); 140 | entry.mId = row.getColumnLong(0); 141 | entry.mInt = (int) row.getColumnLong(1); 142 | entry.mText = row.getColumnString(2); 143 | entry.mReal = row.getColumnDouble(3); 144 | entry.mBlob = row.getColumnBlob(4); 145 | return entry; 146 | } 147 | 148 | @Override 149 | public boolean equals(Object o) { 150 | if (this == o) { 151 | return true; 152 | } 153 | if (o == null || getClass() != o.getClass()) { 154 | return false; 155 | } 156 | Entry entry = (Entry) o; 157 | return mInt == entry.mInt 158 | && Double.compare(entry.mReal, mReal) == 0 159 | && (mText != null ? mText.equals(entry.mText) : entry.mText == null 160 | && Arrays.equals(mBlob, entry.mBlob)); 161 | 162 | } 163 | 164 | @Override 165 | public int hashCode() { 166 | int result; 167 | long temp; 168 | result = mInt; 169 | result = 31 * result + (mText != null ? mText.hashCode() : 0); 170 | temp = Double.doubleToLongBits(mReal); 171 | result = 31 * result + (int) (temp ^ (temp >>> 32)); 172 | result = 31 * result + Arrays.hashCode(mBlob); 173 | return result; 174 | } 175 | 176 | } 177 | 178 | } -------------------------------------------------------------------------------- /sqlite4a/src/androidTest/java/sqlite4a/SQLiteTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.test.InstrumentationRegistry; 20 | import android.support.test.runner.AndroidJUnit4; 21 | 22 | import com.getkeepsafe.relinker.ReLinker; 23 | 24 | import org.hamcrest.core.Is; 25 | import org.junit.Assert; 26 | import org.junit.BeforeClass; 27 | import org.junit.Test; 28 | import org.junit.runner.RunWith; 29 | 30 | @RunWith(AndroidJUnit4.class) 31 | public class SQLiteTest { 32 | 33 | @BeforeClass 34 | public static void loadLibrary() { 35 | ReLinker.loadLibrary(InstrumentationRegistry.getContext(), SQLite.JNI_LIB); 36 | } 37 | 38 | @Test 39 | public void sqlite_libversion() throws Exception { 40 | Assert.assertThat(SQLite.getLibVersion(), Is.is(3018000L)); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /sqlite4a/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /sqlite4a/src/main/cpp/sqlite3_jni.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "sqlite3.h" 5 | 6 | #ifndef LOG_TAG 7 | #define LOG_TAG "sqlite3_jni" 8 | #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__) 9 | #endif // LOG_TAG 10 | 11 | static JavaVM *gJavaVm = nullptr; 12 | 13 | static struct { 14 | jclass clazz; 15 | } gSQLiteException; 16 | 17 | static struct { 18 | jclass clazz; 19 | jmethodID method; 20 | } gTrace; 21 | 22 | static struct { 23 | jclass clazz; 24 | jmethodID method; 25 | } gComparator; 26 | 27 | static struct { 28 | jclass clazz; 29 | jmethodID method; 30 | } gFunc; 31 | 32 | struct SQLiteDb { 33 | sqlite3 *handle = nullptr; 34 | jobject trace = nullptr; 35 | 36 | SQLiteDb(sqlite3 *db) { 37 | handle = db; 38 | } 39 | }; 40 | 41 | JNIEXPORT jint JNICALL 42 | JNI_OnLoad(JavaVM *vm, void *reserved) { 43 | JNIEnv *env; 44 | if (JNI_OK != vm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6)) { 45 | return JNI_ERR; 46 | } 47 | gJavaVm = vm; 48 | //gString.clazz = static_cast(env->NewGlobalRef(env->FindClass("java/lang/String"))); 49 | gSQLiteException.clazz = static_cast(env->NewGlobalRef(env->FindClass("sqlite4a/SQLiteException"))); 50 | gTrace.clazz = static_cast(env->NewGlobalRef(env->FindClass("sqlite4a/SQLiteDb$Trace"))); 51 | gTrace.method = env->GetMethodID(gTrace.clazz, "trace", "(Ljava/lang/String;)V"); 52 | gComparator.clazz = static_cast(env->NewGlobalRef(env->FindClass("java/util/Comparator"))); 53 | gComparator.method = env->GetMethodID(gComparator.clazz, "compare", "(Ljava/lang/Object;Ljava/lang/Object;)I"); 54 | gFunc.clazz = static_cast(env->NewGlobalRef(env->FindClass("sqlite4a/JniFunc"))); 55 | gFunc.method = env->GetMethodID(gFunc.clazz, "call", "(J[J)V"); 56 | sqlite3_soft_heap_limit64(8 * 1024 * 1024); 57 | sqlite3_initialize(); 58 | return JNI_VERSION_1_6; 59 | } 60 | 61 | static void throw_sqlite_exception(JNIEnv *env, const char *error, const char *sql = nullptr) { 62 | std::string message(error); 63 | if (sql) { 64 | message += ", while executing: "; 65 | message += sql; 66 | } 67 | if (gSQLiteException.clazz) { 68 | env->ThrowNew(gSQLiteException.clazz, message.c_str()); 69 | } else { 70 | LOGE("%s", message.c_str()); 71 | } 72 | } 73 | 74 | static int java_trace(unsigned mask, void *jfunc, void *p, void *x) { 75 | JNIEnv *env; 76 | if (jfunc && mask == SQLITE_TRACE_STMT && 77 | JNI_OK == gJavaVm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6)) { 78 | jobject func = env->NewLocalRef(static_cast(jfunc)); 79 | std::string sql(static_cast(x)); 80 | std::string trigger("--"); 81 | if (sql.compare(0, trigger.length(), trigger) != 0) { 82 | sqlite3_stmt *stmt = static_cast(p); 83 | char *sqlChars = sqlite3_expanded_sql(stmt); 84 | sql = static_cast(sqlChars); 85 | sqlite3_free(sqlChars); 86 | } 87 | env->CallVoidMethod(func, gTrace.method, env->NewStringUTF(sql.c_str())); 88 | env->DeleteLocalRef(func); 89 | } 90 | return 0; 91 | } 92 | 93 | static int java_compare(void *data, int lhsl, const void *lhsv, int rhsl, const void *rhsv) { 94 | JNIEnv *env; 95 | if (data && JNI_OK == gJavaVm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6)) { 96 | jobject comparator = env->NewLocalRef(static_cast(data)); 97 | std::string lhs(static_cast(lhsv), static_cast(lhsl)); 98 | std::string rhs(static_cast(rhsv), static_cast(rhsl)); 99 | int ret = env->CallIntMethod(comparator, gComparator.method, 100 | env->NewStringUTF(lhs.c_str()), 101 | env->NewStringUTF(rhs.c_str())); 102 | env->DeleteLocalRef(comparator); 103 | return ret; 104 | } 105 | return 0; 106 | } 107 | 108 | static void java_func(sqlite3_context *context, int argc, sqlite3_value **argv) { 109 | JNIEnv *env; 110 | if (JNI_OK == gJavaVm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6)) { 111 | void *data = sqlite3_user_data(context); 112 | if (data) { 113 | jobject func = env->NewLocalRef(static_cast(data)); 114 | jlong values[argc]; 115 | for (int i = 0; i < argc; ++i) { 116 | values[i] = reinterpret_cast(argv[i]); 117 | } 118 | jlongArray jvalues = env->NewLongArray(argc); 119 | env->SetLongArrayRegion(jvalues, 0, argc, values); 120 | env->CallVoidMethod(func, gFunc.method, reinterpret_cast(context), jvalues); 121 | env->DeleteLocalRef(jvalues); 122 | env->DeleteLocalRef(func); 123 | } 124 | } 125 | } 126 | 127 | static void java_destroy(void *data) { 128 | JNIEnv *env; 129 | if (data && JNI_OK == gJavaVm->GetEnv(reinterpret_cast(&env), JNI_VERSION_1_6)) { 130 | env->DeleteGlobalRef(static_cast(data)); 131 | } 132 | } 133 | 134 | extern "C" JNIEXPORT jlong JNICALL 135 | Java_sqlite4a_SQLite_getLibVersion(JNIEnv *env, jclass type) { 136 | return sqlite3_libversion_number(); 137 | } 138 | 139 | extern "C" JNIEXPORT jlong JNICALL 140 | Java_sqlite4a_SQLite_nativeOpen(JNIEnv *env, jclass type, jstring jpath, jint jflags) { 141 | sqlite3 *handle; 142 | const char *path = env->GetStringUTFChars(jpath, nullptr); 143 | int ret = sqlite3_open_v2(path, &handle, jflags, nullptr); 144 | env->ReleaseStringUTFChars(jpath, path); 145 | if (SQLITE_OK != ret) { 146 | throw_sqlite_exception(env, sqlite3_errmsg(handle)); 147 | return 0; 148 | } 149 | if ((jflags & SQLITE_OPEN_READWRITE) && sqlite3_db_readonly(handle, nullptr)) { 150 | sqlite3_close_v2(handle); 151 | throw_sqlite_exception(env, "Could not open the database in read/write mode."); 152 | return 0; 153 | } 154 | ret = sqlite3_busy_timeout(handle, 2500); 155 | if (SQLITE_OK != ret) { 156 | throw_sqlite_exception(env, "Could not set busy timeout"); 157 | sqlite3_close(handle); 158 | return 0; 159 | } 160 | return reinterpret_cast(new SQLiteDb(handle)); 161 | } 162 | 163 | extern "C" JNIEXPORT void JNICALL 164 | Java_sqlite4a_SQLiteDb_nativeClose(JNIEnv *env, jclass type, jlong jptr) { 165 | SQLiteDb *db = reinterpret_cast(jptr); 166 | if (db->trace) { 167 | env->DeleteGlobalRef(db->trace); 168 | } 169 | sqlite3_close_v2(db->handle); 170 | delete db; 171 | } 172 | 173 | extern "C" JNIEXPORT jint JNICALL 174 | Java_sqlite4a_SQLiteDb_nativeIsReadOnly(JNIEnv *env, jclass type, jlong jptr) { 175 | SQLiteDb *db = reinterpret_cast(jptr); 176 | return sqlite3_db_readonly(db->handle, nullptr); 177 | } 178 | 179 | extern "C" JNIEXPORT jint JNICALL 180 | Java_sqlite4a_SQLiteDb_nativeGetAutocommit(JNIEnv *env, jclass type, jlong jptr) { 181 | SQLiteDb *db = reinterpret_cast(jptr); 182 | return sqlite3_get_autocommit(db->handle); 183 | } 184 | 185 | extern "C" JNIEXPORT void JNICALL 186 | Java_sqlite4a_SQLiteDb_nativeExec(JNIEnv *env, jclass type, jlong jptr, jstring jsql) { 187 | SQLiteDb *db = reinterpret_cast(jptr); 188 | const char *sqlChars = env->GetStringUTFChars(jsql, nullptr); 189 | std::string sql(sqlChars); 190 | env->ReleaseStringUTFChars(jsql, sqlChars); 191 | int ret = sqlite3_exec(db->handle, sql.c_str(), nullptr, nullptr, nullptr); 192 | if (SQLITE_OK != ret) { 193 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle), sql.c_str()); 194 | } 195 | } 196 | 197 | extern "C" JNIEXPORT void JNICALL 198 | Java_sqlite4a_SQLiteDb_nativeTrace(JNIEnv *env, jclass type, jlong jptr, jobject jfunc) { 199 | SQLiteDb *db = reinterpret_cast(jptr); 200 | if (db->trace) { 201 | env->DeleteGlobalRef(db->trace); 202 | db->trace = nullptr; 203 | } 204 | if (jfunc) { 205 | db->trace = env->NewGlobalRef(jfunc); 206 | int ret = sqlite3_trace_v2(db->handle, SQLITE_TRACE_STMT, java_trace, db->trace); 207 | if (SQLITE_OK != ret) { 208 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle)); 209 | } 210 | } 211 | } 212 | 213 | extern "C" JNIEXPORT jdouble JNICALL 214 | Java_sqlite4a_SQLiteDb_nativeExecForDouble(JNIEnv *env, jclass type, jlong jptr, jstring jsql) { 215 | SQLiteDb *db = reinterpret_cast(jptr); 216 | const char *csql = env->GetStringUTFChars(jsql, nullptr); 217 | std::string sql(csql); 218 | env->ReleaseStringUTFChars(jsql, csql); 219 | sqlite3_stmt *stmt; 220 | int ret = sqlite3_prepare_v2(db->handle, sql.c_str(), static_cast(sql.length()), &stmt, nullptr); 221 | if (SQLITE_OK != ret) { 222 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle), sql.c_str()); 223 | } 224 | double value = 0; 225 | if (SQLITE_ROW == sqlite3_step(stmt)) { 226 | value = sqlite3_column_double(stmt, 0); 227 | } 228 | sqlite3_finalize(stmt); 229 | return value; 230 | } 231 | 232 | extern "C" JNIEXPORT jlong JNICALL 233 | Java_sqlite4a_SQLiteDb_nativePrepare(JNIEnv *env, jclass type, jlong jptr, jstring jsql) { 234 | SQLiteDb *db = reinterpret_cast(jptr); 235 | const char *sqlChars = env->GetStringUTFChars(jsql, nullptr); 236 | std::string sql(sqlChars); 237 | env->ReleaseStringUTFChars(jsql, sqlChars); 238 | sqlite3_stmt *stmt; 239 | int ret = sqlite3_prepare_v2(db->handle, sql.c_str(), static_cast(sql.length()), &stmt, nullptr); 240 | if (SQLITE_OK != ret) { 241 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle), sql.c_str()); 242 | } 243 | return reinterpret_cast(stmt); 244 | } 245 | 246 | extern "C" JNIEXPORT void JNICALL 247 | Java_sqlite4a_SQLiteDb_nativeCreateCollation(JNIEnv *env, jclass type, jlong jptr, jstring jname, 248 | jobject jcomparator) { 249 | SQLiteDb *db = reinterpret_cast(jptr); 250 | jobject comparator = env->NewGlobalRef(jcomparator); 251 | const char *nameChars = env->GetStringUTFChars(jname, nullptr); 252 | std::string name(nameChars); 253 | env->ReleaseStringUTFChars(jname, nameChars); 254 | int ret = sqlite3_create_collation_v2(db->handle, name.c_str(), SQLITE_UTF8, comparator, java_compare, 255 | java_destroy); 256 | if (SQLITE_OK != ret) { 257 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle)); 258 | } 259 | } 260 | 261 | extern "C" JNIEXPORT void JNICALL 262 | Java_sqlite4a_SQLiteDb_nativeCreateFunction(JNIEnv *env, jclass type, jlong jptr, jstring jname, jint numArgs, 263 | jobject jfunc) { 264 | SQLiteDb *db = reinterpret_cast(jptr); 265 | const char *nameChars = env->GetStringUTFChars(jname, nullptr); 266 | std::string name(nameChars); 267 | env->ReleaseStringUTFChars(jname, nameChars); 268 | jobject func = env->NewGlobalRef(jfunc); 269 | int ret = sqlite3_create_function_v2(db->handle, name.c_str(), numArgs, SQLITE_UTF8, func, java_func, nullptr, 270 | nullptr, java_destroy); 271 | if (SQLITE_OK != ret) { 272 | throw_sqlite_exception(env, sqlite3_errmsg(db->handle)); 273 | } 274 | } 275 | 276 | extern "C" JNIEXPORT void JNICALL 277 | Java_sqlite4a_SQLiteStmt_nativeBindNull(JNIEnv *env, jclass type, jlong jptr, jint index) { 278 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 279 | int ret = sqlite3_bind_null(stmt, index); 280 | if (SQLITE_OK != ret) { 281 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 282 | } 283 | } 284 | 285 | extern "C" JNIEXPORT void JNICALL 286 | Java_sqlite4a_SQLiteStmt_nativeBindLong(JNIEnv *env, jclass type, jlong jptr, jint index, jlong value) { 287 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 288 | int ret = sqlite3_bind_int64(stmt, index, value); 289 | if (SQLITE_OK != ret) { 290 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 291 | } 292 | } 293 | 294 | extern "C" JNIEXPORT void JNICALL 295 | Java_sqlite4a_SQLiteStmt_nativeBindDouble(JNIEnv *env, jclass type, jlong jptr, jint index, jdouble value) { 296 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 297 | int ret = sqlite3_bind_double(stmt, index, value); 298 | if (SQLITE_OK != ret) { 299 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 300 | } 301 | } 302 | 303 | extern "C" JNIEXPORT void JNICALL 304 | Java_sqlite4a_SQLiteStmt_nativeBindString(JNIEnv *env, jclass type, jlong jptr, jint index, jstring jvalue) { 305 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 306 | const char *value = env->GetStringUTFChars(jvalue, nullptr); 307 | int ret = sqlite3_bind_text(stmt, index, value, static_cast(strlen(value)), SQLITE_TRANSIENT); 308 | env->ReleaseStringUTFChars(jvalue, value); 309 | if (SQLITE_OK != ret) { 310 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 311 | } 312 | } 313 | 314 | extern "C" JNIEXPORT void JNICALL 315 | Java_sqlite4a_SQLiteStmt_nativeBindBlob(JNIEnv *env, jclass type, jlong jptr, jint index, jbyteArray jvalue) { 316 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 317 | jbyte *value = env->GetByteArrayElements(jvalue, nullptr); 318 | int ret = sqlite3_bind_blob(stmt, index, value, env->GetArrayLength(jvalue), SQLITE_TRANSIENT); 319 | env->ReleaseByteArrayElements(jvalue, value, 0); 320 | if (SQLITE_OK != ret) { 321 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 322 | } 323 | } 324 | 325 | extern "C" JNIEXPORT void JNICALL 326 | Java_sqlite4a_SQLiteStmt_nativeClearBindings(JNIEnv *env, jclass type, jlong jptr) { 327 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 328 | int ret = sqlite3_reset(stmt); 329 | if (SQLITE_OK == ret) { 330 | ret = sqlite3_clear_bindings(stmt); 331 | } 332 | if (SQLITE_OK != ret) { 333 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 334 | } 335 | } 336 | 337 | extern "C" JNIEXPORT jlong JNICALL 338 | Java_sqlite4a_SQLiteStmt_nativeInsert(JNIEnv *env, jclass type, jlong jptr) { 339 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 340 | sqlite3 *db = sqlite3_db_handle(stmt); 341 | int ret = sqlite3_step(stmt); 342 | if (SQLITE_DONE != ret) { 343 | sqlite3_finalize(stmt); 344 | throw_sqlite_exception(env, sqlite3_errmsg(db)); 345 | return -1; 346 | } 347 | return sqlite3_last_insert_rowid(db); 348 | } 349 | 350 | extern "C" JNIEXPORT jint JNICALL 351 | Java_sqlite4a_SQLiteStmt_nativeExecute(JNIEnv *env, jclass type, jlong jptr) { 352 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 353 | sqlite3 *db = sqlite3_db_handle(stmt); 354 | int ret = sqlite3_step(stmt); 355 | if (SQLITE_DONE != ret) { 356 | sqlite3_finalize(stmt); 357 | throw_sqlite_exception(env, sqlite3_errmsg(db)); 358 | return -1; 359 | } 360 | return sqlite3_changes(db); 361 | } 362 | 363 | extern "C" JNIEXPORT jint JNICALL 364 | Java_sqlite4a_SQLiteStmt_nativeBusy(JNIEnv *env, jclass type, jlong jptr) { 365 | return sqlite3_stmt_busy(reinterpret_cast(jptr)); 366 | } 367 | 368 | extern "C" JNIEXPORT void JNICALL 369 | Java_sqlite4a_SQLiteStmt_nativeReset(JNIEnv *env, jclass type, jlong jptr) { 370 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 371 | int ret = sqlite3_reset(stmt); 372 | if (SQLITE_OK != ret) { 373 | throw_sqlite_exception(env, sqlite3_errmsg(sqlite3_db_handle(stmt))); 374 | } 375 | } 376 | 377 | extern "C" JNIEXPORT void JNICALL 378 | Java_sqlite4a_SQLiteStmt_nativeFinalize(JNIEnv *env, jclass type, jlong jptr) { 379 | sqlite3_finalize(reinterpret_cast(jptr)); 380 | } 381 | 382 | extern "C" JNIEXPORT jint JNICALL 383 | Java_sqlite4a_RowIterator_nativeStep(JNIEnv *env, jclass type, jlong jptr) { 384 | return sqlite3_step(reinterpret_cast(jptr)); 385 | } 386 | 387 | extern "C" JNIEXPORT jint JNICALL 388 | Java_sqlite4a_RowIterator_nativeGetColumnCount(JNIEnv *env, jclass type, jlong jptr) { 389 | return sqlite3_column_count(reinterpret_cast(jptr)); 390 | } 391 | 392 | extern "C" JNIEXPORT jstring JNICALL 393 | Java_sqlite4a_RowIterator_nativeGetColumnName(JNIEnv *env, jclass type, jlong jptr, jint index) { 394 | return env->NewStringUTF(sqlite3_column_name(reinterpret_cast(jptr), index)); 395 | } 396 | 397 | extern "C" JNIEXPORT jlong JNICALL 398 | Java_sqlite4a_RowIterator_nativeGetColumnLong(JNIEnv *env, jclass type, jlong jptr, jint index) { 399 | return sqlite3_column_int64(reinterpret_cast(jptr), index); 400 | } 401 | 402 | extern "C" JNIEXPORT jdouble JNICALL 403 | Java_sqlite4a_RowIterator_nativeGetColumnDouble(JNIEnv *env, jclass type, jlong jptr, jint index) { 404 | return sqlite3_column_double(reinterpret_cast(jptr), index); 405 | } 406 | 407 | extern "C" JNIEXPORT jstring JNICALL 408 | Java_sqlite4a_RowIterator_nativeGetColumnString(JNIEnv *env, jclass type, jlong jptr, jint index) { 409 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 410 | const unsigned char *text = sqlite3_column_text(stmt, index); 411 | return env->NewStringUTF(reinterpret_cast(text)); 412 | } 413 | 414 | extern "C" JNIEXPORT jbyteArray JNICALL 415 | Java_sqlite4a_RowIterator_nativeGetColumnBlob(JNIEnv *env, jclass type, jlong jptr, jint index) { 416 | sqlite3_stmt *stmt = reinterpret_cast(jptr); 417 | int size = sqlite3_column_bytes(stmt, index); 418 | const void *value = sqlite3_column_blob(stmt, index); 419 | jbyteArray jvalue = env->NewByteArray(size); 420 | env->SetByteArrayRegion(jvalue, 0, size, reinterpret_cast(value)); 421 | return jvalue; 422 | } 423 | 424 | extern "C" JNIEXPORT jlong JNICALL 425 | Java_sqlite4a_SQLiteValue_nativeLongValue(JNIEnv *env, jclass type, jlong jptr) { 426 | return sqlite3_value_int64(reinterpret_cast(jptr)); 427 | } 428 | 429 | extern "C" JNIEXPORT jdouble JNICALL 430 | Java_sqlite4a_SQLiteValue_nativeDoubleValue(JNIEnv *env, jclass type, jlong jptr) { 431 | return sqlite3_value_double(reinterpret_cast(jptr)); 432 | } 433 | 434 | extern "C" JNIEXPORT jstring JNICALL 435 | Java_sqlite4a_SQLiteValue_nativeStringValue(JNIEnv *env, jclass type, jlong jptr) { 436 | sqlite3_value *value = reinterpret_cast(jptr); 437 | const unsigned char *text = sqlite3_value_text(value); 438 | return env->NewStringUTF(reinterpret_cast(text)); 439 | } 440 | 441 | extern "C" JNIEXPORT jbyteArray JNICALL 442 | Java_sqlite4a_SQLiteValue_nativeBlobValue(JNIEnv *env, jclass type, jlong jptr) { 443 | sqlite3_value *value = reinterpret_cast(jptr); 444 | int size = sqlite3_value_bytes(value); 445 | const void *blob = sqlite3_value_blob(value); 446 | jbyteArray jvalue = env->NewByteArray(size); 447 | env->SetByteArrayRegion(jvalue, 0, size, reinterpret_cast(blob)); 448 | return jvalue; 449 | } 450 | 451 | extern "C" JNIEXPORT void JNICALL 452 | Java_sqlite4a_SQLiteContext_nativeResultNull(JNIEnv *env, jclass type, jlong jptr) { 453 | sqlite3_result_null(reinterpret_cast(jptr)); 454 | } 455 | 456 | extern "C" JNIEXPORT void JNICALL 457 | Java_sqlite4a_SQLiteContext_nativeResultLong(JNIEnv *env, jclass type, jlong jptr, jlong result) { 458 | sqlite3_result_int64(reinterpret_cast(jptr), result); 459 | } 460 | 461 | extern "C" JNIEXPORT void JNICALL 462 | Java_sqlite4a_SQLiteContext_nativeResultText(JNIEnv *env, jclass type, jlong jptr, jstring resultStr) { 463 | sqlite3_context *context = reinterpret_cast(jptr); 464 | const char *result = env->GetStringUTFChars(resultStr, nullptr); 465 | sqlite3_result_text(context, result, static_cast(strlen(result)), SQLITE_TRANSIENT); 466 | env->ReleaseStringUTFChars(resultStr, result); 467 | } 468 | 469 | extern "C" JNIEXPORT void JNICALL 470 | Java_sqlite4a_SQLiteContext_nativeResultDouble(JNIEnv *env, jclass type, jlong jptr, jdouble result) { 471 | sqlite3_result_double(reinterpret_cast(jptr), result); 472 | } 473 | 474 | extern "C" JNIEXPORT void JNICALL 475 | Java_sqlite4a_SQLiteContext_nativeResultBlob(JNIEnv *env, jclass type, jlong jptr, jbyteArray resultArr) { 476 | sqlite3_context *context = reinterpret_cast(jptr); 477 | jbyte *result = env->GetByteArrayElements(resultArr, nullptr); 478 | sqlite3_result_blob(context, result, env->GetArrayLength(resultArr), SQLITE_TRANSIENT); 479 | env->ReleaseByteArrayElements(resultArr, result, 0); 480 | } 481 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/JniFunc.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | class JniFunc { 20 | 21 | private final SQLiteDb.Func mFunc; 22 | 23 | JniFunc(SQLiteDb.Func func) { 24 | mFunc = func; 25 | } 26 | 27 | void call(long contextPtr, long[] valuePtrs) { 28 | final SQLiteValue[] values = new SQLiteValue[valuePtrs.length]; 29 | for (int i = 0; i < valuePtrs.length; ++i) { 30 | values[i] = new SQLiteValue(valuePtrs[i]); 31 | } 32 | mFunc.call(new SQLiteContext(contextPtr), values); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/RowIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.NonNull; 20 | 21 | import java.util.NoSuchElementException; 22 | 23 | class RowIterator implements SQLiteIterator, SQLiteRow { 24 | 25 | private static final int SQLITE_ROW = 100; 26 | 27 | private static final int SQLITE_DONE = 101; 28 | 29 | private final long mStmtPtr; 30 | 31 | private boolean mHasNext; 32 | 33 | private boolean mDone; 34 | 35 | RowIterator(long stmtPtr) { 36 | mStmtPtr = stmtPtr; 37 | } 38 | 39 | private static native int nativeStep(long ptr); 40 | 41 | private static native int nativeGetColumnCount(long ptr); 42 | 43 | private static native String nativeGetColumnName(long ptr, int index); 44 | 45 | private static native long nativeGetColumnLong(long ptr, int index); 46 | 47 | private static native double nativeGetColumnDouble(long ptr, int index); 48 | 49 | private static native String nativeGetColumnString(long ptr, int index); 50 | 51 | private static native byte[] nativeGetColumnBlob(long ptr, int index); 52 | 53 | @Override 54 | public boolean hasNext() { 55 | if (!mDone) { 56 | final int step = nativeStep(mStmtPtr); 57 | mDone = step == SQLITE_DONE; 58 | mHasNext = step == SQLITE_ROW; 59 | } 60 | return !mDone && mHasNext; 61 | } 62 | 63 | @Override 64 | public SQLiteRow next() { 65 | if (mHasNext) { 66 | mHasNext = false; 67 | return this; 68 | } 69 | throw new NoSuchElementException(); 70 | } 71 | 72 | @Override 73 | public void remove() { 74 | throw new UnsupportedOperationException(); 75 | } 76 | 77 | @Override 78 | public void close() { 79 | SQLiteStmt.nativeFinalize(mStmtPtr); 80 | } 81 | 82 | public int getColumnCount() { 83 | return nativeGetColumnCount(mStmtPtr); 84 | } 85 | 86 | @NonNull 87 | public String getColumnName(int index) { 88 | return nativeGetColumnName(mStmtPtr, index); 89 | } 90 | 91 | public long getColumnLong(int index) { 92 | return nativeGetColumnLong(mStmtPtr, index); 93 | } 94 | 95 | public double getColumnDouble(int index) { 96 | return nativeGetColumnDouble(mStmtPtr, index); 97 | } 98 | 99 | public String getColumnString(int index) { 100 | return nativeGetColumnString(mStmtPtr, index); 101 | } 102 | 103 | public byte[] getColumnBlob(int index) { 104 | return nativeGetColumnBlob(mStmtPtr, index); 105 | } 106 | 107 | } 108 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLite.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.IntDef; 20 | import android.support.annotation.NonNull; 21 | 22 | import java.lang.annotation.Retention; 23 | import java.lang.annotation.RetentionPolicy; 24 | 25 | public class SQLite { 26 | 27 | public static final String JNI_LIB = "sqlite3_jni"; 28 | 29 | public static final int OPEN_READONLY = 0x00000001; 30 | 31 | public static final int OPEN_READWRITE = 0x00000002; 32 | 33 | public static final int OPEN_CREATE = 0x00000004; 34 | 35 | public static final int OPEN_URI = 0b1000000; 36 | 37 | public static final int OPEN_NOMUTEX = 0x00008000; 38 | 39 | public static final int OPEN_FULLMUTEX = 0x00010000; 40 | 41 | public static native long getLibVersion(); 42 | 43 | @NonNull 44 | public static SQLiteDb open(@NonNull String path, @OpenFlags int flags) { 45 | return new SQLiteDb(nativeOpen(path, flags)); 46 | } 47 | 48 | private static native long nativeOpen(String path, int flags); 49 | 50 | @Retention(RetentionPolicy.SOURCE) 51 | @IntDef(value = { 52 | OPEN_READONLY, 53 | OPEN_READWRITE, 54 | OPEN_CREATE, 55 | OPEN_URI, 56 | OPEN_NOMUTEX, 57 | OPEN_FULLMUTEX 58 | }, flag = true) 59 | public @interface OpenFlags { 60 | 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | public class SQLiteContext { 20 | 21 | private final long mContextPtr; 22 | 23 | SQLiteContext(long contextPtr) { 24 | mContextPtr = contextPtr; 25 | } 26 | 27 | private static native void nativeResultNull(long contextPtr); 28 | 29 | private static native void nativeResultLong(long contextPtr, long result); 30 | 31 | private static native void nativeResultText(long contextPtr, String result); 32 | 33 | private static native void nativeResultDouble(long contextPtr, double result); 34 | 35 | private static native void nativeResultBlob(long contextPtr, byte[] result); 36 | 37 | public void resultNull() { 38 | nativeResultNull(mContextPtr); 39 | } 40 | 41 | public void resultLong(long result) { 42 | nativeResultLong(mContextPtr, result); 43 | } 44 | 45 | public void resultString(String result) { 46 | if (result != null) { 47 | nativeResultText(mContextPtr, result); 48 | } 49 | } 50 | 51 | public void resultDouble(double result) { 52 | nativeResultDouble(mContextPtr, result); 53 | } 54 | 55 | public void resultBlob(byte[] result) { 56 | if (result != null) { 57 | nativeResultBlob(mContextPtr, result); 58 | } 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteDb.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.NonNull; 20 | 21 | import java.io.Closeable; 22 | import java.util.Comparator; 23 | 24 | public class SQLiteDb implements Closeable { 25 | 26 | private final long mDbPtr; 27 | 28 | SQLiteDb(long ptr) { 29 | mDbPtr = ptr; 30 | } 31 | 32 | private static native void nativeClose(long ptr); 33 | 34 | private static native void nativeTrace(long ptr, Trace func); 35 | 36 | private static native int nativeIsReadOnly(long ptr); 37 | 38 | private static native int nativeGetAutocommit(long ptr); 39 | 40 | private static native void nativeExec(long ptr, String sql); 41 | 42 | private static native double nativeExecForDouble(long ptr, String sql); 43 | 44 | private static native long nativePrepare(long ptr, String sql); 45 | 46 | private static native void nativeCreateCollation(long ptr, String name, Comparator comparator); 47 | 48 | private static native void nativeCreateFunction(long ptr, String name, int numArgs, JniFunc func); 49 | 50 | public void trace(@NonNull Trace func) { 51 | nativeTrace(mDbPtr, func); 52 | } 53 | 54 | public boolean isReadOnly() { 55 | return nativeIsReadOnly(mDbPtr) != 0; 56 | } 57 | 58 | public boolean inTransaction() { 59 | return nativeGetAutocommit(mDbPtr) <= 0; 60 | } 61 | 62 | public void exec(@NonNull String sql) { 63 | nativeExec(mDbPtr, sql); 64 | } 65 | 66 | @NonNull 67 | public Number execForNumber(@NonNull String sql) { 68 | return nativeExecForDouble(mDbPtr, sql); 69 | } 70 | 71 | @NonNull 72 | public SQLiteStmt prepare(@NonNull String sql) { 73 | return new SQLiteStmt(nativePrepare(mDbPtr, sql)); 74 | } 75 | 76 | public void createCollation(@NonNull String name, @NonNull Comparator comparator) { 77 | nativeCreateCollation(mDbPtr, name, comparator); 78 | } 79 | 80 | public void createFunction(@NonNull String name, int numArgs, @NonNull Func func) { 81 | nativeCreateFunction(mDbPtr, name, numArgs, new JniFunc(func)); 82 | } 83 | 84 | @Override 85 | public void close() { 86 | nativeClose(mDbPtr); 87 | } 88 | 89 | public interface Trace { 90 | void trace(String sql); 91 | } 92 | 93 | public interface Func { 94 | void call(@NonNull SQLiteContext context, @NonNull SQLiteValue[] values); 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | public class SQLiteException extends RuntimeException { 20 | 21 | public SQLiteException(String message) { 22 | super(message); 23 | } 24 | 25 | public SQLiteException(Throwable cause) { 26 | super(cause); 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteIterator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import java.io.Closeable; 20 | import java.util.Iterator; 21 | 22 | public interface SQLiteIterator extends Iterator, Closeable { 23 | 24 | @Override 25 | void close(); 26 | 27 | } 28 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteRow.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.NonNull; 20 | 21 | public interface SQLiteRow { 22 | 23 | int getColumnCount(); 24 | 25 | @NonNull 26 | String getColumnName(int index); 27 | 28 | long getColumnLong(int index); 29 | 30 | double getColumnDouble(int index); 31 | 32 | String getColumnString(int index); 33 | 34 | byte[] getColumnBlob(int index); 35 | 36 | } 37 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteStmt.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | import android.support.annotation.NonNull; 20 | import android.support.annotation.Nullable; 21 | 22 | import java.io.Closeable; 23 | 24 | public class SQLiteStmt implements Closeable { 25 | 26 | private final long mStmtPtr; 27 | 28 | SQLiteStmt(long stmtPtr) { 29 | mStmtPtr = stmtPtr; 30 | } 31 | 32 | static native void nativeFinalize(long ptr); 33 | 34 | private static native void nativeBindNull(long ptr, int index); 35 | 36 | private static native void nativeBindLong(long ptr, int index, long value); 37 | 38 | private static native void nativeBindDouble(long ptr, int index, double value); 39 | 40 | private static native void nativeBindString(long ptr, int index, String value); 41 | 42 | private static native void nativeBindBlob(long ptr, int index, byte[] value); 43 | 44 | private static native void nativeClearBindings(long ptr); 45 | 46 | private static native long nativeInsert(long ptr); 47 | 48 | private static native int nativeExecute(long ptr); 49 | 50 | private static native int nativeBusy(long ptr); 51 | 52 | private static native void nativeReset(long ptr); 53 | 54 | public void bindNull(int index) { 55 | nativeBindNull(mStmtPtr, index); 56 | } 57 | 58 | public void bindLong(int index, long value) { 59 | nativeBindLong(mStmtPtr, index, value); 60 | } 61 | 62 | public void bindDouble(int index, double value) { 63 | nativeBindDouble(mStmtPtr, index, value); 64 | } 65 | 66 | public void bindString(int index, @Nullable String value) { 67 | if (value != null) { 68 | nativeBindString(mStmtPtr, index, value); 69 | } 70 | } 71 | 72 | public void bindBlob(int index, @Nullable byte[] value) { 73 | if (value != null) { 74 | nativeBindBlob(mStmtPtr, index, value); 75 | } 76 | } 77 | 78 | public void clearBindings() { 79 | nativeClearBindings(mStmtPtr); 80 | } 81 | 82 | public long insert() { 83 | return nativeInsert(mStmtPtr); 84 | } 85 | 86 | @NonNull 87 | public SQLiteIterator select() { 88 | if (nativeBusy(mStmtPtr) > 0) { 89 | nativeReset(mStmtPtr); 90 | } 91 | return new RowIterator(mStmtPtr); 92 | } 93 | 94 | public int execute() { 95 | return nativeExecute(mStmtPtr); 96 | } 97 | 98 | @Override 99 | public void close() { 100 | nativeFinalize(mStmtPtr); 101 | } 102 | 103 | } 104 | -------------------------------------------------------------------------------- /sqlite4a/src/main/java/sqlite4a/SQLiteValue.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-2017 exzogeni.com 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package sqlite4a; 18 | 19 | public class SQLiteValue { 20 | 21 | private final long mValuePtr; 22 | 23 | SQLiteValue(long valuePtr) { 24 | mValuePtr = valuePtr; 25 | } 26 | 27 | static native long nativeLongValue(long valuePtr); 28 | 29 | static native String nativeStringValue(long valuePtr); 30 | 31 | static native double nativeDoubleValue(long valuePtr); 32 | 33 | static native byte[] nativeBlobValue(long valuePtr); 34 | 35 | public long longValue() { 36 | return nativeLongValue(mValuePtr); 37 | } 38 | 39 | public String stringValue() { 40 | return nativeStringValue(mValuePtr); 41 | } 42 | 43 | public double doubleValue() { 44 | return nativeDoubleValue(mValuePtr); 45 | } 46 | 47 | public byte[] blobValue() { 48 | return nativeBlobValue(mValuePtr); 49 | } 50 | 51 | } 52 | --------------------------------------------------------------------------------