Sunday, August 5, 2012

SQLite wrapper based on java.lang.reflect

In Android development, data persistence is often realized with SQLite. Sometimes the act of preparing all the classes, the adapter, every kind of query (CRUD) and rewrap into model,is a bit frustrating. It's like something already done, to do again every time.

I never see this kind of class on the web, so I decided to make my own one.
What I'm talking about?

A class that simplifies the common use of SQLite with a friendly usage (inspired by .NET's LINQ one).
SQL Scripts are defined by the model, so you need to supply the object instance or just its class.

For the moment I provided:
  • select (distinct, count,where, limit, order by)
  • delete (where)
  • insert
  • transactions

Where statements miss of IN, NOT IN , BETWEEN clause... but I think to do them soon.
No track of JOIN, GROUPBY, CONSTRAINTS for now :(

Here the usage:

RSQLiteDatabase db=RSQLiteDatabase.getSingleton();

//create a DummyObject
DummyObject obj= new DummyObject();

MyObject myObj= new MyObject(1);
obj.extra=myObj;


//insert
db.insert(obj) //obj.extra (if exists) will be serialized
  .execute(this);
  
  
//select
List<DummyObject> list= db.select()
                                .from(DummyObject.class)
                                .execute(this);
        
//select with where and limit of 10
list= db.select(10)
  .from(DummyObject.class)
  .where("field1",RSQLiteOperator.EQUALS, 100)
  .or("field1", RSQLiteOperator.LESSER_OR_EQUALS_THAN_, "300")
  .execute(this);
  
//select count
int count =db.select()
    .from(DummyObject.class)
    .where("field1",RSQLiteOperator.GREATER_THAN , 100)
    .and("field2", RSQLiteOperator.LIKE, "ita")
    .or("field3",SQLiteOperator.EQUALS, myObj)
    .count(this);
  
//delete (can be combined with where)
int del= db.deleteFrom(DummyObject.class);

//transaction
Insert insert= db.insert(new DummyObject());
RSQLiteDatabase.RSQLiteTransaction trans=db.beginTransaction();
for (int i = 0; i <8000; i++) 
{
 trans.add(insert);
}
List<Object> transa=trans.executeAll(this);


It's can honestly say it's all quite fast ,except SELECT of huge amount of data.
It's a single thread worker, but I'm planning to fork it according to bigness.


It's a open project you can find on http://code.google.com/p/rsqlite-wrapper/.


No comments:

Post a Comment