Skip to content

Commit b204ab5

Browse files
committed
feat(dev): fk records;
- Build sql strings from ds info for ref records export to Excel.
1 parent 4a4de4c commit b204ab5

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

ckanext/recombinant/views.py

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import re
44
import simplejson as json
55
from markupsafe import Markup
6+
import sqlalchemy as sa
67

78
from typing import Union, Dict, Tuple, Any
89
from ckan.types import Response
@@ -291,8 +292,6 @@ def template(dataset_type: str, lang: str, owner_org: str) -> Response:
291292
chromo = get_chromo(resource['name'])
292293
record_data = []
293294

294-
# TODO: see if we can complete the datastore_info fk mappings and just get from there...
295-
296295
for keys in primary_keys:
297296
temp = keys.split(",")
298297
for f, pkf in zip(temp, pk_fields):
@@ -307,7 +306,34 @@ def template(dataset_type: str, lang: str, owner_org: str) -> Response:
307306

308307
append_data(book, record_data, chromo)
309308

310-
# TODO: check if there are any foreign references and append any data
309+
ds_info = lc.action.datastore_info(id=resource['id'])
310+
if 'foreignkeys' in ds_info['meta']:
311+
for fk in ds_info['meta']['foreignkeys']:
312+
foreign_constraints_sql = None
313+
if resource['id'] == fk['child_table']:
314+
foreign_constraints_sql = sa.text('''
315+
SELECT * FROM "{0}" parent
316+
JOIN "{1}" child ON {2}
317+
ORDER BY parent._id;
318+
'''.format(fk['parent_table'],
319+
fk['child_table'],
320+
' AND '.join(['parent.{0} = child.{1}'.format(fk_c, fk['child_columns'][fk_i])
321+
for fk_i, fk_c in enumerate(fk['parent_columns'])])))
322+
elif resource['id'] == fk['parent_table']:
323+
foreign_constraints_sql = sa.text('''
324+
SELECT * FROM "{0}" child
325+
JOIN "{1}" parent ON {2}
326+
ORDER BY child._id;
327+
'''.format(fk['child_table'],
328+
fk['parent_table'],
329+
' AND '.join(['child.{0} = parent.{1}'.format(fk_c, fk['parent_columns'][fk_i])
330+
for fk_i, fk_c in enumerate(fk['child_columns'])])))
331+
if foreign_constraints_sql is not None:
332+
# TODO: get results and chromo and put them into the workbook
333+
continue
334+
# foreign_constraints_results = connection.execute(foreign_constraints_sql)
335+
for result in foreign_constraints_results.fetchall():
336+
continue
311337

312338
blob = BytesIO()
313339
book.save(blob)

0 commit comments

Comments
 (0)