Last active
April 26, 2019 12:46
-
-
Save s3rgeym/d80fe13b7b38c317fa6656ad89b32081 to your computer and use it in GitHub Desktop.
Концепт ORM
This file contains hidden or 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
| class ModelOptions: | |
| ... | |
| class ModelMeta(type): | |
| def __new__(mcls, name, bases, attrs): | |
| cls = super().__new__(mcls, name, bases, attrs) | |
| # if name == 'Model': | |
| # return cls | |
| parents = [b for b in bases[::-1] if isinstance(b, mcls)] | |
| if not parents: | |
| return cls | |
| cls._fields = ... | |
| cls._opts = ... | |
| ... | |
| cls.objects = ModelManager(cls) | |
| return cls | |
| class ModelManager: | |
| def __init__(self, model): | |
| self.model = model | |
| @propery | |
| def db(self): | |
| return self.model.__database__ | |
| async def scalar(self, *, using_db=None): | |
| db = using_db or self.db | |
| ... | |
| async def first(self, *, using_db=None): | |
| db = using_db or self.db | |
| ... | |
| async def all(self, *, using_db=None): | |
| db = using_db or self.db | |
| ... | |
| class Model(metaclass=ModelMeta): | |
| async def save(self, *, using_db=None): | |
| ... | |
| class Employe(Model): | |
| ... | |
| employe = Employe(first_name='John', last_name='Doe', position='Python Programmer') | |
| await employe.save() | |
| # INSERT INTO employees (first_name, last_name) VALUES (%s, %s); | |
| employe.position = 'Teamlead' | |
| await employe.save() | |
| # UPDATE employees SET position = %s WHERE id = %s; | |
| await employe.remove() | |
| # DELETE FROM employees WHERE id = %s; | |
| await Employe.objects.where(Employe.company_id == 123).order_by(Employe.salary.desc())[25:50].all() | |
| # SELECT employees.* FROM employees WHERE (employees.company_id = %s) ORDER BY employees.salary DESC LIMIT 25 OFFSET 50; | |
| await Employe.objects.where(Employe.company_id == 123).avg(Employe.salary).scalar() | |
| # SELECT AVG(employees.salary) FROM employees WHERE (employees.company_id = %s); | |
| await Employe.objects.where(Employe.company_id == 123 & Employe.salary == fn.MAX(Employe.salary)).first() | |
| # SELECT employees.* FROM employees WHERE ((employees.company_id = %s) AND (employees.salary = MAX(employees.salary)) LIMIT 1 OFFSET 0; |
Author
Author
sql/__init__.py:
sql/nodes.py:
class Node:
def accept(self, v):
v.visit(self)sql/visitors.py:
class Visitor:
def visit(self, node):
method = 'visit_' + node.__class__.__name__
getattr(self, method)(node)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://searchcode.com/file/54131568/svarga/contrib/appengine/models/gae.py#l-1