├── AndroidShillelagh.png
├── gradle
├── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── credentials.gradle
├── dependencies.gradle
├── javaDoc.gradle
├── artifactory.gradle
└── bintray.gradle
├── shillelagh-sample
├── src
│ └── main
│ │ ├── res
│ │ ├── drawable-hdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-mdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xhdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xxhdpi
│ │ │ └── ic_launcher.png
│ │ ├── drawable-xxxhdpi
│ │ │ └── ic_launcher.png
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── java
│ │ └── com
│ │ │ └── example
│ │ │ └── shillelagh
│ │ │ ├── model
│ │ │ ├── Base.java
│ │ │ ├── Chapter.java
│ │ │ ├── Author.java
│ │ │ ├── Image.java
│ │ │ ├── CollectionsTest.java
│ │ │ └── Book.java
│ │ │ ├── ExampleSqliteHelper.java
│ │ │ ├── ShillelaghApp.java
│ │ │ └── MainActivity.java
│ │ └── AndroidManifest.xml
├── proguard-rules.txt
└── shillelagh-sample.gradle
├── shillelagh-tests
├── src
│ ├── main
│ │ ├── res
│ │ │ ├── drawable-hdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-mdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-xhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-xxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── drawable-xxxhdpi
│ │ │ │ └── ic_launcher.png
│ │ │ ├── values
│ │ │ │ └── strings.xml
│ │ │ └── layout
│ │ │ │ └── activity_speed_test.xml
│ │ ├── java
│ │ │ └── com
│ │ │ │ └── example
│ │ │ │ └── shillelagh
│ │ │ │ ├── model
│ │ │ │ ├── TestNotTableObject.java
│ │ │ │ ├── TestJavaObjectsTable.java
│ │ │ │ ├── TestOneToOne.java
│ │ │ │ ├── TestOneToMany.java
│ │ │ │ ├── TestBlobs.java
│ │ │ │ ├── SimpleObject.java
│ │ │ │ ├── TestPrimitiveTable.java
│ │ │ │ ├── TestBoxedPrimitivesTable.java
│ │ │ │ └── TestParcelable.java
│ │ │ │ ├── TestSQLiteOpenHelper.java
│ │ │ │ └── SpeedTestActivity.java
│ │ └── AndroidManifest.xml
│ └── androidTest
│ │ ├── res
│ │ └── values
│ │ │ └── strings.xml
│ │ ├── AndroidManifest.xml
│ │ └── java
│ │ └── shillelagh
│ │ ├── crud
│ │ ├── DropTableTest.java
│ │ ├── MapTest.java
│ │ └── InsertTest.java
│ │ └── QueryBuilderTest.java
├── README.md
└── shillelagh-tests.gradle
├── gradle.properties
├── .gitignore
├── CHANGELOG.md
├── shillelagh-processor
├── src
│ └── main
│ │ ├── resources
│ │ └── META-INF
│ │ │ └── services
│ │ │ └── javax.annotation.processing.Processor
│ │ └── java
│ │ └── shillelagh
│ │ └── internal
│ │ ├── SqliteText.java
│ │ ├── Strings.java
│ │ ├── ShillelaghLogger.java
│ │ ├── SqliteReal.java
│ │ ├── SqliteInteger.java
│ │ ├── CursorFunctions.java
│ │ ├── SqliteType.java
│ │ └── TableColumn.java
└── shillelagh-processor.gradle
├── shillelagh
├── src
│ ├── test
│ │ ├── java
│ │ │ └── shillelagh
│ │ │ │ └── test
│ │ │ │ ├── IntConstructor.java
│ │ │ │ ├── ByteConstructor.java
│ │ │ │ ├── CharConstructor.java
│ │ │ │ ├── LongConstructor.java
│ │ │ │ ├── FloatConstructor.java
│ │ │ │ ├── NoParamConstructor.java
│ │ │ │ ├── ShortConstructor.java
│ │ │ │ ├── DoubleConstructor.java
│ │ │ │ ├── StringConstructor.java
│ │ │ │ ├── BooleanConstructor.java
│ │ │ │ └── LotsOfParamConstructor.java
│ │ └── groovy
│ │ │ └── shillelagh
│ │ │ └── internal
│ │ │ └── ShillelaghUtilSpec.groovy
│ └── main
│ │ └── java
│ │ └── shillelagh
│ │ ├── CursorLoader.java
│ │ ├── Id.java
│ │ ├── Operator.java
│ │ ├── Table.java
│ │ ├── Preconditions.java
│ │ ├── Column.java
│ │ ├── OrderByBuilder.java
│ │ ├── WhereBuilder.java
│ │ ├── Builder.java
│ │ ├── internal
│ │ └── ShillelaghUtil.java
│ │ └── QueryBuilder.java
└── shillelagh.gradle
├── settings.gradle
├── gradlew.bat
├── README.md
├── gradlew
├── checkstyle.xml
└── LICENSE
/AndroidShillelagh.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/AndroidShillelagh.png
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-sample/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-sample/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-tests/src/main/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-tests/src/main/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-tests/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Used for annotation processor debugging
2 | #org.gradle.daemon=true
3 | #org.gradle.jvmargs=-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005
4 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/drawable-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-sample/src/main/res/drawable-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-sample/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/drawable-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-tests/src/main/res/drawable-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/drawable-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-tests/src/main/res/drawable-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/drawable-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AndrewReitz/shillelagh/HEAD/shillelagh-sample/src/main/res/drawable-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/shillelagh-tests/README.md:
--------------------------------------------------------------------------------
1 | # Test Project to Test Shillelagh
2 |
3 | For accurate tests these need to be run on an Android device. This is the reason these tests
4 | are not in the Shillelagh Project
--------------------------------------------------------------------------------
/shillelagh-sample/proguard-rules.txt:
--------------------------------------------------------------------------------
1 | -ignorewarnings
2 | -dontobfuscate
3 |
4 | -keep class **$$Shillelagh { *; }
5 |
6 | -keep class com.facebook.stetho.** { *; }
7 |
8 | -dontwarn rx.internal.**
9 | -dontwarn shillelagh.internal.objenesis.**
10 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Dec 01 09:28:01 CST 2014
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-2.2.1-all.zip
7 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # built application files
2 | *.apk
3 | *.ap_
4 |
5 | # files for the dex VM
6 | *.dex
7 |
8 | # Java class files
9 | *.class
10 |
11 | # generated files
12 | bin/
13 | gen/
14 |
15 | # Local configuration file (sdk path, etc)
16 | local.properties
17 |
18 | # Eclipse project files
19 | .classpath
20 | .project
21 |
22 | # Proguard folder generated by Eclipse
23 | proguard/
24 |
25 | # Intellij project files
26 | *.iml
27 | *.ipr
28 | *.iws
29 | .idea/
30 |
31 | # Gradle Stuff
32 | .gradle
33 | build/
34 |
35 | # Cached Checkstyle
36 | checkstyle.cache
37 |
--------------------------------------------------------------------------------
/gradle/credentials.gradle:
--------------------------------------------------------------------------------
1 | ext.bintrayUser = project.hasProperty('bintrayUsername')?project.getProperty('bintrayUsername'):System.getenv('BINTRAY_USER')?:''
2 | ext.bintrayKey = project.hasProperty('bintrayKey')?project.getProperty('bintrayKey'):System.getenv('BINTRAY_KEY')?:''
3 | ext.signingPassword = project.hasProperty('signingPassword')?project.getProperty('signingPassword'):System.getenv('SIGNING_PASSWORD')?:''
4 | ext.sonatypeUserName = project.hasProperty('sonatypeUserName')?project.getProperty('sonatypeUserName'):System.getenv('SONATYPE_USER_NAME')?:''
5 | ext.sonatypePassword = project.hasProperty('sonatypePassword')?project.getProperty('sonatypePassword'):System.getenv('SONATYPE_PASSWORD')?:''
6 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | ## Version 1.0.0
4 |
5 | - Allowed Lists and Maps to be saved as blobs.
6 | - Fixed issues with constructing objects that don't have default empty constructors.
7 | - Removed final modifier from Shillelagh to allow for mocking.
8 |
9 | ## Version 0.5.0 (11-30-2014)
10 |
11 | - Added ability to define column, id, and table names.
12 | - Renamed `@Field` annotation to `@Column`.
13 | - Removed `@OrmOnly` annotation and need for empty no arg constructors.
14 |
15 | ## Version 0.4.0 (11-15-2014)
16 |
17 | - Added query builder functionality. Returned from `selectFrom`
18 | - Removed namespacing on tables. All tables MUST have unique names.
19 | - Create statements written out.
20 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright 2014 Andrew Reitz
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 | shillelagh.internal.ShillelaghProcessor
18 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | Shillelagh
20 |
21 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | Shillelagh
20 |
21 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
19 | Shillelagh
20 |
21 |
--------------------------------------------------------------------------------
/gradle/dependencies.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | ext {
18 | commonVersions = [
19 | rxjava: "1.0.9",
20 | rxandroid: "0.24.0",
21 | buildToolsVersion: "22.0.1",
22 | compileSdkVersion: 22
23 | ]
24 | }
25 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/Base.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Id;
20 |
21 | public class Base {
22 | @Id long id;
23 |
24 | public final long getId() {
25 | return id;
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/IntConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class IntConstructor {
20 | private final int test;
21 |
22 | public IntConstructor(int test) {
23 | this.test = test;
24 | }
25 |
26 | public int getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/gradle/javaDoc.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | // custom tasks for creating source/javadoc jars
18 | task sourcesJar(type: Jar, dependsOn: classes) {
19 | classifier = 'sources'
20 | from sourceSets.main.allSource
21 | }
22 |
23 | task javadocJar(type: Jar, dependsOn: javadoc) {
24 | classifier = 'javadoc'
25 | from javadoc.destinationDir
26 | }
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/CursorLoader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import android.database.Cursor;
20 |
21 | /**
22 | * Interface for getting a cursor so that the cursor has different
23 | * ways of being loaded in observables.
24 | */
25 | interface CursorLoader {
26 | Cursor getCursor();
27 | }
28 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/ByteConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class ByteConstructor {
20 | private final byte test;
21 |
22 | public ByteConstructor(byte test) {
23 | this.test = test;
24 | }
25 |
26 | public byte getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/CharConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class CharConstructor {
20 | private final char test;
21 |
22 | public CharConstructor(char test) {
23 | this.test = test;
24 | }
25 |
26 | public char getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/LongConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class LongConstructor {
20 | private final long test;
21 |
22 | public LongConstructor(long test) {
23 | this.test = test;
24 | }
25 |
26 | public long getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/FloatConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class FloatConstructor {
20 | private final float test;
21 |
22 | public FloatConstructor(float test) {
23 | this.test = test;
24 | }
25 |
26 | public float getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/NoParamConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public class NoParamConstructor {
20 | private String test;
21 |
22 | public final String getTest() {
23 | return test;
24 | }
25 |
26 | public final void setTest(String test) {
27 | this.test = test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/ShortConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class ShortConstructor {
20 | private final short test;
21 |
22 | public ShortConstructor(short test) {
23 | this.test = test;
24 | }
25 |
26 | public short getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/DoubleConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class DoubleConstructor {
20 | private final double test;
21 |
22 | public DoubleConstructor(double test) {
23 | this.test = test;
24 | }
25 |
26 | public double getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/StringConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class StringConstructor {
20 | private final String test;
21 |
22 | public StringConstructor(String test) {
23 | this.test = test;
24 | }
25 |
26 | public String getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/BooleanConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class BooleanConstructor {
20 | private final boolean test;
21 |
22 | public BooleanConstructor(boolean test) {
23 | this.test = test;
24 | }
25 |
26 | public boolean getTest() {
27 | return test;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | include \
18 | ':shillelagh',
19 | ':shillelagh-processor',
20 | ':shillelagh-sample',
21 | ':shillelagh-tests'
22 |
23 | rootProject.name = 'shillelagh-parent'
24 |
25 | def setBuildFile(project) {
26 | project.buildFileName = "${project.name}.gradle"
27 | project.children.each {
28 | setBuildFile(it)
29 | }
30 | }
31 |
32 | rootProject.children.each {
33 | setBuildFile(it)
34 | }
35 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/SqliteText.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import javax.lang.model.type.TypeMirror;
20 |
21 | class SqliteText {
22 | /**
23 | * Checks if a TypeMirror is mapped to Sqlite Integer Type
24 | *
25 | * @param typeMirror The TypeMirror to check if it's an Sqlite Integer Type
26 | * @return true if it maps to Sqlite Integer false otherwise
27 | */
28 | boolean isTypeOf(TypeMirror typeMirror) {
29 | return "java.lang.String".equals(typeMirror.toString());
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/Chapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Table;
21 |
22 | @Table
23 | public class Chapter extends Base {
24 | @Column String chapter;
25 |
26 | public Chapter(String chapter) {
27 | this.chapter = chapter;
28 | }
29 |
30 | public String getChapter() {
31 | return chapter;
32 | }
33 |
34 | @Override public String toString() {
35 | return "Chapter{"
36 | + "chapter='" + chapter + '\''
37 | + '}';
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Id.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.Target;
21 |
22 | import static java.lang.annotation.ElementType.FIELD;
23 | import static java.lang.annotation.RetentionPolicy.SOURCE;
24 |
25 | /** Declare a field to be the database ID column. This MUST be placed on a long. */
26 | @Retention(SOURCE) @Target(FIELD)
27 | public @interface Id {
28 | /** Set the name of the column that shillelagh will use to read and write to the database as. */
29 | String name() default "";
30 | }
31 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestNotTableObject.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | /** Class not annotated with Table for testing exceptions */
20 | public class TestNotTableObject {
21 | private String name;
22 | private int value;
23 |
24 | public String getName() {
25 | return name;
26 | }
27 |
28 | public void setName(String name) {
29 | this.name = name;
30 | }
31 |
32 | public int getValue() {
33 | return value;
34 | }
35 |
36 | public void setValue(int value) {
37 | this.value = value;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/Author.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Table;
21 |
22 | @Table
23 | public final class Author extends Base {
24 | @Column String name;
25 |
26 | public Author(String name) {
27 | this.name = name;
28 | }
29 |
30 | public String getName() {
31 | return name;
32 | }
33 |
34 | public void setName(String name) {
35 | this.name = name;
36 | }
37 |
38 | @Override public String toString() {
39 | return "Author{" +
40 | "name='" + name + '\'' +
41 | '}';
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Operator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | /** Operators used for building queries */
20 | enum Operator {
21 | BETWEEN(" BETWEEN "),
22 | ORDER_BY(" ORDER BY "),
23 | WHERE(" WHERE "),
24 | OR(" OR "),
25 | AND(" AND "),
26 | EQUAL(" = "),
27 | NOT_EQUAL(" != "),
28 | GREATER_THAN_EQUAL(" >= "),
29 | GREATER_THAN(" > "),
30 | LESS_THAN_EQUAL(" <= "),
31 | LESS_THAN(" < "),
32 | IS(" IS "),
33 | NOT(" NOT "),
34 | LIKE(" LIKE "),
35 | NULL(" NULL ");
36 |
37 | final String operator;
38 |
39 | private Operator(String operator) {
40 | this.operator = operator;
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/gradle/artifactory.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | // handles distribution of snapshots to Artifactory (oss.jfrog.org)
18 |
19 | apply plugin: 'com.jfrog.artifactory'
20 |
21 | artifactory {
22 | contextUrl = 'http://oss.jfrog.org/artifactory'
23 | publish {
24 | contextUrl = 'http://oss.jfrog.org/artifactory'
25 | repository {
26 | repoKey = 'oss-snapshot-local'
27 | username = bintrayUser
28 | password = bintrayKey
29 | }
30 | defaults {
31 | publications('mavenJava')
32 | }
33 | }
34 | resolve {
35 | contextUrl = 'http://oss.jfrog.org/artifactory'
36 | repository {
37 | repoKey = 'libs-release'
38 | }
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Table.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.Target;
21 |
22 | import static java.lang.annotation.ElementType.TYPE;
23 | import static java.lang.annotation.RetentionPolicy.RUNTIME;
24 |
25 | /**
26 | * To be placed on class that will be inserted into the database.
27 | *
28 | * @see shillelagh.Id
29 | * @see Column
30 | */
31 | @Retention(RUNTIME) @Target(TYPE)
32 | public @interface Table {
33 | /**
34 | * Define the name of the table to be used by shillelagh. By default shillelagh uses the classes
35 | * name
36 | */
37 | String name() default "";
38 | }
39 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Preconditions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | final class Preconditions {
20 | static T checkNotNull(T object, String message) {
21 | if (object == null) {
22 | throw new NullPointerException(message);
23 | }
24 |
25 | return object;
26 | }
27 |
28 | static Table checkTableObject(Class tableClass) {
29 | Table annotation = tableClass.getAnnotation(Table.class);
30 | if (annotation == null) {
31 | throw new IllegalArgumentException(tableClass.getName() + " is not a table object.");
32 | }
33 |
34 | return annotation;
35 | }
36 |
37 | private Preconditions() {
38 | // No instances
39 | }
40 | }
41 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Column.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import java.lang.annotation.Retention;
20 | import java.lang.annotation.Target;
21 |
22 | import static java.lang.annotation.ElementType.FIELD;
23 | import static java.lang.annotation.RetentionPolicy.SOURCE;
24 |
25 | /** All Database fields must be marked with this annotation. */
26 | @Retention(SOURCE) @Target(FIELD)
27 | public @interface Column {
28 | /** Set the name of the column that shillelagh will use to read and write to the database as. */
29 | String name() default "";
30 |
31 | /** Tells if the field should be converted to a byte array and stored as a blob */
32 | boolean isBlob() default false;
33 | }
34 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/OrderByBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | /** Builder for queries after the order by statement has been called */
20 | public final class OrderByBuilder extends Builder {
21 | OrderByBuilder(Shillelagh shillelagh, Class extends T> tableObject, StringBuilder query) {
22 | super(shillelagh, tableObject, query);
23 | }
24 |
25 | /** Order the results in ascending order */
26 | public Builder ascending() {
27 | this.query.append(" ASC");
28 | return this;
29 | }
30 |
31 | /** Order the results in descending order */
32 | public Builder descending() {
33 | this.query.append(" DESC");
34 | return new Builder(shillelagh, tableObject, query);
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
24 |
25 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
20 |
21 |
24 |
25 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestJavaObjectsTable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.util.Date;
20 |
21 | import shillelagh.Column;
22 | import shillelagh.Id;
23 | import shillelagh.Table;
24 |
25 | @Table
26 | public class TestJavaObjectsTable {
27 | @Id long id;
28 |
29 | @Column String aString;
30 | @Column Date aDate;
31 |
32 | public long getId() {
33 | return id;
34 | }
35 |
36 | public void setId(long id) {
37 | this.id = id;
38 | }
39 |
40 | public String getaString() {
41 | return aString;
42 | }
43 |
44 | public void setaString(String aString) {
45 | this.aString = aString;
46 | }
47 |
48 | public Date getaDate() {
49 | return aDate;
50 | }
51 |
52 | public void setaDate(Date aDate) {
53 | this.aDate = aDate;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/gradle/bintray.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | // Handles publication of distributions to Bintray
18 |
19 | apply plugin: 'com.jfrog.bintray'
20 |
21 | bintray {
22 | user = bintrayUser
23 | key = bintrayKey
24 | publications = ['mavenJava']
25 | pkg {
26 | repo = 'maven'
27 | name = 'Shillelagh'
28 | desc = 'Quick and Easy Android ORM'
29 | websiteUrl = 'https://github.com/pieces029/shillelagh'
30 | issueTrackerUrl = 'https://github.com/pieces029/shillelagh/issues'
31 | vcsUrl = 'https://github.com/pieces029/shillelagh.git'
32 | licenses = ['Apache-2.0']
33 | labels = ['Android', 'ORM', 'Database', 'SQLite']
34 | version {
35 | name = project.version
36 | gpg {
37 | sign = true
38 | passphrase = signingPassword
39 | }
40 | mavenCentralSync {
41 | sync = true
42 | user = sonatypeUserName
43 | password = sonatypePassword
44 | }
45 | }
46 | }
47 | }
48 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/Image.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.io.Serializable;
20 | import java.util.Arrays;
21 | import java.util.Date;
22 |
23 | public class Image implements Serializable {
24 | private String name;
25 | private Date created;
26 | private byte[] data;
27 |
28 | public Image(String name, Date created, byte[] data) {
29 | this.name = name;
30 | this.created = created;
31 | this.data = data;
32 | }
33 |
34 | public String getName() {
35 | return name;
36 | }
37 |
38 | public Date getCreated() {
39 | return created;
40 | }
41 |
42 | public byte[] getData() {
43 | return data;
44 | }
45 |
46 | @Override public String toString() {
47 | return "Image{" +
48 | "name='" + name + '\'' +
49 | ", created=" + created +
50 | ", data=" + Arrays.toString(data) +
51 | '}';
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/shillelagh-tests/shillelagh-tests.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | apply plugin: 'com.android.application'
18 |
19 | android {
20 | compileSdkVersion commonVersions.compileSdkVersion
21 | buildToolsVersion commonVersions.buildToolsVersion
22 |
23 | defaultConfig {
24 | minSdkVersion project.minSdkVersion
25 | targetSdkVersion project.targetSdkVersion
26 |
27 | versionCode versionCode
28 | versionName version
29 | }
30 |
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_1_6
33 | targetCompatibility JavaVersion.VERSION_1_6
34 | }
35 |
36 | packagingOptions {
37 | exclude 'META-INF/INDEX.LIST'
38 | exclude 'META-INF/LICENSE'
39 | exclude 'META-INF/NOTICE'
40 | }
41 | }
42 |
43 | dependencies {
44 | compile(project(':shillelagh')) {
45 | // exclude since optional doesn't work through project includes and objenesis is
46 | // included in the jar with jarjar
47 | exclude group: 'org.objenesis'
48 | }
49 | provided project(':shillelagh-processor')
50 |
51 | compile "io.reactivex:rxandroid:${commonVersions.rxandroid}"
52 |
53 | androidTestCompile 'com.squareup.assertj:assertj-android:1.0.0'
54 | }
55 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/WhereBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import static shillelagh.Operator.ORDER_BY;
20 | import static shillelagh.Operator.WHERE;
21 | import static shillelagh.Shillelagh.getTableName;
22 |
23 | /**
24 | * Builder for constructing where statements to query the database with RxJava.
25 | *
26 | * @param The resulting database model object.
27 | */
28 | public final class WhereBuilder extends Builder {
29 | WhereBuilder(Shillelagh shillelagh, Class extends T> tableObject) {
30 | super(shillelagh, tableObject,
31 | new StringBuilder("SELECT * FROM ").append(getTableName(tableObject)));
32 | }
33 |
34 | public QueryBuilder where(String columnName) {
35 | checkColumnName(columnName);
36 | query.append(WHERE.operator).append(columnName);
37 | return new QueryBuilder(tableObject, shillelagh, columnName, query);
38 | }
39 |
40 | public OrderByBuilder orderBy(String columnName) {
41 | checkColumnName(columnName);
42 | query.append(ORDER_BY.operator).append(columnName);
43 | return new OrderByBuilder(shillelagh, tableObject, query);
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/CollectionsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.util.Collections;
20 | import java.util.HashMap;
21 | import java.util.LinkedList;
22 | import java.util.List;
23 | import java.util.Map;
24 | import shillelagh.Column;
25 | import shillelagh.Id;
26 | import shillelagh.Table;
27 |
28 | @Table
29 | public final class CollectionsTest {
30 | @Id long id;
31 | @Column(isBlob = true) Map maps;
32 | @Column(isBlob = true) List lists;
33 |
34 | public CollectionsTest(Map maps, List lists) {
35 | this.maps = maps == null ? Collections.emptyMap() : maps;
36 | this.lists = lists == null ? Collections.emptyList() : lists;
37 | }
38 |
39 | public Map getMaps() {
40 | return maps;
41 | }
42 |
43 | public List getLists() {
44 | return lists;
45 | }
46 |
47 | @Override public String toString() {
48 | return "CollectionsTest{" +
49 | "id=" + id +
50 | ", maps=" + maps +
51 | ", lists=" + lists +
52 | '}';
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/Strings.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | final class Strings {
20 |
21 | private Strings() {
22 | // No instances.
23 | }
24 |
25 | /** Checks if the string is blank, like TextUtils.isEmpty() but better */
26 | static boolean isBlank(CharSequence string) {
27 | return (string == null || string.toString().trim().length() == 0);
28 | }
29 |
30 | /** Checks if a string there, if not returns the default string */
31 | static String valueOrDefault(String string, String defaultString) {
32 | return isBlank(string) ? defaultString : string;
33 | }
34 |
35 | /** Truncates the string at the length specified */
36 | static String truncateAt(String string, int length) {
37 | return string.length() > length ? string.substring(0, length) : string;
38 | }
39 |
40 | /** Capitalizes the first letter of the string passed in */
41 | static String capitalize(String string) {
42 | if (isBlank(string)) {
43 | return "";
44 | }
45 | char first = string.charAt(0);
46 | if (Character.isUpperCase(first)) {
47 | return string;
48 | } else {
49 | return Character.toUpperCase(first) + string.substring(1);
50 | }
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestOneToOne.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Id;
21 | import shillelagh.Table;
22 |
23 | @Table public class TestOneToOne {
24 | @Id long id;
25 | @Column OneToOneChild child;
26 |
27 | public TestOneToOne(OneToOneChild child) {
28 | this.child = child;
29 | }
30 |
31 | public long getId() {
32 | return id;
33 | }
34 |
35 | public void setId(long id) {
36 | this.id = id;
37 | }
38 |
39 | public void setChild(OneToOneChild child) {
40 | this.child = child;
41 | }
42 |
43 | public OneToOneChild getChild() {
44 | return child;
45 | }
46 |
47 | @Table public static class OneToOneChild {
48 | @Id long id;
49 | @Column String childName;
50 |
51 | public long getId() {
52 | return id;
53 | }
54 |
55 | public void setId(long id) {
56 | this.id = id;
57 | }
58 |
59 | public OneToOneChild(String childName) {
60 | this.childName = childName;
61 | }
62 |
63 | public String getChildName() {
64 | return childName;
65 | }
66 |
67 | public void setChildName(String childName) {
68 | this.childName = childName;
69 | }
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/ShillelaghLogger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import javax.annotation.processing.Messager;
20 |
21 | import static javax.tools.Diagnostic.Kind.ERROR;
22 | import static javax.tools.Diagnostic.Kind.NOTE;
23 | import static shillelagh.internal.ShillelaghProcessor.DEBUG;
24 |
25 | final class ShillelaghLogger {
26 | private final Messager messenger;
27 |
28 | ShillelaghLogger(Messager messenger) {
29 | this.messenger = messenger;
30 | }
31 |
32 | /**
33 | * Print out debug logs, will only print if {@link shillelagh.internal.ShillelaghProcessor#DEBUG}
34 | * is true.
35 | */
36 | void d(String message, Object... args) {
37 | if (DEBUG) {
38 | messenger.printMessage(NOTE, formatString(message, args));
39 | }
40 | }
41 |
42 | /** Print out notes */
43 | void n(String message, Object... args) {
44 | messenger.printMessage(NOTE, formatString(message, args));
45 | }
46 |
47 | /** Print out errors, this will stop the build from succeeding */
48 | void e(String message, Object... args) {
49 | messenger.printMessage(ERROR, formatString(message, args));
50 | }
51 |
52 | private String formatString(String message, Object... args) {
53 | return args.length == 0 ? message : String.format(message, args);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestOneToMany.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.util.List;
20 |
21 | import shillelagh.Column;
22 | import shillelagh.Id;
23 | import shillelagh.Table;
24 |
25 | @Table public class TestOneToMany {
26 | @Id long id;
27 | @Column String someValue;
28 | @Column List children;
29 |
30 | public TestOneToMany(String someValue, List children) {
31 | this.someValue = someValue;
32 | this.children = children;
33 | }
34 |
35 | public void setSomeValue(String someValue) {
36 | this.someValue = someValue;
37 | }
38 |
39 | public List getChildren() {
40 | return children;
41 | }
42 |
43 | @Table public static class OneToManyChild {
44 | @Id long id;
45 | @Column String testString;
46 | @Column int testInt;
47 |
48 | public OneToManyChild(String testString, int testInt) {
49 | this.testString = testString;
50 | this.testInt = testInt;
51 | }
52 |
53 | public void setTestString(String testString) {
54 | this.testString = testString;
55 | }
56 |
57 | @Override public String toString() {
58 | return "Child{"
59 | + "id=" + id
60 | + ", testString='" + testString + '\''
61 | + ", testInt=" + testInt
62 | + '}';
63 | }
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestBlobs.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.io.Serializable;
20 |
21 | import shillelagh.Column;
22 | import shillelagh.Id;
23 | import shillelagh.Table;
24 |
25 | @Table public class TestBlobs {
26 | @Id long id;
27 | @Column(isBlob = true) Byte[] aByteArray;
28 | @Column(isBlob = true) byte[] anotherByteArray; // TODO Make this not require isBlob == true
29 | @Column(isBlob = true) TestBlobObject aTestBlobObject;
30 |
31 | public long getId() {
32 | return id;
33 | }
34 |
35 | public void setId(long id) {
36 | this.id = id;
37 | }
38 |
39 | public Byte[] getaByteArray() {
40 | return aByteArray;
41 | }
42 |
43 | public void setaByteArray(Byte[] aByteArray) {
44 | this.aByteArray = aByteArray;
45 | }
46 |
47 | public byte[] getAnotherByteArray() {
48 | return anotherByteArray;
49 | }
50 |
51 | public void setAnotherByteArray(byte[] anotherByteArray) {
52 | this.anotherByteArray = anotherByteArray;
53 | }
54 |
55 | public void setaTestBlobObject(TestBlobObject testBlobObject) {
56 | this.aTestBlobObject = testBlobObject;
57 | }
58 |
59 | public TestBlobObject getaTestBlobObject() {
60 | return this.aTestBlobObject;
61 | }
62 |
63 | public static class TestBlobObject implements Serializable {
64 | public String testString;
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/SqliteReal.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import java.util.Arrays;
20 | import java.util.HashSet;
21 | import java.util.List;
22 |
23 | import javax.lang.model.type.TypeKind;
24 | import javax.lang.model.type.TypeMirror;
25 |
26 | class SqliteReal {
27 | static final List REAL_KINDS = Arrays.asList(
28 | TypeKind.DOUBLE,
29 | TypeKind.FLOAT
30 | );
31 |
32 | static final List REAL_OBJECTS = Arrays.asList(
33 | "java.lang.Double",
34 | "java.lang.Float",
35 | "java.lang.Number"
36 | );
37 |
38 | private HashSet realKinds = new HashSet(REAL_KINDS);
39 | private HashSet realObjects = new HashSet(REAL_OBJECTS);
40 |
41 | SqliteReal() {
42 | realKinds.addAll(REAL_KINDS);
43 | realObjects.addAll(REAL_OBJECTS);
44 | }
45 |
46 | /**
47 | * Checks if a TypeMirror is mapped to Sqlite Type
48 | *
49 | * @param typeMirror The TypeMirror to check if it's an Sqlite Type
50 | * @return true if it maps to the Sqlite Object false otherwise
51 | */
52 | boolean isTypeOf(TypeMirror typeMirror) {
53 | if (realKinds.contains(typeMirror.getKind())) {
54 | return true;
55 | }
56 |
57 | if (realObjects.contains(typeMirror.toString())) {
58 | return true;
59 | }
60 |
61 | return false;
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/SimpleObject.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Id;
21 | import shillelagh.Table;
22 |
23 | @Table
24 | public class SimpleObject {
25 |
26 | @Id long id;
27 | @Column String name;
28 | @Column String address;
29 | @Column long customerId;
30 |
31 | public SimpleObject(String name, String address, long customerId) {
32 | this.name = name;
33 | this.address = address;
34 | this.customerId = customerId;
35 | }
36 |
37 | public String getName() {
38 | return name;
39 | }
40 |
41 | public String getAddress() {
42 | return address;
43 | }
44 |
45 | public long getCustomerId() {
46 | return customerId;
47 | }
48 |
49 | @Override
50 | public boolean equals(Object o) {
51 | if (this == o) return true;
52 | if (o == null || getClass() != o.getClass()) return false;
53 |
54 | SimpleObject that = (SimpleObject) o;
55 |
56 | if (id != that.id) return false;
57 | if (!address.equals(that.address)) return false;
58 | if (!name.equals(that.name)) return false;
59 |
60 | return true;
61 | }
62 |
63 | @Override
64 | public int hashCode() {
65 | int result = (int) (id ^ (id >>> 32));
66 | result = 31 * result + name.hashCode();
67 | result = 31 * result + address.hashCode();
68 | return result;
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/shillelagh-sample/shillelagh-sample.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | apply plugin: 'com.android.application'
18 |
19 | android {
20 | compileSdkVersion commonVersions.compileSdkVersion
21 | buildToolsVersion commonVersions.buildToolsVersion
22 |
23 | defaultConfig {
24 | minSdkVersion project.minSdkVersion
25 | targetSdkVersion project.targetSdkVersion
26 |
27 | versionCode versionCode
28 | versionName version
29 | }
30 |
31 | compileOptions {
32 | sourceCompatibility JavaVersion.VERSION_1_6
33 | targetCompatibility JavaVersion.VERSION_1_6
34 | }
35 |
36 | buildTypes {
37 | debug {
38 | minifyEnabled true
39 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
40 | }
41 | release {
42 | minifyEnabled true
43 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
44 | }
45 | }
46 |
47 | packagingOptions {
48 | exclude 'META-INF/INDEX.LIST'
49 | exclude 'META-INF/LICENSE'
50 | exclude 'META-INF/NOTICE'
51 | }
52 | }
53 |
54 | dependencies {
55 | compile(project(':shillelagh')) {
56 | // exclude since optional doesn't work through project includes and objenesis is
57 | // included in the jar with jarjar
58 | exclude group: 'org.objenesis'
59 | }
60 | provided project(':shillelagh-processor')
61 |
62 | compile "io.reactivex:rxandroid:${commonVersions.rxandroid}"
63 |
64 | compile 'com.facebook.stetho:stetho:1.1.0'
65 | }
66 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/ExampleSqliteHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh;
18 |
19 | import android.content.Context;
20 | import android.database.sqlite.SQLiteDatabase;
21 | import android.database.sqlite.SQLiteOpenHelper;
22 |
23 | import com.example.shillelagh.model.Author;
24 | import com.example.shillelagh.model.Book;
25 | import com.example.shillelagh.model.Chapter;
26 |
27 | import com.example.shillelagh.model.CollectionsTest;
28 | import shillelagh.Shillelagh;
29 |
30 | public class ExampleSqliteHelper extends SQLiteOpenHelper {
31 | private static final String DATABASE_NAME = "shillelagh_example.db";
32 | private static final int DATABASE_VERSION = 6;
33 |
34 | public ExampleSqliteHelper(Context context) {
35 | super(context, DATABASE_NAME, null, DATABASE_VERSION);
36 | }
37 |
38 | @Override public void onCreate(SQLiteDatabase db) {
39 | Shillelagh.createTable(db, Author.class);
40 | Shillelagh.createTable(db, Book.class);
41 | Shillelagh.createTable(db, Chapter.class);
42 | Shillelagh.createTable(db, CollectionsTest.class);
43 | }
44 |
45 | @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
46 | // Simplistic solution, you will lose your data though, good for debug builds bad for prod
47 | Shillelagh.dropTable(db, Author.class);
48 | Shillelagh.dropTable(db, Book.class);
49 | Shillelagh.dropTable(db, Chapter.class);
50 | onCreate(db);
51 | }
52 | }
53 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestPrimitiveTable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Id;
21 | import shillelagh.Table;
22 |
23 | @Table public class TestPrimitiveTable {
24 | @Id long id;
25 |
26 | @Column short aShort;
27 | @Column int anInt;
28 | @Column long aLong;
29 | @Column float aFloat;
30 | @Column double aDouble;
31 | @Column boolean aBoolean;
32 |
33 | public long getId() {
34 | return id;
35 | }
36 |
37 | public void setId(long id) {
38 | this.id = id;
39 | }
40 |
41 | public short getaShort() {
42 | return aShort;
43 | }
44 |
45 | public void setaShort(short aShort) {
46 | this.aShort = aShort;
47 | }
48 |
49 | public int getAnInt() {
50 | return anInt;
51 | }
52 |
53 | public void setAnInt(int anInt) {
54 | this.anInt = anInt;
55 | }
56 |
57 | public long getaLong() {
58 | return aLong;
59 | }
60 |
61 | public void setaLong(long aLong) {
62 | this.aLong = aLong;
63 | }
64 |
65 | public float getaFloat() {
66 | return aFloat;
67 | }
68 |
69 | public void setaFloat(float aFloat) {
70 | this.aFloat = aFloat;
71 | }
72 |
73 | public double getaDouble() {
74 | return aDouble;
75 | }
76 |
77 | public void setaDouble(double aDouble) {
78 | this.aDouble = aDouble;
79 | }
80 |
81 | public boolean isaBoolean() {
82 | return aBoolean;
83 | }
84 |
85 | public void setaBoolean(boolean aBoolean) {
86 | this.aBoolean = aBoolean;
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/model/Book.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import java.util.Date;
20 | import java.util.List;
21 |
22 | import shillelagh.Column;
23 | import shillelagh.Table;
24 |
25 | @Table
26 | public final class Book extends Base {
27 | @Column String title;
28 | @Column Author author;
29 | @Column Date published;
30 | @Column List chapters;
31 | @Column(isBlob = true) Image image;
32 |
33 | public Book(String title, Author author, Date published, List chapters, Image image) {
34 | this.title = title;
35 | this.author = author;
36 | this.published = published;
37 | this.chapters = chapters;
38 | this.image = image;
39 | }
40 |
41 | public String getTitle() {
42 | return title;
43 | }
44 |
45 | public void setTitle(String title) {
46 | this.title = title;
47 | }
48 |
49 | public Author getAuthor() {
50 | return author;
51 | }
52 |
53 | public void setAuthor(Author author) {
54 | this.author = author;
55 | }
56 |
57 | public Date getPublished() {
58 | return published;
59 | }
60 |
61 | public List getChapters() {
62 | return chapters;
63 | }
64 |
65 | public Image getImage() {
66 | return image;
67 | }
68 |
69 | @Override public String toString() {
70 | return "Book{" +
71 | "title='" + title + '\'' +
72 | ", author=" + author +
73 | ", published=" + published +
74 | ", chapters=" + chapters +
75 | ", image=" + image +
76 | '}';
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestBoxedPrimitivesTable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import shillelagh.Column;
20 | import shillelagh.Id;
21 | import shillelagh.Table;
22 |
23 | @Table
24 | public class TestBoxedPrimitivesTable {
25 | @Id Long _id;
26 |
27 | @Column Boolean aBoolean;
28 | @Column Double aDouble;
29 | @Column Float aFloat;
30 | @Column Integer anInteger;
31 | @Column Long aLong;
32 | @Column Short aShort;
33 |
34 | public Long getId() {
35 | return _id;
36 | }
37 |
38 | public void setId(Long id) {
39 | this._id = id;
40 | }
41 |
42 | public Boolean getaBoolean() {
43 | return aBoolean;
44 | }
45 |
46 | public void setaBoolean(Boolean aBoolean) {
47 | this.aBoolean = aBoolean;
48 | }
49 |
50 | public Double getaDouble() {
51 | return aDouble;
52 | }
53 |
54 | public void setaDouble(Double aDouble) {
55 | this.aDouble = aDouble;
56 | }
57 |
58 | public Float getaFloat() {
59 | return aFloat;
60 | }
61 |
62 | public void setaFloat(Float aFloat) {
63 | this.aFloat = aFloat;
64 | }
65 |
66 | public Integer getAnInteger() {
67 | return anInteger;
68 | }
69 |
70 | public void setAnInteger(Integer anInteger) {
71 | this.anInteger = anInteger;
72 | }
73 |
74 | public Long getaLong() {
75 | return aLong;
76 | }
77 |
78 | public void setaLong(Long aLong) {
79 | this.aLong = aLong;
80 | }
81 |
82 | public Short getaShort() {
83 | return aShort;
84 | }
85 |
86 | public void setaShort(Short aShort) {
87 | this.aShort = aShort;
88 | }
89 | }
90 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/model/TestParcelable.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2015 Andrew Reitz
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 com.example.shillelagh.model;
18 |
19 | import android.os.Parcel;
20 | import android.os.Parcelable;
21 | import shillelagh.Column;
22 | import shillelagh.Id;
23 | import shillelagh.Table;
24 |
25 | @Table
26 | public class TestParcelable implements Parcelable {
27 | @Id long id;
28 | @Column int testInt;
29 | @Column String testString;
30 |
31 | public TestParcelable(int testInt, String testString) {
32 | this.testInt = testInt;
33 | this.testString = testString;
34 | }
35 |
36 | private TestParcelable(Parcel parcel) {
37 | this.id = parcel.readLong();
38 | this.testInt = parcel.readInt();
39 | this.testString = parcel.readString();
40 | }
41 |
42 | public String getTestString() {
43 | return testString;
44 | }
45 |
46 | public int getTestInt() {
47 | return testInt;
48 | }
49 |
50 | public long getId() {
51 | return id;
52 | }
53 |
54 | @Override public int describeContents() {
55 | return 0;
56 | }
57 |
58 | @Override public void writeToParcel(Parcel dest, int flags) {
59 | dest.writeLong(this.id);
60 | dest.writeInt(this.testInt);
61 | dest.writeString(this.testString);
62 | }
63 |
64 | public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
65 | @Override
66 | public TestParcelable createFromParcel(Parcel source) {
67 | return new TestParcelable(source);
68 | }
69 |
70 | @Override
71 | public TestParcelable[] newArray(int size) {
72 | return new TestParcelable[size];
73 | }
74 | };
75 | }
76 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/SqliteInteger.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import java.util.Arrays;
20 | import java.util.HashSet;
21 | import java.util.List;
22 |
23 | import javax.lang.model.type.TypeKind;
24 | import javax.lang.model.type.TypeMirror;
25 |
26 | class SqliteInteger {
27 | static final List INTEGER_KINDS = Arrays.asList(
28 | TypeKind.INT,
29 | TypeKind.SHORT,
30 | TypeKind.LONG,
31 | TypeKind.BYTE, // true false types
32 | TypeKind.BOOLEAN // true false types
33 | );
34 |
35 | static final List INTEGER_OBJECTS = Arrays.asList(
36 | "java.lang.Integer",
37 | "java.lang.Short",
38 | "java.lang.Long",
39 | "java.lang.Boolean",
40 | "java.lang.Byte",
41 | "java.util.Date"
42 | );
43 |
44 | private HashSet integerKinds = new HashSet(INTEGER_KINDS.size());
45 | private HashSet integerObjects = new HashSet(INTEGER_OBJECTS.size());
46 |
47 | SqliteInteger() {
48 | integerKinds.addAll(INTEGER_KINDS);
49 | integerObjects.addAll(INTEGER_OBJECTS);
50 | }
51 |
52 | /**
53 | * Checks if a TypeMirror is mapped to Sqlite Integer Type
54 | *
55 | * @param typeMirror The TypeMirror to check if it's an Sqlite Integer Type
56 | * @return true if it maps to Sqlite Integer false otherwise
57 | */
58 | boolean isTypeOf(TypeMirror typeMirror) {
59 | if (integerKinds.contains(typeMirror.getKind())) {
60 | return true;
61 | }
62 |
63 | if (integerObjects.contains(typeMirror.toString())) {
64 | return true;
65 | }
66 |
67 | return false;
68 | }
69 | }
70 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/ShillelaghApp.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh;
18 |
19 | import android.annotation.TargetApi;
20 | import android.app.Application;
21 | import android.content.Context;
22 | import android.database.sqlite.SQLiteOpenHelper;
23 | import android.os.Build;
24 | import android.os.StrictMode;
25 |
26 | import com.facebook.stetho.Stetho;
27 | import shillelagh.Shillelagh;
28 |
29 | @TargetApi(Build.VERSION_CODES.HONEYCOMB)
30 | public class ShillelaghApp extends Application {
31 |
32 | /** Shillelagh Singleton */
33 | private Shillelagh shillelagh;
34 |
35 | @Override public void onCreate() {
36 | super.onCreate();
37 |
38 | // stetho for debugging databases
39 | Stetho.initialize(Stetho.newInitializerBuilder(this)
40 | .enableDumpapp(Stetho.defaultDumperPluginsProvider(this))
41 | .enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this))
42 | .build());
43 |
44 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
45 | StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
46 | .detectAll()
47 | .penaltyDeath()
48 | .build());
49 | StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
50 | .detectAll()
51 | .penaltyDeath()
52 | .build());
53 | }
54 |
55 | SQLiteOpenHelper sqliteOpenHelper = new ExampleSqliteHelper(this);
56 | shillelagh = new Shillelagh(sqliteOpenHelper);
57 | }
58 |
59 | /** Returns the instance of shillelagh for this application */
60 | public Shillelagh getShillelagh() {
61 | return shillelagh;
62 | }
63 |
64 | public static ShillelaghApp get(Context context) {
65 | return (ShillelaghApp) context.getApplicationContext();
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/Builder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import android.database.Cursor;
20 | import java.util.List;
21 | import rx.Observable;
22 |
23 | import static shillelagh.Shillelagh.HAS_RX_JAVA;
24 |
25 | /** Builder for turning sql statements into lists, observables or cursors */
26 | public class Builder {
27 | final StringBuilder query;
28 |
29 | final Class extends T> tableObject;
30 | final Shillelagh shillelagh;
31 |
32 | Builder(Shillelagh shillelagh, Class extends T> tableObject, StringBuilder query) {
33 | this.shillelagh = shillelagh;
34 | this.tableObject = tableObject;
35 | this.query = query;
36 | }
37 |
38 | /** Executes a query and returns the results as a list */
39 | public final List toList() {
40 | return shillelagh.rawQuery(tableObject, query.toString());
41 | }
42 |
43 | /** Executes a query and returns the results wrapped in an observable */
44 | public final Observable toObservable() {
45 | if (!HAS_RX_JAVA) {
46 | throw new RuntimeException(
47 | "RxJava not available! Add RxJava to your build to use this feature");
48 | }
49 |
50 | return shillelagh.getObservable(tableObject, new CursorLoader() {
51 | @Override public Cursor getCursor() {
52 | return shillelagh.rawQuery(query.toString());
53 | }
54 | });
55 | }
56 |
57 | /** Executes a query and returns the results in a cursor */
58 | public final Cursor toCursor() {
59 | return shillelagh.rawQuery(query.toString());
60 | }
61 |
62 | /** Returns the created query as a string */
63 | @Override public final String toString() {
64 | return query.toString().trim();
65 | }
66 |
67 | /** Check to ensure that the column name provided is valid */
68 | final void checkColumnName(String columnName) {
69 | try {
70 | tableObject.getDeclaredField(columnName);
71 | } catch (NoSuchFieldException e) {
72 | throw new RuntimeException(
73 | String.format("%s isEqualTo not a field found in %s", columnName, tableObject));
74 | }
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/CursorFunctions.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import java.util.HashMap;
20 |
21 | final class CursorFunctions {
22 | private static final String BLOB = "blob";
23 | private static final HashMap SUPPORTED_CURSOR_METHODS
24 | = new HashMap();
25 |
26 | static {
27 | final String cursorFunctionInt = "getInt";
28 | final String cursorFunctionDouble = "getDouble";
29 | final String cursorFunctionFloat = "getFloat";
30 | final String cursorFunctionLong = "getLong";
31 | final String cursorFunctionShort = "getShort";
32 | final String cursorFunctionString = "getString";
33 | final String cursorFunctionBlob = "getBlob";
34 |
35 | SUPPORTED_CURSOR_METHODS.put(int.class.getName(), cursorFunctionInt);
36 | SUPPORTED_CURSOR_METHODS.put(Integer.class.getName(), cursorFunctionInt);
37 | SUPPORTED_CURSOR_METHODS.put(boolean.class.getName(), cursorFunctionInt);
38 | SUPPORTED_CURSOR_METHODS.put(Boolean.class.getName(), cursorFunctionInt);
39 | SUPPORTED_CURSOR_METHODS.put(double.class.getName(), cursorFunctionDouble);
40 | SUPPORTED_CURSOR_METHODS.put(Double.class.getName(), cursorFunctionDouble);
41 | SUPPORTED_CURSOR_METHODS.put(float.class.getName(), cursorFunctionFloat);
42 | SUPPORTED_CURSOR_METHODS.put(Float.class.getName(), cursorFunctionFloat);
43 | SUPPORTED_CURSOR_METHODS.put(long.class.getName(), cursorFunctionLong);
44 | SUPPORTED_CURSOR_METHODS.put(Long.class.getName(), cursorFunctionLong);
45 | SUPPORTED_CURSOR_METHODS.put(short.class.getName(), cursorFunctionShort);
46 | SUPPORTED_CURSOR_METHODS.put(Short.class.getName(), cursorFunctionShort);
47 | SUPPORTED_CURSOR_METHODS.put(String.class.getName(), cursorFunctionString);
48 | SUPPORTED_CURSOR_METHODS.put(BLOB, cursorFunctionBlob);
49 | }
50 |
51 | /**
52 | * Maps a type to the corresponding Cursor get function. For mapping objects between the database
53 | * and java. If a type is not found getBlob is returned
54 | */
55 | public static String get(String type) {
56 | final String returnValue = SUPPORTED_CURSOR_METHODS.get(type);
57 | return returnValue != null ? returnValue : SUPPORTED_CURSOR_METHODS.get(BLOB);
58 | }
59 |
60 | private CursorFunctions() {
61 | throw new UnsupportedOperationException();
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/shillelagh-processor/shillelagh-processor.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | apply plugin: 'java'
18 | apply plugin: 'provided-base'
19 | apply plugin: 'maven-publish'
20 | apply from: rootProject.file('gradle/javaDoc.gradle')
21 | apply from: rootProject.file('gradle/bintray.gradle')
22 | apply from: rootProject.file('gradle/artifactory.gradle')
23 |
24 | targetCompatibility = JavaVersion.VERSION_1_6
25 | sourceCompatibility = JavaVersion.VERSION_1_6
26 |
27 | dependencies {
28 | provided project(':shillelagh')
29 | compile 'com.google.guava:guava:18.0'
30 | compile 'com.squareup:javawriter:2.5.0'
31 | }
32 |
33 | publishing {
34 | publications {
35 | mavenJava(MavenPublication) {
36 | from components.java
37 |
38 | artifact sourcesJar {
39 | classifier "sources"
40 | }
41 |
42 | artifact javadocJar {
43 | classifier "javadoc"
44 | }
45 |
46 | groupId 'com.andrewreitz'
47 | artifactId 'shillelagh-processor'
48 |
49 | pom.withXml {
50 | def Node root = asNode()
51 | root.appendNode('name', 'Shillelagh Processor')
52 | root.appendNode('description', 'Shillelagh Sqlite Android library')
53 | root.appendNode('url', 'https://github.com/pieces029/shillelagh')
54 |
55 | def issues = root.appendNode('issueManagement')
56 | issues.appendNode('system', 'github')
57 | issues.appendNode('url', 'https://github.com/pieces029/shillelagh/issues')
58 |
59 | def scm = root.appendNode('scm')
60 | scm.appendNode('url', 'scm:https://github.com/pieces029/shillelagh')
61 | scm.appendNode('connection', 'scm:git:git@github.com:pieces029/shillelagh.git')
62 | scm.appendNode('developerConnection', 'scm:git:git@github.com:pieces029/shillelagh.git')
63 |
64 | def license = root.appendNode('licenses').appendNode('license');
65 | license.appendNode('name', 'The Apache Software License, Version 2.0')
66 | license.appendNode('url', 'http://www.apache.org/licenses/LICENSE-2.0.txt')
67 | license.appendNode('distribution', 'repo')
68 |
69 | def dev = root.appendNode('developers').appendNode('developer');
70 | dev.appendNode('id', 'areitz')
71 | dev.appendNode('name', 'Andrew Reitz')
72 | dev.appendNode('email', 'andrew@andrewreitz.com')
73 | dev.appendNode('organizationUrl', 'http://andrewreitz.com')
74 | }
75 | }
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/TestSQLiteOpenHelper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh;
18 |
19 | import android.content.Context;
20 | import android.database.sqlite.SQLiteDatabase;
21 | import android.database.sqlite.SQLiteOpenHelper;
22 |
23 | import com.example.shillelagh.model.TestBlobs;
24 | import com.example.shillelagh.model.TestBoxedPrimitivesTable;
25 | import com.example.shillelagh.model.TestJavaObjectsTable;
26 | import com.example.shillelagh.model.TestOneToMany;
27 | import com.example.shillelagh.model.TestOneToOne;
28 | import com.example.shillelagh.model.TestParcelable;
29 | import com.example.shillelagh.model.TestPrimitiveTable;
30 |
31 | import shillelagh.Shillelagh;
32 |
33 | public class TestSQLiteOpenHelper extends SQLiteOpenHelper {
34 | public static final String DATABASE_NAME = "shillelagh_test.db";
35 | private static final int DATABASE_VERSION = 7;
36 |
37 | public TestSQLiteOpenHelper(Context context) {
38 | super(context, DATABASE_NAME, null, DATABASE_VERSION);
39 | }
40 |
41 | @Override public void onCreate(SQLiteDatabase db) {
42 | Shillelagh.createTable(db, TestBoxedPrimitivesTable.class);
43 | Shillelagh.createTable(db, TestPrimitiveTable.class);
44 | Shillelagh.createTable(db, TestJavaObjectsTable.class);
45 | Shillelagh.createTable(db, TestBlobs.class);
46 | Shillelagh.createTable(db, TestOneToOne.class);
47 | Shillelagh.createTable(db, TestOneToOne.OneToOneChild.class);
48 | Shillelagh.createTable(db, TestOneToMany.class);
49 | Shillelagh.createTable(db, TestOneToMany.OneToManyChild.class);
50 | Shillelagh.createTable(db, TestParcelable.class);
51 | }
52 |
53 | @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
54 | // Simplistic solution, you will lose your data though, good for debug builds bad for prod
55 | Shillelagh.dropTable(db, TestPrimitiveTable.class);
56 | Shillelagh.dropTable(db, TestBoxedPrimitivesTable.class);
57 | Shillelagh.dropTable(db, TestPrimitiveTable.class);
58 | Shillelagh.dropTable(db, TestBlobs.class);
59 | Shillelagh.dropTable(db, TestOneToOne.class);
60 | Shillelagh.dropTable(db, TestOneToOne.OneToOneChild.class);
61 | Shillelagh.dropTable(db, TestOneToMany.class);
62 | Shillelagh.dropTable(db, TestOneToMany.OneToManyChild.class);
63 | Shillelagh.dropTable(db, TestParcelable.class);
64 | onCreate(db);
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Shillelagh
2 |
3 | 
4 |
5 | [](https://snap-ci.com/pieces029/shillelagh/branch/master)
6 | [](https://android-arsenal.com/details/1/1026)
7 |
8 | Shillelagh is an sqlite library. It was built to make life easier. The entire library
9 | was built around simplicity when using sqlite in Android.
10 |
11 | Quick and dirty.
12 | - Create your model objects, the ones you want to persist
13 | - Add the `@Table` annotation to the model class, and make sure you have a field `@Id long id`
14 | - Create your SQLiteOpenHelper and use `Shillelagh.createTable` to make your tables
15 | - Create an instance of `Shillelagh`
16 | - Create and save your objects!
17 |
18 | For how to use see the
19 | [example](//github.com/pieces029/shillelagh/tree/master/shillelagh-sample) or the
20 | [JavaDocs](//pieces029.github.io/shillelagh).
21 |
22 | # Supported Types
23 |
24 | Supported Types (and corresponding primitives)
25 | - Integer
26 | - Double
27 | - Float
28 | - Long
29 | - Short
30 | - String
31 | - Date
32 | - Boolean
33 |
34 | ## One to Many and One to One
35 |
36 | One to one and one to many relationships are supported. You will need to make sure that the child
37 | objects are annotated like any other tables. For one to many, make sure you use a list, arrays
38 | are currently not supported.
39 |
40 | ## Blobs
41 |
42 | Byte arrays are supported with nothing out of the ordinary needing to be done. If you would like to
43 | save another object type as a blob, you will need to tell Shillelagh that it should be serialized
44 | by adding `@Column(isBlob = true)` to the annotation. These objects MUST also implement the
45 | Serializable interface.
46 |
47 | ## Other Notes
48 |
49 | - Constructors must be provided at package protected level or higher (Put in a ticket if there is a
50 | legitimate use case for private).
51 | - Inner classes MUST be marked static.
52 | - Don't forget to update your database version if you change your models
53 | (Also create migration scripts).
54 | - For proguard just add `-keep class **$$Shillelagh { *; }` to your rules.
55 | - If you do not provide a defualt constructor, Shillelagh will attempt to use the constructor you
56 | provided and pass in null.
57 |
58 | # Download
59 |
60 | ```groovy
61 | dependencies {
62 | ...
63 | implementation 'com.andrewreitz:shillelagh:0.5.0'
64 | provided 'com.andrewreitz:shillelagh-processor:0.5.0'
65 | ...
66 | }
67 | ```
68 |
69 | # License
70 |
71 | Copyright 2015 Andrew Reitz
72 |
73 | Licensed under the Apache License, Version 2.0 (the "License");
74 | you may not use this file except in compliance with the License.
75 | You may obtain a copy of the License at
76 |
77 | http://www.apache.org/licenses/LICENSE-2.0
78 |
79 | Unless required by applicable law or agreed to in writing, software
80 | under the License is distributed on an "AS IS" BASIS,
81 | WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
82 | the License for the specific language governing permissions and
83 | under the License.
84 |
--------------------------------------------------------------------------------
/shillelagh/src/test/groovy/shillelagh/internal/ShillelaghUtilSpec.groovy:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal
18 |
19 | import groovy.transform.TypeChecked
20 | import shillelagh.test.BooleanConstructor
21 | import shillelagh.test.ByteConstructor
22 | import shillelagh.test.CharConstructor
23 | import shillelagh.test.FloatConstructor
24 | import shillelagh.test.IntConstructor
25 | import shillelagh.test.LongConstructor
26 | import shillelagh.test.LotsOfParamConstructor
27 | import shillelagh.test.NoParamConstructor
28 | import shillelagh.test.ShortConstructor
29 | import shillelagh.test.StringConstructor
30 | import spock.lang.Specification
31 | import spock.lang.Unroll
32 |
33 | import static shillelagh.internal.ShillelaghUtil.*
34 |
35 | class ShillelaghUtilSpec extends Specification {
36 | def "serialize then deserialize"() {
37 | given:
38 | String expectedString = "ItWorks"
39 | int expectedInt = 11
40 | TestSerializeClass input = new TestSerializeClass(expectedString, expectedInt)
41 |
42 | when: "serialize then deserialize"
43 | TestSerializeClass output = deserialize(serialize(input))
44 |
45 | then: "expected values of output to be the same as input"
46 | output.testString == expectedString
47 | output.testInt == expectedInt
48 | }
49 |
50 | @Unroll
51 | def "should create new instance of #classToCreate"() {
52 | given:
53 | def object = createInstance(classToCreate)
54 |
55 | expect:
56 | object != null
57 |
58 | where:
59 | classToCreate | _
60 | NoParamConstructor | _
61 | BooleanConstructor | _
62 | ByteConstructor | _
63 | IntConstructor | _
64 | ShortConstructor | _
65 | LongConstructor | _
66 | FloatConstructor | _
67 | CharConstructor | _
68 | BooleanConstructor | _
69 | StringConstructor | _
70 | LotsOfParamConstructor | _
71 | HashMap | _
72 | List | _
73 | Map | _
74 | }
75 |
76 | @TypeChecked
77 | def "should create a new list"() {
78 | given:
79 | List stringList = createInstance(List)
80 |
81 | when:
82 | stringList.add("Hello")
83 |
84 | then:
85 | noExceptionThrown()
86 | stringList.get(0) == "Hello"
87 | }
88 |
89 | @TypeChecked
90 | def "should create a new map"() {
91 | given:
92 | Map stringMap = createInstance(Map)
93 |
94 | when:
95 | stringMap.put("John", "Doe")
96 |
97 | then:
98 | noExceptionThrown()
99 | stringMap.get("John") == "Doe"
100 | }
101 |
102 | final static class TestSerializeClass implements Serializable {
103 | String testString
104 | int testInt
105 |
106 | TestSerializeClass(String testString, int testInt) {
107 | this.testString = testString
108 | this.testInt = testInt
109 | }
110 | }
111 | }
112 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/java/shillelagh/crud/DropTableTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.crud;
18 |
19 | import android.content.Context;
20 | import android.database.Cursor;
21 | import android.database.sqlite.SQLiteDatabase;
22 | import android.test.AndroidTestCase;
23 |
24 | import com.example.shillelagh.model.TestNotTableObject;
25 | import com.example.shillelagh.model.TestPrimitiveTable;
26 |
27 | import java.io.File;
28 |
29 | import shillelagh.Shillelagh;
30 |
31 | import static org.assertj.core.api.Assertions.assertThat;
32 | import static shillelagh.Shillelagh.getTableName;
33 |
34 | public class DropTableTest extends AndroidTestCase {
35 |
36 | private static final int CURRENT_DATABASE_VERSION = 1;
37 | private SQLiteDatabase database;
38 | private File databaseFile;
39 |
40 | @Override
41 | protected void setUp() throws Exception {
42 | super.setUp();
43 | File dbDir = getContext().getDir("tests", Context.MODE_PRIVATE);
44 | databaseFile = new File(dbDir, "database_test.db");
45 |
46 | if (databaseFile.exists()) {
47 | //noinspection ResultOfMethodCallIgnored
48 | databaseFile.delete();
49 | }
50 | database = SQLiteDatabase.openOrCreateDatabase(databaseFile.getPath(), null);
51 | assertNotNull(database);
52 | database.setVersion(CURRENT_DATABASE_VERSION);
53 | }
54 |
55 | @Override
56 | protected void tearDown() throws Exception {
57 | database.close();
58 | //noinspection ResultOfMethodCallIgnored
59 | databaseFile.delete();
60 | super.tearDown();
61 | }
62 |
63 | public void testShouldDropTable() {
64 | // Arrange
65 | String tableName = getTableName(TestPrimitiveTable.class);
66 | String tableCheckQuery = String.format("SELECT DISTINCT tbl_name FROM " +
67 | "sqlite_master WHERE tbl_name = \'%s\'", tableName);
68 | String create = String.format("CREATE TABLE %s (id INTEGER PRIMARY KEY AUTOINCREMENT, aShort " +
69 | "INTEGER, anInt INTEGER, aLong INTEGER, aFloat REAL, aDouble REAL, aBoolean INTEGER);",
70 | tableName);
71 | database.execSQL(create);
72 |
73 | // Act
74 | Shillelagh.dropTable(database, TestPrimitiveTable.class);
75 |
76 | // Assert
77 | Cursor cursor = database.rawQuery(tableCheckQuery, null);
78 |
79 | boolean exists = false;
80 | if (cursor != null) {
81 | if (cursor.getCount() > 0) {
82 | cursor.close();
83 | exists = true;
84 | }
85 | }
86 |
87 | assertThat(exists).isFalse();
88 | }
89 |
90 | public void testShouldThrowErrorWhenNotAnnotated() {
91 | // Arrange
92 | String create = String.format("CREATE TABLE %s (_id INTEGER PRIMARY KEY AUTOINCREMENT, name " +
93 | "TEXT, value INTEGER);", TestNotTableObject.class.getSimpleName());
94 | database.execSQL(create);
95 |
96 | // Act
97 | try {
98 | Shillelagh.dropTable(database, TestNotTableObject.class);
99 | } catch (RuntimeException e) {
100 | assertThat(e.getMessage()).isEqualTo("com.example.shillelagh.model.TestNotTableObject is not "
101 | + "a table object.");
102 | return;
103 | }
104 |
105 | // Assert
106 | throw new AssertionError("Expected Exception Not Thrown");
107 | }
108 | }
109 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/SqliteType.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import com.google.common.collect.Sets;
20 |
21 | import java.util.Arrays;
22 | import java.util.Collections;
23 | import java.util.Date;
24 | import java.util.Set;
25 |
26 | import javax.lang.model.element.Element;
27 | import javax.lang.model.type.TypeKind;
28 | import javax.lang.model.type.TypeMirror;
29 |
30 | import shillelagh.Column;
31 |
32 | /** Sqlite3 Types */
33 | enum SqliteType {
34 | NULL(Sets.newHashSet(Arrays.asList(TypeKind.NULL)), Collections.emptySet()),
35 | INTEGER(Sets.newHashSet(Arrays.asList(
36 | TypeKind.INT,
37 | TypeKind.SHORT,
38 | TypeKind.LONG,
39 | TypeKind.BOOLEAN // true false types
40 | )), Sets.newHashSet(Arrays.asList(
41 | Integer.class.getName(),
42 | Short.class.getName(),
43 | Long.class.getName(),
44 | Boolean.class.getName(), // true false types
45 | Date.class.getName()
46 | ))),
47 | REAL(Sets.newHashSet(Arrays.asList(
48 | TypeKind.DOUBLE,
49 | TypeKind.FLOAT
50 | )), Sets.newHashSet(Arrays.asList(
51 | Double.class.getName(),
52 | Float.class.getName(),
53 | Number.class.getName()
54 | ))),
55 | TEXT(Collections.emptySet(), Sets.newHashSet(Arrays.asList(
56 | String.class.getName()
57 | ))),
58 | BLOB(Collections.emptySet(), Collections.emptySet()),
59 | ONE_TO_MANY(Collections.emptySet(), Collections.emptySet()),
60 | ONE_TO_MANY_CHILD(Collections.emptySet(), Collections.emptySet()),
61 | // signals an unknown type probably should be a key into another table
62 | UNKNOWN(Collections.emptySet(), Collections.emptySet());
63 |
64 | private final Set kinds;
65 | private final Set objects;
66 |
67 | /**
68 | * @param kinds TypeKinds that the SqliteType is associated with
69 | * @param objects Strings of the objects this SqliteType is associated with
70 | */
71 | SqliteType(Set kinds, Set objects) {
72 | this.kinds = kinds;
73 | this.objects = objects;
74 | }
75 |
76 | @Override public String toString() {
77 | if (this == ONE_TO_MANY_CHILD) {
78 | return INTEGER.name();
79 | } else if (this == ONE_TO_MANY) {
80 | throw new RuntimeException("Should not be using ONE_TO_MANY to write sql");
81 | }
82 | return name();
83 | }
84 |
85 | static SqliteType from(Element element) {
86 | if (element == null) {
87 | throw new NullPointerException("element must not be null");
88 | }
89 |
90 | if (element.getAnnotation(Column.class).isBlob()) {
91 | return BLOB;
92 | }
93 |
94 | String typeString = element.asType().toString();
95 | // TODO Arrays?
96 | if (typeString.contains("java.util.List")) {
97 | return ONE_TO_MANY;
98 | }
99 |
100 | final TypeMirror typeMirror = element.asType();
101 | for (SqliteType sqliteType : values()) {
102 | if (sqliteType.kinds.contains(typeMirror.getKind())
103 | || sqliteType.objects.contains(typeMirror.toString())) {
104 | return sqliteType;
105 | }
106 | }
107 |
108 | return UNKNOWN;
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/shillelagh-processor/src/main/java/shillelagh/internal/TableColumn.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import java.util.Date;
20 |
21 | import javax.lang.model.element.Element;
22 |
23 | import static shillelagh.internal.SqliteType.INTEGER;
24 |
25 | /** Represents the data for a column in a database and mapping it back to its java counter part */
26 | class TableColumn {
27 | private final SqliteType sqliteType;
28 | private final String columnName;
29 |
30 | /** The name of the member variable this column should read/write. */
31 | private final String memberName;
32 |
33 | private String type;
34 |
35 | /** Indicates if column is a one to one mapping */
36 | private boolean oneToOne = false;
37 |
38 | /**
39 | * Construct a table column from the element
40 | *
41 | * @param element element to construct this object from
42 | * @param type Type that created this column should map back to in java as a String.
43 | * Ex. "java.lang.Integer"
44 | * @param columnName The name of this column.
45 | */
46 | TableColumn(Element element, String type, String columnName) {
47 | this.columnName = Strings.isBlank(columnName) ? element.getSimpleName().toString() : columnName;
48 | this.memberName = element.getSimpleName().toString();
49 | this.sqliteType = SqliteType.from(element);
50 | this.type = type;
51 | }
52 |
53 | /**
54 | * Construct a table column directly
55 | *
56 | * @param columnName the name of this column
57 | * @param type the type this column should map back from sql to in java
58 | * @param sqliteType the sqlite type this column will be
59 | */
60 | TableColumn(String columnName, String memberName, String type, SqliteType sqliteType) {
61 | this.columnName = columnName;
62 | this.memberName = memberName;
63 | this.type = type;
64 | this.sqliteType = sqliteType;
65 | }
66 |
67 | String getColumnName() {
68 | return columnName;
69 | }
70 |
71 | String getMemberName() {
72 | return memberName;
73 | }
74 |
75 | SqliteType getSqlType() {
76 | return isOneToOne() ? INTEGER : sqliteType;
77 | }
78 |
79 | String getType() {
80 | return type;
81 | }
82 |
83 | /** Allow setting the generic type for one to manys */
84 | void setType(String type) {
85 | this.type = type;
86 | }
87 |
88 | boolean isDate() {
89 | return getType().equals(Date.class.getName());
90 | }
91 |
92 | boolean isBoolean() {
93 | final String typeString = getType();
94 | return typeString.equals(boolean.class.getName()) || typeString.equals(Boolean.class.getName());
95 | }
96 |
97 | boolean isByteArray() {
98 | final String typeString = getType();
99 | return typeString.equals("byte[]");
100 | }
101 |
102 | boolean isBlob() {
103 | return sqliteType == SqliteType.BLOB;
104 | }
105 |
106 | boolean isOneToMany() {
107 | return sqliteType == SqliteType.ONE_TO_MANY;
108 | }
109 |
110 | boolean isOneToManyChild() {
111 | return sqliteType == SqliteType.ONE_TO_MANY_CHILD;
112 | }
113 |
114 | void setOneToOne(boolean oneToOne) {
115 | this.oneToOne = oneToOne;
116 | }
117 |
118 | boolean isOneToOne() {
119 | return oneToOne;
120 | }
121 |
122 | @Override public String toString() {
123 | return columnName + " " + getSqlType().toString();
124 | }
125 | }
126 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/internal/ShillelaghUtil.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.internal;
18 |
19 | import java.io.ByteArrayInputStream;
20 | import java.io.ByteArrayOutputStream;
21 | import java.io.IOException;
22 | import java.io.ObjectInputStream;
23 | import java.io.ObjectOutputStream;
24 | import java.util.ArrayList;
25 | import java.util.HashMap;
26 | import java.util.List;
27 | import java.util.Map;
28 | import org.objenesis.Objenesis;
29 | import org.objenesis.ObjenesisStd;
30 | import org.objenesis.instantiator.ObjectInstantiator;
31 |
32 | /**
33 | * Set of utility functions used by code generated by shillelagh.
34 | */
35 | public final class ShillelaghUtil {
36 |
37 | private static final Objenesis OBJENESIS = new ObjenesisStd();
38 |
39 | /**
40 | * Takes an object and serializes it to a byte array. Don't enforce that it extends serializable
41 | * to allow for lists and maps to be passed in.
42 | *
43 | * @param object The object to serialize. Must implement {@link java.io.Serializable}
44 | * @return The object as a byte array.
45 | */
46 | public static byte[] serialize(T object) {
47 | try {
48 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
49 | ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
50 | objectOutputStream.writeObject(object);
51 | return byteArrayOutputStream.toByteArray();
52 | } catch (IOException e) {
53 | throw new RuntimeException(e);
54 | }
55 | }
56 |
57 | /**
58 | * De-serialize a byte array back to it's original object.
59 | *
60 | * @param bytes The bytes that where serialized from an object.
61 | * @param The type the bytes should be serialised back too.
62 | * @return The de-serialized object.
63 | */
64 | public static K deserialize(byte[] bytes) {
65 | try {
66 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
67 | ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
68 | @SuppressWarnings("unchecked") final K k = (K) objectInputStream.readObject();
69 | return k;
70 | } catch (IOException e) {
71 | throw new RuntimeException(e);
72 | } catch (ClassNotFoundException e) {
73 | throw new RuntimeException(e);
74 | }
75 | }
76 |
77 | /**
78 | * Takes a class type and constructs it. If the class does not have an empty constructor this
79 | * will
80 | * find the parametrized constructor and use nulls and default values to construct the class.
81 | *
82 | * @param clazz The class to construct.
83 | * @param The type of the class to construct.
84 | * @return The constructed object.
85 | */
86 | @SuppressWarnings("unchecked")
87 | public static T createInstance(Class clazz) {
88 | if (clazz.isInterface()) {
89 | if (clazz == List.class) {
90 | return (T) new ArrayList();
91 | } else if (clazz == Map.class) {
92 | return (T) new HashMap();
93 | }
94 |
95 | throw new UnsupportedOperationException("Interface types can not be instantiated.");
96 | }
97 |
98 | ObjectInstantiator instantiator = OBJENESIS.getInstantiatorOf(clazz);
99 | return (T) instantiator.newInstance();
100 | }
101 |
102 | private ShillelaghUtil() {
103 | /* No Instances */
104 | }
105 | }
106 |
--------------------------------------------------------------------------------
/shillelagh/src/test/java/shillelagh/test/LotsOfParamConstructor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.test;
18 |
19 | public final class LotsOfParamConstructor {
20 | private final byte testByte;
21 | private final short testShort;
22 | private final int testInt;
23 | private final long testLong;
24 | private final float testFloat;
25 | private final double testDouble;
26 | private final char testChar;
27 | private final boolean testBool;
28 | private final String testString;
29 |
30 | public LotsOfParamConstructor(byte testByte, short testShort, int testInt, long testLong,
31 | float testFloat, double testDouble, char testChar, boolean testBool, String testString) {
32 | this.testByte = testByte;
33 | this.testShort = testShort;
34 | this.testInt = testInt;
35 | this.testLong = testLong;
36 | this.testFloat = testFloat;
37 | this.testDouble = testDouble;
38 | this.testChar = testChar;
39 | this.testBool = testBool;
40 | this.testString = testString;
41 | }
42 |
43 | public byte getTestByte() {
44 | return testByte;
45 | }
46 |
47 | public short getTestShort() {
48 | return testShort;
49 | }
50 |
51 | public int getTestInt() {
52 | return testInt;
53 | }
54 |
55 | public long getTestLong() {
56 | return testLong;
57 | }
58 |
59 | public float getTestFloat() {
60 | return testFloat;
61 | }
62 |
63 | public double getTestDouble() {
64 | return testDouble;
65 | }
66 |
67 | public char getTestChar() {
68 | return testChar;
69 | }
70 |
71 | public boolean isTestBool() {
72 | return testBool;
73 | }
74 |
75 | public String getTestString() {
76 | return testString;
77 | }
78 |
79 | @Override
80 | public boolean equals(Object o) {
81 | if (this == o) return true;
82 | if (o == null || getClass() != o.getClass()) return false;
83 |
84 | LotsOfParamConstructor that = (LotsOfParamConstructor) o;
85 |
86 | if (testBool != that.testBool) return false;
87 | if (testByte != that.testByte) return false;
88 | if (testChar != that.testChar) return false;
89 | if (Double.compare(that.testDouble, testDouble) != 0) return false;
90 | if (Float.compare(that.testFloat, testFloat) != 0) return false;
91 | if (testInt != that.testInt) return false;
92 | if (testLong != that.testLong) return false;
93 | if (testShort != that.testShort) return false;
94 | if (testString != null ? !testString.equals(that.testString) : that.testString != null) {
95 | return false;
96 | }
97 |
98 | return true;
99 | }
100 |
101 | @Override
102 | public int hashCode() {
103 | int result;
104 | long temp;
105 | result = (int) testByte;
106 | result = 31 * result + (int) testShort;
107 | result = 31 * result + testInt;
108 | result = 31 * result + (int) (testLong ^ (testLong >>> 32));
109 | result = 31 * result + (testFloat != +0.0f ? Float.floatToIntBits(testFloat) : 0);
110 | temp = Double.doubleToLongBits(testDouble);
111 | result = 31 * result + (int) (temp ^ (temp >>> 32));
112 | result = 31 * result + (int) testChar;
113 | result = 31 * result + (testBool ? 1 : 0);
114 | result = 31 * result + (testString != null ? testString.hashCode() : 0);
115 | return result;
116 | }
117 |
118 | @Override public String toString() {
119 | return "LotsOfParamConstructor{"
120 | + "testByte=" + testByte
121 | + ", testShort=" + testShort
122 | + ", testInt=" + testInt
123 | + ", testLong=" + testLong
124 | + ", testFloat=" + testFloat
125 | + ", testDouble=" + testDouble
126 | + ", testChar=" + testChar
127 | + ", testBool=" + testBool
128 | + ", testString='" + testString + '\''
129 | + '}';
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/shillelagh/src/main/java/shillelagh/QueryBuilder.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import static shillelagh.Operator.AND;
20 | import static shillelagh.Operator.BETWEEN;
21 | import static shillelagh.Operator.EQUAL;
22 | import static shillelagh.Operator.GREATER_THAN_EQUAL;
23 | import static shillelagh.Operator.GREATER_THAN;
24 | import static shillelagh.Operator.IS;
25 | import static shillelagh.Operator.LESS_THAN;
26 | import static shillelagh.Operator.LESS_THAN_EQUAL;
27 | import static shillelagh.Operator.LIKE;
28 | import static shillelagh.Operator.NOT;
29 | import static shillelagh.Operator.NOT_EQUAL;
30 | import static shillelagh.Operator.NULL;
31 | import static shillelagh.Operator.OR;
32 | import static shillelagh.Operator.ORDER_BY;
33 |
34 | /** A builder for building sql queries. */
35 | public final class QueryBuilder extends Builder {
36 | private final String columnName;
37 |
38 | QueryBuilder(Class extends T> tableObject, Shillelagh shillelagh, String columnName,
39 | StringBuilder query) {
40 | super(shillelagh, tableObject, query);
41 | this.columnName = columnName;
42 | }
43 |
44 | public QueryBuilder isEqualTo(Object value) {
45 | query.append(EQUAL.operator).append(valueOf(columnName, value));
46 | return this;
47 | }
48 |
49 | public QueryBuilder isNotEqualTo(Object value) {
50 | query.append(NOT_EQUAL.operator).append(valueOf(columnName, value));
51 | return this;
52 | }
53 |
54 | public QueryBuilder isGreaterThanOrEqualTo(Object value) {
55 | query.append(GREATER_THAN_EQUAL.operator).append(valueOf(columnName, value));
56 | return this;
57 | }
58 |
59 | public QueryBuilder isGreaterThan(Object value) {
60 | query.append(GREATER_THAN.operator).append(valueOf(columnName, value));
61 | return this;
62 | }
63 |
64 | public QueryBuilder isLessThanOrEqualTo(Object value) {
65 | query.append(LESS_THAN_EQUAL.operator).append(valueOf(columnName, value));
66 | return this;
67 | }
68 |
69 | public QueryBuilder isLessThan(Object value) {
70 | query.append(LESS_THAN.operator).append(valueOf(columnName, value));
71 | return this;
72 | }
73 |
74 | public QueryBuilder between(Object value1, Object value2) {
75 | query.append(BETWEEN.operator)
76 | .append(valueOf(columnName, value1))
77 | .append(AND.operator)
78 | .append(valueOf(columnName, value2));
79 | return this;
80 | }
81 |
82 | public QueryBuilder and(String columnName) {
83 | checkColumnName(columnName);
84 | query.append(AND.operator).append(columnName);
85 | return this;
86 | }
87 |
88 | public QueryBuilder or(String columnName) {
89 | checkColumnName(columnName);
90 | query.append(OR.operator).append(columnName);
91 | return this;
92 | }
93 |
94 | public QueryBuilder like(Object value) {
95 | query.append(LIKE.operator).append("\'").append(value).append("\'");
96 | return this;
97 | }
98 |
99 | public QueryBuilder isNotNull() {
100 | query.append(IS.operator).append(NOT.operator).append(NULL.operator);
101 | return this;
102 | }
103 |
104 | public QueryBuilder isNull() {
105 | query.append(IS.operator).append(NULL.operator);
106 | return this;
107 | }
108 |
109 | public QueryBuilder not() {
110 | query.append(NOT.operator);
111 | return this;
112 | }
113 |
114 | public OrderByBuilder orderBy(String columnName) {
115 | checkColumnName(columnName);
116 | query.append(ORDER_BY.operator).append(columnName);
117 | return new OrderByBuilder(shillelagh, tableObject, query);
118 | }
119 |
120 | /** Forces the value to be wrapped with ' if it isEqualTo for a string field. */
121 | private Object valueOf(String columnName, Object value) {
122 | java.lang.reflect.Field field;
123 | try {
124 | field = tableObject.getDeclaredField(columnName);
125 | } catch (NoSuchFieldException e) {
126 | throw new RuntimeException(
127 | String.format("%s isEqualTo not a field found in %s", columnName, tableObject));
128 | }
129 | return field.getType() == String.class ? String.format("\'%s\'", value) : value;
130 | }
131 | }
132 |
--------------------------------------------------------------------------------
/shillelagh/shillelagh.gradle:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 | apply plugin: 'groovy'
18 | apply plugin: 'maven-publish'
19 | apply from: rootProject.file('gradle/javaDoc.gradle')
20 | apply from: rootProject.file('gradle/bintray.gradle')
21 | apply from: rootProject.file('gradle/artifactory.gradle')
22 |
23 | targetCompatibility = JavaVersion.VERSION_1_6
24 | sourceCompatibility = JavaVersion.VERSION_1_6
25 |
26 | configurations {
27 | tools
28 | }
29 |
30 | dependencies {
31 | compile 'com.google.android:android:4.1.1.4', optional
32 | compile "io.reactivex:rxjava:${commonVersions.rxjava}", optional
33 | compile 'org.objenesis:objenesis:2.1', optional
34 |
35 | testCompile 'org.codehaus.groovy:groovy-all:2.3.6'
36 | testCompile 'org.spockframework:spock-core:1.0-groovy-2.4'
37 |
38 | tools "com.googlecode.jarjar:jarjar:1.3"
39 | }
40 |
41 | task publishJavadoc(type: Exec) {
42 | dependsOn "javadoc"
43 | commandLine "bash", "-c",
44 | """
45 | REPO="git@github.com:pieces029/shillelagh.git"
46 | DIR=temp-clone
47 |
48 | # Delete any existing temporary website clone
49 | rm -rf \$DIR
50 |
51 | # Clone the current repo into temp folder
52 | git clone \$REPO \$DIR
53 |
54 | # Move working directory into temp folder
55 | cd \$DIR
56 |
57 | # Checkout and track the gh-pages branch
58 | git checkout -t origin/gh-pages
59 |
60 | # Delete everything
61 | rm -rf *
62 |
63 | # Copy everything from javadocs folder
64 | cp -r $buildDir/docs/javadoc/* .
65 |
66 | # Stage all files in git and create a commit
67 | git add .
68 | git add -u
69 | git commit -m "Website at \$(date)"
70 |
71 | # Push the new files up to GitHub
72 | git push origin gh-pages
73 |
74 | # Delete our temp folder
75 | cd ..
76 | rm -rf \$DIR
77 | """
78 | }
79 |
80 | task jarjar(type: Jar, dependsOn: jar) {
81 | destinationDir = jar.destinationDir
82 | baseName = jar.baseName
83 | appendix = jar.appendix
84 | classifier = jar.classifier
85 | includeEmptyDirs = false
86 | def target = new File("${archivePath}.tmp")
87 |
88 | doFirst {
89 | from zipTree(target)
90 | ant {
91 | taskdef name: 'jarjar', classname: 'com.tonicsystems.jarjar.JarJarTask', classpath: configurations.tools.asPath
92 | jarjar(jarfile: target) {
93 | zipfileset(src: jar.archivePath)
94 | zipfileset(src: configurations.runtime.files.find { it.name.startsWith('objenesis') })
95 | rule pattern: 'org.objenesis.**', result: 'shillelagh.internal.objenesis.@1'
96 | }
97 | }
98 |
99 | }
100 | doLast {
101 | target.delete()
102 | }
103 | }
104 | jar.finalizedBy jarjar
105 |
106 | publishing {
107 | publications {
108 | mavenJava(MavenPublication) {
109 | from components.java
110 |
111 | artifact sourcesJar {
112 | classifier "sources"
113 | }
114 |
115 | artifact javadocJar {
116 | classifier "javadoc"
117 | }
118 |
119 | groupId 'com.andrewreitz'
120 | artifactId 'shillelagh'
121 |
122 | pom.withXml {
123 | def Node root = asNode()
124 | root.appendNode('name', 'Shillelagh')
125 | root.appendNode('description', 'Shillelagh Sqlite Android library')
126 | root.appendNode('url', 'https://github.com/pieces029/shillelagh')
127 |
128 | def issues = root.appendNode('issueManagement')
129 | issues.appendNode('system', 'github')
130 | issues.appendNode('url', 'https://github.com/pieces029/shillelagh/issues')
131 |
132 | def scm = root.appendNode('scm')
133 | scm.appendNode('url', 'scm:https://github.com/pieces029/shillelagh')
134 | scm.appendNode('connection', 'scm:git:git@github.com:pieces029/shillelagh.git')
135 | scm.appendNode('developerConnection', 'scm:git:git@github.com:pieces029/shillelagh.git')
136 |
137 | def license = root.appendNode('licenses').appendNode('license');
138 | license.appendNode('name', 'The Apache Software License, Version 2.0')
139 | license.appendNode('url', 'http://www.apache.org/licenses/LICENSE-2.0.txt')
140 | license.appendNode('distribution', 'repo')
141 |
142 | def dev = root.appendNode('developers').appendNode('developer');
143 | dev.appendNode('id', 'areitz')
144 | dev.appendNode('name', 'Andrew Reitz')
145 | dev.appendNode('email', 'andrew@andrewreitz.com')
146 | dev.appendNode('organizationUrl', 'http://andrewreitz.com')
147 | }
148 | }
149 | }
150 | }
151 |
--------------------------------------------------------------------------------
/shillelagh-sample/src/main/java/com/example/shillelagh/MainActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh;
18 |
19 | import android.app.Activity;
20 | import android.database.Cursor;
21 | import android.os.Bundle;
22 | import android.util.Log;
23 |
24 | import com.example.shillelagh.model.Author;
25 | import com.example.shillelagh.model.Book;
26 | import com.example.shillelagh.model.Chapter;
27 | import com.example.shillelagh.model.CollectionsTest;
28 | import com.example.shillelagh.model.Image;
29 |
30 | import java.util.Arrays;
31 | import java.util.Calendar;
32 | import java.util.Collections;
33 | import java.util.Date;
34 | import java.util.GregorianCalendar;
35 | import java.util.HashMap;
36 | import java.util.LinkedList;
37 | import java.util.List;
38 |
39 | import java.util.Map;
40 | import java.util.concurrent.TimeUnit;
41 | import rx.Notification;
42 | import rx.Observer;
43 | import rx.android.schedulers.AndroidSchedulers;
44 | import rx.functions.Action1;
45 | import rx.functions.Func1;
46 | import rx.schedulers.Schedulers;
47 | import shillelagh.Shillelagh;
48 |
49 | import static shillelagh.Shillelagh.getTableName;
50 |
51 | public class MainActivity extends Activity {
52 | private static final String TAG = "ShillelaghExample";
53 |
54 | @Override protected void onCreate(Bundle savedInstanceState) {
55 | super.onCreate(savedInstanceState);
56 |
57 | ShillelaghApp shillelaghApp = ShillelaghApp.get(this);
58 | final Shillelagh shillelagh = shillelaghApp.getShillelagh();
59 |
60 | Author author1 = new Author("Icculus");
61 |
62 | final List chapters =
63 | Arrays.asList(new Chapter("Chapter 1"), new Chapter("Chapter 2"), new Chapter("Chapter 3"));
64 |
65 | final byte[] imageData = { 1, 2, 3, 4, 5 };
66 | final Image image =
67 | new Image("Awesome Image", new GregorianCalendar(2000, 1, 1).getTime(), imageData);
68 |
69 | final Date published = Calendar.getInstance().getTime();
70 | Book book = new Book("The Helping Phriendly Book", author1, published, chapters, image);
71 |
72 | shillelagh.insert(book);
73 |
74 | author1.setName("Wilson");
75 | shillelagh.update(author1);
76 |
77 | List authors = shillelagh.rawQuery(Author.class, "SELECT * FROM %s WHERE name = \'%s\'",
78 | getTableName(Author.class), author1.getName());
79 | for (Author a : authors) {
80 | Log.d(TAG, String.format("Author single select: %s", a.getName()));
81 | }
82 |
83 | Cursor bookCursor = shillelagh.rawQuery("SELECT * FROM %s", getTableName(Book.class));
84 | List books = shillelagh.map(Book.class, bookCursor);
85 | for (Book b : books) {
86 | Log.d(TAG, String.format("Book: %s", b));
87 | shillelagh.delete(Book.class, b.getId());
88 | }
89 |
90 | for (Author a : authors) {
91 | shillelagh.delete(a);
92 | }
93 |
94 | shillelagh.get(Chapter.class)
95 | .observeOn(AndroidSchedulers.mainThread())
96 | .subscribeOn(Schedulers.io())
97 | .doOnNext(new Action1() {
98 | @Override public void call(Chapter chapter) {
99 | shillelagh.delete(chapter);
100 | }
101 | })
102 | .map(new Func1() {
103 | @Override public String call(Chapter chapter) {
104 | return chapter.getChapter();
105 | }
106 | })
107 | .subscribe(new Action1() {
108 | @Override public void call(String title) {
109 | Log.d(TAG, title);
110 | }
111 | });
112 |
113 | shillelagh.selectFrom(Chapter.class)
114 | .where("chapter")
115 | .isEqualTo("Chapter 1")
116 | .toObservable()
117 | .subscribeOn(Schedulers.io())
118 | .observeOn(AndroidSchedulers.mainThread())
119 | .subscribe(new Action1() {
120 | @Override public void call(Chapter chapter) {
121 | Log.d(TAG, chapter.toString());
122 | }
123 | });
124 |
125 | Map maps = new HashMap();
126 | maps.put("Test1", "Test1");
127 | maps.put("Test2", "Test2");
128 |
129 | List strings = new LinkedList();
130 | strings.add("Test1");
131 | strings.add("Test2");
132 |
133 | CollectionsTest test = new CollectionsTest(maps, strings);
134 | shillelagh.insert(test);
135 |
136 | shillelagh.get(CollectionsTest.class).subscribe(new Observer() {
137 | @Override public void onCompleted() {
138 | Log.d("TEST", "Complete");
139 | }
140 |
141 | @Override public void onError(Throwable e) {
142 | throw new RuntimeException(e);
143 | }
144 |
145 | @Override public void onNext(CollectionsTest collectionsTest) {
146 | Log.d("TEST", collectionsTest.toString());
147 | }
148 | });
149 |
150 | shillelagh.delete(test);
151 | }
152 | }
153 |
--------------------------------------------------------------------------------
/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 | # For Cygwin, ensure paths are in UNIX format before anything is touched.
46 | if $cygwin ; then
47 | [ -n "$JAVA_HOME" ] && JAVA_HOME=`cygpath --unix "$JAVA_HOME"`
48 | fi
49 |
50 | # Attempt to set APP_HOME
51 | # Resolve links: $0 may be a link
52 | PRG="$0"
53 | # Need this for relative symlinks.
54 | while [ -h "$PRG" ] ; do
55 | ls=`ls -ld "$PRG"`
56 | link=`expr "$ls" : '.*-> \(.*\)$'`
57 | if expr "$link" : '/.*' > /dev/null; then
58 | PRG="$link"
59 | else
60 | PRG=`dirname "$PRG"`"/$link"
61 | fi
62 | done
63 | SAVED="`pwd`"
64 | cd "`dirname \"$PRG\"`/" >&-
65 | APP_HOME="`pwd -P`"
66 | cd "$SAVED" >&-
67 |
68 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
69 |
70 | # Determine the Java command to use to start the JVM.
71 | if [ -n "$JAVA_HOME" ] ; then
72 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
73 | # IBM's JDK on AIX uses strange locations for the executables
74 | JAVACMD="$JAVA_HOME/jre/sh/java"
75 | else
76 | JAVACMD="$JAVA_HOME/bin/java"
77 | fi
78 | if [ ! -x "$JAVACMD" ] ; then
79 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
80 |
81 | Please set the JAVA_HOME variable in your environment to match the
82 | location of your Java installation."
83 | fi
84 | else
85 | JAVACMD="java"
86 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
87 |
88 | Please set the JAVA_HOME variable in your environment to match the
89 | location of your Java installation."
90 | fi
91 |
92 | # Increase the maximum file descriptors if we can.
93 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then
94 | MAX_FD_LIMIT=`ulimit -H -n`
95 | if [ $? -eq 0 ] ; then
96 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
97 | MAX_FD="$MAX_FD_LIMIT"
98 | fi
99 | ulimit -n $MAX_FD
100 | if [ $? -ne 0 ] ; then
101 | warn "Could not set maximum file descriptor limit: $MAX_FD"
102 | fi
103 | else
104 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
105 | fi
106 | fi
107 |
108 | # For Darwin, add options to specify how the application appears in the dock
109 | if $darwin; then
110 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
111 | fi
112 |
113 | # For Cygwin, switch paths to Windows format before running java
114 | if $cygwin ; then
115 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
116 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules
158 | function splitJvmOpts() {
159 | JVM_OPTS=("$@")
160 | }
161 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS
162 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME"
163 |
164 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@"
165 |
--------------------------------------------------------------------------------
/checkstyle.xml:
--------------------------------------------------------------------------------
1 |
2 |
17 |
18 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/res/layout/activity_speed_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
18 |
19 |
25 |
26 |
27 |
32 |
37 |
38 |
44 |
45 |
46 |
51 |
56 |
57 |
63 |
64 |
65 |
70 |
75 |
76 |
82 |
83 |
84 |
89 |
94 |
95 |
101 |
102 |
103 |
108 |
113 |
114 |
120 |
121 |
122 |
127 |
132 |
133 |
139 |
140 |
141 |
146 |
151 |
152 |
158 |
159 |
160 |
165 |
170 |
171 |
177 |
178 |
179 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/java/shillelagh/QueryBuilderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh;
18 |
19 | import android.content.Context;
20 | import android.database.sqlite.SQLiteDatabase;
21 | import android.database.sqlite.SQLiteOpenHelper;
22 | import android.test.AndroidTestCase;
23 | import com.example.shillelagh.model.SimpleObject;
24 | import java.util.List;
25 |
26 | import static org.assertj.core.api.Assertions.assertThat;
27 |
28 | public class QueryBuilderTest extends AndroidTestCase {
29 |
30 | private Shillelagh shillelagh;
31 |
32 | @Override protected void setUp() throws Exception {
33 | super.setUp();
34 |
35 | SQLiteOpenHelper sqliteOpenHelper = new QueryBuilderTestSQLiteOpenHelper(getContext());
36 | shillelagh = new Shillelagh(sqliteOpenHelper);
37 |
38 | for (int i = 0; i < 1000; i++) {
39 | final SimpleObject simpleObject =
40 | new SimpleObject(String.valueOf(i), String.valueOf((i % 10) + 1), (i % 100) + 1);
41 | shillelagh.insert(simpleObject);
42 | }
43 | }
44 |
45 | @Override protected void tearDown() throws Exception {
46 | getContext().deleteDatabase(QueryBuilderTestSQLiteOpenHelper.DATABASE_NAME);
47 | super.tearDown();
48 | }
49 |
50 | public void testSelect() {
51 | final WhereBuilder builder = shillelagh.selectFrom(SimpleObject.class);
52 |
53 | assertThat(builder.toString()).isEqualTo("SELECT * FROM SimpleObject");
54 | assertThat(builder.toList()).hasSize(1000);
55 | assertThat(builder.toCursor().getCount()).isEqualTo(1000);
56 | assertThat(builder.toObservable().toList().toBlocking().first().size()).isEqualTo(1000);
57 | }
58 |
59 | public void testWhere() {
60 | final QueryBuilder selectStatement =
61 | shillelagh.selectFrom(SimpleObject.class).where("id").isEqualTo(14);
62 |
63 | assertThat(selectStatement.toString()).isEqualTo("SELECT * FROM SimpleObject WHERE id = 14");
64 | assertThat(selectStatement.toList()).hasSize(1);
65 | }
66 |
67 | public void testWhereNotNull() {
68 | final QueryBuilder selectStatement =
69 | shillelagh.selectFrom(SimpleObject.class).where("id").isNotNull();
70 |
71 | assertThat(selectStatement.toList()).hasSize(1000);
72 | }
73 |
74 | public void testWhereNull() {
75 | final QueryBuilder selectStatement =
76 | shillelagh.selectFrom(SimpleObject.class).where("id").isNull();
77 |
78 | assertThat(selectStatement.toList()).hasSize(0);
79 | }
80 |
81 | public void testWhereNotEqual() {
82 | final QueryBuilder selectStatement =
83 | shillelagh.selectFrom(SimpleObject.class).where("name").isNotEqualTo(100);
84 |
85 | assertThat(selectStatement.toList()).hasSize(999);
86 | }
87 |
88 | public void testWhereGreaterThanEqualTo() {
89 | final QueryBuilder selectStatement =
90 | shillelagh.selectFrom(SimpleObject.class).where("id").isGreaterThanOrEqualTo(999);
91 |
92 | assertThat(selectStatement.toList()).hasSize(2);
93 | }
94 |
95 | public void testWhereGreaterThan() {
96 | final QueryBuilder selectStatement =
97 | shillelagh.selectFrom(SimpleObject.class).where("id").isGreaterThan(999);
98 |
99 | assertThat(selectStatement.toList()).hasSize(1);
100 | }
101 |
102 | public void testWhereLessThanEqualTo() {
103 | final QueryBuilder selectStatement =
104 | shillelagh.selectFrom(SimpleObject.class).where("id").isLessThanOrEqualTo(2);
105 |
106 | assertThat(selectStatement.toList()).hasSize(2);
107 | }
108 |
109 | public void testWhereLessThan() {
110 | final QueryBuilder selectStatement =
111 | shillelagh.selectFrom(SimpleObject.class).where("id").isLessThan(2);
112 |
113 | assertThat(selectStatement.toList()).hasSize(1);
114 | }
115 |
116 | public void testBetween() {
117 | final QueryBuilder selectStatement =
118 | shillelagh.selectFrom(SimpleObject.class).where("id").between(10, 12);
119 |
120 | assertThat(selectStatement.toList()).hasSize(3);
121 | }
122 |
123 | public void testAnd() {
124 | final QueryBuilder selectStatement = shillelagh.selectFrom(SimpleObject.class)
125 | .where("name")
126 | .isEqualTo(0)
127 | .and("address")
128 | .isEqualTo(1);
129 |
130 | assertThat(selectStatement.toList()).hasSize(1);
131 | }
132 |
133 | public void testOr() {
134 | final QueryBuilder selectStatement = shillelagh.selectFrom(SimpleObject.class)
135 | .where("name")
136 | .isEqualTo(0)
137 | .or("address")
138 | .isEqualTo(1);
139 |
140 | assertThat(selectStatement.toList()).hasSize(100);
141 | }
142 |
143 | public void testLike() {
144 | final QueryBuilder selectStatement =
145 | shillelagh.selectFrom(SimpleObject.class).where("name").like("%00");
146 |
147 | assertThat(selectStatement.toList()).hasSize(9);
148 | }
149 |
150 | public void testOrderBy() {
151 | final List objects =
152 | shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").toList();
153 |
154 | int last = 0;
155 | for (final SimpleObject simpleObject : objects) {
156 | assertThat(simpleObject.getCustomerId()).isGreaterThanOrEqualTo(last);
157 | last = (int) simpleObject.getCustomerId();
158 | }
159 | }
160 |
161 | public void testOrderByAscending() {
162 | final List objects =
163 | shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").ascending().toList();
164 |
165 | int last = 0;
166 | for (final SimpleObject simpleObject : objects) {
167 | assertThat(simpleObject.getCustomerId()).isGreaterThanOrEqualTo(last);
168 | last = (int) simpleObject.getCustomerId();
169 | }
170 | }
171 |
172 | public void testOrderByDescending() {
173 | final List objects =
174 | shillelagh.selectFrom(SimpleObject.class).orderBy("customerId").descending().toList();
175 |
176 | int last = Integer.MAX_VALUE;
177 | for (final SimpleObject simpleObject : objects) {
178 | assertThat(simpleObject.getCustomerId()).isLessThanOrEqualTo(last);
179 | last = (int) simpleObject.getCustomerId();
180 | }
181 | }
182 |
183 | private static class QueryBuilderTestSQLiteOpenHelper extends SQLiteOpenHelper {
184 | public static final String DATABASE_NAME = "query_builder.db";
185 | private static final int DATABASE_VERSION = 3;
186 |
187 | public QueryBuilderTestSQLiteOpenHelper(Context context) {
188 | super(context, DATABASE_NAME, null, DATABASE_VERSION);
189 | }
190 |
191 | @Override public void onCreate(SQLiteDatabase db) {
192 | Shillelagh.createTable(db, SimpleObject.class);
193 | }
194 |
195 | @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
196 | Shillelagh.dropTable(db, SimpleObject.class);
197 | onCreate(db);
198 | }
199 | }
200 | }
201 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/main/java/com/example/shillelagh/SpeedTestActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 com.example.shillelagh;
18 |
19 | import android.annotation.TargetApi;
20 | import android.app.Activity;
21 | import android.content.SharedPreferences;
22 | import android.os.Build;
23 | import android.os.Bundle;
24 | import android.preference.PreferenceManager;
25 | import android.widget.TextView;
26 | import com.example.shillelagh.model.TestPrimitiveTable;
27 | import java.util.LinkedList;
28 | import java.util.List;
29 | import java.util.Queue;
30 | import java.util.Random;
31 | import java.util.Stack;
32 | import java.util.concurrent.TimeUnit;
33 | import java.util.concurrent.atomic.AtomicInteger;
34 | import rx.Observable;
35 | import rx.Subscriber;
36 | import rx.android.schedulers.AndroidSchedulers;
37 | import rx.functions.Action1;
38 | import rx.functions.Func1;
39 | import rx.schedulers.Schedulers;
40 | import shillelagh.Shillelagh;
41 |
42 | public class SpeedTestActivity extends Activity {
43 |
44 | private final Observable> insertValues =
45 | Observable.create(new Observable.OnSubscribe>() {
46 | @Override public void call(Subscriber super Queue> subscriber) {
47 |
48 | Queue values = new LinkedList();
49 | final Random random = new Random(System.currentTimeMillis());
50 | for (int i = 0; i < 50000; i++) {
51 | TestPrimitiveTable value = new TestPrimitiveTable();
52 | value.setaBoolean(false);
53 | value.setaDouble(random.nextDouble());
54 | value.setaFloat(random.nextFloat());
55 | value.setAnInt(random.nextInt());
56 | value.setaLong(random.nextLong());
57 | value.setaShort((short) random.nextInt(Short.MAX_VALUE));
58 | values.add(value);
59 | }
60 |
61 | subscriber.onNext(values);
62 | subscriber.onCompleted();
63 | }
64 | }).cache();
65 |
66 | @Override protected void onCreate(Bundle savedInstanceState) {
67 | super.onCreate(savedInstanceState);
68 | setContentView(R.layout.activity_speed_test);
69 |
70 | setupHeaders();
71 |
72 | final Shillelagh shillelagh = new Shillelagh(new TestSQLiteOpenHelper(this));
73 | insertValues.flatMap(new Func1, Observable>() {
74 | @Override public Observable call(Queue testPrimitiveTables) {
75 | return runWrites(shillelagh, testPrimitiveTables);
76 | }
77 | }).subscribeOn(Schedulers.computation()) //
78 | .observeOn(AndroidSchedulers.mainThread()) //
79 | .doOnNext(new Action1() {
80 | @Override public void call(Integer writes) {
81 | findTextViewById(R.id.writes_per_second) //
82 | .setText(String.valueOf(writes));
83 | }
84 | }) //
85 | .flatMap(new Func1>>() {
86 | @Override public Observable> call(Integer integer) {
87 | return insertValues;
88 | }
89 | }) //
90 | .flatMap(new Func1, Observable>() {
91 | @Override public Observable call(Queue queue) {
92 | return runReads(shillelagh, queue);
93 | }
94 | }) //
95 | .subscribeOn(Schedulers.computation()) //
96 | .observeOn(AndroidSchedulers.mainThread()) //
97 | .doOnNext(new Action1() {
98 | @Override public void call(Integer reads) {
99 | findTextViewById(R.id.reads_per_second) //
100 | .setText(String.valueOf(reads));
101 | }
102 | }) //
103 | .flatMap(new Func1>() {
104 | @Override public Observable call(Integer integer) {
105 | return runSelect1(shillelagh);
106 | }
107 | }) //
108 | .subscribeOn(Schedulers.computation()) //
109 | .observeOn(AndroidSchedulers.mainThread()) //
110 | .doOnNext(new Action1() {
111 | @Override public void call(Long time) {
112 | findTextViewById(R.id.select_time_1).setText(time + "ms");
113 | }
114 | }) //
115 | .flatMap(new Func1>() {
116 | @Override public Observable call(Long aLong) {
117 | return runSelect2(shillelagh);
118 | }
119 | }) //
120 | .subscribeOn(Schedulers.computation()) //
121 | .observeOn(AndroidSchedulers.mainThread()) //
122 | .subscribe(new Action1() {
123 | @Override public void call(Long time) {
124 | findTextViewById(R.id.select_time_2).setText(time + "ms");
125 | }
126 | });
127 | }
128 |
129 | private Observable runWrites(final Shillelagh shillelagh,
130 | final Queue values) {
131 | return Observable.create(new Observable.OnSubscribe() {
132 | @Override public void call(Subscriber super Integer> subscriber) {
133 | Queue valueQueue = new LinkedList(values);
134 | int inserts = 0;
135 | for (long stop = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
136 | System.nanoTime() < stop; ) {
137 | shillelagh.insert(valueQueue.poll());
138 | inserts++;
139 | }
140 |
141 | subscriber.onNext(inserts);
142 | subscriber.onCompleted();
143 | }
144 | });
145 | }
146 |
147 | private Observable runReads(final Shillelagh shillelagh,
148 | final Queue values) {
149 | return Observable.create(new Observable.OnSubscribe() {
150 | @Override public void call(final Subscriber super Integer> subscriber) {
151 | final String inserted = "inserted";
152 | final SharedPreferences sharedPreferences =
153 | PreferenceManager.getDefaultSharedPreferences(SpeedTestActivity.this);
154 |
155 | if (!sharedPreferences.getBoolean(inserted, false)) {
156 | // Insert a bunch
157 | for (; !values.isEmpty(); ) {
158 | shillelagh.insert(values.poll());
159 | }
160 | final SharedPreferences.Editor editor = sharedPreferences.edit();
161 | editor.putBoolean(inserted, true);
162 | editor.commit();
163 | }
164 |
165 | final AtomicInteger reads = new AtomicInteger(0);
166 | final long stop = System.nanoTime() + TimeUnit.SECONDS.toNanos(1);
167 | shillelagh.get(TestPrimitiveTable.class).subscribe(new Action1() {
168 | @Override public void call(TestPrimitiveTable testBoxedPrimitivesTable) {
169 | if (System.nanoTime() < stop) {
170 | reads.getAndAdd(1);
171 | }
172 | }
173 | });
174 |
175 | subscriber.onNext(reads.get());
176 | subscriber.onCompleted();
177 | }
178 | });
179 | }
180 |
181 | private Observable runSelect1(final Shillelagh shillelagh) {
182 | // we already know there are 50,000 some rows inserted in runReads
183 | final long startTime = System.currentTimeMillis();
184 | return shillelagh.get(TestPrimitiveTable.class)
185 | .filter(new Func1() {
186 | @Override public Boolean call(TestPrimitiveTable testPrimitiveTable) {
187 | return testPrimitiveTable.getId() == 25000;
188 | }
189 | })
190 | .map(new Func1() {
191 | @Override public Long call(TestPrimitiveTable testPrimitiveTable) {
192 | return System.currentTimeMillis() - startTime;
193 | }
194 | });
195 | }
196 |
197 | private Observable runSelect2(final Shillelagh shillelagh) {
198 | final long start = System.currentTimeMillis();
199 | return shillelagh.createQuery(TestPrimitiveTable.class, "SELECT * FROM %s WHERE id = 25000",
200 | Shillelagh.getTableName(TestPrimitiveTable.class))
201 | .map(new Func1() {
202 | @Override public Long call(TestPrimitiveTable testPrimitiveTable) {
203 | return System.currentTimeMillis() - start;
204 | }
205 | });
206 | }
207 |
208 | /** Setup the info headers */
209 | @TargetApi(Build.VERSION_CODES.DONUT)
210 | private void setupHeaders() {
211 | if (Build.VERSION_CODES.DONUT <= Build.VERSION.SDK_INT) {
212 | findTextViewById(R.id.device_make).setText(truncateAt(Build.MANUFACTURER, 20));
213 | } else {
214 | findTextViewById(R.id.device_make).setText("Old");
215 | }
216 | findTextViewById(R.id.device_model).setText(Build.MODEL);
217 | findTextViewById(R.id.android_version).setText(Build.VERSION.RELEASE);
218 | findTextViewById(R.id.sdk_version).setText(String.valueOf(Build.VERSION.SDK_INT));
219 | }
220 |
221 | @SuppressWarnings({ "unchecked", "UnusedDeclaration" }) // Checked by runtime cast. Public API.
222 | private TextView findTextViewById(int id) {
223 | return (TextView) findViewById(id);
224 | }
225 |
226 | private String truncateAt(String string, int length) {
227 | return string.length() > length ? string.substring(0, length) : string;
228 | }
229 | }
230 |
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/java/shillelagh/crud/MapTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.crud;
18 |
19 | import android.content.ContentValues;
20 | import android.database.Cursor;
21 | import android.database.sqlite.SQLiteOpenHelper;
22 | import android.test.AndroidTestCase;
23 |
24 | import com.example.shillelagh.TestSQLiteOpenHelper;
25 | import com.example.shillelagh.model.TestBlobs;
26 | import com.example.shillelagh.model.TestBoxedPrimitivesTable;
27 | import com.example.shillelagh.model.TestJavaObjectsTable;
28 | import com.example.shillelagh.model.TestOneToMany;
29 | import com.example.shillelagh.model.TestOneToOne;
30 | import com.example.shillelagh.model.TestPrimitiveTable;
31 |
32 | import java.io.ByteArrayOutputStream;
33 | import java.io.IOException;
34 | import java.io.ObjectOutputStream;
35 | import java.util.Arrays;
36 | import java.util.Date;
37 | import java.util.List;
38 |
39 | import shillelagh.Shillelagh;
40 |
41 | import static org.assertj.core.api.Assertions.assertThat;
42 | import static shillelagh.Shillelagh.getTableName;
43 |
44 | /** Tests for mapping db objects to jave objects in Shillelagh */
45 | public class MapTest extends AndroidTestCase {
46 |
47 | private SQLiteOpenHelper sqliteOpenHelper;
48 | private Shillelagh shillelagh;
49 |
50 | @Override protected void setUp() throws Exception {
51 | super.setUp();
52 |
53 | sqliteOpenHelper = new TestSQLiteOpenHelper(getContext());
54 | shillelagh = new Shillelagh(sqliteOpenHelper);
55 | }
56 |
57 | public void testMapCursorToBoxedPrimitives() {
58 | // Arrange
59 | final int expectedBoolean = 0;
60 | final double expectedDouble = 100000;
61 | final float expectedFloat = 4.5f;
62 | final long expectedLong = 300000;
63 | final int expectedInt = 100;
64 | final short expectedShort = 1;
65 |
66 | String testBoxedPrimitivesInsert = String.format("INSERT INTO %s (aBoolean, aDouble, " +
67 | "aFloat, anInteger, aLong, aShort) VALUES (%s, %s, %s, %s, %s, %s);",
68 | getTableName(TestBoxedPrimitivesTable.class), expectedBoolean, expectedDouble,
69 | expectedFloat, expectedInt, expectedLong, expectedShort);
70 |
71 | // Act
72 | sqliteOpenHelper.getWritableDatabase().execSQL(testBoxedPrimitivesInsert);
73 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
74 | "SELECT * FROM " + getTableName(TestBoxedPrimitivesTable.class), null);
75 |
76 | List result = shillelagh.map(TestBoxedPrimitivesTable.class, cursor);
77 |
78 | // Assert
79 | assertThat(result.size()).isEqualTo(1);
80 | TestBoxedPrimitivesTable resultRow = result.get(0);
81 | assertThat(resultRow.getId()).isEqualTo(1);
82 | assertThat(resultRow.getaShort()).isEqualTo(expectedShort);
83 | assertThat(resultRow.getAnInteger()).isEqualTo(expectedInt);
84 | assertThat(resultRow.getaLong()).isEqualTo(expectedLong);
85 | assertThat(resultRow.getaDouble()).isEqualTo(expectedDouble);
86 | assertThat(resultRow.getaBoolean()).isFalse();
87 | }
88 |
89 | public void testMapToPrimitives() {
90 | // Arrange
91 | final int expectedBoolean = 1;
92 | final double expectedDouble = 2900;
93 | final float expectedFloat = -3.5f;
94 | final long expectedLong = 3000000;
95 | final int expectedInt = -100;
96 | final short expectedShort = 23;
97 |
98 | String tableName = getTableName(TestPrimitiveTable.class);
99 |
100 | String testPrimitiveInsert = String.format("INSERT INTO %s (aShort, anInt," +
101 | "aLong, aFloat, aDouble, aBoolean) VALUES (%s, %s, %s, %s, %s, %s);",
102 | tableName, expectedShort, expectedInt,
103 | expectedLong, expectedFloat, expectedDouble, expectedBoolean);
104 |
105 | // Act
106 | sqliteOpenHelper.getWritableDatabase().execSQL(testPrimitiveInsert);
107 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
108 | "SELECT * FROM " + tableName, null);
109 | List result = shillelagh.map(TestPrimitiveTable.class, cursor);
110 |
111 | // Assert
112 | assertThat(result.size()).isEqualTo(1);
113 | TestPrimitiveTable resultRow = result.get(0);
114 | assertThat(resultRow.getId()).isEqualTo(1);
115 | assertThat(resultRow.getaDouble()).isEqualTo(expectedDouble);
116 | assertThat(resultRow.getaFloat()).isEqualTo(expectedFloat);
117 | assertThat(resultRow.getaLong()).isEqualTo(expectedLong);
118 | assertThat(resultRow.getAnInt()).isEqualTo(expectedInt);
119 | assertThat(resultRow.getaShort()).isEqualTo(expectedShort);
120 | assertThat(resultRow.isaBoolean()).isTrue();
121 |
122 | }
123 |
124 | public void testMapToJavaObjects() {
125 | // Arrange
126 | final String expectedString = "TestString";
127 | final Date expectedDate = new Date();
128 | final String testJavaObjectsInsert = String.format("INSERT INTO %s (aString, aDate)" +
129 | " VALUES ('%s', %s);", getTableName(TestJavaObjectsTable.class),
130 | expectedString, expectedDate.getTime());
131 |
132 | // Act
133 | sqliteOpenHelper.getWritableDatabase().execSQL(testJavaObjectsInsert);
134 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
135 | "SELECT * FROM " + getTableName(TestJavaObjectsTable.class), null);
136 |
137 | List result = shillelagh.map(TestJavaObjectsTable.class, cursor);
138 |
139 | // Assert
140 | assertThat(result.size()).isEqualTo(1);
141 | TestJavaObjectsTable resultRow = result.get(0);
142 | assertThat(resultRow.getId()).isEqualTo(1);
143 | assertThat(resultRow.getaDate()).isEqualTo(expectedDate);
144 | assertThat(resultRow.getaString()).isEqualTo(expectedString);
145 | }
146 |
147 | public void testMapToBlobs() throws IOException {
148 | // Arrange
149 | Byte[] expectedByteArray = new Byte[5];
150 | for (int i = 0; i < expectedByteArray.length; i++) {
151 | expectedByteArray[i] = (byte) (expectedByteArray.length - i);
152 | }
153 |
154 | byte[] expectedOtherByteArray = new byte[100];
155 | for (byte i = 0; i < expectedOtherByteArray.length; i++) {
156 | expectedOtherByteArray[i] = i;
157 | }
158 |
159 | TestBlobs.TestBlobObject expectedTestBlobObject = new TestBlobs.TestBlobObject();
160 | expectedTestBlobObject.testString = "hello world!!";
161 |
162 | ContentValues values = new ContentValues();
163 | values.put("aByteArray", serialize(expectedByteArray));
164 | values.put("anotherByteArray", expectedOtherByteArray);
165 | values.put("aTestBlobObject", serialize(expectedTestBlobObject));
166 |
167 | // Act
168 | sqliteOpenHelper.getWritableDatabase().insert(getTableName(TestBlobs.class), null, values);
169 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
170 | "SELECT * FROM " + getTableName(TestBlobs.class), null);
171 |
172 | List result = shillelagh.map(TestBlobs.class, cursor);
173 |
174 | // Assert
175 | assertThat(result.size()).isEqualTo(1);
176 | TestBlobs resultRow = result.get(0);
177 | assertThat(resultRow.getId()).isEqualTo(1);
178 | assertThat(resultRow.getaByteArray()).isEqualTo(expectedByteArray);
179 | assertThat(resultRow.getAnotherByteArray()).isEqualTo(expectedOtherByteArray);
180 | assertThat(resultRow.getaTestBlobObject()).isEqualsToByComparingFields(expectedTestBlobObject);
181 | }
182 |
183 | public void testMapOneToOne() {
184 | // Arrange
185 | final String expected = "TEST STRING";
186 | final TestOneToOne.OneToOneChild expectedChild = new TestOneToOne.OneToOneChild(expected);
187 | final TestOneToOne expectedOneToOne = new TestOneToOne(expectedChild);
188 |
189 | final ContentValues childContentValues = new ContentValues();
190 | childContentValues.put("childName", expected);
191 |
192 | final ContentValues oneToOneContentValues = new ContentValues();
193 | oneToOneContentValues.put("child", 1);
194 |
195 | final String tableName = getTableName(TestOneToOne.class);
196 |
197 | // Act
198 | sqliteOpenHelper.getWritableDatabase()
199 | .insert(getTableName(TestOneToOne.OneToOneChild.class), null, childContentValues);
200 | sqliteOpenHelper.getWritableDatabase()
201 | .insert(tableName, null, oneToOneContentValues);
202 | Cursor cursor = sqliteOpenHelper.getReadableDatabase()
203 | .rawQuery("SELECT * FROM " + tableName, null);
204 |
205 | List result = shillelagh.map(TestOneToOne.class, cursor);
206 |
207 | // Assert
208 | assertThat(result.size()).isEqualTo(1);
209 | TestOneToOne resultRow = result.get(0);
210 | assertThat(resultRow).isEqualsToByComparingFields(expectedOneToOne);
211 | }
212 |
213 | public void testMapOneToMany() {
214 | // Arrange
215 | final String childExpected = "TestString";
216 | final int childIntExpected = 12345;
217 | final String parentExpected = "SomeValue";
218 | final TestOneToMany.OneToManyChild
219 | child = new TestOneToMany.OneToManyChild(childExpected, childIntExpected);
220 | final TestOneToMany parent = new TestOneToMany(parentExpected, Arrays.asList(child));
221 |
222 | final ContentValues childContentValues = new ContentValues();
223 | childContentValues.put("testString", childExpected);
224 | childContentValues.put("testInt", childIntExpected);
225 | childContentValues.put("TestOneToMany", 1);
226 |
227 | final ContentValues parentContentValues = new ContentValues();
228 | parentContentValues.put("someValue", parentExpected);
229 |
230 | final String tableName = getTableName(TestOneToMany.class);
231 |
232 | // Act
233 | sqliteOpenHelper.getWritableDatabase()
234 | .insert(tableName, null, parentContentValues);
235 | sqliteOpenHelper.getWritableDatabase()
236 | .insert(getTableName(TestOneToMany.OneToManyChild.class), null, childContentValues);
237 | Cursor cursor = sqliteOpenHelper.getReadableDatabase()
238 | .rawQuery("SELECT * FROM " + tableName, null);
239 |
240 | List result = shillelagh.map(TestOneToMany.class, cursor);
241 |
242 | // Assert
243 | assertThat(result.size()).isEqualTo(1);
244 | TestOneToMany resultRow = result.get(0);
245 | assertThat(resultRow).isEqualToComparingFieldByField(parent);
246 | assertThat(resultRow.getChildren().size()).isEqualTo(1);
247 | assertThat(resultRow.getChildren().get(0)).isEqualToComparingFieldByField(child);
248 | }
249 |
250 | private byte[] serialize(K object) throws IOException {
251 | ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
252 | ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
253 | objectOutputStream.writeObject(object);
254 | return byteArrayOutputStream.toByteArray();
255 | }
256 | }
257 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright {yyyy} {name of copyright owner}
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
--------------------------------------------------------------------------------
/shillelagh-tests/src/androidTest/java/shillelagh/crud/InsertTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright 2014 Andrew Reitz
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 shillelagh.crud;
18 |
19 | import android.database.Cursor;
20 | import android.database.sqlite.SQLiteOpenHelper;
21 | import android.test.AndroidTestCase;
22 |
23 | import com.example.shillelagh.TestSQLiteOpenHelper;
24 | import com.example.shillelagh.model.TestBlobs;
25 | import com.example.shillelagh.model.TestBoxedPrimitivesTable;
26 | import com.example.shillelagh.model.TestJavaObjectsTable;
27 | import com.example.shillelagh.model.TestNotTableObject;
28 | import com.example.shillelagh.model.TestOneToMany;
29 | import com.example.shillelagh.model.TestOneToOne;
30 | import com.example.shillelagh.model.TestPrimitiveTable;
31 |
32 | import java.io.ByteArrayInputStream;
33 | import java.io.IOException;
34 | import java.io.ObjectInputStream;
35 | import java.util.Arrays;
36 | import java.util.Date;
37 |
38 | import shillelagh.Shillelagh;
39 |
40 | import static org.assertj.core.api.Assertions.assertThat;
41 | import static shillelagh.Shillelagh.getTableName;
42 |
43 | public class InsertTest extends AndroidTestCase {
44 |
45 | private SQLiteOpenHelper sqliteOpenHelper;
46 | private Shillelagh shillelagh;
47 |
48 | @Override protected void setUp() throws Exception {
49 | super.setUp();
50 |
51 | sqliteOpenHelper = new TestSQLiteOpenHelper(getContext());
52 | shillelagh = new Shillelagh(sqliteOpenHelper);
53 | }
54 |
55 | @Override protected void tearDown() throws Exception {
56 | getContext().deleteDatabase(TestSQLiteOpenHelper.DATABASE_NAME);
57 | super.tearDown();
58 | }
59 |
60 | public void testInsertPrimitives() {
61 | // Arrange
62 | double expectedDouble = 2342342.2323;
63 | float expectedFloat = 4.0f;
64 | long expectedLong = 10000;
65 | int expectedInt = 23;
66 | short expectedShort = 234;
67 |
68 | TestPrimitiveTable row = new TestPrimitiveTable();
69 | row.setaBoolean(true);
70 | row.setaDouble(expectedDouble);
71 | row.setaFloat(expectedFloat);
72 | row.setaLong(expectedLong);
73 | row.setAnInt(expectedInt);
74 | row.setaShort(expectedShort);
75 |
76 | // Act
77 | shillelagh.insert(row);
78 |
79 | // Assert
80 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
81 | "SELECT * FROM " + getTableName(TestPrimitiveTable.class), null);
82 |
83 | assertThat(cursor.getCount()).isEqualTo(1);
84 |
85 | assertThat(cursor.moveToFirst()).isTrue();
86 | assertThat(cursor.getLong(0)).isEqualTo(1); // id column
87 | assertThat(cursor.getShort(1)).isEqualTo(expectedShort); // aShort
88 | assertThat(cursor.getInt(2)).isEqualTo(expectedInt); // anInt
89 | assertThat(cursor.getLong(3)).isEqualTo(expectedLong); // aLong
90 | assertThat(cursor.getFloat(4)).isEqualTo(expectedFloat); // aFloat
91 | assertThat(cursor.getDouble(5)).isEqualTo(expectedDouble); // aDouble
92 | assertThat(cursor.getInt(6)).isEqualTo(1); // aBoolean, true maps to 1
93 |
94 | assertThat(cursor.moveToNext()).isFalse();
95 | cursor.close();
96 | }
97 |
98 | public void testInsertBoxedPrimitives() {
99 | // Arrange
100 | double expectedDouble = 10000.55;
101 | float expectedFloat = 2.0f;
102 | long expectedLong = 200000;
103 | int expectedInt = 42;
104 | short expectedShort = 2;
105 |
106 | TestBoxedPrimitivesTable row = new TestBoxedPrimitivesTable();
107 | row.setaBoolean(false);
108 | row.setaDouble(expectedDouble);
109 | row.setaFloat(expectedFloat);
110 | row.setAnInteger(expectedInt);
111 | row.setaLong(expectedLong);
112 | row.setaShort(expectedShort);
113 |
114 | // Act
115 | shillelagh.insert(row);
116 |
117 | // Assert
118 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
119 | "SELECT * FROM " + getTableName(TestBoxedPrimitivesTable.class), null);
120 |
121 | assertThat(cursor.getCount()).isEqualTo(1);
122 |
123 | assertThat(cursor.moveToFirst()).isTrue();
124 | assertThat(cursor.getLong(0)).isEqualTo(1); // id column
125 | assertThat(cursor.getInt(1)).isEqualTo(0); // aBoolean
126 | assertThat(cursor.getDouble(2)).isEqualTo(expectedDouble); // aDouble
127 | assertThat(cursor.getFloat(3)).isEqualTo(expectedFloat); // aFloat
128 | assertThat(cursor.getInt(4)).isEqualTo(expectedInt); // anInteger
129 | assertThat(cursor.getLong(5)).isEqualTo(expectedLong); // aLong
130 | assertThat(cursor.getShort(6)).isEqualTo(expectedShort); // aShort
131 |
132 | assertThat(cursor.moveToNext()).isFalse();
133 | cursor.close();
134 | }
135 |
136 | public void testInsertJavaObjects() {
137 | // Arrange
138 | final Date now = new Date();
139 | final String expected = "TestString";
140 | TestJavaObjectsTable row = new TestJavaObjectsTable();
141 | row.setaDate(now);
142 | row.setaString(expected);
143 |
144 | // Act
145 | shillelagh.insert(row);
146 |
147 | // Assert
148 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
149 | "SELECT * FROM " + getTableName(TestJavaObjectsTable.class), null);
150 |
151 | assertThat(cursor.getCount()).isEqualTo(1);
152 |
153 | assertThat(cursor.moveToFirst()).isTrue();
154 | assertThat(cursor.getLong(0)).isEqualTo(1);
155 | assertThat(cursor.getString(1)).isEqualTo(expected);
156 | assertThat(cursor.getLong(2)).isEqualTo(now.getTime());
157 |
158 | assertThat(cursor.moveToNext()).isFalse();
159 | cursor.close();
160 | }
161 |
162 | public void testInsertBlobs() throws IOException, ClassNotFoundException {
163 | // Arrange
164 | final Byte[] expectedByteArray = new Byte[5];
165 | for (byte i = 0; i < expectedByteArray.length; i++) {
166 | expectedByteArray[i] = i;
167 | }
168 | final byte[] expectedOtherByteArray = new byte[10];
169 | for (byte i = 0; i < expectedOtherByteArray.length; i++) {
170 | expectedOtherByteArray[i] = i;
171 | }
172 | final TestBlobs.TestBlobObject expectedBlobObject = new TestBlobs.TestBlobObject();
173 | expectedBlobObject.testString = "this is expected string";
174 | TestBlobs row = new TestBlobs();
175 | row.setaByteArray(expectedByteArray);
176 | row.setAnotherByteArray(expectedOtherByteArray);
177 | row.setaTestBlobObject(expectedBlobObject);
178 |
179 | // Act
180 | shillelagh.insert(row);
181 |
182 | // Assert
183 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
184 | "SELECT * FROM " + getTableName(TestBlobs.class), null);
185 |
186 | assertThat(cursor.getCount()).isEqualTo(1);
187 | assertThat(cursor.moveToFirst()).isTrue();
188 | assertThat(cursor.getLong(0)).isEqualTo(1);
189 | assertThat(this.deserialize(cursor.getBlob(1))).isEqualTo(expectedByteArray);
190 | assertThat(cursor.getBlob(2)).isEqualTo(expectedOtherByteArray);
191 | TestBlobs.TestBlobObject resultBlob = deserialize(cursor.getBlob(3));
192 | assertThat(resultBlob).isEqualsToByComparingFields(expectedBlobObject);
193 |
194 | assertThat(cursor.moveToNext()).isFalse();
195 | cursor.close();
196 | }
197 |
198 | public void testOneToOneInsertion() {
199 | // Arrange
200 | final String expected = "TEST STRING";
201 | final TestOneToOne.OneToOneChild expectedChild = new TestOneToOne.OneToOneChild(expected);
202 | final TestOneToOne expectedOneToOne = new TestOneToOne(expectedChild);
203 |
204 | // Act
205 | shillelagh.insert(expectedOneToOne);
206 |
207 | // Assert
208 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
209 | "SELECT * FROM " + getTableName(TestOneToOne.class), null);
210 |
211 | assertThat(cursor.getCount()).isEqualTo(1);
212 | assertThat(cursor.moveToFirst()).isTrue();
213 | assertThat(cursor.getLong(0)).isEqualTo(1);
214 | assertThat(cursor.getLong(1)).isEqualTo(1);
215 |
216 | assertThat(cursor.moveToNext()).isFalse();
217 | cursor.close();
218 |
219 | cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
220 | "SELECT * FROM " + getTableName(TestOneToOne.OneToOneChild.class), null);
221 |
222 | assertThat(cursor.getCount()).isEqualTo(1);
223 | assertThat(cursor.moveToFirst()).isTrue();
224 | assertThat(cursor.getLong(0)).isEqualTo(1);
225 | assertThat(cursor.getString(1)).isEqualTo(expected);
226 |
227 | assertThat(cursor.moveToNext()).isFalse();
228 | cursor.close();
229 |
230 | }
231 |
232 | public void testOneToManyInsertion() {
233 | // Arrange
234 | String childExpectedString1 = "some test string";
235 | int childExpectedInt1 = 123;
236 | TestOneToMany.OneToManyChild
237 | child1 = new TestOneToMany.OneToManyChild(childExpectedString1, childExpectedInt1);
238 |
239 | String childExpectedString2 = "some other string";
240 | int childExpectedInt2 = -1;
241 | TestOneToMany.OneToManyChild
242 | child2 = new TestOneToMany.OneToManyChild(childExpectedString2, childExpectedInt2);
243 |
244 | String someValueExpected = "some value";
245 | TestOneToMany testOneToMany = new TestOneToMany(someValueExpected,
246 | Arrays.asList(child1, child2));
247 |
248 | // Act
249 | shillelagh.insert(testOneToMany);
250 |
251 | // Assert
252 | Cursor cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
253 | "SELECT * FROM " + getTableName(TestOneToMany.class), null);
254 |
255 | assertThat(cursor.getCount()).isEqualTo(1);
256 | assertThat(cursor.moveToFirst()).isTrue();
257 | assertThat(cursor.getLong(0)).isEqualTo(1);
258 | assertThat(cursor.getString(1)).isEqualTo(someValueExpected);
259 |
260 | assertThat(cursor.moveToNext()).isFalse();
261 | cursor.close();
262 |
263 | cursor = sqliteOpenHelper.getReadableDatabase().rawQuery(
264 | "SELECT * FROM " + getTableName(TestOneToMany.OneToManyChild.class), null);
265 |
266 | assertThat(cursor.getCount()).isEqualTo(2);
267 |
268 | assertThat(cursor.moveToFirst()).isTrue();
269 | assertThat(cursor.getLong(0)).isEqualTo(1);
270 | assertThat(cursor.getString(1)).isEqualTo(childExpectedString1);
271 | assertThat(cursor.getInt(2)).isEqualTo(childExpectedInt1);
272 | assertThat(cursor.getLong(3)).isEqualTo(1);
273 |
274 | assertThat(cursor.moveToNext()).isTrue();
275 | assertThat(cursor.getLong(0)).isEqualTo(2);
276 | assertThat(cursor.getString(1)).isEqualTo(childExpectedString2);
277 | assertThat(cursor.getInt(2)).isEqualTo(childExpectedInt2);
278 | assertThat(cursor.getLong(3)).isEqualTo(1);
279 | }
280 |
281 | public void testInsertShouldFailWhenNotAnnotated() {
282 | // Arrange
283 | TestNotTableObject row = new TestNotTableObject();
284 | row.setName("some text");
285 | row.setValue(6);
286 |
287 | // Act
288 | try {
289 | shillelagh.insert(row);
290 | } catch (RuntimeException e) {
291 | assertThat(e.getMessage()).isEqualTo("com.example.shillelagh.model.TestNotTableObject is "
292 | + "not a table object.");
293 | return;
294 | }
295 |
296 | // Assert
297 | throw new AssertionError("Expected Exception Not Thrown");
298 | }
299 |
300 | @SuppressWarnings("unchecked")
301 | private K deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
302 | ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
303 | ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
304 | return (K) objectInputStream.readObject();
305 | }
306 |
307 | // TODO Tests for null values
308 | }
309 |
--------------------------------------------------------------------------------