Created
February 22, 2019 13:31
-
-
Save bhrdn/c9e52bb8f1751a031a4d3104cf7c4835 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"mahasiswa": [ | |
"nim", | |
"nama", | |
"alamat", | |
"ipk" | |
], | |
"matakuliah": [ | |
"kode", | |
"nama", | |
"sks" | |
], | |
"registrasi": [ | |
"nim", | |
"kode", | |
"semester", | |
"tahun_ajar", | |
"nilai" | |
] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
## dataset | |
with open('datas.json') as f: | |
datas = json.load(f) | |
## helper | |
parser = lambda x, y, z = '': x[x.find(y) + len(y) + 0x01:x.find(z) - 0x01] | |
error = lambda x: exit('SQL Error (Missing ;)' if not x else 'SQL Error (Syntax Error) || Reason: {}'.format(x)) | |
## input | |
_ = "SELECT m.nim,nama,kode,nilai FROM mahasiswa m JOIN registrasi r ON (m.nim=r.nim);".lower() | |
if _[-1] != ';': error(None) | |
tables, alias = parser(_, 'from', 'join').split() | |
if tables not in datas: | |
error('tables [{}] not found !!'.format(tables)) | |
print 'Table Main: {} -> {}'.format(tables, alias) | |
columns, ct = parser(_, 'select', 'from').split(','), [] | |
for c in columns: | |
if '{}.'.format(alias) in c: | |
temp = c.split('.')[1] | |
if temp not in datas[tables]: | |
error('columns [{}] not found !!'.format(temp)) | |
else: | |
ct.append(temp) | |
for c in columns: | |
if c in datas[tables] and c not in ct: | |
ct.append(c) | |
print 'List Kolom: {}'.format(', '.join(ct)) | |
## extend (JOIN Query) | |
if 'join' in _: | |
tables, alias = parser(_, 'join', 'on').split() | |
print 'Table Join: {} -> {}'.format(tables, alias) | |
condition, ct = parser(_, 'on')[1:-1], [] | |
for c in condition.split('='): | |
if '{}.'.format(alias) in c: | |
ct.append(c.split('.')[1]) | |
for c in columns: | |
if c in datas[tables]: | |
ct.append(c) | |
print 'List Kolom: {}'.format(', '.join(ct)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment