-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathericlib.py
438 lines (293 loc) · 9.82 KB
/
ericlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# vim: set expandtab ts=4 sw=4 filetype=python fileencoding=utf8:
import logging
import textwrap
import psycopg2.extras
log = logging.getLogger(__name__)
fighters_and_moves = dict({
"Liu Kang": [
("Fire blast", 20),
("Flying kick", 30),
],
'Scorpion': [
("Harpoon", 30),
("Teleport punch", 30),
],
'Sub Zero': [
("Ice ball", 10),
("Foot slide", 20),
]
})
def create_tables(pgconn):
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
create table fighters
(
fighter_id serial primary key,
title text not null unique
)
"""))
cursor.execute(textwrap.dedent("""
create table special_moves
(
special_move_id serial primary key,
fighter_id integer references fighters (fighter_id),
title text not null,
unique(fighter_id, title),
damage integer not null
)
"""))
def insert_data(pgconn):
global fighters_and_moves
cursor = pgconn.cursor()
for fighter, special_moves in fighters_and_moves.items():
# I discovered the "returning" keyword a few years ago and it
# has vastly simplified a lot of my database code.
cursor.execute(textwrap.dedent("""
insert into fighters
(title)
values
(%(fighter)s)
returning fighter_id
"""), {
'fighter': fighter,
})
fighter_id = cursor.fetchone().fighter_id
log.info("Stored fighter {0} with fighter ID {1}.".format(
fighter, fighter_id))
for title, damage in special_moves:
cursor.execute(textwrap.dedent("""
insert into special_moves
(fighter_id, title, damage)
values
(
%(fighter_id)s, %(title)s, %(damage)s
)
returning special_move_id
"""), {
'fighter_id': fighter_id,
'title': title,
'damage': damage
})
special_move_id = cursor.fetchone().special_move_id
log.info(
"Stored special move {0} with special move "
"ID {1}.".format(
title, special_move_id))
def do_ugly_report(pgconn):
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select f.title, sm.title as move_name, sm.damage
from fighters f
join special_moves sm
on f.fighter_id = sm.fighter_id
order by f.title, sm.title
"""))
print("+" * 60)
print("UGLY REPORT")
print("+" * 60)
print("")
print("{0:20} {1:20} {2:20}".format(
"Fighter",
"Move",
"Damage"))
print("-"*20 + " " + "-"*20 + " " + "-"*18 + " ")
for row in cursor:
# the < symbol means "left-justify", which seems to be the
# default for strings, but not for integers.
print("{0:20} {1:20} {2:<20}".format(*row))
print("")
def do_pretty_report_with_array_agg_1(pgconn):
"""
Use array_agg to roll up the just the titles of the special moves.
The titles will come back as a list of strings.
"""
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select f.title,
array_agg(sm.title order by sm.title) as special_moves
from fighters f
join special_moves sm
on f.fighter_id = sm.fighter_id
group by f.fighter_id
order by f.title
"""))
print("+" * 60)
print("PRETTY REPORT 1")
print("+" * 60)
print("")
for row in cursor:
print("{0}".format(row.title))
log.debug("In array_agg_1, type(row.special_moves) is {0}".format(
type(row.special_moves)))
for move in row.special_moves:
print(" {0}".format(move))
print("")
def do_pretty_report_with_array_agg_2(pgconn):
"""
Try to use array_agg to roll up more than one columns from the
special moves table.
But beware! This doesn't work right! Because psycopg2 has no
understanding of how to convert the thing made with the row(...)
function, it just returns it as a string.
"""
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select f.title,
array_agg(row(sm.title, sm.damage) order by sm.title) as special_moves
from fighters f
join special_moves sm
on f.fighter_id = sm.fighter_id
group by f.fighter_id
order by f.title
"""))
print("+" * 60)
print("PRETTY REPORT 2")
print("+" * 60)
print("")
for row in cursor:
print("{0}".format(row.title))
log.debug("In array_agg_2, type(row.special_moves) is {0}".format(
type(row.special_moves)))
print(" {0}".format(row.special_moves))
print("")
def register_type(pgconn):
# Tell psycopg2 that when it gets an instance of a special moves
# type, it should make a named tuple instance for the special moves
# table.
psycopg2.extras.register_composite('special_moves', pgconn)
def do_pretty_report_with_array_agg_3(pgconn):
"""
Note this weird syntax in the SQL::
row(
sm.special_move_id,
sm.fighter_id,
sm.title,
sm.damage)::special_moves
That :: operator casts whatever is on the left to a different type.
Every table in postgresql is also a user-defined type.
In this case, I'm saying "treat these four values in this row as a
special_moves type instance.
Here are much simpler / less scary examples::
>>> cursor.execute("select '2014-08-01' as x")
>>> type(cursor.fetchone().x)
<type 'str'>
>>> cursor.execute("select '2014-08-01'::date as x")
>>> type(cursor.fetchone().x)
<type 'datetime.date'>
"""
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select f.title,
array_agg(row(
sm.special_move_id,
sm.fighter_id,
sm.title,
sm.damage)::special_moves) as special_moves
from fighters f
join special_moves sm
on f.fighter_id = sm.fighter_id
group by f.fighter_id
order by f.title
"""))
print("+" * 60)
print("PRETTY REPORT 3")
print("+" * 60)
print("")
for row in cursor:
print("{0}".format(row.title))
log.debug("In array_agg_3, type(row.special_moves) is {0}".format(
type(row.special_moves)))
for sm in row.special_moves:
log.debug("type(sm) is {0}.".format(type(sm)))
print(" {0:20} {1:<20}".format(sm.title, sm.damage))
print("")
class Fighter(object):
def __init__(self, fighter_id, title):
self.fighter_id = fighter_id
self.title = title
def __str__(self):
return "{0}: {1} (fighter ID: {2})".format(
self.__class__.__name__,
self.title,
self.fighter_id)
class FighterFactory(psycopg2.extras.CompositeCaster):
def make(self, values):
d = dict(zip(self.attnames, values))
return Fighter(**d)
class SpecialMove(object):
def __init__(self, special_move_id, fighter_id, title, damage):
self.special_move_id = special_move_id
self.fighter_id = fighter_id
self.title = title
self.damage = damage
def __str__(self):
return "{0}: {1} (special move ID: {2})".format(
self.__class__.__name__,
self.title,
self.special_move_id)
class SpecialMoveFactory(psycopg2.extras.CompositeCaster):
def make(self, values):
d = dict(zip(self.attnames, values))
return SpecialMove(**d)
def register_home_made_types(pgconn):
# Register our own home-made FighterFactory to instantiate instances
# of our own Fighter class.
psycopg2.extras.register_composite(
'fighters',
pgconn,
factory=FighterFactory)
# Same thing, but different tables.
psycopg2.extras.register_composite(
'special_moves',
pgconn,
factory=SpecialMoveFactory)
def cast_to_our_own_classes(pgconn):
"""
In this one, I use this syntax::
(f.*)::fighters
instead of something like::
row(f.fighter_id,
f.title)::fighters
They do the exact same thing.
"""
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select (f.*)::fighters as fighter
from fighters f
order by f.title
"""))
log.debug("cast to our own Fighter class")
for row in cursor:
log.debug(row.fighter)
def do_pretty_report_with_array_agg_4(pgconn):
"""
Get a single row back for each fighter, with two columns in each
row.
The first column should hold an instance of our homemade Fighter
class.
The second column should hold an array of instances of our
customized
SpecialMove class.
"""
cursor = pgconn.cursor()
cursor.execute(textwrap.dedent("""
select (f.*)::fighters as fighter,
array_agg((sm.*)::special_moves order by sm.title) as special_moves
from fighters f
join special_moves sm
on f.fighter_id = sm.fighter_id
group by f.fighter_id
order by f.title
"""))
print("+" * 60)
print("PRETTY REPORT 4")
print("+" * 60)
print("")
for row in cursor:
log.debug("type(row.fighter): {0}".format(type(row.fighter)))
# This uses the Fighter.__str__ method
print(row.fighter)
log.debug("type(row.special_moves): {0}".format(type(row.special_moves)))
for sm in row.special_moves:
log.debug("type(sm): {0}".format(type(sm)))
print(sm)