Creating Tables in DrProject

Courtesy of David Scannell, here's a quick rundown of how to create a new table in DrProject's database. (Yes, I know, we should convert to SQLObject or SQLAlchemy; if you have time to do the work, please let me know...) Suppose I want to create a table called Demo with three fields:
  • Named: string
  • ID: integer (primary key)
  • TicketID: Integer (foreign key)
We'll assume that all work is being done in a drproject/demo directory, that you have __init__.py set up, and you have modified setup.py file to recognize the new package.

Step 1: Create the Model

A. Create a file call model.py. B. Import the following:
from drproject.db.record import *         # Base for all database modelling
from drproject.ticket.model import Ticket # Because we want a foreign key
C. Create a new subclass for record.
Class Demo(Record):
D. Associated this model with a database table (by default the table it gets associated with is the same as the name of the class):
Class Demo(Record):   _table='demo_table'
E. Now add the columns to the table:
Class Demo(Record):
_table='demo_table'
id = IdColumn()                # Creates a self-incrementing id
name = TextColumn()            # String column
ticket_id = ForeignKey(Ticket) # Makes this a foreign key to the Ticket Table
F. Make the ID column our primary key:
Class Demo(Record):
_table='demo_table'
id = IdColumn()
name = TextColumn()
ticket_id = ForeignKey(Ticket)
_key = (id,)
Done.

Step 2: Create the System

A. Create a file called api.py. B. Import the following:
from drproject.core import *
from drproject.env import EnvironmentSetupParticipant # For database creation
from drproject.demo.model import *                    # Our database model
C. Create our EnviromentSetupParticipant subclass.
Class DemoSystem(EnvironmentSetupParticipant):
D. Associate the table that this new system will work with. In our case, it is the demo table.
Class DemoSystem(EnvironmentSetupParticipant):
database_tables = (Demo,)
E. Give our system a name and version number:
Class DemoSystem(EnvironmentSetupParticipant):
database_tables = (Demo,)
version_propery = 'demo_system'
version = 1
Done.

Step 3: Finishing Off

Now, when we create a new environment, Drproject will go over all the EnvironmentSetupParticipant objects, and create all the database tables each one is associated with. Process occurs in the method __init__ of the class Environment in the file drproject/env.py.
comments powered by Disqus