Commit b691f9c1 authored by Mantas Zimnickas's avatar Mantas Zimnickas

Fix issue with multi column primary keys

Generate `_id` entry for primary key and list all columns used for
primary keys in a comma separated list.

#835
parent 926e7bd0
Pipeline #111595051 passed with stage
in 2 minutes and 29 seconds
......@@ -27,6 +27,14 @@ def inspect(engine, schema=None):
insp = reflection.Inspector.from_engine(engine)
for table in insp.get_table_names(schema):
pkey = insp.get_pk_constraint(table, schema)
if pkey:
yield (
table,
pkey['constrained_columns'],
'pk',
'',
)
fkeys = insp.get_foreign_keys(table, schema)
refs = {}
for fkey in fkeys:
......@@ -37,12 +45,12 @@ def inspect(engine, schema=None):
'table': fkey['referred_table'],
'column': ref,
}
for column in insp.get_columns(table, schema):
yield (
table,
column['name'],
detect_type(column['type']),
column['name'] in pkey['constrained_columns'],
refs.get(column['name'], ''),
)
......@@ -82,25 +90,30 @@ def writecsv(f, cols, params=None):
'ref.table',
'ref.column',
])
for table, column, ctype, pkey, ref in cols:
for table, column, ctype, ref in cols:
kwargs = {
'table': table.lower(),
'column': column.lower(),
'type': ctype,
}
if pkey:
mtype = 'pk'
elif ref:
mtype = 'ref'
if ctype == 'pk':
dtype = 'pk'
prop = '_id'
column = ','.join(column)
else:
mtype = ctype
prop = column.lower()
if ref:
dtype = 'ref'
else:
dtype = ctype
writer.writerow([
params['dataset'].format(**kwargs),
params['resource'].format(**kwargs),
params['origin'].format(**kwargs),
params['model'].format(**kwargs),
column.lower(),
mtype,
prop,
dtype,
params['model'].format(**{**kwargs, 'table': ref['table'].lower()}) if ref else '',
'', # const
'', # title
......
......@@ -8,7 +8,7 @@ from lodam.services.sqlschema import inspect, writecsv
def test_inspect():
engine = sa.create_engine('sqlite://')
engine.execute('CREATE TABLE t(id INTEGER PRIMARY KEY);')
engine.execute('CREATE TABLE t(foo INTEGER NOT NULL, bar INTEGER NOT NULL, PRIMARY KEY(foo, bar));')
cols = inspect(engine)
f = io.StringIO()
writecsv(f, cols)
......@@ -19,14 +19,46 @@ def test_inspect():
'resource': '',
'origin': '',
'model': 't',
'property': 'id',
'property': '_id',
'type': 'pk',
'ref': '',
'const': '',
'title': '',
'description': '',
'table': 't',
'column': 'id',
'column': 'foo,bar',
'ref.table': '',
'ref.column': '',
},
{
'dataset': '',
'resource': '',
'origin': '',
'model': 't',
'property': 'foo',
'type': 'integer',
'ref': '',
'const': '',
'title': '',
'description': '',
'table': 't',
'column': 'foo',
'ref.table': '',
'ref.column': '',
},
{
'dataset': '',
'resource': '',
'origin': '',
'model': 't',
'property': 'bar',
'type': 'integer',
'ref': '',
'const': '',
'title': '',
'description': '',
'table': 't',
'column': 'bar',
'ref.table': '',
'ref.column': '',
},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment