Skip to content

Instantly share code, notes, and snippets.

@isouzasoares
Created November 25, 2013 19:40
Show Gist options
  • Save isouzasoares/7647446 to your computer and use it in GitHub Desktop.
Save isouzasoares/7647446 to your computer and use it in GitHub Desktop.
class Q:
_AVAIBLE_COMPARATORS = ('=', '>', '<', '>=', '<=', 'LIKE', '<>', 'IS', )
def __init__(self):
self.data = []
def where(self, field, comparator, value, escape=True, condition_or=False):
if not comparator in self._AVAIBLE_COMPARATORS:
raise "not comparator"
self.data.append({"field": field,
"comparator": comparator,
"value": value,
"escape": escape,
"condition_or": condition_or})
return self
def group(self, q, condition_or=False):
#if not type(q) == type(self):
# raise "type is not Q"
self.data.append({"q": q, "condition_or": condition_or})
return self
def _escape(self, value):
return _quote(value)
def render(self):
output = []
for index, i in enumerate(self.data):
if "q" in i and type(i['q']) == type(self):
#import pdb; pdb.set_trace()
ln = '(' + i["q"].render() + ')'
else:
tv = type(i['value'])
value = i["value"]
if tv == int:
value = str(int(value))
elif tv == float:
value = float(value)
elif value is None:
value = "NULL"
elif tv == datetime:
value = "'" + i["value"].strftime("%Y-%m-%d %H:%M:%s") +\
"'"
elif tv == date:
value = "'" + i["value"].strftime("%Y-%m-%d") + "'"
elif i["escape"]:
value = self._escape(value)
value = "'" + value + "'"
ln = i["field"] + ' ' + i['comparator'] + ' ' + value
cond = ""
if index > 0:
cond = "AND "
if i['condition_or']:
cond = "OR "
output.append(cond + ln)
return " ".join(output)
@isouzasoares
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment