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
  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 natural.date import compress as compress_date
  13. from more_itertools import peekable
  14. import psycopg2, psycopg2.errorcodes
  15. import sqlparse
  16. _log = logging.getLogger(__name__)
  17. # Meta-schema for storing stage and file status in the database
  18. _ms_path = Path(__file__).parent.parent / 'schemas' / 'meta-schema.sql'
  19. meta_schema = _ms_path.read_text()
  20. def db_url():
  21. if 'DB_URL' in os.environ:
  22. return os.environ['DB_URL']
  23. host = os.environ.get('PGHOST', 'localhost')
  24. port = os.environ.get('PGPORT', None)
  25. db = os.environ['PGDATABASE']
  26. user = os.environ.get('PGUSER', None)
  27. pw = os.environ.get('PGPASSWORD', None)
  28. url = 'postgresql://'
  29. if user:
  30. url += user
  31. if pw:
  32. url += ':' + pw
  33. url += '@'
  34. url += host
  35. if port:
  36. url += ':' + port
  37. url += '/' + db
  38. return url
  39. @contextmanager
  40. def connect():
  41. "Connect to a database. This context manager yields the connection, and closes it when exited."
  42. _log.info('connecting to %s', db_url())
  43. conn = psycopg2.connect(db_url())
  44. try:
  45. yield conn
  46. finally:
  47. conn.close()
  48. def save_file(cur, path, stage=None):
  49. h = hashlib.md5()
  50. with open(path, 'rb') as f:
  51. data = f.read(8192 * 4)
  52. while data:
  53. h.update(data)
  54. data = f.read(8192 * 4)
  55. hash = h.hexdigest()
  56. path = Path(path).as_posix()
  57. _log.info('recording file %s with hash %s', path, hash)
  58. cur.execute('''
  59. INSERT INTO source_file (filename, checksum)
  60. VALUES (%(fn)s, %(hash)s)
  61. ON CONFLICT (filename)
  62. DO UPDATE SET reg_time = now(), checksum = %(hash)s
  63. ''', {'fn': path, 'hash': hash})
  64. if stage:
  65. cur.execute('''
  66. INSERT INTO stage_file (stage_name, filename)
  67. VALUES (%s, %s)
  68. ''', [stage, path])
  69. def start_stage(cur, stage):
  70. if hasattr(cur, 'cursor'):
  71. # this is a connection
  72. with cur, cur.cursor() as c:
  73. start_stage(c, stage)
  74. _log.info('starting or resetting stage %s', stage)
  75. cur.execute('''
  76. INSERT INTO stage_status (stage_name)
  77. VALUES (%s)
  78. ON CONFLICT (stage_name)
  79. DO UPDATE SET started_at = now(), finished_at = NULL, stage_key = NULL
  80. ''', [stage])
  81. cur.execute('DELETE FROM stage_file WHERE stage_name = %s', [stage])
  82. def finish_stage(cur, stage, key=None):
  83. if hasattr(cur, 'cursor'):
  84. # this is a connection
  85. with cur, cur.cursor() as c:
  86. finish_stage(c, stage, key)
  87. _log.info('finishing stage %s', stage)
  88. cur.execute('''
  89. UPDATE stage_status
  90. SET finished_at = NOW(), stage_key = %(key)s
  91. WHERE stage_name = %(stage)s
  92. ''', {'stage': stage, 'key': key})
  93. def _tokens(s, start=-1, skip_ws=True, skip_cm=True):
  94. i, t = s.token_next(start, skip_ws=skip_ws, skip_cm=skip_cm)
  95. while t is not None:
  96. yield t
  97. i, t = s.token_next(i, skip_ws=skip_ws, skip_cm=skip_cm)
  98. def describe_statement(s):
  99. "Describe an SQL statement"
  100. label = s.get_type()
  101. li, lt = s.token_next(-1, skip_cm=True)
  102. if lt is None:
  103. return None
  104. if lt and lt.ttype == sqlparse.tokens.DDL:
  105. # DDL - build up!
  106. parts = []
  107. first = True
  108. skipping = False
  109. for t in _tokens(s, li):
  110. if not first:
  111. if isinstance(t, sqlparse.sql.Identifier) or isinstance(t, sqlparse.sql.Function):
  112. parts.append(t.normalized)
  113. break
  114. elif t.ttype != sqlparse.tokens.Keyword:
  115. break
  116. first = False
  117. if t.normalized == 'IF':
  118. skipping = True
  119. if not skipping:
  120. parts.append(t.normalized)
  121. label = label + ' ' + ' '.join(parts)
  122. elif label == 'UNKNOWN':
  123. ls = []
  124. for t in _tokens(s):
  125. if t.ttype == sqlparse.tokens.Keyword:
  126. ls.append(t.normalized)
  127. else:
  128. break
  129. if ls:
  130. label = ' '.join(ls)
  131. name = s.get_real_name()
  132. if name:
  133. label += f' {name}'
  134. return label
  135. def is_empty(s):
  136. "check if an SQL statement is empty"
  137. lt = s.token_first(skip_cm=True, skip_ws=True)
  138. return lt is None
  139. class ScriptChunk(NamedTuple):
  140. "A single chunk of an SQL script."
  141. label: str
  142. allowed_errors: List[str]
  143. src: str
  144. use_transaction: bool = True
  145. @property
  146. def statements(self):
  147. return [s for s in sqlparse.parse(self.src) if not is_empty(s)]
  148. class SqlScript:
  149. """
  150. Class for processing & executing SQL scripts.
  151. """
  152. _sep_re = re.compile(r'^---\s*(?P<inst>.*)')
  153. _icode_re = re.compile(r'#(?P<code>\w+)\s*(?P<args>.*\S)?\s*$')
  154. chunks: List[ScriptChunk]
  155. def __init__(self, file):
  156. if hasattr(file, 'read'):
  157. self._parse(peekable(file))
  158. else:
  159. with open(file, 'r', encoding='utf8') as f:
  160. self._parse(peekable(f))
  161. def _parse(self, lines):
  162. self.chunks = []
  163. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  164. while next_chunk is not None:
  165. if next_chunk:
  166. self.chunks.append(next_chunk)
  167. next_chunk = self._parse_chunk(lines, len(self.chunks) + 1)
  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 step in self.chunks:
  261. _log.info('Chunk ‘%s’', step.label)
  262. for s in step.statements:
  263. _log.info('Statement %s', describe_statement(s))
  264. def _run_step(self, step, dbc, cur, commit, transcript):
  265. try:
  266. for sql in step.statements:
  267. start = time.perf_counter()
  268. _log.debug('Executing %s', describe_statement(sql))
  269. _log.debug('Query: %s', sql)
  270. if transcript is not None:
  271. print('STMT', describe_statement(sql), file=transcript)
  272. cur.execute(str(sql))
  273. elapsed = time.perf_counter() - start
  274. elapsed = timedelta(seconds=elapsed)
  275. rows = cur.rowcount
  276. if transcript is not None:
  277. print('ELAPSED', elapsed, file=transcript)
  278. if rows is not None and rows >= 0:
  279. if transcript is not None:
  280. print('ROWS', rows, file=transcript)
  281. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  282. compress_date(elapsed), rows)
  283. else:
  284. _log.info('finished %s in %s (%d rows)', describe_statement(sql),
  285. compress_date(elapsed), rows)
  286. if commit:
  287. dbc.commit()
  288. except psycopg2.Error as e:
  289. if e.pgcode in step.allowed_errors:
  290. _log.info('Failed with acceptable error %s (%s)',
  291. e.pgcode, psycopg2.errorcodes.lookup(e.pgcode))
  292. if transcript is not None:
  293. print('ERROR', e.pgcode, psycopg2.errorcodes.lookup(e.pgcode), file=transcript)
  294. else:
  295. _log.error('Error in "%s" %s: %s: %s',
  296. step.label, describe_statement(sql),
  297. psycopg2.errorcodes.lookup(e.pgcode), e)
  298. if e.pgerror:
  299. _log.info('Query diagnostics:\n%s', e.pgerror)
  300. raise e
Tip!

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

Comments

Loading...