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

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

Comments

Loading...