A simple file based Ruby Database - KirbyBase
Have you ever been in a situation where you wanted to write a simple application for internal use that should be portable and completely self contained (including the database)? I am pretty sure you have. I had to do this recently for one of the simple reporting applications and I didn’t really want to create a dependency on external database like MySQL or PostgreSQL. This application needed only 4 tables and the data in these table is never going to be large enough to warrant an extensive database system. I thought about putting the data in flat files and write the code to access it. But, then I found this really neat gem called KirbyBase that does exactly the same and little more.
KirbyBase has some neat features that mirror the traditional RDBMS while still sticking to it’s simple roots:
- Pure Ruby code
- Data is kept in simple delimited files, allowing the modification in any text editor
- It’s not an in-memory DB. The data is actually stored on the disk
- Allows various data types like String, Integer, Float, Boolean, Time, Date, DateTime, Memo, Blob, and YAML
- Allows creating indexes on fields
- Query results can be sorted
- Allows to define one-many links between tables similar to joins in RDBMS
- The columns can be defined with a formula, so the value will be calculated during insertion
- Automatic lookup fields can be defined to lookup the related values from another table
To give a simple example on how all this works, let’s consider a scenario of Department and Employees. The simple requirements can be laid out as each employee has personal information and belongs to a department. Also, each department has a name and identifier and can contain multiple employees. Following is how the code going to look using KirbyBase. Please keep in mind that I have tried to write a reusable DAO, hence the code may look a little verbose. You can very well short circuit the whole thing and write very concise code.
The output after execution will look like this:
Employee in IT department Doe John Employee in IT department John Doe
This should also generate 2 files in your current directory, department.tbl and employee.tbl. Let’s look at content of these files now.
department.tbl
000001|000000|Department|recno:Integer|dept_name:String:Key->true:Index->1|employee:ResultSet:Link_many->recno=employee.dept_id 1|IT|kb_nil
employee.tbl
000002|000000|Employee|recno:Integer|dept_id:Integer:Key->true:Index->1|name:String:Key->true:Index->1 1|1|John 2|1|Doe
That’s all there to it. It is very powerful and easy to work with library.












