Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Getting into REAL(M) business by dumping SQLite

Dhrumil Shah
December 28, 2015

Getting into REAL(M) business by dumping SQLite

Presented this talk at DevFest Ahmedabad 2015 (#DevFestAhm). In this talk I have covered what is Realm? Why you should use Realm over SQLite and ORM with code snippets.

Dhrumil Shah

December 28, 2015
Tweet

More Decks by Dhrumil Shah

Other Decks in Programming

Transcript

  1. Getting into REAL
    (M) business by
    dumping SQLite

    View Slide

  2. Hello!
    I am Dhrumil Shah
    I work at Bugle Technologies Pvt. Ltd. &
    Co-organizer at GDG Ahmedabad.
    You can find me at:
    @dhuma1981
    +DhrumilShah

    View Slide


  3. View Slide

  4. Why you should dump
    SQLite?

    View Slide

  5. Typical Apps Requirement
    Lot of Data
    Tables
    W
    orks Offline
    Persist Locally

    View Slide

  6. Problems :(
    More Data
    More Tables

    View Slide

  7. Duplicate Data
    Normalization

    View Slide

  8. Normalization
    More m:n

    View Slide

  9. More m:n

    View Slide

  10. BoilerPlate mess
    ▷ 1000’s of lines of boilerplate
    mess
    ▷ Lot of string just to define a
    single table
    ▷ Tightly coupled schema
    ▷ RAW SQL Queries

    View Slide

  11. Nested Queries
    SELECT table1.col, table3.col FROM table1
    JOIN table2 ON table1.primarykey = table2.foreignkey
    JOIN table3 ON table2.primarykey = table3.foreignkey

    View Slide

  12. Nested Queries
    String query = “select” + table1.col + ”,” + table3.col +
    “FROM” + table1 +
    “JOIN” + table2 + “ON” + table1.primarykey + “=” +
    table2.foreignkey +
    “JOIN” + table3 + “ON” + table2.primarykey + “=” +
    table3.foreignkey

    View Slide

  13. View Slide

  14. Let’s abstract the problem
    Use ORM

    View Slide

  15. ▷ SugarORM
    ▷ ORMLite
    ▷ CubBoard
    ▷ ActiveRecord
    ▷ Ollie
    ▷ DBFLow
    ORM Options
    ▷ DBQuery
    ▷ GreenDao
    ▷ EasyLiteORM
    ▷ RushORM
    ▷ SpringkilesBlack
    ▷ . . . .

    View Slide

  16. ▷ Easy setup
    ▷ Abstract SQLite boilerplate codes
    ▷ No direct dealing with SQL
    ▷ Object Mapping
    ORM Good Part

    View Slide

  17. ▷ Slow, Most ORM uses reflections, read write
    performance is slow
    ▷ Not entirely SQL free, still need to write queries
    for certain task
    ▷ And as underlying is SQLite all the issues with
    database scaling.
    ORM Bad Part

    View Slide

  18. What is Realm?
    Realm is an object database designed for mobile

    View Slide


  19. Zero Copy Object Store

    View Slide

  20. Object Store
    A
    E
    B
    D
    C
    VS

    View Slide

  21. Object Store
    SELECT table1.col, table3.col FROM table1
    JOIN table2 ON table1.primarykey = table2.
    foreignkey
    JOIN table3 ON table2.primarykey = table3.
    foreignkey

    View Slide

  22. Object Store
    A
    E
    B
    D
    C
    Realm.getA().getB().getD()

    View Slide


  23. Zero Copy

    View Slide

  24. // create Cursor in order to parse our sqlite results
    Cursor cursor = sqliteDB.rawQuery("SELECT bookTitle FROM " + tableName, null);
    // if Cursor contains results
    if (cursor != null) {
    // move cursor to first row
    if (cursor.moveToFirst()) {
    do {
    // Get version from Cursor
    String bookName = cursor.getString(cursor.getColumnIndex("bookTitle"));
    } while (cursor.moveToNext());
    }
    }
    What is Zero Copy

    View Slide

  25. Zero Copy
    Src: Building Mobile DataBase by Christian Melchior http://www.slideshare.net/ChristianMelchior/realm-
    building-a-mobile-database#25

    View Slide

  26. Person person = new Person() //Standard Java
    Person proxyperson = realm.copyToRealm(person) //Proxy object
    Person proxyperson = realm.createObject(Person.class) //Proxy object
    //Query Results are Lazy
    RealmResults queryResults = realm.allObjects(Person.class)
    queryResult.get(0) != queryResult.get(0) //different objects
    queryResult.get(0).equals(queryResult.get(0)) //same data
    Zero Copy

    View Slide

  27. ▷ Easy Setup
    ▷ Memory mapped files
    ▷ C++ core
    ▷ B+ trees
    ▷ Column Oriented
    ▷ Minimize IO overhead
    ▷ Cross platform
    ▷ Faster Read & writes
    ▷ Read > Writes
    ▷ Simple Querying interface
    Designed for Mobile

    View Slide

  28. Benchmarking
    Benchmarking realm against other databases

    View Slide

  29. Src: Building Mobile DataBase by Christian Melchior http://www.slideshare.net/ChristianMelchior/realm-
    building-a-mobile-database#25

    View Slide

  30. Sample against 1,00,000 objects read and write

    View Slide

  31. Let’s See
    some Code

    View Slide

  32. Setup
    compile 'io.realm:realm-android:
    0.86.1'
    Realm realm = Realm.getInstance(context)

    View Slide

  33. Method and Size
    ▷ ~ 1750 method counts
    ▷ adds ~730 KB fat to apk
    ▷ install size less

    View Slide

  34. Realm Objects
    //Standard Java POJO from RealmObject
    public class Person extends RealmObject {
    @PrimaryKey
    private String personName;
    private int personAge;
    …..
    …...
    //Getters and Setters
    }

    View Slide

  35. Writing Data
    //Standard Java extend person from RealmObject
    Person person = new Person()
    //call setter to set data
    ….
    //save data
    try{
    realm.beginTransaction();
    realm.copyToRealm(person);
    realm.commitTransaction();
    }catch(Exception e){
    realm.cancelTransaction(); // rollback data
    }

    View Slide

  36. Writing Data Async Block
    //transaction block
    realm.executeTransaction(new Realm.Transaction() {
    @Override
    public void execute(Realm realm) {
    Person person = realm.createObject(Person.class);
    person.setName("John");
    person.setEmail("[email protected]");
    }
    });

    View Slide

  37. ▷ Supports Primary Key
    ▷ Supports primitive data types like int, long, boolean
    etc.
    ▷ Supports Box types like Integer, Long, String etc.
    ▷ Allows null value for non primitives types
    ▷ Supports Indexing
    Realm Object

    View Slide

  38. Query Data
    // Build the query looking at all users:
    RealmQuery query = realm.where(User.class);
    // Add query conditions:
    query.equalTo("name", "John");
    query.or().equalTo("name", "Peter");
    // Execute the query:
    RealmResults result1 = query.findAll();
    // Or alternatively do the same all at once (the "Fluent interface"):
    RealmResults result2 = realm.where(User.class)
    .equalTo("name", "John")
    .or()
    .equalTo("name", "Peter") .findAll();

    View Slide

  39. Query Data
    // Queries use Builder pattern to build up the query conditions
    RealmResults query = realm.where(Dog.class)
    .greaterThan("age", 8)
    .findAll();
    // Queries are chainable
    RealmResults allRex = query.where()
    .contains("name", "rex")
    .findAll();

    View Slide

  40. ▷ Conditions like lessThan, greaterThan, contains,
    beginsWith etc
    ▷ Modifiers for ignoring Cases
    ▷ Logical Operations OR AND
    ▷ Sorting Ascending, Descending
    ▷ Chaining Queries
    ▷ Aggregations like SUM, MIN, MAX, AVG
    ▷ Synchronous, Asynchronous operations
    Query Data Supports

    View Slide

  41. Relationships
    // Any Realm Object can be linked together
    public class Email extends RealmObject {
    private String address;
    private boolean active;
    // ... setters and getters left out
    }
    public class Contact extends RealmObject {
    private String name;
    private Email email;
    // ... setters and getters left out
    }

    View Slide

  42. Link Queries
    // You can now link queries together
    RealmResults contacts = realm.where(Contact.
    class).equalTo("emails.active", true).findAll();

    View Slide

  43. ▷ Direct support for Json to Object store
    ▷ Notification for database change like CP
    ▷ Encryption support in built
    ▷ Adapters for binding data with views
    ▷ Cross Platform, same data can work across iOS and
    Android
    ▷ Robust 3rd parties addons
    Other Features

    View Slide

  44. Limitations

    View Slide

  45. ▷ Not Entirely NOSQL, need migration on schema
    Changes
    ▷ No support for auto incrementing primary keys
    ▷ Closed source code
    ▷ Mutable, thread-confined objects
    ▷ No support for realm objects across threads
    ▷ Slower write
    ▷ Increase method count and size of apk
    Limitations

    View Slide

  46. Realm Browser

    View Slide

  47. Mac App to browse data stored on realm files
    (there is a separate plugin for STETHO)

    View Slide

  48. Who else is using Realm
    Is it production ready?

    View Slide

  49. View Slide

  50. Thanks!
    Any questions?
    You can find me at:
    @dhuma1981
    +DhrumilShah
    [email protected]

    View Slide

  51. Credits
    Special thanks to all the people who made and
    released these awesome resources for free:
    ▷ Realm by realm.io
    ▷ Christian Melchior from Realm Team
    ▷ Pranay Airan from GDG BlrDroid
    ▷ Presentation template by SlidesCarnival

    View Slide