Git Product home page Git Product logo

android-inquiry's Introduction

android-inquiry

jitpack.io Build Status Apache License 2.0

DEPRECATED: This library won't be continued as most of the features are now part of the original library.

This is a forked and improved version of Aidan Follestad's awesome library Inquiry.
Credit goes to him for the idea of annotation based automatic SQLite database modification 😅.

Inquiry is a simple library for Android that makes construction and use of SQLite databases super easy.

Read and write class objects from tables in a database and supports deep object insertion. Let Inquiry handle the heavy lifting.

Dependency

Inquiry is available on jitpack.io

Gradle dependency:

Project build.gradle:

allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}

Module build.gradle

dependencies {
    compile 'com.heinrichreimersoftware:android-inquiry:3.0.4'
}

Table of Contents

  1. Dependency
  2. Quick Setup
  3. Example Row
  4. References
  5. Converters
  6. Querying Rows
    1. Basics
    2. Where
    3. Sorting and Limiting
  7. Inserting Rows
  8. Updating Rows
    1. Basics
    2. Updating Specific Columns
  9. Deleting Rows
  10. Dropping Tables
  11. Accessing Content Providers
  12. Changelog
  13. Open source libraries
  14. License

Quick setup

When your app starts, you need to initialize Inquiry. Inquiry.init() and Inquiry.deinit() can be used from anywhere, but a reliable place to do so is in an Activity:

public class MainActivity extends AppCompatActivity {

    @Override
    public void onResume() {
        super.onResume();
        Inquiry.init(this, "myDatabase", 1);
    }

    @Override
    public void onPause() {
        super.onPause();
        Inquiry.deinit();
    }
}

Inquiry.init() takes a Context in the first parameter, and the name of the database that'll you be using in the second parameter. The third parameter is the database version, which could always be '1' if you want. Incrementing the number will drop tables created with a lower number next time they are accessed.

Think of a database like a file that contains a set of tables (a table is basically a spreadsheet; it contains rows and columns).

When using the singleton you should use Inquiry.get() to obtain the current instance.

When your app is done with Inquiry, you should call Inquiry.deinit() to help clean up references and avoid memory leaks.

(You can initialize multiple Inquiry instances too by using new Inquiry(this, "myDatabase", 1) and inquiry.destroy())

Example row

In Inquiry, a row is just an object which contains a set of values that can be read from and written to a table in your database.

@Table
public class Person {
    // Default constructor is needed so Inquiry can auto construct instances
    public Person() {}

    public Person(String name, int age, float rank, boolean admin) {
        this.name = name;
        this.age = age;
        this.rank = rank;
        this.admin = admin;
    }

    @Column public String name;
    @Column public int age;
    @Column public float rank;
    @Column public boolean admin;
}

Notice that the class is annotated with the @Table annotation and all the fields are annotated with the @Column annotation. If you have classes/fields without that annotations, they will be ignored by Inquiry.

Notice that the @Table and @Column annotation can be used with optional parameters:

@Table or @Table("table_name") @Column, @Column("column_name") or @Column(value = "column_name", unique = true, notNull = true, autoIncrement = true)

  • value indicates a table/column name, if the name is different than what you name the class field.
  • primaryKey indicates its column is unique.
  • notNull indicates that you can never insert null as a value for that column.
  • autoIncrement indicates that you don't manually set the value of this column. Every time you insert a row into the table, this column will be incremented by one automatically. This can only be used with INTEGER columns (short, int, or long fields), however.

References

In addition to saving primitive data types, Inquiry will also save fields that point to a class annotated with @Table.

Let's take the Person class from the previous section, but simplify it a bit:

@Table
public class Person {
    // Default constructor is needed so Inquiry can auto construct instances
    public Person() {}

    public Person(String name) {
        this.name = name;
    }

    @Column public String name;
}
@Table
public class LovingPerson extends Person {
    // Default constructor is needed so Inquiry can auto construct instances
    public LovingPerson() {}

    public LovingPerson(String name, Person spouse) {
        super(name)
        this.spouse = spouse;
    }

    @Column public Person spouse;
}

During insertion of a LovingPerson, Inquiry will insert the spouse Field into the persons table. The value of the spouse column in the current table will be set to the ID of the new row in the persons table.

During querying, Inquiry will detect the reference from the @Column annotation, and do an automatic lookup for you. The value of the spouse field is automatically pulled from the second table into the current table.

Basically, this allows you to have non-primitive column types that are blazing fast to insert or query. No serialization is necessary. You can even have two rows which reference the same object (a single object with the same ID).

Pro Tip: This example showcases class inheritance too. All @Column's from Person get inherited to LovingPerson.

Attention: Make sure you don't create looping back references when using the reference feature.

Converters

Inquiry internally uses Converters to convert some basic Java types to insertable ContentValues.

Currently Inquiry can automatically convert the following types:

  • Java primitives (including String)
  • References (see above)
  • byte[]
  • char[]
  • Character[]
  • Bitmap
  • Serializable

If you need to convert other objects you can simply add your own converter:

Person[] result = Inquiry.get()
    .addConverter(new CustomConverter())
    ...

Querying rows

Basics

Querying retrieves rows, whether its every row in a table or rows that match a specific criteria. Here's how you would retrieve all rows from the type Person:

Person[] result = Inquiry.get()
    .select(Person.class)
    .all();

If you only needed one row, using one() instead of all() is more efficient:

Person result = Inquiry.get()
    .select(Person.class)
    .one();

You can also perform the query on a separate thread using a callback:

Inquiry.get()
    .select(Person.class)
    .all(new GetCallback<Person>() {
        @Override
        public void result(Person[] result) {
            // Do something with result
        }
    });

Inquiry will automatically fill in your @Column fields with matching columns in each row of the table.

Where

If you wanted to find rows with specific values in their columns, you can use where() selection:

Person[] result = Inquiry.get()
    .select(Person.class)
    .where("name = ?", "Aidan")
    .where("age = ?", 20)
    .all();

The first parameter is a string, specifying the condition that must be true. The question marks are placeholders, which are replaced by the values you specify in the second comma-separated vararg (or array) parameter. If you set more than one where() selections they get chained using AND, so the example above is actually the same as this:

.where("name = ? AND age = ?", "Aidan", 20)

If you wanted, you could skip using the question marks and only use one parameter:

.where("name = 'Aidan' AND age = 20");

However, using the question marks and filler parameters can be easier to read if you're filling them in with variables. Plus, this will automatically escape any strings that contain reserved SQL characters.

Inquiry includes a convenience method called atPosition() which lets you perform operations on a specific row in your tables:

Person result = Inquiry.get()
    .select(Person.class)
    .atPosition(24)
    .one();

Behind the scenes, it's using where() to select the row. atPosition() moves to a row position and retrieves the row's ID.

Sorting and limiting

This code would limit the maximum number of rows returned to 100. It would sort the results by values in the "name" column, in descending (Z-A, or greater to smaller) order:

Person[] result = Inquiry.get()
    .select(Person.class)
    .limit(100)
    .sort("name DESC")
    .sort("age ASC")
    .all();

If you understand SQL, you'll know you can specify multiple sort parameters separated by commas (or by using multiple sort() conditions).

.sort("name DESC, age ASC");

The above sort value would sort every column by name descending (large to small, Z-A) first, and then by age ascending (small to large).

Inserting rows

Insertion is pretty straight forward. This inserts three People:

Person one = new Person("Waverly", 18, 8.9f, false);
Person two = new Person("Natalie", 42, 10f, false);
Person three = new Person("Aidan", 20, 5.7f, true);

Long[] insertedIds = Inquiry.get()
        .insert(Person.class)
        .values(one, two, three)
        .run();

Inquiry will automatically pull your @Column fields out and insert them into the table defined by @Table.

Like all(), run() has a callback variation that will run the operation in a separate thread:

Inquiry.get()
    .insert(Person.class)
    .values(one, two, three)
    .run(new RunCallback() {
        @Override
        public void result(Long[] insertedIds) {
            // Do something
        }
    });

An ID will be added and incrementet automatically.

Updating rows

Basics

Updating is similar to insertion, however it results in changed rows rather than new rows:

Person two = new Person("Natalie", 42, 10f, false);

Integer updatedCount = Inquiry.get()
    .update(Person.class)
    .values(two)
    .where("name = ?", "Aidan")
    .run();

The above will update all rows whose name is equal to "Aidan", setting all columns to the values in the Person object called two. If you didn't specify where() args, every row in the table would be updated.

(Like querying, atPosition(int) can be used in place of where(String) to update a specific row.)

Updating specific columns

Sometimes, you don't want to change every column in a row when you update them. You can choose specifically what columns you want to be changed using onlyUpdate:

Person two = new Person("Natalie", 42, 10f, false);

Integer updatedCount = Inquiry.get()
    .update(Person.class)
    .values(two)
    .where("name = ?", "Aidan")
    .onlyUpdate("age", "rank")
    .run();

The above code will update any rows with their name equal to "Aidan", however it will only modify the age and rank columns of the updated rows. The other columns will be left alone.

Deleting rows

Deletion is simple:

Integer deletedCount = Inquiry.get()
    .delete(People.class)
    .where("age = ?", 20)
    .run();

The above code results in any rows with their age column set to 20 removed. If you didn't specify where() args, every row in the table would be deleted.

(Like querying, atPosition(int) can be used in place of where(String) to delete a specific row.)

Dropping tables

Dropping a table means deleting it. It's pretty straight forward:

Inquiry.get()
    .dropTable(People.class);

Just pass the data type name, and it's gone.

Accessing Content Providers

Accessing content providers has been removed from this fork of Inquiry. If you need to access content providers, I highly recommend you to check out the original library.

Changelog

See the releases section for a detailed changelog.

Open source libraries

Inquiry is based on Aidan Follestad's awesome library Inquiry which is licensed under the Apache License 2.0.

License

Copyright 2016 Heinrich Reimer

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

android-inquiry's People

Contributors

afollestad avatar janheinrichmerker avatar aitorvs avatar pluscubed avatar

Stargazers

Sanjay Shyamal avatar Khalid ElSayed avatar Mahmoud Kamal avatar Abhinav Sharma avatar Julien Quiévreux avatar

Watchers

Simon Kenyon avatar James Cloos avatar  avatar  avatar

Forkers

yzp531 aitorvs keove

android-inquiry's Issues

New ID behavior notice in readme

Add information to the readme that you have to have a field _id INTEGER AUTOINCREMENT PRIMARY_KEY in all @Tables referenced from other @Tables.

Multiple instances

It would be useful to have multiple instances of Inquiry running at a time.

Example:

I have a Service that is running in background and sometimes needs to write to a database. An Activity is reading from the database every time it is opened or a refresh is triggered. The problem here is that I can't use Inquiry.init() and Inquiry.deinit() in my Activity's/Service's lifecycle methods as the activity may still be running when the service has finished its work. It shouldn't be any problem if I had one Inquiry instance for the service and one for the activity

(See the original issue)

Singleton pattern missing, intended?

Overview

the init static method does not enforce Singleton pattern.

    @NonNull
    public static Inquiry init(@NonNull Context context, @Nullable String databaseName,
                               @IntRange(from = 1, to = Integer.MAX_VALUE) int databaseVersion) {
        inquiry = new Inquiry(context, databaseName, databaseVersion);
        return inquiry;
    }

One could cal Inquiry.init() twice without deinit. Is this intended?

Proposed solution

Either:

  1. deinit previous inquiry instance inside init method
  2. Throw IllegalStateException when trying to re-init

Crash with arabic input

Inquiry crashes when used with arabic language.

05-15 13:57:34.158 16635-16635/eu.pinpong.equalizer E/SQLiteLog: (1) no such column: ١
05-15 13:57:34.158 16635-16635/eu.pinpong.equalizer D/AndroidRuntime: Shutting down VM
05-15 13:57:34.158 16635-16635/eu.pinpong.equalizer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                      Process: eu.pinpong.equalizer, PID: 16635
                                                                      android.database.sqlite.SQLiteException: no such column: ١ (code 1): , while compiling: SELECT BAND_LEVEL_0, BAND_LEVEL_1, BAND_LEVEL_2, BAND_LEVEL_3, BAND_LEVEL_4, BASS_BOOST_ENABLED, BASS_BOOST_LEVEL, _id, LOUDNESS_ENHANCER_ENABLED, LOUDNESS_ENHANCER_LEVEL, PRESET_NAME, VIRTUALIZER_ENABLED, VIRTUALIZER_LEVEL FROM PRESETS WHERE PRESET_NAME = ? ORDER BY null LIMIT ١
                                                                          at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                          at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:887)
                                                                          at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:498)
                                                                          at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                          at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                          at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
                                                                          at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
                                                                          at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1316)
                                                                          at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1163)
                                                                          at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1034)
                                                                          at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1202)
                                                                          at com.afollestad.inquiry.SQLiteHelper.query(SQLiteHelper.java:42)
                                                                          at com.afollestad.inquiry.Query.getInternal(Query.java:147)
                                                                          at com.afollestad.inquiry.Query.one(Query.java:169)

(See the original issue) by @pinpong

Add support for WHERE IN clause

Would be super useful to have, however I gather the rawQuery method has to be used.
i.e.

DELETE WHERE id IN(1,2,3,4)
int[ ] deleteIds = { 3,4,5 };
Integer deletedCount = Inquiry.get()
        .deleteFrom("people", Person.class)
        .where("_id IN(?)", deleteIds)
        .run();

(See the original issue by @ritdaw)

Can't query the database

I'm having problems querying the db using.

Will not return any result

myRecord[] result = Inquiry.get()
.select(myRecord.class)
.where("mHomeAbbrName = 'TOR'")
.all();

Even this will not work

myRecord[] result = Inquiry.get()
.select(myRecord.class)
.all();

This will work

myRecord[] result = Inquiry.get()
.select(myRecord.class)
.limit(10)
.all();

Reference feature

The idea is to reference other @Table annotated classes directly from @Collumn annotated fields.

@Table
class A{
    @Column int a;
    @Column B b; //<- This is the reference
    @Column String c;
    public A(){}
}
@Table
class B{
    @Column long a;
    @Column byte[] c;
    public B(){}
}

A would reference B and when A gets inserted B is saved in its own table and A will store the row ID.
When you load A from the database Inquiry will read out the referenced row from B's table and load that into A.

(See the original issue by @jlelse)

Migrate to MIT license

As the MIT is easier to include for developers using this library I want to change the library license from Apache license 2.0 to the more permissive and simpler MIT license.
Because the license change would give library users more permissions than with the APLv2 all contributors need to approve this change.

Here's a list of all contributors to keep track of all confirmations:

I'll notify the contributors so that we can change the license ASAP.

Add conflict() method

Add conflict() method to define how SQLite should handle conflicts during insertion.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.