Skip to content

Instantly share code, notes, and snippets.

@jackeyGao
Created August 25, 2016 02:41
Show Gist options
  • Save jackeyGao/da1d12257b72b1b842ed9963c5b44066 to your computer and use it in GitHub Desktop.
Save jackeyGao/da1d12257b72b1b842ed9963c5b44066 to your computer and use it in GitHub Desktop.
UPDATE TO UPDATE
KEYS = {
"1": "id",
"2": "name",
"3": "class",
"4": "score",
}
def dict_to_sqlstring(d):
string = ""
for k, v in d.items():
string += '%s=%s,' % (k, v)
return string.strip(',')
with open('upd.sql', 'r') as f:
_where, _set, d_where, d_set = {}, {}, {}, {}
for i in f.readlines():
if i.startswith('### UPDATE'):
if _where and _set:
for key in KEYS.values():
_value_w = _where.get(key, None)
_value_s = _set.get(key, None)
if not _value_w and not _value_s:
continue
if _value_w == _value_s:
d_where[key] = _value_w
else:
d_set[key] = _value_s
print "UPDATE %s SET %s WHERE %s;" % (
table,
dict_to_sqlstring(d_set),
dict_to_sqlstring(d_where)
)
# Get table name from segment header.
table = i.split('UPDATE')[1].strip()
if i.startswith('### WHERE'):
in_where = True
in_set = False
if i.startswith('### SET'):
in_set = True
in_where = False
if i.startswith('### @'):
index, value = i.split('@')[1].split('=')
if in_where:
_where[KEYS[index]] = value.strip()
if in_set:
_set[KEYS[index]] = value.strip()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment