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 13 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
  1. import os
  2. import sys
  3. import re
  4. import time
  5. import logging
  6. import hashlib
  7. import threading
  8. from configparser import ConfigParser
  9. from pathlib import Path
  10. from contextlib import contextmanager
  11. from datetime import timedelta
  12. from typing import NamedTuple, List
  13. from docopt import docopt
  14. from natural.date import compress as compress_date
  15. import pandas as pd
  16. from more_itertools import peekable
  17. import psycopg2, psycopg2.errorcodes
  18. from psycopg2 import sql
  19. import sqlparse
  20. import git
  21. _log = logging.getLogger(__name__)
  22. # Meta-schema for storing stage and file status in the database
  23. _ms_path = Path(__file__).parent.parent / 'schemas' / 'meta-schema.sql'
  24. meta_schema = _ms_path.read_text()
  25. def db_url():
  26. "Get the URL to connect to the database."
  27. if 'DB_URL' in os.environ:
  28. return os.environ['DB_URL']
  29. cfg = ConfigParser()
  30. _log.debug('reading config from db.cfg')
  31. cfg.read(['db.cfg'])
  32. repo = git.Repo()
  33. branch = repo.head.reference.name
  34. _log.info('reading database config for branch %s', branch)
  35. if branch in cfg:
  36. section = cfg[branch]
  37. else:
  38. _log.warn('No configuration for branch %s, using default', branch)
  39. section = cfg['DEFAULT']
  40. host = section.get('host', 'localhost')
  41. port = section.get('port', None)
  42. db = section.get('database', None)
  43. user = section.get('user', None)
  44. pw = section.get('password', None)
  45. if db is None:
  46. _log.error('No database specified for branch %s', branch)
  47. url = 'postgresql://'
  48. if user:
  49. url += user
  50. if pw:
  51. url += ':' + pw
  52. url += '@'
  53. url += host
  54. if port:
  55. url += ':' + port
  56. url += '/' + db
  57. return url
  58. @contextmanager
  59. def connect():
  60. "Connect to a database. This context manager yields the connection, and closes it when exited."
  61. _log.info('connecting to %s', db_url())
  62. conn = psycopg2.connect(db_url())
  63. try:
  64. yield conn
  65. finally:
  66. conn.close()
  67. def _tokens(s, start=-1, skip_ws=True, skip_cm=True):
  68. i, t = s.token_next(start, skip_ws=skip_ws, skip_cm=skip_cm)
  69. while t is not None:
  70. yield t
  71. i, t = s.token_next(i, skip_ws=skip_ws, skip_cm=skip_cm)
  72. def describe_statement(s):
  73. "Describe an SQL statement. This utility function is used to summarize statements."
  74. label = s.get_type()
  75. li, lt = s.token_next(-1, skip_cm=True)
  76. if lt is None:
  77. return None
  78. if lt and lt.ttype == sqlparse.tokens.DDL:
  79. # DDL - build up!
  80. parts = []
  81. first = True
  82. skipping = False
  83. for t in _tokens(s, li):
  84. if not first:
  85. if isinstance(t, sqlparse.sql.Identifier) or isinstance(t, sqlparse.sql.Function):
  86. parts.append(t.normalized)
  87. break
  88. elif t.ttype != sqlparse.tokens.Keyword:
  89. break
  90. first = False
  91. if t.normalized == 'IF':
  92. skipping = True
  93. if not skipping:
  94. parts.append(t.normalized)
  95. label = label + ' ' + ' '.join(parts)
  96. elif label == 'UNKNOWN':
  97. ls = []
  98. for t in _tokens(s):
  99. if t.ttype == sqlparse.tokens.Keyword:
  100. ls.append(t.normalized)
  101. else:
  102. break
  103. if ls:
  104. label = ' '.join(ls)
  105. name = s.get_real_name()
  106. if name:
  107. label += f' {name}'
  108. return label
  109. def is_empty(s):
  110. "check if an SQL statement is empty"
  111. lt = s.token_first(skip_cm=True, skip_ws=True)
  112. return lt is None
  113. class ScriptChunk(NamedTuple):
  114. "A single chunk of an SQL script."
  115. label: str
  116. allowed_errors: List[str]
  117. src: str
  118. use_transaction: bool = True
  119. @property
  120. def statements(self):
  121. return [s for s in sqlparse.parse(self.src) if not is_empty(s)]
  122. class SqlScript:
  123. """
  124. Class for processing & executing SQL scripts with the following features ``psql``
  125. does not have:
  126. * Splitting the script into (named) steps, to commit chunks in transactions
  127. * Recording metadata (currently just dependencies) for the script
  128. * Allowing chunks to fail with specific errors
  129. The last feature is to help with writing _idempotent_ scripts: by allowing a chunk
  130. to fail with a known error (e.g. creating a constraint that already exists), you
  131. can write a script that can run cleanly even if it has already been run.
  132. Args:
  133. file: the path to the SQL script to read.
  134. """
  135. _sep_re = re.compile(r'^---\s*(?P<inst>.*)')
  136. _icode_re = re.compile(r'#(?P<code>\w+)\s*(?P<args>.*\S)?\s*$')
  137. chunks: List[ScriptChunk]
  138. def __init__(self, file):
  139. if hasattr(file, 'read'):
  140. self._parse(peekable(file))
  141. else:
  142. with open(file, 'r', encoding='utf8') as f:
  143. self._parse(peekable(f))
  144. def _parse(self, lines):
  145. self.chunks = []
  146. self.deps, self.tables = self._parse_script_header(lines)
  147. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  148. while next_chunk is not None:
  149. if next_chunk:
  150. self.chunks.append(next_chunk)
  151. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  152. @classmethod
  153. def _parse_script_header(cls, lines):
  154. deps = []
  155. tables = []
  156. line = lines.peek(None)
  157. while line is not None:
  158. hm = cls._sep_re.match(line)
  159. if hm is None:
  160. break
  161. inst = hm.group('inst')
  162. cm = cls._icode_re.match(inst)
  163. if cm is None:
  164. next(lines) # eat line
  165. continue
  166. code = cm.group('code')
  167. args = cm.group('args')
  168. if code == 'dep':
  169. deps.append(args)
  170. next(lines) # eat line
  171. elif code == 'table':
  172. parts = args.split('.', 2)
  173. if len(parts) > 1:
  174. ns, tbl = parts
  175. tables.append((ns, tbl))
  176. else:
  177. tables.append(('public', args))
  178. next(lines) # eat line
  179. else: # any other code, we're out of header
  180. break
  181. line = lines.peek(None)
  182. return deps, tables
  183. @classmethod
  184. def _parse_chunk(cls, lines: peekable, n: int):
  185. qlines = []
  186. chunk = cls._read_header(lines)
  187. qlines = cls._read_query(lines)
  188. # end of file, do we have a chunk?
  189. if qlines:
  190. if chunk.label is None:
  191. chunk = chunk._replace(label=f'Step {n}')
  192. return chunk._replace(src='\n'.join(qlines))
  193. elif qlines is not None:
  194. return False # empty chunk
  195. @classmethod
  196. def _read_header(cls, lines: peekable):
  197. label = None
  198. errs = []
  199. tx = True
  200. line = lines.peek(None)
  201. while line is not None:
  202. hm = cls._sep_re.match(line)
  203. if hm is None:
  204. break
  205. next(lines) # eat line
  206. line = lines.peek(None)
  207. inst = hm.group('inst')
  208. cm = cls._icode_re.match(inst)
  209. if cm is None:
  210. continue
  211. code = cm.group('code')
  212. args = cm.group('args')
  213. if code == 'step':
  214. label = args
  215. elif code == 'allow':
  216. err = getattr(psycopg2.errorcodes, args.upper())
  217. _log.debug('step allows error %s (%s)', args, err)
  218. errs.append(err)
  219. elif code == 'notx':
  220. _log.debug('chunk will run outside a transaction')
  221. tx = False
  222. else:
  223. _log.error('unrecognized query instruction %s', code)
  224. raise ValueError(f'invalid query instruction {code}')
  225. return ScriptChunk(label=label, allowed_errors=errs, src=None,
  226. use_transaction=tx)
  227. @classmethod
  228. def _read_query(cls, lines: peekable):
  229. qls = []
  230. line = lines.peek(None)
  231. while line is not None and not cls._sep_re.match(line):
  232. qls.append(next(lines))
  233. line = lines.peek(None)
  234. # trim lines
  235. while qls and not qls[0].strip():
  236. qls.pop(0)
  237. while qls and not qls[-1].strip():
  238. qls.pop(-1)
  239. if qls or line is not None:
  240. return qls
  241. else:
  242. return None # end of file
  243. def execute(self, dbc, transcript=None):
  244. """
  245. Execute the SQL script.
  246. Args:
  247. dbc: the database connection.
  248. transcript: a file to receive the run transcript.
  249. """
  250. all_st = time.perf_counter()
  251. for step in self.chunks:
  252. start = time.perf_counter()
  253. _log.info('Running ‘%s’', step.label)
  254. if transcript is not None:
  255. print('CHUNK', step.label, file=transcript)
  256. if step.use_transaction:
  257. with dbc, dbc.cursor() as cur:
  258. self._run_step(step, dbc, cur, True, transcript)
  259. else:
  260. ac = dbc.autocommit
  261. try:
  262. dbc.autocommit = True
  263. with dbc.cursor() as cur:
  264. self._run_step(step, dbc, cur, False, transcript)
  265. finally:
  266. dbc.autocommit = ac
  267. elapsed = time.perf_counter() - start
  268. elapsed = timedelta(seconds=elapsed)
  269. print('CHUNK ELAPSED', elapsed, file=transcript)
  270. _log.info('Finished ‘%s’ in %s', step.label, compress_date(elapsed))
  271. elapsed = time.perf_counter() - all_st
  272. elasped = timedelta(seconds=elapsed)
  273. _log.info('Script completed in %s', compress_date(elapsed))
  274. def describe(self):
  275. for dep in self.deps:
  276. _log.info('Dependency ‘%s’', dep)
  277. for step in self.chunks:
  278. _log.info('Chunk ‘%s’', step.label)
  279. for s in step.statements:
  280. _log.info('Statement %s', describe_statement(s))
  281. def _run_step(self, step, dbc, cur, commit, transcript):
  282. try:
  283. for sql in step.statements:
  284. start = time.perf_counter()
  285. _log.debug('Executing %s', describe_statement(sql))
  286. _log.debug('Query: %s', sql)
  287. if transcript is not None:
  288. print('STMT', describe_statement(sql), file=transcript)
  289. cur.execute(str(sql))
  290. elapsed = time.perf_counter() - start
  291. elapsed = timedelta(seconds=elapsed)
  292. rows = cur.rowcount
  293. if transcript is not None:
  294. print('ELAPSED', elapsed, file=transcript)
  295. if rows is not None and rows >= 0:
  296. if transcript is not None:
  297. print('ROWS', rows, file=transcript)
  298. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  299. compress_date(elapsed), rows)
  300. else:
  301. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  302. compress_date(elapsed), rows)
  303. if commit:
  304. dbc.commit()
  305. except psycopg2.Error as e:
  306. if e.pgcode in step.allowed_errors:
  307. _log.info('Failed with acceptable error %s (%s)',
  308. e.pgcode, psycopg2.errorcodes.lookup(e.pgcode))
  309. if transcript is not None:
  310. print('ERROR', e.pgcode, psycopg2.errorcodes.lookup(e.pgcode), file=transcript)
  311. else:
  312. _log.error('Error in "%s" %s: %s: %s',
  313. step.label, describe_statement(sql),
  314. psycopg2.errorcodes.lookup(e.pgcode), e)
  315. if e.pgerror:
  316. _log.info('Query diagnostics:\n%s', e.pgerror)
  317. raise e
  318. class _LoadThread(threading.Thread):
  319. """
  320. Thread worker for copying database results to a stream we can read.
  321. """
  322. def __init__(self, dbc, query, dir='out'):
  323. super().__init__()
  324. self.database = dbc
  325. self.query = query
  326. rfd, wfd = os.pipe()
  327. self.reader = os.fdopen(rfd)
  328. self.writer = os.fdopen(wfd, 'w')
  329. self.chan = self.writer if dir == 'out' else self.reader
  330. def run(self):
  331. with self.chan, self.database.cursor() as cur:
  332. cur.copy_expert(self.query, self.chan)
  333. def load_table(dbc, query):
  334. """
  335. Load a query into a Pandas data frame.
  336. This is substantially more efficient than Pandas ``read_sql``, because it directly
  337. streams CSV data from the database instead of going through SQLAlchemy.
  338. """
  339. cq = sql.SQL('COPY ({}) TO STDOUT WITH CSV HEADER')
  340. q = sql.SQL(query)
  341. thread = _LoadThread(dbc, cq.format(q))
  342. thread.start()
  343. data = pd.read_csv(thread.reader)
  344. thread.join()
  345. return data
  346. def save_table(dbc, table, data: pd.DataFrame):
  347. """
  348. Save a table from a Pandas data frame.
  349. This is substantially more efficient than Pandas ``read_sql``, because it directly
  350. streams CSV data from the database instead of going through SQLAlchemy.
  351. """
  352. cq = sql.SQL('COPY {} FROM STDIN WITH CSV')
  353. thread = _LoadThread(dbc, cq.format(table), 'in')
  354. thread.start()
  355. data.to_csv(thread.writer, header=False, index=False)
  356. thread.writer.close()
  357. thread.join()
Tip!

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

Comments

Loading...