Update of /cvsroot/sqlobject/SQLObject/examples
In directory sc8-pr-cvs1:/tmp/cvs-serv28975/examples
Modified Files:
codebits.py
Added Files:
leftjoin.py
Log Message:
Added a FAQ, with requisite examples
--- NEW FILE: leftjoin.py ---
from SQLObject import *
## Use one of these to define your connection:
"""
conn = MySQLConnection(user='test', db='testdb')
conn = PostgresConnection('user=test dbname=testdb')
conn = SQLiteConnect('database.db')
conn = DBMConnection('database/')
"""
__connection__ = MySQLConnection(user='test', db='test')
class Customer(SQLObject):
firstName = StringCol(length=100)
lastName = StringCol(length=100)
contacts = MultipleJoin('Contact')
class Contact(SQLObject):
customer = ForeignKey('Customer')
phoneNumber = StringCol(length=20)
Customer.dropTable(ifExists=True)
Customer.createTable()
Contact.dropTable(ifExists=True)
Contact.createTable()
data = [
['Joe Henry', '384-374-3584', '984-384-8594', '384-957-3948'],
['Tim Jackson', '204-485-9384'],
['Jane Austin'],
]
for insert in data:
firstName, lastName = insert[0].split(' ', 1)
customer = Customer.new(firstName=firstName, lastName=lastName)
for number in insert[1:]:
contact = Contact.new(customer=customer, phoneNumber=number)
## Snippet "leftjoin-simple"
for customer in Customer.select():
print customer.firstName, customer.lastName
for contact in customer.contacts:
print ' ', contact.phoneNumber
## end snippet
## Snippet "leftjoin-more"
custContacts = {}
for contact in Contact.select():
custContacts.setdefault(contact.customerID, []).append(contact)
for customer in Customer.select():
print customer.firstName, customer.lastName
for contact in custContacts.get(customer.id, []):
print ' ', contact.phoneNumber
## end snippet
## Snippet "leftjoin-more-query"
query = Customer.q.firstName.startswith('J')
custContacts = {}
for contact in Contact.select(AND(Contact.q.customerID == Customer.q.id,
query)):
custContacts.setdefault(contact.customerID, []).append(contact)
for customer in Customer.select(query):
print customer.firstName, customer.lastName
for contact in custContacts.get(customer.id, []):
print ' ', contact.phoneNumber
## end snippet
Index: codebits.py
===================================================================
RCS file: /cvsroot/sqlobject/SQLObject/examples/codebits.py,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** codebits.py 28 Jun 2003 22:17:36 -0000 1.1
--- codebits.py 21 Aug 2003 05:02:17 -0000 1.2
***************
*** 81,82 ****
--- 81,222 ----
## end snippet
+ ## Snippet "site-sqlobject"
+ class SiteSQLObject(SQLObject):
+ _connection = DBConnection.MySQLConnection(user='test', db='test')
+ _style = MixedCaseStyle()
+
+ # And maybe you want a list of the columns, to autogenerate
+ # forms from:
+ def columns(self):
+ return [col.name for col in self._columns]
+ ## end snippet
+
+ ## Snippet "inheritance"
+ class Person(SQLObject):
+ firstName = StringCol()
+ lastName = StringCol()
+
+ class Employee(Person):
+ position = StringCol()
+ ## end snippet
+
+ """
+ ## Snippet "inheritance-schema"
+ CREATE TABLE person (
+ id INT PRIMARY KEY,
+ first_name TEXT,
+ last_name TEXT
+ );
+
+ CREATE TABLE employee (
+ id INT PRIMARY KEY
+ first_name TEXT,
+ last_name TEXT,
+ position TEXT
+ )
+ ## end snippet
+ """
+
+ ## Snippet "inheritance-faked"
+ class Person(SQLObject):
+ firstName = StringCol()
+ lastName = StringCol()
+
+ def _get_employee(self):
+ value = Employee.selectBy(person=self)
+ if value:
+ return value[0]
+ else:
+ raise AttributeError, '%r is not an employee' % self
+ def _get_isEmployee(self):
+ value = Employee.selectBy(person=self)
+ # turn into a bool:
+ return not not value
+ def _set_isEmployee(self, value):
+ if value:
+ # Make sure we are an employee...
+ if not self.isEmployee:
+ Empoyee.new(person=self, position=None)
+ else:
+ if self.isEmployee:
+ self.employee.destroySelf()
+ def _get_position(self):
+ return self.employee.position
+ def _set_position(self, value):
+ self.employee.position = value
+
+ class Employee(SQLObject):
+ person = ForeignKey('Person')
+ position = StringCol()
+ ## end snippet
+
+ """
+ ## Snippet "composite-schema"
+ CREATE TABLE invoice_item (
+ id INT PRIMARY KEY,
+ amount NUMERIC(10, 2),
+ currency CHAR(3)
+ );
+ ## end snippet
+ """
+
+ ## Snippet "composite"
+ class InvoiceItem(SQLObject):
+ amount = Currency()
+ currency = StringChar(length=3)
+
+ def _get_price(self):
+ return Price(self.amount, self.currency)
+ def _set_price(self, price):
+ self.amount = price.amount
+ self.currency = price.currency
+
+ class Price(object):
+ def __init__(self, amount, currency):
+ self._amount = amount
+ self._currency = currency
+
+ def _get_amount(self):
+ return self._amount
+ amount = property(_get_amount)
+
+ def _get_currency(self):
+ return self._currency
+ currency = property(_get_currency)
+
+ def __repr__(self):
+ return '<Price: %s %s>' % (self.amount, self.currency)
+ ## end snippet
+
+ ## Snippet "composite-mutable"
+ class Address(SQLObject):
+ street = StringCol()
+ city = StringCol()
+ state = StringCol(length=2)
+
+ latitude = FloatCol()
+ longitude = FloatCol()
+
+ def _init(self, id):
+ SQLObject._init(self, id)
+ self._coords = SOCoords(self)
+
+ def _get_coords(self):
+ return self._coords
+
+ class SOCoords(object):
+ def __init__(self, so):
+ self._so = so
+
+ def _get_latitude(self):
+ return self._so.latitude
+ def _set_latitude(self, value):
+ self._so.latitude = value
+ latitude = property(_get_latitude, set_latitude)
+
+ def _get_longitude(self):
+ return self._so.longitude
+ def _set_longitude(self, value):
+ self._so.longitude = value
+ longitude = property(_get_longitude, set_longitude)
+ ## end snippet
|