Created
March 27, 2018 06:42
-
-
Save everilae/b7d48f3abab8338a9f1bf18c1f8876b4 to your computer and use it in GitHub Desktop.
Relational division for SQLAlchemy, inspired by jOOQ.
This file contains 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
from sqlalchemy.ext.compiler import compiles | |
from sqlalchemy.sql.elements import ClauseElement | |
from sqlalchemy.sql import util as sqlutil | |
from sqlalchemy.sql.base import Executable, _generative | |
from sqlalchemy import select, exists, and_ | |
class Divide(Executable, ClauseElement): | |
def __init__(self, dividend, divisor, on=None, returning=None): | |
self._dividend = dividend | |
self._divisor = divisor | |
self._on = on | |
self._returning = returning | |
self._unique_columns = [] | |
self._common_columns = [] | |
self._inspect_columns() | |
@_generative | |
def on(self, *criterion): | |
self._on = and_(*criterion) | |
@_generative | |
def returning(self, *cols): | |
self._returning = cols | |
def _inspect_columns(self): | |
for col in self._dividend.columns: | |
rcol = self._divisor.columns.get(col.name) | |
if rcol is None: | |
self._unique_columns.append(col) | |
else: | |
self._common_columns.append((col, rcol)) | |
@property | |
def _default_on(self): | |
return and_(*[l == r for l, r in self._common_columns]) | |
@property | |
def _default_returning(self): | |
return self._unique_columns | |
@property | |
def select(self): | |
d2 = self._dividend.alias() | |
adapter = sqlutil.ClauseAdapter(d2) | |
on = (self._on if self._on is not None | |
else self._default_on) | |
returning = (self._returning if self._returning is not None | |
else self._default_returning) | |
div_on = adapter.traverse(on) | |
join_on = and_(*[c == adapter.traverse(c) for c in returning]) | |
return select(list(returning)).\ | |
where(~exists(). | |
select_from(self._divisor).\ | |
where(~exists(). | |
where(and_(join_on, div_on)). | |
correlate_except(d2))).\ | |
distinct() | |
@compiles(Divide) | |
def compile_divide(element, compiler, **kw): | |
return compiler.process(element.select, **kw) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
A:
B: