~vcs-imports/sqlobject/trunk

« back to all changes in this revision

Viewing changes to examples/people.py

  • Committer: ianb
  • Date: 2004-02-05 03:29:19 UTC
  • Revision ID: svn-v4:95a46c32-92d2-0310-94a5-8d71aeb3d4b3:trunk/SQLObject:1
Initial import of SQLObject and DataTest

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#!/usr/bin/env python
 
2
from SQLObject import *
 
3
import os
 
4
 
 
5
############################################################
 
6
## Configuration parameters:
 
7
############################################################
 
8
 
 
9
user = os.environ.get('SQLOBJECT_USER', 'sqlobject_test')
 
10
passwd = os.environ.get('SQLOBJECT_PASSWORD', '')
 
11
database = os.environ.get('SQLOBJECT_DATABASE', 'sqlobject_test')
 
12
debug = 1
 
13
 
 
14
############################################################
 
15
## Setup connections:
 
16
############################################################
 
17
 
 
18
print 'Accessing with user %s and password %s' % (user, passwd)
 
19
 
 
20
if 1:
 
21
    # do MySQL test
 
22
    __connection__ = MySQLConnection('localhost', database,
 
23
                                     user, passwd, debug=debug)
 
24
else:
 
25
    # do Postgres test
 
26
    __connection__ = PostgresConnection('dbname=%s user=%s' %
 
27
                                        (database, user), debug=debug)
 
28
 
 
29
 
 
30
############################################################
 
31
## Define classes:
 
32
############################################################
 
33
 
 
34
class Person(SQLObject):
 
35
 
 
36
    _columns = [StringCol('username', length=20, alternateID=True,
 
37
                          notNull=1),
 
38
                StringCol('firstName', length=30,
 
39
                          notNull=1),
 
40
                StringCol('middleInitial', length=1, default=None),
 
41
                StringCol('lastName', length=50, notNull=1)]
 
42
    _joins = [RelatedJoin('Role'), MultipleJoin('PhoneNumber')]
 
43
 
 
44
    def imageFilename(self):
 
45
        return 'images/person-%s.jpg' % self.id
 
46
 
 
47
    def _get_image(self):
 
48
        if not os.path.exists(self.imageFilename()):
 
49
            return None
 
50
        f = open(self.imageFilename())
 
51
        v = f.read()
 
52
        f.close()
 
53
        return v
 
54
 
 
55
    def _set_image(self, value):
 
56
        # assume we get a string for the image
 
57
        f = open(self.imageFilename(), 'w')
 
58
        f.write(value)
 
59
        f.close()
 
60
 
 
61
    def _del_image(self, value):
 
62
        # I usually wouldn't include a method like this, but for
 
63
        # instructional purposes...
 
64
        os.unlink(self.imageFilename())
 
65
 
 
66
    _doc_image = 'The headshot for the person'
 
67
 
 
68
class PhoneNumber(SQLObject):
 
69
 
 
70
    _columns = [KeyCol('personID', foreignKey='Person'),
 
71
                StringCol('phoneNumber', length=14, notNull=1),
 
72
                EnumCol('phoneType',
 
73
                        enumValues=['home', 'work', 'mobile'], notNull=1)]
 
74
 
 
75
class Role(SQLObject):
 
76
 
 
77
    _columns = [StringCol('name', length=30)]
 
78
    _joins = [RelatedJoin('Person')]
 
79
 
 
80
 
 
81
tableClasses = [Person, PhoneNumber, Role]
 
82
 
 
83
############################################################
 
84
## Process command-line arguments:
 
85
############################################################
 
86
 
 
87
import sys
 
88
args = sys.argv[1:]
 
89
 
 
90
if 'drop' in args:
 
91
    for table in tableClasses:
 
92
        table.dropTable(ifExists=True)
 
93
 
 
94
if 'create' in args:
 
95
    for table in tableClasses:
 
96
        table.createTable(ifExists=True)
 
97
 
 
98
if 'clear' in args:
 
99
    for table in tableClasses:
 
100
        table.clearTable(ifExists=True)
 
101
 
 
102
 
 
103
############################################################
 
104
## Define tests:
 
105
############################################################
 
106
 
 
107
test1 = """
 
108
>>> p = Person.new(firstName="John", lastName="Doe", username="johnd")
 
109
>>> print p
 
110
<Person 1 firstName='John' middleInitial=None lastName='Doe'>
 
111
>>> print p.firstName
 
112
John
 
113
>>> p.middleInitial = 'Q'
 
114
>>> print p.middleInitial
 
115
Q
 
116
>>> p2 = Person(p.id)
 
117
>>> print p2
 
118
<Person 1 firstName='John' middleInitial='Q' lastName='Doe'>
 
119
>>> print p is p2
 
120
1
 
121
>>> p3 = Person.byUsername("johnd")
 
122
>>> print p3
 
123
<Person 1 firstName='John' middleInitial='Q' lastName='Doe'>
 
124
"""
 
125
 
 
126
test2 = """
 
127
>>> r = Role.new(name="editor")
 
128
>>> p = list(Person.select('all'))[-1]
 
129
>>> p.addRole(r)
 
130
>>> print p.roles
 
131
[<Role 1 name='editor'>]
 
132
>>> print r.persons
 
133
[<Person 1 firstName='John' middleInitial='Q' lastName='Doe'>]
 
134
>>> r.removePerson(p)
 
135
>>> print p.roles
 
136
[]
 
137
>>> phone = PhoneNumber.new(person=p, phoneNumber='773-555-1023', phoneType='home')
 
138
>>> print p.phoneNumbers
 
139
"""
 
140
 
 
141
test3 = """
 
142
>>> peeps1 = Person.select(Person.q.firstName=="John")
 
143
>>> print [p.id for p in peeps1]
 
144
>>> peeps2 = Person.select(AND(PhoneNumber.q.personID == Person.q.id, PhoneNumber.q.phoneNumber.startswith('612')))
 
145
>>> print [p.id for p in peeps2]
 
146
>>> peeps3 = Person.select("phone_number.id = person.id AND phone_number.phone_number LIKE '773%'", clauseTables=['phone_number'])[2:5]
 
147
>>> print [p.id for p in peeps3]
 
148
"""
 
149
 
 
150
 
 
151
############################################################
 
152
## Run tests:
 
153
############################################################
 
154
 
 
155
def runTest(s):
 
156
    lines = s.split('\n')
 
157
    for line in lines:
 
158
        if line.startswith('>>> '):
 
159
            print line
 
160
            exec line[4:]
 
161
 
 
162
runTest(test1)
 
163
runTest(test2)
 
164
runTest(test3)