This document describes the BKeeney ActiveRecord library for Real Studio. I wrote ActiveRecord because I got tired of manually creating mappings between my database tables and my object model. Download the project below for an unencrypted set of RealBasic modules and classes.
Active record is a design pattern for accessing databases from object-oriented languages. It was described by Martin Fowler in his book Patterns of Enterprise Application Architecture, although he didn’t invent the idea. You can find more details and links to other resources on Wikipedia.
The basic idea is that access to each table is wrapped by a class. The class has a property for each field in the table and it has methods to load and save from the database.
The main way that you interact with ActiveRecord in your code is through the Base class in the BKS_ActiveRecord project. Base implements the standard Save, Load, and Delete methods and you create subclasses of it for each of your tables (see the end of this document for a complete list of methods provided by Base).
For example, if you’re using REALSQLDatabase and create a table using the following statement:
CREATE TABLE tblPerson(
id INTEGER PRIMARY KEY,
FirstName TEXT,
LastName TEXT,
DateOfBirth TEXT )
You could create a class, say Person, and set it’s super class to BKS_ActiveRecord.Base. Then you would add properties for id, FirstName, LastName, and DateOfBirth.
Before you can start using the active record classes to interact with your database you have to let the class model know what database to use. To connect your model to a database, use the BKS_ActiveRecord.Connect method like this:
BKS_ActiveRecord.Connect(db)
If you want to use more than one database for different parts of the your class model you can send a class to the Connect method:
BKS_ActiveRecord.Connect(GetTypeInfo(clsBankAccount), dbBankAccounts)
Now clsBankAccount and all of its subclasses will use the dbBankAccounts database while the other active records classes will use db. The database can be any of databases support by ActiveRecord, currently: REALSQLDatabase, MySQLCommunityServer, and PostgreSQLDatabase.
To create a new entry in your table you could use the following code:
Dim newPerson As New Person
newPerson.FirstName = "Jane"
newPerson.LastName = "Doe"
newPerson.DateOfBirth = New Date(1971,1,1)
newPerson.Save
Base automatically maps the properties to the correct fields in the database and since the object was created new it knows that it needs to insert a record into the database.
If you have the ID of an existing record you can load it with the Load method:
Dim existingPerson As New Person
Call existingPerson.Load(1)