Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Created May 27, 2011 23:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rochacbruno/996421 to your computer and use it in GitHub Desktop.
Save rochacbruno/996421 to your computer and use it in GitHub Desktop.
ORM inside web2py modules
import myapi
orm = myapi.ORM() #database created, migrated, defined
company = orm.new_company(name='Google Inc.') #New company created or validation errors returned
client = orm.new_client(name='John', company_id=company.id) # new client created
# you could call inline
client = orm.new_client(name='John', company_id=orm.new_company('Google Inc.'))
#this should validate and insert
#TODO: update_or_insert and validate_or_update
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import os
import sys
import unittest
sys.path.append(os.path.realpath('../../../'))
from gluon import *
from gluon.dal import Row
class Database(object):
"""Database Layer and table definitions"""
def __init__(self, uri, folder):
self.db = DAL(uri, folder=folder)
def client(self):
if not 'client' in self.db.tables:
client = self.db.define_table('client',
Field('name', required=True, requires=IS_NOT_EMPTY() ),
Field('company_id', required=True, requires=IS_IN_DB(self.db, 'company.id')),
)
else:
client = self.db.client
return client
def company(self):
if not 'company' in self.db.tables:
company = self.db.define_table('company',
Field('name', required=True, unique=True, requires=IS_NOT_EMPTY()),
)
else:
company = self.db.company
return company
def commit(self):
self.db.commit()
def rollback(self):
self.db.rollback()
class ORM(object):
"""Creates an app ORM """
def __init__(self):
self.db = Database('sqlite://mydatabase.sqlite', folder=os.path.realpath('../databases'))
commit = self.db.commit
rollback = self.db.rollback
self.errors = []
def new_company(self, name):
company = self.db.company()
new_company = False
try:
new_company = company.validate_and_insert(name=name)
self.db.commit()
except Exception, e:
self.errors.append(('InsertError','company',e))
self.db.rollback()
print self.errors
return new_company
def new_client(self, name, company_id):
client = self.db.client()
company = self.db.company()
if isinstance(company_id, str):
CID = company(name=company_id)
elif isinstance(company_id, int):
CID = company_id
elif isinstance(company_id, Row):
CID = company_id.id
else:
raise TypeError('company type not suported')
new_client = False
try:
new_client = client.validate_and_insert(name=name, company_id=CID)
self.db.commit()
except Exception, e:
self.errors.append(('Insert Error','client',e))
self.db.rollback()
print self.errors
return new_client
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment