Skip to content

Instantly share code, notes, and snippets.

@shon
Created November 25, 2019 11:14
Show Gist options
  • Save shon/4517fcb8550c90af19ced14578e860ae to your computer and use it in GitHub Desktop.
Save shon/4517fcb8550c90af19ced14578e860ae to your computer and use it in GitHub Desktop.
NoORM | SQL Construction library
from dataclasses import dataclass
@dataclass
class Query:
db: object = None
def sql(self):
raise NotImplementedError
def __call__(self):
self.db.conn.execute(self.sql())
@dataclass
class Field:
name: str
table: object
def __eq__(self, x):
return f'{self.table}.{self.name} = {repr(x)}'
def __str__(self):
return f'{self.table}.{self.name}'
@dataclass
class Table:
_name: str
def __getattr__(self, name):
f = Field(name, table=self)
setattr(self, name, f)
return f
def __str__(self):
return self._name
def Condition(NAME, things):
return f'( {f" {NAME} ".join(things)} )'
def AND(*things):
return Condition('AND', things)
def OR(*things):
return Condition('OR', things)
@dataclass
class Select(Query):
table = None
op = 'SELECT'
fields: list = None
_limit: int = ''
_where: str = ''
def from_(self, table):
self.table = table
return self
def limit(self, n=None):
self._limit = f'LIMIT {n}' if n else ''
return self
def where(self, conds):
if conds:
self._where = f'WHERE {conds}'
return self
def sql(self):
fields = f'{", ".join(str(f) for f in self.fields)}' if self.fields else '*'
return f'{self.op} {fields} FROM {self.table} {self._where} {self._limit}'
class DB:
def select(self, *fields):
q = Select(db=self, fields=fields)
return q
def test():
db = DB()
users = Table('users')
q = db.select().from_(users)
print(q.sql())
q = db.select('name', 'email').from_(users).where(AND(users.name == 'Michael Scott').limit(1)
print(q.sql())
q = db.select('name', 'email').from_(users).where(AND(users.id == 7))).limit(1)
print(q.sql())
if __name__ == '__main__':
test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment