|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import inflection |
| 4 | + |
| 5 | +from lib.renderer import Renderer |
| 6 | +from lib.dbscheme import * |
| 7 | +from lib import paths, schema, generator |
| 8 | + |
| 9 | +log = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +def dbtype(typename): |
| 13 | + if typename[0].isupper(): |
| 14 | + return "@" + inflection.underscore(typename) |
| 15 | + return typename |
| 16 | + |
| 17 | + |
| 18 | +def cls_to_dbscheme(cls: schema.Class): |
| 19 | + if cls.derived: |
| 20 | + yield DbUnion(dbtype(cls.name), (dbtype(c) for c in cls.derived)) |
| 21 | + if not cls.derived or any(f.is_single() for f in cls.fields): |
| 22 | + binding = not cls.derived |
| 23 | + keyset = DbKeySet(["id"]) if cls.derived else None |
| 24 | + yield DbTable( |
| 25 | + keyset=keyset, |
| 26 | + name=inflection.tableize(cls.name), |
| 27 | + columns=[ |
| 28 | + DbColumn("id", type=dbtype(cls.name), binding=binding), |
| 29 | + ] + [ |
| 30 | + DbColumn(f.name, dbtype(f.type)) for f in cls.fields if f.is_single() |
| 31 | + ] |
| 32 | + ) |
| 33 | + for f in cls.fields: |
| 34 | + if f.is_optional(): |
| 35 | + yield DbTable( |
| 36 | + keyset=DbKeySet(["id"]), |
| 37 | + name=inflection.tableize(f"{cls.name}_{f.name}"), |
| 38 | + columns=[ |
| 39 | + DbColumn("id", type=dbtype(cls.name)), |
| 40 | + DbColumn(f.name, dbtype(f.type)), |
| 41 | + ], |
| 42 | + ) |
| 43 | + elif f.is_repeated(): |
| 44 | + yield DbTable( |
| 45 | + keyset=DbKeySet(["id", "index"]), |
| 46 | + name=inflection.tableize(f"{cls.name}_{f.name}"), |
| 47 | + columns=[ |
| 48 | + DbColumn("id", type=dbtype(cls.name)), |
| 49 | + DbColumn("index", type="int"), |
| 50 | + DbColumn(inflection.singularize(f.name), dbtype(f.type)), |
| 51 | + ] |
| 52 | + ) |
| 53 | + |
| 54 | + |
| 55 | +def generate(opts): |
| 56 | + input = opts.schema.resolve() |
| 57 | + out = opts.dbscheme.resolve() |
| 58 | + renderer = Renderer(opts.check) |
| 59 | + |
| 60 | + with open(input) as src: |
| 61 | + data = schema.load(src) |
| 62 | + |
| 63 | + declarations = [d for cls in data.classes.values() for d in cls_to_dbscheme(cls)] |
| 64 | + |
| 65 | + includes = [] |
| 66 | + for inc in data.includes: |
| 67 | + inc = input.parent / inc |
| 68 | + with open(inc) as inclusion: |
| 69 | + includes.append({"src": inc.relative_to(paths.swift_dir), "data": inclusion.read()}) |
| 70 | + renderer.render("dbscheme", out, includes=includes, src=input.relative_to(paths.swift_dir), |
| 71 | + declarations=declarations) |
| 72 | + return renderer.written |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + generator.run(generate, tags=["schema", "dbscheme"]) |
0 commit comments