|
| 1 | +#! /usr/bin/env nix-shell |
| 2 | +#! nix-shell -i python3 -p python3 python3Packages.pyyaml |
| 3 | + |
| 4 | +import collections |
| 5 | +import glob |
| 6 | +import sqlite3 |
| 7 | + |
| 8 | +import yaml |
| 9 | + |
| 10 | + |
| 11 | +def flatten(d, parent_key='', sep='_'): |
| 12 | + items = [] |
| 13 | + for k, v in d.items(): |
| 14 | + new_key = parent_key + sep + k if parent_key else k |
| 15 | + if isinstance(v, collections.MutableMapping): |
| 16 | + items.extend(flatten(v, new_key, sep=sep).items()) |
| 17 | + else: |
| 18 | + items.append((new_key, v)) |
| 19 | + return dict(items) |
| 20 | + |
| 21 | + |
| 22 | +def generate_schema(table_name, column_names): |
| 23 | + columns = ', '.join(['"{}" TEXT'.format(column_name) for column_name in column_names]) |
| 24 | + return f'CREATE TABLE IF NOT EXISTS "{table_name}" ({columns})' |
| 25 | + |
| 26 | + |
| 27 | +def insert_metadata(connection, table_name, metadata): |
| 28 | + |
| 29 | + question_marks = ", ".join(["?" for i in range(len(metadata))]) |
| 30 | + column_names = ', '.join('"%s"' % _ for _ in metadata.keys()) |
| 31 | + values = tuple(metadata.values()) |
| 32 | + connection.execute( |
| 33 | + f'INSERT INTO {table_name} ({column_names}) VALUES ({question_marks})', |
| 34 | + values) |
| 35 | + |
| 36 | + |
| 37 | +connection = sqlite3.connect('db.sqlite') |
| 38 | + |
| 39 | +for section in {'bloggers', 'conferences', 'coworking_spaces', 'event_spaces', 'groups', 'organizations', 'organizers'}: |
| 40 | + keys = set() |
| 41 | + for filename in glob.glob(f'{section}/*.yml'): |
| 42 | + with open(filename) as f: |
| 43 | + metadata = yaml.safe_load(f) |
| 44 | + keys = keys | flatten(metadata).keys() |
| 45 | + |
| 46 | + section_schema = generate_schema(section, keys) |
| 47 | + connection.execute(section_schema) |
| 48 | + |
| 49 | + for filename in glob.glob(f'{section}/*.yml'): |
| 50 | + with open(filename) as f: |
| 51 | + metadata = yaml.safe_load(f) |
| 52 | + try: |
| 53 | + insert_metadata(connection, section, flatten(metadata)) |
| 54 | + except: |
| 55 | + print('failed to insert', filename) |
0 commit comments