- if 'where' in parsed_sql:
- query = ''
- start = 0
- end = table.nrows
- try:
- conditions = []
- for condition in parsed_sql['where'].get_sublists():
- if str(condition) == '"rowid"=:p0':
- start = int(params['p0'])
- end = start + 1
- else:
- translated, params = _translate_condition(table, condition, params)
- conditions.append(translated)
- if conditions:
- query = ') & ('.join(conditions)
- query = '(' + query + ')'
- except:
- # Probably it's a PyTables query
- query = str(parsed_sql['where'])[6:] # without where keyword
+ def _cast_param(field, pname):
+ # Cast value to the column type
+ if type(table) is tables.table.Table:
+ coltype = table.coltypes[field]
+ else:
+ coltype = table.dtype.name
+ fcast = None
+ if coltype == 'string':
+ fcast = str
+ elif coltype.startswith('int'):
+ fcast = int
+ elif coltype.startswith('float'):
+ fcast = float
+ if fcast:
+ params[pname] = fcast(params[pname])
+
+ def _translate_where(where):
+ # Translate SQL to PyTables expression
+ nonlocal start, end
+ expr = ''
+ operator = list(where)[0]
+
+ if operator in ['and', 'or']:
+ subexpr = [_translate_where(e) for e in where[operator]]
+ subexpr = filter(lambda e: e, subexpr)
+ subexpr = ["({})".format(e) for e in subexpr]
+ expr = " {} ".format(_operators[operator]).join(subexpr)
+ elif operator == 'exists':
+ pass
+ elif where == {'eq': ['rowid', 'p0']}:
+ start = int(params['p0'])
+ end = start + 1
+ elif where == {'gt': ['rowid', 'p0']}:
+ start = int(params['p0']) + 1
+ else:
+ left, right = where[operator]
+ if left in params:
+ _cast_param(right, left)
+ elif right in params:
+ _cast_param(left, right)
+
+ expr = "{left} {operator} {right}".format(left=left, operator=_operators.get(operator, operator), right=right)