-
Notifications
You must be signed in to change notification settings - Fork 17
/
dbt_docs_to_notion.py
516 lines (482 loc) · 13.4 KB
/
dbt_docs_to_notion.py
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
import json
import os
import sys
import time
import requests
DATABASE_PARENT_ID = os.environ['DATABASE_PARENT_ID']
DATABASE_NAME = os.environ['DATABASE_NAME']
NOTION_TOKEN = os.environ['NOTION_TOKEN']
NUMERIC_ZERO_VALUE = -1
def make_request(endpoint, querystring='', method='GET', **request_kwargs):
time.sleep(0.34) # notion api limit is 3 requests per second
headers = {
'Authorization': NOTION_TOKEN,
'Content-Type': 'application/json',
'Notion-Version': '2022-02-22'
}
url = f'https://api.notion.com/v1/{endpoint}{querystring}'
resp = requests.request(method, url, headers=headers, **request_kwargs)
if not resp.status_code == 200:
raise Exception(
f"Request returned status code {resp.status_code}\nResponse text: {resp.text}"
)
return resp.json()
def get_paths_or_empty(parent_object, paths_array, zero_value=''):
"""Used for catalog_nodes accesses, since structure is variable"""
for path in paths_array:
obj = parent_object
for el in path:
if el not in obj:
obj = zero_value
break
obj = obj[el]
if obj != zero_value:
return obj
return zero_value
def get_owner(data, catalog_nodes, model_name):
"""
Check for an owner field explicitly named in the DBT Config
If none present, fall back to database table owner
"""
owner = get_paths_or_empty(data, [['config', 'meta', 'owner']], None)
if owner is not None:
return owner
return get_paths_or_empty(catalog_nodes, [[model_name, 'metadata', 'owner']], '')
def main(argv=None):
if argv is None:
argv = sys.argv
model_records_to_write = argv[1:] # 'all' or list of model names
print(f'Model records to write: {model_records_to_write}')
###### load nodes from dbt docs ######
with open('target/manifest.json', encoding='utf-8') as f:
manifest = json.load(f)
manifest_nodes = manifest['nodes']
with open('target/catalog.json', encoding='utf-8') as f:
catalog = json.load(f)
catalog_nodes = catalog['nodes']
models = {node_name: data
for (node_name, data)
in manifest_nodes.items() if data['resource_type'] == 'model'}
###### create database if not exists ######
children_query_resp = make_request(
endpoint='blocks/',
querystring=f'{DATABASE_PARENT_ID}/children',
method='GET'
)
database_id = ''
for child in children_query_resp['results']:
if('child_database' in child
and child['child_database'] == {'title': DATABASE_NAME}):
database_id = child['id']
break
if database_id:
print(f'database {database_id} already exists, proceeding to update records!')
else:
database_obj = {
"title": [
{
"type": "text",
"text": {
"content": DATABASE_NAME,
"link": None
}
}
],
"parent": {
"type": "page_id",
"page_id": DATABASE_PARENT_ID
},
"properties": {
"Name": {
"title": {}
},
"Description": {
"rich_text": {}
},
"Owner": {
"rich_text": {}
},
"Relation": {
"rich_text": {}
},
"Approx Rows": {
"number": {
"format": "number_with_commas"
}
},
"Approx GB": {
"number": {
"format": "number_with_commas"
}
},
"Depends On": {
"rich_text": {}
},
"Tags": {
"rich_text": {}
}
}
}
print('creating database')
database_creation_resp = make_request(
endpoint='databases/',
querystring='',
method='POST',
json=database_obj
)
database_id = database_creation_resp['id']
print(f'\ncreated database {database_id}, proceeding to create records!')
##### create / update database records #####
for model_name, data in sorted(list(models.items()), reverse=True):
if model_records_to_write == ['all'] or model_name in model_records_to_write:
# form record object
column_descriptions = {name: metadata['description']
for name, metadata
in data['columns'].items()}
columns_table_children_obj = [
{
"type": "table_row",
"table_row": {
"cells": [
[
{
"type": "text",
"text": {
"content": "Column"
},
"plain_text": "Column"
}
],
[
{
"type": "text",
"text": {
"content": "Type"
},
"plain_text": "Type"
}
],
[
{
"type": "text",
"text": {
"content": "Description"
},
"plain_text": "Description"
}
]
]
}
}
]
col_names_and_data = list(get_paths_or_empty(
catalog_nodes,
[[model_name, 'columns']],
{}
).items())
for (col_name, col_data) in col_names_and_data[:98]: # notion api limit is 100 table rows
columns_table_children_obj.append(
{
"type": "table_row",
"table_row": {
"cells": [
[
{
"type": "text",
"text": {
"content": col_name
},
"plain_text": col_name
}
],
[
{
"type": "text",
"text": {
"content": col_data['type']
},
"plain_text": col_data['type']
}
],
[
{
"type": "text",
"text": {
"content": (
column_descriptions[col_name.lower()]
if col_name.lower() in column_descriptions
else ''
)
},
"plain_text": (
column_descriptions[col_name.lower()]
if col_name.lower() in column_descriptions
else ''
)
}
]
]
}
}
)
if len(col_names_and_data) > 98:
# make that columns have been truncated
columns_table_children_obj.append(
{
"type": "table_row",
"table_row": {
"cells": [
[
{
"type": "text",
"text": {
"content": "..."
},
"plain_text": "..."
}
],
[
{
"type": "text",
"text": {
"content": "..."
},
"plain_text": "..."
}
],
[
{
"type": "text",
"text": {
"content": "..."
},
"plain_text": "..."
}
]
]
}
}
)
record_children_obj = [
# Table of contents
{
"object": "block",
"type": "table_of_contents",
"table_of_contents": {
"color": "default"
}
},
# Columns
{
"object": "block",
"type": "heading_1",
"heading_1": {
"rich_text": [
{
"type": "text",
"text": { "content": "Columns" }
}
]
}
},
{
"object": "block",
"type": "table",
"table": {
"table_width": 3,
"has_column_header": True,
"has_row_header": False,
"children": columns_table_children_obj
}
},
# Raw Code
{
"object": "block",
"type": "heading_1",
"heading_1": {
"rich_text": [
{
"type": "text",
"text": { "content": "Raw Code" }
}
]
}
},
{
"object": "block",
"type": "code",
"code": {
"rich_text": [
{
"type": "text",
"text": {
"content": data['raw_code'][:2000] if 'raw_code' in data else data['raw_sql'][:2000]
}
}
],
"language": "sql"
}
},
# Compiled Code
{
"object": "block",
"type": "heading_1",
"heading_1": {
"rich_text": [
{
"type": "text",
"text": { "content": "Compiled Code" }
}
]
}
},
{
"object": "block",
"type": "code",
"code": {
"rich_text": [
{
"type": "text",
"text": {
"content": data['compiled_code'][:2000] if 'compiled_code' in data else data['compiled_sql'][:2000]
}
}
],
"language": "sql"
}
}
]
record_obj = {
"parent": {
"database_id": database_id
},
"properties": {
"Name": {
"title": [
{
"text": {
"content": data['name']
}
}
]
},
"Description": {
"rich_text": [
{
"text": {
"content": data['description'][:2000]
# notion api limit is 2k characters per rich text block
}
}
]
},
"Owner": {
"rich_text": [
{
"text": {
"content": str(
get_owner(data, catalog_nodes, model_name)
)[:2000]
}
}
]
},
"Relation": {
"rich_text": [
{
"text": {
"content": data['relation_name'][:2000] if data['relation_name'] else ""
}
}
]
},
"Approx Rows": {
"number": get_paths_or_empty(
catalog_nodes,
[[model_name, 'stats', 'num_rows', 'value'],
[model_name, 'stats', 'row_count', 'value']],
NUMERIC_ZERO_VALUE
)
},
"Approx GB": {
"number": get_paths_or_empty(
catalog_nodes,
[[model_name, 'stats', 'bytes', 'value'],
[model_name, 'stats', 'num_bytes', 'value']],
NUMERIC_ZERO_VALUE
) / 1e9
},
"Depends On": {
"rich_text": [
{
"text": {
"content": json.dumps(data['depends_on'])[:2000]
}
}
]
},
"Tags": {
"rich_text": [
{
"text": {
"content": json.dumps(data['tags'])[:2000]
}
}
]
}
}
}
###### query to see if record already exists ######
query_obj = {
"filter": {
"property": "Name",
"title": {
"equals": data['name']
}
}
}
record_query_resp = make_request(
endpoint='databases/',
querystring=f'{database_id}/query',
method='POST',
json=query_obj
)
if record_query_resp['results']:
print(f'\nupdating {model_name} record')
record_id = record_query_resp['results'][0]['id']
_record_update_resp = make_request(
endpoint=f'pages/{record_id}',
querystring='',
method='PATCH',
json=record_obj
)
# children can't be updated via record update, so we'll delete and re-add
record_children_resp = make_request(
endpoint='blocks/',
querystring=f'{record_id}/children',
method='GET'
)
for record_child in record_children_resp['results']:
record_child_id = record_child['id']
_record_child_deletion_resp = make_request(
endpoint='blocks/',
querystring=record_child_id,
method='DELETE'
)
_record_children_replacement_resp = make_request(
endpoint='blocks/',
querystring=f'{record_id}/children',
method='PATCH',
json={"children": record_children_obj}
)
else:
print(f'\ncreating {model_name} record')
record_obj['children'] = record_children_obj
_record_creation_resp = make_request(
endpoint='pages/',
querystring='',
method='POST',
json=record_obj
)
if __name__ == '__main__':
main()