Orbit’s orbit.model is an abstraction over LuaSQL that adds simple CRUD and parameterized queries, a sort of ORM super-lite. When you create a model, orbit.model introspects the database table that corresponds to your model and uses this metadata to do type conversions and build SQL statements.
Intializing models is very simple. The code below creates an orbit.model instance connected to an SQLite3 database, and then creates a model object backed by the todo_list table:
Once you have a model object, you can create new objects with new. You can set fields in this object just like a plain Lua table, and call its method save to write it to the database. Continuing the previous example:
All model database tables need to have an autogenerated field named id. If the table has a created_at field of type timestamp, orbit.model will automatically store the timestamp when you created the record. An updated_at field, if it exists, will be automatically kept with the timestamp of the last call to save.
Well, adding new records is useless if you do not have a way to get them back. That is what the finders are for. The basic finders is find_all, which returns all records that match its parameters (or all records of called without arguments). It is best to show an example:
This code snippet gets all todo items that are done and were updated since November 1st, 2009, ordered by descending date of creation, then iterates over this list and prints their titles. The first argument of find_all is a template for the WHERE clause, with question marks in place of the values. The second is a table of parameters, where the list part has the values that replace the question marks in the template, and the hash part has options that control other parts of the query.
There is an analogous find_first method that works just like find_all, but returns only the first record that matches.
In another post I will show how to do more magic with orbit.model’s finders.