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 11 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
  1. import os
  2. import sys
  3. import re
  4. import time
  5. import logging
  6. import hashlib
  7. from pathlib import Path
  8. from contextlib import contextmanager
  9. from datetime import timedelta
  10. from typing import NamedTuple, List
  11. from docopt import docopt
  12. from more_itertools import peekable
  13. import psycopg2, psycopg2.errorcodes
  14. import sqlparse
  15. _log = logging.getLogger(__name__)
  16. # Meta-schema for storing stage and file status in the database
  17. meta_schema = """
  18. CREATE TABLE IF NOT EXISTS stage_status (
  19. stage_name VARCHAR PRIMARY KEY,
  20. started_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  21. finished_at TIMESTAMP NULL,
  22. stage_key VARCHAR NULL
  23. );
  24. CREATE TABLE IF NOT EXISTS source_file (
  25. filename VARCHAR NOT NULL PRIMARY KEY,
  26. reg_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  27. checksum VARCHAR NOT NULL
  28. );
  29. CREATE TABLE IF NOT EXISTS stage_file (
  30. stage_name VARCHAR NOT NULL REFERENCES stage_status,
  31. filename VARCHAR NOT NULL REFERENCES source_file
  32. );
  33. INSERT INTO stage_status (stage_name, started_at, finished_at, stage_key)
  34. VALUES ('init', NOW(), NOW(), uuid_generate_v4())
  35. ON CONFLICT (stage_name) DO NOTHING;
  36. """
  37. def db_url():
  38. if 'DB_URL' in os.environ:
  39. return os.environ['DB_URL']
  40. host = os.environ.get('PGHOST', 'localhost')
  41. port = os.environ.get('PGPORT', None)
  42. db = os.environ['PGDATABASE']
  43. user = os.environ.get('PGUSER', None)
  44. pw = os.environ.get('PGPASSWORD', None)
  45. url = 'postgresql://'
  46. if user:
  47. url += user
  48. if pw:
  49. url += ':' + pw
  50. url += '@'
  51. url += host
  52. if port:
  53. url += ':' + port
  54. url += '/' + db
  55. return url
  56. @contextmanager
  57. def connect():
  58. "Connect to a database. This context manager yields the connection, and closes it when exited."
  59. _log.info('connecting to %s', db_url())
  60. conn = psycopg2.connect(db_url())
  61. try:
  62. yield conn
  63. finally:
  64. conn.close()
  65. def save_file(cur, path, stage=None):
  66. h = hashlib.md5()
  67. with open(path, 'rb') as f:
  68. data = f.read(8192 * 4)
  69. while data:
  70. h.update(data)
  71. data = f.read(8192 * 4)
  72. hash = h.hexdigest()
  73. path = Path(path).as_posix()
  74. _log.info('recording file %s with hash %s', path, hash)
  75. cur.execute('''
  76. INSERT INTO source_file (filename, checksum)
  77. VALUES (%(fn)s, %(hash)s)
  78. ON CONFLICT (filename)
  79. DO UPDATE SET reg_time = now(), checksum = %(hash)s
  80. ''', {'fn': path, 'hash': hash})
  81. if stage:
  82. cur.execute('''
  83. INSERT INTO stage_file (stage_name, filename)
  84. VALUES (%s, %s)
  85. ''', [stage, path])
  86. def start_stage(cur, stage):
  87. if hasattr(cur, 'cursor'):
  88. # this is a connection
  89. with cur, cur.cursor() as c:
  90. start_stage(c, stage)
  91. _log.info('starting or resetting stage %s', stage)
  92. cur.execute('''
  93. INSERT INTO stage_status (stage_name)
  94. VALUES (%s)
  95. ON CONFLICT (stage_name)
  96. DO UPDATE SET started_at = now(), finished_at = NULL, stage_key = NULL
  97. ''', [stage])
  98. cur.execute('DELETE FROM stage_file WHERE stage_name = %s', [stage])
  99. def finish_stage(cur, stage, key=None):
  100. if hasattr(cur, 'cursor'):
  101. # this is a connection
  102. with cur, cur.cursor() as c:
  103. finish_stage(c, stage, key)
  104. _log.info('finishing stage %s', stage)
  105. cur.execute('''
  106. UPDATE stage_status
  107. SET finished_at = NOW(), stage_key = %(key)s
  108. WHERE stage_name = %(stage)s
  109. ''', {'stage': stage, 'key': key})
  110. def _tokens(s, start=-1, skip_ws=True, skip_cm=True):
  111. i, t = s.token_next(start, skip_ws=skip_ws, skip_cm=skip_cm)
  112. while t is not None:
  113. yield t
  114. i, t = s.token_next(i, skip_ws=skip_ws, skip_cm=skip_cm)
  115. def describe_statement(s):
  116. "Describe an SQL statement"
  117. label = s.get_type()
  118. li, lt = s.token_next(-1, skip_cm=True)
  119. if lt is None:
  120. return None
  121. if lt and lt.ttype == sqlparse.tokens.DDL:
  122. # DDL - build up!
  123. parts = []
  124. first = True
  125. skipping = False
  126. for t in _tokens(s, li):
  127. if not first:
  128. if isinstance(t, sqlparse.sql.Identifier) or isinstance(t, sqlparse.sql.Function):
  129. parts.append(t.normalized)
  130. break
  131. elif t.ttype != sqlparse.tokens.Keyword:
  132. break
  133. first = False
  134. if t.normalized == 'IF':
  135. skipping = True
  136. if not skipping:
  137. parts.append(t.normalized)
  138. label = label + ' ' + ' '.join(parts)
  139. elif label == 'UNKNOWN':
  140. ls = []
  141. for t in _tokens(s):
  142. if t.ttype == sqlparse.tokens.Keyword:
  143. ls.append(t.normalized)
  144. else:
  145. break
  146. if ls:
  147. label = ' '.join(ls)
  148. name = s.get_real_name()
  149. if name:
  150. label += f' {name}'
  151. return label
  152. def is_empty(s):
  153. "check if an SQL statement is empty"
  154. lt = s.token_first(skip_cm=True, skip_ws=True)
  155. return lt is None
  156. class ScriptChunk(NamedTuple):
  157. "A single chunk of an SQL script."
  158. label: str
  159. allowed_errors: List[str]
  160. src: str
  161. use_transaction: bool = True
  162. @property
  163. def statements(self):
  164. return [s for s in sqlparse.parse(self.src) if not is_empty(s)]
  165. class SqlScript:
  166. """
  167. Class for processing & executing SQL scripts.
  168. """
  169. _sep_re = re.compile(r'^---\s*(?P<inst>.*)')
  170. _icode_re = re.compile(r'#(?P<code>\w+)\s*(?P<args>.*\S)?\s*$')
  171. chunks: List[ScriptChunk]
  172. def __init__(self, file):
  173. if hasattr(file, 'read'):
  174. self._parse(peekable(file))
  175. else:
  176. with open(file, 'r', encoding='utf8') as f:
  177. self._parse(peekable(f))
  178. def _parse(self, lines):
  179. self.chunks = []
  180. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  181. while next_chunk is not None:
  182. if next_chunk:
  183. self.chunks.append(next_chunk)
  184. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  185. @classmethod
  186. def _parse_chunk(cls, lines: peekable, n: int):
  187. qlines = []
  188. chunk = cls._read_header(lines)
  189. qlines = cls._read_query(lines)
  190. # end of file, do we have a chunk?
  191. if qlines:
  192. if chunk.label is None:
  193. chunk = chunk._replace(label=f'Step {n}')
  194. return chunk._replace(src='\n'.join(qlines))
  195. elif qlines is not None:
  196. return False # empty chunk
  197. @classmethod
  198. def _read_header(cls, lines: peekable):
  199. label = None
  200. errs = []
  201. tx = True
  202. line = lines.peek(None)
  203. while line is not None:
  204. hm = cls._sep_re.match(line)
  205. if hm is None:
  206. break
  207. next(lines) # eat line
  208. line = lines.peek(None)
  209. inst = hm.group('inst')
  210. cm = cls._icode_re.match(inst)
  211. if cm is None:
  212. continue
  213. code = cm.group('code')
  214. args = cm.group('args')
  215. if code == 'step':
  216. label = args
  217. elif code == 'allow':
  218. err = getattr(psycopg2.errorcodes, args.upper())
  219. _log.debug('step allows error %s (%s)', args, err)
  220. errs.append(err)
  221. elif code == 'notx':
  222. _log.debug('chunk will run outside a transaction')
  223. tx = False
  224. else:
  225. _log.error('unrecognized query instruction %s', code)
  226. raise ValueError(f'invalid query instruction {code}')
  227. return ScriptChunk(label=label, allowed_errors=errs, src=None,
  228. use_transaction=tx)
  229. @classmethod
  230. def _read_query(cls, lines: peekable):
  231. qls = []
  232. line = lines.peek(None)
  233. while line is not None and not cls._sep_re.match(line):
  234. qls.append(next(lines))
  235. line = lines.peek(None)
  236. # trim lines
  237. while qls and not qls[0].strip():
  238. qls.pop(0)
  239. while qls and not qls[-1].strip():
  240. qls.pop(-1)
  241. if qls or line is not None:
  242. return qls
  243. else:
  244. return None # end of file
  245. def execute(self, dbc, transcript=None):
  246. """
  247. Execute the SQL script.
  248. Args:
  249. dbc: the database connection.
  250. transcript: a file to receive the run transcript.
  251. """
  252. for step in self.chunks:
  253. start = time.perf_counter()
  254. _log.info('Running ‘%s’', step.label)
  255. if transcript is not None:
  256. print('CHUNK', step.label, file=transcript)
  257. if step.use_transaction:
  258. with dbc, dbc.cursor() as cur:
  259. self._run_step(step, dbc, cur, True, transcript)
  260. else:
  261. ac = dbc.autocommit
  262. try:
  263. dbc.autocommit = True
  264. with dbc.cursor() as cur:
  265. self._run_step(step, dbc, cur, False, transcript)
  266. finally:
  267. dbc.autocommit = ac
  268. elapsed = time.perf_counter() - start
  269. elapsed = timedelta(seconds=elapsed)
  270. _log.info('Finished ‘%s’ in %s', step.label, elapsed)
  271. def describe(self):
  272. for step in self.chunks:
  273. _log.info('Chunk ‘%s’', step.label)
  274. for s in step.statements:
  275. _log.info('Statement %s', describe_statement(s))
  276. def _run_step(self, step, dbc, cur, commit, transcript):
  277. try:
  278. for sql in step.statements:
  279. start = time.perf_counter()
  280. _log.debug('Executing %s', describe_statement(sql))
  281. _log.debug('Query: %s', sql)
  282. if transcript is not None:
  283. print('STMT', describe_statement(sql), file=transcript)
  284. cur.execute(str(sql))
  285. elapsed = time.perf_counter() - start
  286. rows = cur.rowcount
  287. if transcript is not None:
  288. print('ELAPSED', elapsed, file=transcript)
  289. if rows is not None and rows >= 0:
  290. if transcript is not None:
  291. print('ROWS', rows, file=transcript)
  292. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  293. timedelta(seconds=elapsed), rows)
  294. else:
  295. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  296. timedelta(seconds=elapsed), rows)
  297. if commit:
  298. dbc.commit()
  299. except psycopg2.Error as e:
  300. if e.pgcode in step.allowed_errors:
  301. _log.info('Failed with acceptable error %s (%s)',
  302. e.pgcode, psycopg2.errorcodes.lookup(e.pgcode))
  303. if transcript is not None:
  304. print('ERROR', e.pgcode, psycopg2.errorcodes.lookup(e.pgcode), file=transcript)
  305. else:
  306. _log.error('Error in "%s" %s: %s: %s',
  307. step.label, describe_statement(sql),
  308. psycopg2.errorcodes.lookup(e.pgcode), e)
  309. if e.pgerror:
  310. _log.info('Query diagnostics:\n%s', e.pgerror)
  311. raise e
Tip!

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

Comments

Loading...