Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

db.py 15 KB

You have to be logged in to leave a comment. Sign In
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
  1. import os
  2. import sys
  3. import re
  4. import time
  5. import logging
  6. import hashlib
  7. import threading
  8. from pathlib import Path
  9. from contextlib import contextmanager
  10. from datetime import timedelta
  11. from typing import NamedTuple, List
  12. from docopt import docopt
  13. from natural.date import compress as compress_date
  14. import pandas as pd
  15. from more_itertools import peekable
  16. import psycopg2, psycopg2.errorcodes
  17. from psycopg2 import sql
  18. import sqlparse
  19. _log = logging.getLogger(__name__)
  20. # Meta-schema for storing stage and file status in the database
  21. _ms_path = Path(__file__).parent.parent / 'schemas' / 'meta-schema.sql'
  22. meta_schema = _ms_path.read_text()
  23. def db_url():
  24. "Get the URL to connect to the database."
  25. if 'DB_URL' in os.environ:
  26. return os.environ['DB_URL']
  27. host = os.environ.get('PGHOST', 'localhost')
  28. port = os.environ.get('PGPORT', None)
  29. db = os.environ['PGDATABASE']
  30. user = os.environ.get('PGUSER', None)
  31. pw = os.environ.get('PGPASSWORD', None)
  32. url = 'postgresql://'
  33. if user:
  34. url += user
  35. if pw:
  36. url += ':' + pw
  37. url += '@'
  38. url += host
  39. if port:
  40. url += ':' + port
  41. url += '/' + db
  42. return url
  43. @contextmanager
  44. def connect():
  45. "Connect to a database. This context manager yields the connection, and closes it when exited."
  46. _log.info('connecting to %s', db_url())
  47. conn = psycopg2.connect(db_url())
  48. try:
  49. yield conn
  50. finally:
  51. conn.close()
  52. def hash_and_record_file(cur, path, stage=None):
  53. """
  54. Compute the checksum of a file and record it in the database.
  55. """
  56. h = hashlib.md5()
  57. with open(path, 'rb') as f:
  58. data = f.read(8192 * 4)
  59. while data:
  60. h.update(data)
  61. data = f.read(8192 * 4)
  62. hash = h.hexdigest()
  63. path = Path(path).as_posix()
  64. _log.info('recording file %s with hash %s', path, hash)
  65. record_file(cur, path, hash, stage)
  66. return hash
  67. def begin_stage(cur, stage):
  68. """
  69. Record that a stage is beginning.
  70. """
  71. if hasattr(cur, 'cursor'):
  72. # this is a connection
  73. with cur, cur.cursor() as c:
  74. return begin_stage(c, stage)
  75. _log.info('starting or resetting stage %s', stage)
  76. cur.execute('''
  77. INSERT INTO stage_status (stage_name)
  78. VALUES (%s)
  79. ON CONFLICT (stage_name)
  80. DO UPDATE SET started_at = now(), finished_at = NULL, stage_key = NULL
  81. ''', [stage])
  82. cur.execute('DELETE FROM stage_file WHERE stage_name = %s', [stage])
  83. cur.execute('DELETE FROM stage_dep WHERE stage_name = %s', [stage])
  84. def record_dep(cur, stage, dep):
  85. """
  86. Record a dependency for a stage.
  87. """
  88. if hasattr(cur, 'cursor'):
  89. # this is a connection
  90. with cur, cur.cursor() as c:
  91. return record_dep(c, stage, dep)
  92. _log.info('recording dep %s -> %s', stage, dep);
  93. cur.execute('''
  94. INSERT INTO stage_dep (stage_name, dep_name, dep_key)
  95. SELECT %s, stage_name, stage_key
  96. FROM stage_status WHERE stage_name = %s
  97. RETURNING dep_name, dep_key
  98. ''', [stage, dep])
  99. return cur.fetchall()
  100. def record_file(cur, file, hash, stage=None):
  101. """
  102. Record a file and optionally associate it with a stage.
  103. """
  104. if hasattr(cur, 'cursor'):
  105. # this is a connection
  106. with cur, cur.cursor() as c:
  107. return record_file(c, stage)
  108. _log.info('recording checksum %s for file %s', hash, file)
  109. cur.execute("""
  110. INSERT INTO source_file (filename, checksum)
  111. VALUES (%(file)s, %(hash)s)
  112. ON CONFLICT (filename)
  113. DO UPDATE SET checksum = %(hash)s, reg_time = NOW()
  114. """, {'file': file, 'hash': hash})
  115. if stage is not None:
  116. cur.execute("INSERT INTO stage_file (stage_name, filename) VALUES (%s, %s)", [stage, file])
  117. def end_stage(cur, stage, key=None):
  118. """
  119. Record that an import stage has finished.
  120. Args:
  121. cur(psycopg2.connection or psycopg2.cursor): the database connection to use.
  122. stage(string): the name of the stage.
  123. key(string or None): the key (checksum or other key) to record.
  124. """
  125. if hasattr(cur, 'cursor'):
  126. # this is a connection
  127. with cur, cur.cursor() as c:
  128. return end_stage(c, stage, key)
  129. _log.info('finishing stage %s', stage)
  130. cur.execute('''
  131. UPDATE stage_status
  132. SET finished_at = NOW(), stage_key = coalesce(%(key)s, stage_key)
  133. WHERE stage_name = %(stage)s
  134. ''', {'stage': stage, 'key': key})
  135. def _tokens(s, start=-1, skip_ws=True, skip_cm=True):
  136. i, t = s.token_next(start, skip_ws=skip_ws, skip_cm=skip_cm)
  137. while t is not None:
  138. yield t
  139. i, t = s.token_next(i, skip_ws=skip_ws, skip_cm=skip_cm)
  140. def describe_statement(s):
  141. "Describe an SQL statement. This utility function is used to summarize statements."
  142. label = s.get_type()
  143. li, lt = s.token_next(-1, skip_cm=True)
  144. if lt is None:
  145. return None
  146. if lt and lt.ttype == sqlparse.tokens.DDL:
  147. # DDL - build up!
  148. parts = []
  149. first = True
  150. skipping = False
  151. for t in _tokens(s, li):
  152. if not first:
  153. if isinstance(t, sqlparse.sql.Identifier) or isinstance(t, sqlparse.sql.Function):
  154. parts.append(t.normalized)
  155. break
  156. elif t.ttype != sqlparse.tokens.Keyword:
  157. break
  158. first = False
  159. if t.normalized == 'IF':
  160. skipping = True
  161. if not skipping:
  162. parts.append(t.normalized)
  163. label = label + ' ' + ' '.join(parts)
  164. elif label == 'UNKNOWN':
  165. ls = []
  166. for t in _tokens(s):
  167. if t.ttype == sqlparse.tokens.Keyword:
  168. ls.append(t.normalized)
  169. else:
  170. break
  171. if ls:
  172. label = ' '.join(ls)
  173. name = s.get_real_name()
  174. if name:
  175. label += f' {name}'
  176. return label
  177. def is_empty(s):
  178. "check if an SQL statement is empty"
  179. lt = s.token_first(skip_cm=True, skip_ws=True)
  180. return lt is None
  181. class ScriptChunk(NamedTuple):
  182. "A single chunk of an SQL script."
  183. label: str
  184. allowed_errors: List[str]
  185. src: str
  186. use_transaction: bool = True
  187. @property
  188. def statements(self):
  189. return [s for s in sqlparse.parse(self.src) if not is_empty(s)]
  190. class SqlScript:
  191. """
  192. Class for processing & executing SQL scripts with the following features ``psql``
  193. does not have:
  194. * Splitting the script into (named) steps, to commit chunks in transactions
  195. * Recording metadata (currently just dependencies) for the script
  196. * Allowing chunks to fail with specific errors
  197. The last feature is to help with writing _idempotent_ scripts: by allowing a chunk
  198. to fail with a known error (e.g. creating a constraint that already exists), you
  199. can write a script that can run cleanly even if it has already been run.
  200. Args:
  201. file: the path to the SQL script to read.
  202. """
  203. _sep_re = re.compile(r'^---\s*(?P<inst>.*)')
  204. _icode_re = re.compile(r'#(?P<code>\w+)\s*(?P<args>.*\S)?\s*$')
  205. chunks: List[ScriptChunk]
  206. def __init__(self, file):
  207. if hasattr(file, 'read'):
  208. self._parse(peekable(file))
  209. else:
  210. with open(file, 'r', encoding='utf8') as f:
  211. self._parse(peekable(f))
  212. def _parse(self, lines):
  213. self.chunks = []
  214. self.deps = self._parse_script_header(lines)
  215. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  216. while next_chunk is not None:
  217. if next_chunk:
  218. self.chunks.append(next_chunk)
  219. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  220. @classmethod
  221. def _parse_script_header(cls, lines):
  222. deps = []
  223. line = lines.peek(None)
  224. while line is not None:
  225. hm = cls._sep_re.match(line)
  226. if hm is None:
  227. break
  228. inst = hm.group('inst')
  229. cm = cls._icode_re.match(inst)
  230. if cm is None:
  231. next(lines) # eat line
  232. continue
  233. code = cm.group('code')
  234. args = cm.group('args')
  235. if code == 'dep':
  236. deps.append(args)
  237. next(lines) # eat line
  238. else: # any other code, we're out of header
  239. break
  240. line = lines.peek(None)
  241. return deps
  242. @classmethod
  243. def _parse_chunk(cls, lines: peekable, n: int):
  244. qlines = []
  245. chunk = cls._read_header(lines)
  246. qlines = cls._read_query(lines)
  247. # end of file, do we have a chunk?
  248. if qlines:
  249. if chunk.label is None:
  250. chunk = chunk._replace(label=f'Step {n}')
  251. return chunk._replace(src='\n'.join(qlines))
  252. elif qlines is not None:
  253. return False # empty chunk
  254. @classmethod
  255. def _read_header(cls, lines: peekable):
  256. label = None
  257. errs = []
  258. tx = True
  259. line = lines.peek(None)
  260. while line is not None:
  261. hm = cls._sep_re.match(line)
  262. if hm is None:
  263. break
  264. next(lines) # eat line
  265. line = lines.peek(None)
  266. inst = hm.group('inst')
  267. cm = cls._icode_re.match(inst)
  268. if cm is None:
  269. continue
  270. code = cm.group('code')
  271. args = cm.group('args')
  272. if code == 'step':
  273. label = args
  274. elif code == 'allow':
  275. err = getattr(psycopg2.errorcodes, args.upper())
  276. _log.debug('step allows error %s (%s)', args, err)
  277. errs.append(err)
  278. elif code == 'notx':
  279. _log.debug('chunk will run outside a transaction')
  280. tx = False
  281. else:
  282. _log.error('unrecognized query instruction %s', code)
  283. raise ValueError(f'invalid query instruction {code}')
  284. return ScriptChunk(label=label, allowed_errors=errs, src=None,
  285. use_transaction=tx)
  286. @classmethod
  287. def _read_query(cls, lines: peekable):
  288. qls = []
  289. line = lines.peek(None)
  290. while line is not None and not cls._sep_re.match(line):
  291. qls.append(next(lines))
  292. line = lines.peek(None)
  293. # trim lines
  294. while qls and not qls[0].strip():
  295. qls.pop(0)
  296. while qls and not qls[-1].strip():
  297. qls.pop(-1)
  298. if qls or line is not None:
  299. return qls
  300. else:
  301. return None # end of file
  302. def execute(self, dbc, transcript=None):
  303. """
  304. Execute the SQL script.
  305. Args:
  306. dbc: the database connection.
  307. transcript: a file to receive the run transcript.
  308. """
  309. all_st = time.perf_counter()
  310. for step in self.chunks:
  311. start = time.perf_counter()
  312. _log.info('Running ‘%s’', step.label)
  313. if transcript is not None:
  314. print('CHUNK', step.label, file=transcript)
  315. if step.use_transaction:
  316. with dbc, dbc.cursor() as cur:
  317. self._run_step(step, dbc, cur, True, transcript)
  318. else:
  319. ac = dbc.autocommit
  320. try:
  321. dbc.autocommit = True
  322. with dbc.cursor() as cur:
  323. self._run_step(step, dbc, cur, False, transcript)
  324. finally:
  325. dbc.autocommit = ac
  326. elapsed = time.perf_counter() - start
  327. elapsed = timedelta(seconds=elapsed)
  328. print('CHUNK ELAPSED', elapsed, file=transcript)
  329. _log.info('Finished ‘%s’ in %s', step.label, compress_date(elapsed))
  330. elapsed = time.perf_counter() - all_st
  331. elasped = timedelta(seconds=elapsed)
  332. _log.info('Script completed in %s', compress_date(elapsed))
  333. def describe(self):
  334. for dep in self.deps:
  335. _log.info('Dependency ‘%s’', dep)
  336. for step in self.chunks:
  337. _log.info('Chunk ‘%s’', step.label)
  338. for s in step.statements:
  339. _log.info('Statement %s', describe_statement(s))
  340. def _run_step(self, step, dbc, cur, commit, transcript):
  341. try:
  342. for sql in step.statements:
  343. start = time.perf_counter()
  344. _log.debug('Executing %s', describe_statement(sql))
  345. _log.debug('Query: %s', sql)
  346. if transcript is not None:
  347. print('STMT', describe_statement(sql), file=transcript)
  348. cur.execute(str(sql))
  349. elapsed = time.perf_counter() - start
  350. elapsed = timedelta(seconds=elapsed)
  351. rows = cur.rowcount
  352. if transcript is not None:
  353. print('ELAPSED', elapsed, file=transcript)
  354. if rows is not None and rows >= 0:
  355. if transcript is not None:
  356. print('ROWS', rows, file=transcript)
  357. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  358. compress_date(elapsed), rows)
  359. else:
  360. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  361. compress_date(elapsed), rows)
  362. if commit:
  363. dbc.commit()
  364. except psycopg2.Error as e:
  365. if e.pgcode in step.allowed_errors:
  366. _log.info('Failed with acceptable error %s (%s)',
  367. e.pgcode, psycopg2.errorcodes.lookup(e.pgcode))
  368. if transcript is not None:
  369. print('ERROR', e.pgcode, psycopg2.errorcodes.lookup(e.pgcode), file=transcript)
  370. else:
  371. _log.error('Error in "%s" %s: %s: %s',
  372. step.label, describe_statement(sql),
  373. psycopg2.errorcodes.lookup(e.pgcode), e)
  374. if e.pgerror:
  375. _log.info('Query diagnostics:\n%s', e.pgerror)
  376. raise e
  377. class _LoadThread(threading.Thread):
  378. """
  379. Thread worker for copying database results to a stream we can read.
  380. """
  381. def __init__(self, dbc, query, dir='out'):
  382. super().__init__()
  383. self.database = dbc
  384. self.query = query
  385. rfd, wfd = os.pipe()
  386. self.reader = os.fdopen(rfd)
  387. self.writer = os.fdopen(wfd, 'w')
  388. self.chan = self.writer if dir == 'out' else self.reader
  389. def run(self):
  390. with self.chan, self.database.cursor() as cur:
  391. cur.copy_expert(self.query, self.chan)
  392. def load_table(dbc, query):
  393. """
  394. Load a query into a Pandas data frame.
  395. This is substantially more efficient than Pandas ``read_sql``, because it directly
  396. streams CSV data from the database instead of going through SQLAlchemy.
  397. """
  398. cq = sql.SQL('COPY ({}) TO STDOUT WITH CSV HEADER')
  399. q = sql.SQL(query)
  400. thread = _LoadThread(dbc, cq.format(q))
  401. thread.start()
  402. data = pd.read_csv(thread.reader)
  403. thread.join()
  404. return data
  405. def save_table(dbc, table, data: pd.DataFrame):
  406. """
  407. Save a table from a Pandas data frame.
  408. This is substantially more efficient than Pandas ``read_sql``, because it directly
  409. streams CSV data from the database instead of going through SQLAlchemy.
  410. """
  411. cq = sql.SQL('COPY {} FROM STDIN WITH CSV')
  412. thread = _LoadThread(dbc, cq.format(table), 'in')
  413. thread.start()
  414. data.to_csv(thread.writer, header=False, index=False)
  415. thread.writer.close()
  416. thread.join()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...