forked from OpenDataServices/ocdsdata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathocdsdata.py
1742 lines (1394 loc) · 54.7 KB
/
ocdsdata.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import csv
import datetime
import functools
import gzip
import json
import os
import re
import shutil
import subprocess
import sys
import tempfile
import traceback
import zipfile
from collections import Counter, deque, defaultdict
from pathlib import Path
from retry import retry
from textwrap import dedent
import boto3
import click
import lxml.html
import ocdsmerge
import openpyxl
import orjson
import requests
import sqlalchemy as sa
from codetiming import Timer
from fastavro import parse_schema, writer
from google.cloud import bigquery
from google.cloud.bigquery.dataset import AccessEntry
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from jsonref import JsonRef
from ocdsextensionregistry import ProfileBuilder
from openpyxl.cell.cell import ILLEGAL_CHARACTERS_RE
from scrapy import signals
from scrapy.crawler import CrawlerProcess
from scrapy.spiderloader import SpiderLoader
from scrapy.utils.project import get_project_settings
this_path = Path(__file__).parent.absolute()
collect_path = str((this_path / "kingfisher-collect").absolute())
def _first_doc_line(function):
return function.__doc__.split("\n")[0]
def _patched_schema(connection):
extension_result = connection.execute(
"""
SELECT
extension
FROM
_package_data, jsonb_array_elements(package_data -> 'extensions') extension
WHERE
jsonb_typeof(package_data -> 'extensions') = 'array' group by 1;
"""
)
extensions = [row.extension for row in extension_result]
try:
builder = ProfileBuilder("1__1__4", extensions)
patched_schema = builder.patched_release_schema()
print(f'Exensions being used: {" ".join(extensions)}')
except Exception:
print('Warning: Extensions have not been built defaulting to standard schema')
builder = ProfileBuilder("1__1__4", {})
patched_schema = builder.patched_release_schema()
return patched_schema
@functools.lru_cache(None)
def get_engine(schema=None, db_uri=None, pool_size=1):
"""Get SQLAlchemy engine
Will cache engine if all arguments are the same so not expensive to call multiple times.
Parameters
----------
schema : string, optional
Postgres schema that all queries will use. Defaults to using public schema.
db_url : string, optional
SQLAlchemy database connection string. Will defailt to using `DATABASE_URL` environment variable.
pool_size : int
SQLAlchemy connection pool size
Returns
-------
sqlalchemy.Engine
SQLAlchemy Engine object set up to query specified schema (or public schema)
"""
if not db_uri:
db_uri = os.environ["DATABASE_URL"]
connect_args = {}
if schema:
connect_args = {"options": f"-csearch_path={schema}"}
return sa.create_engine(db_uri, pool_size=pool_size, connect_args=connect_args)
def get_s3_bucket():
"""Get S3 bucket object
Needs environment variables:
`AWS_ACCESS_KEY_ID`,
`AWS_S3_ENDPOINT_URL`,
`AWS_SECRET_ACCESS_KEY`,
`AWS_DEFAULT_REGION`,
`AWS_S3_ENDPOINT_URL`
Returns
-------
s3.Bucket
s3.Bucket object to interact with S3
"""
session = boto3.session.Session()
if not os.environ.get("AWS_ACCESS_KEY_ID"):
return
s3 = session.resource("s3", endpoint_url=os.environ.get("AWS_S3_ENDPOINT_URL"))
bucket = s3.Bucket(os.environ.get("AWS_S3_BUCKET"))
return bucket
def get_drive_service():
json_acct_info = orjson.loads(
base64.b64decode(os.environ["GOOGLE_SERVICE_ACCOUNT"])
)
credentials = service_account.Credentials.from_service_account_info(
json_acct_info
)
return build("drive", "v3", credentials=credentials)
def create_table(table, schema, sql, **params):
"""Create table under given schema by supplying SQL
Parameters
----------
table : string
Postgres schema to use.
schema : string
Postgres schema to use.
sql : string
SQL to create table can be parametarized by SQLAlchemy parms that start with a `:` e.g `:param`.
params : key (string), values (any)
keys are params found in sql and values are the values to be replaced.
"""
print(f"creating table {table}")
t = Timer()
t.start()
engine = get_engine(schema)
with engine.connect() as con:
con.execute(
sa.text(
f"""DROP TABLE IF EXISTS {table};
CREATE TABLE {table}
AS
{sql};"""
),
**params,
)
t.stop()
@click.group()
def cli():
pass
def scraper_list():
"""List of scrapers from kingfisher collect.
Returns
-------
list of str
List of scrapers
"""
os.chdir(collect_path)
settings = get_project_settings()
sl = SpiderLoader.from_settings(settings)
return sl.list()
@cli.command(help=_first_doc_line(scraper_list))
def export_scrapers():
click.echo(json.dumps(scraper_list()))
@cli.command()
@click.argument("name")
@click.argument("schema")
def import_scraper(name, schema):
"""Create all postgres tables for a scraper into a target schema."""
create_schema(schema)
scrape(name, schema)
create_base_tables(schema, drop_scrape=False)
compile_releases(schema)
release_objects(schema)
schema_analysis(schema)
postgres_tables(schema, drop_release_objects=False)
@cli.command()
@click.argument("schema")
@click.argument("name")
@click.argument("date")
def export_all(name, schema, date):
"""Export data to all export soruces from schama given a date."""
export_csv(schema, name, date)
export_xlsx(schema, name, date)
export_sqlite(schema, name, date)
export_bigquery(schema, name, date)
export_stats(schema, name, date)
export_pgdump(schema, name, date)
def create_schema(schema):
"""Create Postgres Schema.
Parameters
----------
schema : string
Postgres schema to create.
"""
engine = get_engine()
with engine.begin() as connection:
connection.execute(
f"""DROP SCHEMA IF EXISTS {schema} CASCADE;
create schema {schema};"""
)
@cli.command("create-schema", help=_first_doc_line(create_schema))
@click.argument("schema")
def _create_schema(schema):
create_schema(schema)
def rename_schema(schema, new_schema):
"""Rename Postgres Schema.
Parameters
----------
schema : string
Postgres schema to rename.
new_schema : string
New schema name.
"""
engine = get_engine()
drop_schema(new_schema)
with engine.begin() as connection:
connection.execute(f"""ALTER SCHEMA "{schema}" RENAME TO "{new_schema}";""")
@cli.command("rename-schema", help=_first_doc_line(rename_schema))
@click.argument("schema")
@click.argument("new_schema")
def _rename_schema(schema, new_schema):
rename_schema(schema, new_schema)
def drop_schema(schema):
"""Drop Postgres Schema.
Parameters
----------
schema : string
Postgres schema to drop.
"""
engine = get_engine()
with engine.begin() as connection:
connection.execute(f"""DROP SCHEMA IF EXISTS {schema} CASCADE;""")
@cli.command("drop-schema", help=_first_doc_line(drop_schema))
@click.argument("schema")
def _drop_schema(schema):
drop_schema(schema)
def scrape(name, schema):
"""Scrape data into postgres.
Creates "_scrape_data" and "_job_info" tables.
Parameters
----------
name : string
Name of scraper.
schema : string
Postgres schema to put scrape data in.
"""
data_dir = this_path / "data" / schema
shutil.rmtree(data_dir, ignore_errors=True)
data_dir.mkdir(parents=True, exist_ok=True)
csv_file_path = data_dir / "all.csv"
engine = get_engine(schema)
with engine.begin() as connection:
connection.execute(
"""DROP TABLE IF EXISTS _scrape_data;
DROP TABLE IF EXISTS _job_info;
CREATE TABLE _scrape_data(id SERIAL, name TEXT, url TEXT, data_type TEXT, file_name TEXT,
valid BOOLEAN, data JSONB, error_data TEXT);
CREATE TABLE _job_info(name TEXT, info JSONB, logs TEXT);
"""
)
os.chdir(collect_path)
settings = get_project_settings()
settings.pop("FILES_STORE")
settings["LOG_FILE"] = str(data_dir / "all.log")
with gzip.open(str(csv_file_path), "wt", newline="") as csv_file:
csv_writer = csv.writer(csv_file)
count_data_types = Counter()
def save_to_csv(item, spider):
if "error" in item:
print(item)
return
if "data" not in item:
print(item)
return
try:
if isinstance(item["data"], dict):
data = orjson.dumps(item["data"], default=str)
valid = "t"
error_data = ""
else:
try:
orjson.loads(item["data"])
data = item["data"]
valid = "t"
error_data = ""
except orjson.JSONDecodeError:
valid = "f"
data = "{}"
error_data = item["data"]
if isinstance(data, bytes):
data = data.decode()
data = data.replace(r"\u0000", "")
count_data_types.update([item["data_type"]])
csv_writer.writerow(
[
name,
item["url"],
item["data_type"],
item["file_name"],
valid,
data,
error_data,
]
)
except Exception:
traceback.print_exc()
raise
runner = CrawlerProcess(settings)
crawler = runner.create_crawler(name)
crawler.signals.connect(save_to_csv, signal=signals.item_scraped)
runner.crawl(crawler)
runner.start()
info = crawler.stats.spider_stats[name]
info["name"] = name
info["data_types"] = dict(count_data_types)
info_file = data_dir / "info.json"
info_data = json.dumps(info, default=str)
info_file.write_text(info_data)
log_file = data_dir / "all.log"
def tail(filename, n=10000):
with open(filename) as file:
return "".join(deque(file, n))
with engine.begin() as connection, gzip.open(str(csv_file_path), "rt") as f:
connection.execute(
sa.text("INSERT INTO _job_info VALUES (:name, :info, :logs)"),
name=name,
info=info_data,
logs=tail(log_file),
)
dbapi_conn = connection.connection
copy_sql = "COPY _scrape_data (name, url, data_type, file_name, valid, data, error_data) FROM STDIN WITH CSV"
cur = dbapi_conn.cursor()
cur.copy_expert(copy_sql, f)
result = connection.execute("SELECT count(*) FROM _scrape_data").first()
print(f"{result['count']} files scraped")
if result.count == 0:
print("No data scraped!")
sys.exit(1)
shutil.rmtree(data_dir)
@cli.command("scrape", help=_first_doc_line(scrape))
@click.argument("name")
@click.argument("schema")
def _scrape(name, schema):
scrape(name, schema)
def create_base_tables(schema, drop_scrape=True):
"""Create "_compiled_release" and "_package_data" tables"
Parameters
----------
schema : string
Postgres schema where the "_scrape_data" table is.
drop_scrape : boolean default True
Drop the _scrape_data table when finished with it.
"""
engine = get_engine(schema)
package_data_sql = """
SELECT
id,
data - 'releases' - 'records' package_data
FROM
_scrape_data
WHERE
data_type in ('release_package', 'record_package')
"""
create_table("_package_data", schema, package_data_sql)
engine.execute(
"""
drop sequence IF EXISTS _generated_release_id;
create sequence _generated_release_id;
"""
)
compiled_releases_sql = """
SELECT
min(nextval('_generated_release_id')) compiled_release_id,
name,
data_type,
jsonb_agg(id) package_data_ids,
coalesce(release ->> 'ocid', gen_random_uuid()::text) ocid,
jsonb_agg(release) release_list,
null rest_of_record,
null compiled_release,
null compile_error
FROM
_scrape_data,
jsonb_path_query(data, '$.releases[*]') release
WHERE
data_type in ('release_package')
GROUP BY name, data_type, coalesce(release ->> 'ocid', gen_random_uuid()::text)
UNION ALL
SELECT
nextval('_generated_release_id'),
name,
data_type,
jsonb_build_array(id),
record ->> 'ocid',
record -> 'releases',
record - 'compiledRelease' rest_of_record,
record -> 'compiledRelease' compiled_release,
null compile_error
FROM
_scrape_data,
jsonb_path_query(data, '$.records[*]') record
WHERE
data_type in ('record_package')
"""
create_table("_compiled_releases", schema, compiled_releases_sql)
if drop_scrape:
engine.execute("DROP TABLE IF EXISTS _scrape_data")
result = engine.execute("SELECT count(*) FROM _compiled_releases").first()
print(f"{result['count']} compiled releases")
if result.count == 0:
print("No compiled releases!")
sys.exit(1)
@cli.command("create-base-tables", help=_first_doc_line(create_base_tables))
@click.argument("schema")
def _create_base_tables(schema):
create_base_tables(schema)
def compile_releases(schema):
"""Merge releases into a compiled_release.
For release packages merge releases to _compiled_release.compiled_release column.
Parameters
----------
schema : string
Postgres schema where the "_scrape_data" table is.
"""
with tempfile.TemporaryDirectory() as tmpdirname:
csv_file_path = tmpdirname + "/compiled_release.csv"
engine = get_engine(schema)
engine.execute(
"""
DROP TABLE IF EXISTS _tmp_compiled_releases;
CREATE TABLE _tmp_compiled_releases(compiled_release_id bigint, compiled_release JSONB, compile_error TEXT)
"""
)
patched_schema = _patched_schema(engine)
merger = ocdsmerge.Merger(patched_schema)
print("Making CSV file")
with gzip.open(str(csv_file_path), "wt", newline="") as csv_file, engine.begin() as connection, Timer():
connection = connection.execution_options(stream_results=True, max_row_buffer=1000)
results = connection.execute(
"SELECT compiled_release_id, release_list FROM _compiled_releases WHERE compiled_release is null"
)
csv_writer = csv.writer(csv_file)
for num, result in enumerate(results):
try:
compiled_release = merger.create_compiled_release(
result.release_list
)
error = ""
except Exception as e:
traceback.print_exc()
compiled_release = {}
error = str(e)
csv_writer.writerow(
[result.compiled_release_id, json.dumps(compiled_release), error]
)
print("Importing file")
with engine.begin() as connection, Timer(), gzip.open(
str(csv_file_path), "rt"
) as f:
dbapi_conn = connection.connection
copy_sql = "COPY _tmp_compiled_releases FROM STDIN WITH CSV"
cur = dbapi_conn.cursor()
cur.copy_expert(copy_sql, f)
print("Updating table")
with engine.begin() as connection, Timer():
connection.execute(
"""UPDATE _compiled_releases cr
SET compiled_release = tmp.compiled_release,
compile_error = tmp.compile_error
FROM _tmp_compiled_releases tmp
WHERE tmp.compiled_release_id = cr.compiled_release_id"""
)
connection.execute(
"""
DROP TABLE IF EXISTS _tmp_compiled_releases;
"""
)
@cli.command("compile-releases", help=_first_doc_line(compile_releases))
@click.argument("schema")
def _compile_releases(schema):
compile_releases(schema)
EMIT_OBJECT_PATHS = [
("planning",),
("tender",),
("contracts", "implementation"),
("buyer",),
("tender", "procuringEntity"),
]
PARTIES_PATHS = [
"buyer",
"awards_suppliers",
"tender_procuringEntity",
"tender_tenderers",
]
def flatten_object(obj, current_path=""):
for key, value in list(obj.items()):
if isinstance(value, dict):
yield from flatten_object(value, f"{current_path}{key}_")
else:
yield f"{current_path}{key}", value
def traverse_object(obj, emit_object, full_path=tuple(), no_index_path=tuple()):
for key, value in list(obj.items()):
if isinstance(value, list) and value and isinstance(value[0], dict):
for num, item in enumerate(value):
if not isinstance(item, dict):
item = {"__error": "A non object is in array of objects"}
yield from traverse_object(
item, True, full_path + (key, num), no_index_path + (key,)
)
obj.pop(key)
elif isinstance(value, list):
if not all(isinstance(item, str) for item in value):
obj[key] = json.dumps(value)
elif isinstance(value, dict):
if no_index_path + (key,) in EMIT_OBJECT_PATHS:
yield from traverse_object(
value, True, full_path + (key,), no_index_path + (key,)
)
obj.pop(key)
else:
yield from traverse_object(
value, False, full_path + (key,), no_index_path + (key,)
)
if obj and emit_object:
yield obj, full_path, no_index_path
@functools.lru_cache(1000)
def path_info(full_path, no_index_path):
all_paths = []
for num, part in enumerate(full_path):
if isinstance(part, int):
all_paths.append(full_path[: num + 1])
parent_paths = all_paths[:-1]
path_key = all_paths[-1] if all_paths else []
object_key = ".".join(str(key) for key in path_key)
parent_keys_list = [
".".join(str(key) for key in parent_path) for parent_path in parent_paths
]
parent_keys_no_index = [
"_".join(str(key) for key in parent_path if not isinstance(key, int))
for parent_path in parent_paths
]
object_type = "_".join(str(key) for key in no_index_path) or "release"
parent_keys = (dict(zip(parent_keys_no_index, parent_keys_list)),)
return object_key, parent_keys_list, parent_keys_no_index, object_type, parent_keys
def create_rows(result):
rows = []
awards = {}
parties = {}
for object, full_path, no_index_path in traverse_object(result.compiled_release, 1):
(
object_key,
parent_keys_list,
parent_keys_no_index,
object_type,
parent_keys,
) = path_info(full_path, no_index_path)
object[
"_link"
] = f'{result.compiled_release_id}{"." if object_key else ""}{object_key}'
object["_link_release"] = str(result.compiled_release_id)
for no_index_path, full_path in zip(parent_keys_no_index, parent_keys_list):
object[
f"_link_{no_index_path}"
] = f"{result.compiled_release_id}.{full_path}"
row = dict(
compiled_release_id=result.compiled_release_id,
object_key=object_key,
parent_keys=parent_keys,
object_type=object_type,
object=object,
)
rows.append(row)
if object_type == "awards":
award_id = object.get("id")
if award_id:
awards[award_id] = object
if object_type == "parties":
parties_id = object.get("id")
parties[parties_id] = object
for row in rows:
object = row["object"]
if row["object_type"] in PARTIES_PATHS:
parties_id = object.get("id")
if parties_id:
party = parties.get(parties_id)
if party:
object["_link_party"] = party["_link"]
object["_party"] = {
key: value
for key, value in party.items()
if not key.startswith("_")
}
if row["object_type"] == "contracts":
award_id = object.get("awardID")
if award_id:
award = awards.get(award_id)
if award:
object["_link_award"] = award["_link"]
object["_award"] = {
key: value
for key, value in award.items()
if not key.startswith("_")
}
try:
row["object"] = orjson.dumps(dict(flatten_object(object))).decode()
except TypeError:
# orjson more strict about ints
row["object"] = json.dumps(dict(flatten_object(object)))
row["parent_keys"] = orjson.dumps(row["parent_keys"]).decode()
return [list(row.values()) for row in rows]
@cli.command("release-objects")
@click.argument("schema")
def _release_objects(schema):
release_objects(schema)
def release_objects(schema):
engine = get_engine(schema)
engine.execute(
"""
DROP TABLE IF EXISTS _release_objects;
CREATE TABLE _release_objects(compiled_release_id bigint,
object_key TEXT, parent_keys JSONB, object_type TEXT, object JSONB);
"""
)
with tempfile.TemporaryDirectory() as tmpdirname:
with engine.begin() as connection, Timer():
connection = connection.execution_options(stream_results=True, max_row_buffer=1000)
results = connection.execute(
"SELECT compiled_release_id, compiled_release FROM _compiled_releases"
)
paths_csv_file = tmpdirname + "/paths.csv"
print("Making CSV file")
with gzip.open(paths_csv_file, "wt", newline="") as csv_file, Timer():
csv_writer = csv.writer(csv_file)
for result in results:
csv_writer.writerows(create_rows(result))
print("Uploading Data")
with engine.begin() as connection, gzip.open(
paths_csv_file, "rt"
) as f, Timer():
dbapi_conn = connection.connection
copy_sql = f"COPY {schema}._release_objects FROM STDIN WITH CSV"
cur = dbapi_conn.cursor()
cur.copy_expert(copy_sql, f)
def process_schema_object(path, current_name, flattened, obj):
string_path = ("_".join(path)) or "release"
properties = obj.get("properties", {}) # an object may have patternProperties only
current_object = flattened.get(string_path)
if current_object is None:
current_object = {}
flattened[string_path] = current_object
for name, prop in list(properties.items()):
prop_type = prop["type"]
prop_info = dict(
schema_type=prop["type"],
description=prop.get("description"),
)
if prop_type == "object":
if path + (name,) in EMIT_OBJECT_PATHS:
flattened = process_schema_object(
path + (name,), tuple(), flattened, prop
)
else:
flattened = process_schema_object(
path, current_name + (name,), flattened, prop
)
elif prop_type == "array":
if "object" not in prop["items"]["type"]:
current_object["_".join(current_name + (name,))] = prop_info
else:
flattened = process_schema_object(
path + current_name + (name,), tuple(), flattened, prop["items"]
)
else:
current_object["_".join(current_name + (name,))] = prop_info
return flattened
def link_info(link_name):
name = link_name[6:]
if not name:
doc = "Link to this row that can be found in other tables"
else:
doc = f"Link to the {name} row that this row relates to"
return {"name": link_name, "description": doc, "type": "string"}
@cli.command("schema-analysis")
@click.argument("schema")
def _schema_analysis(schema):
schema_analysis(schema)
# only accept years 1000-3999
DATE_RE = r'^([1-3]\d{3})-(\d{2})-(\d{2})([T ](\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)((-(\d{2}):(\d{2})|Z)?))?$'
def schema_analysis(schema):
create_table(
"_object_type_aggregate",
schema,
f"""SELECT
object_type,
each.key,
CASE
WHEN jsonb_typeof(value) != 'string'
THEN jsonb_typeof(value)
WHEN (value ->> 0) ~ '{DATE_RE}'
THEN 'datetime'
ELSE 'string'
END value_type,
count(*)
FROM
_release_objects ro, jsonb_each(object) each
GROUP BY 1,2,3;
""",
)
create_table(
"_object_type_fields",
schema,
"""SELECT
object_type,
key,
CASE WHEN
count(*) > 1
THEN 'string'
ELSE max(value_type) end value_type,
SUM("count") AS "count"
FROM
_object_type_aggregate
WHERE
value_type != 'null'
GROUP BY 1,2;
""",
)
patched_schema = _patched_schema(get_engine(schema))
schema_info = process_schema_object(
tuple(), tuple(), {}, JsonRef.replace_refs(patched_schema)
)
with get_engine(schema).begin() as connection:
result = connection.execute(
"""SELECT object_type, jsonb_object_agg(key, value_type) fields FROM _object_type_fields GROUP BY 1;"""
)
result_dict = {row.object_type: row.fields for row in result}
object_type_order = ["release"]
for key in schema_info:
if key in result_dict:
object_type_order.append(key)
for key in result_dict:
if key not in object_type_order:
object_type_order.append(key)
object_details = {}
for object_type in object_type_order:
fields = result_dict[object_type]
details = [link_info("_link"), link_info("_link_release")]
fields_added = set(["_link", "_link_release"])
for field in fields:
if field.startswith("_link_") and field not in fields_added:
details.append(link_info(field))
fields_added.add(field)
schema_object_detials = schema_info.get(object_type, {})
for schema_field, field_info in schema_object_detials.items():
if schema_field not in fields:
continue
detail = {"name": schema_field, "type": fields[schema_field]}
detail.update(field_info)
details.append(detail)
fields_added.add(schema_field)
for field in sorted(fields):
if field in fields_added:
continue
details.append(
{
"name": field,
"description": "No Docs as not in OCDS",
"type": fields[field],
}
)
object_details[object_type] = details
connection.execute(
"""
DROP TABLE IF EXISTS _object_details;
CREATE TABLE _object_details(id SERIAL, object_type text, object_details JSONB);
"""
)
for object_type, object_details in object_details.items():
connection.execute(
sa.text(
"insert into _object_details(object_type, object_details) values (:object_type, :object_details)"
),
object_type=object_type,
object_details=json.dumps(object_details),
)
def create_field_sql(object_details, sqlite=False):
fields = []
lowered_fields = set()
fields_with_type = []
for num, item in enumerate(object_details):
name = item["name"]
if sqlite and name.lower() in lowered_fields:
name = f'{name}_{num}'
type = item["type"]
if type == "number":
field = f'"{name}" numeric'
elif type == "array":
field = f'"{name}" JSONB'
elif type == "boolean":
field = f'"{name}" boolean'
elif type == "datetime":
field = f'"{name}" timestamp'
else:
field = f'"{name}" TEXT'
lowered_fields.add(name.lower())
fields.append(f'"{name}"')
fields_with_type.append(field)
return ", ".join(fields), ", ".join(fields_with_type)
@cli.command("postgres-tables")
@click.argument("schema")
def _postgres_tables(schema):
postgres_tables(schema)
def postgres_tables(schema, drop_release_objects=True):
with get_engine(schema).begin() as connection:
result = list(
connection.execute(
"SELECT object_type, object_details FROM _object_details order by id"
)
)
for object_type, object_details in result: