Skip to content
This repository has been archived by the owner on Mar 21, 2021. It is now read-only.

Commit

Permalink
Add execute()
Browse files Browse the repository at this point in the history
  • Loading branch information
andreypopp committed Oct 12, 2020
1 parent 744c9a8 commit 219f2f1
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
21 changes: 20 additions & 1 deletion qc0/__init__.py
@@ -1,10 +1,29 @@
import sqlalchemy as sa

from .syn import Q, q
from .syn_to_op import syn_to_op
from .op_to_sql import op_to_sql
from .scope import Cardinality

__version__ = "0.1.0"

__all__ = ("parse", "Q", "q", "syn_to_op", "op_to_sql")
__all__ = ("execute", "parse", "Q", "q", "syn_to_op", "op_to_sql")


def execute(query, meta: sa.MetaData, engine: sa.engine.Engine):
""" Execute query."""
if isinstance(query, Q):
query = query.syn
elif isinstance(query, str):
query = parse(query)
op = syn_to_op(query, meta)
sql = op_to_sql(op)
with engine.connect() as conn:
res = conn.execute(sql)
value = [row.value for row in res.fetchall()]
if op.card != Cardinality.SEQ:
value = value[0]
return value


def parse(q):
Expand Down
8 changes: 2 additions & 6 deletions qc0/cli.py
Expand Up @@ -6,19 +6,15 @@
def shell(db):
from IPython.terminal.embed import embed
from sqlalchemy import create_engine, MetaData
from qc0 import Q as BaseQ, syn_to_op, op_to_sql
from qc0 import Q as BaseQ, execute

engine = create_engine(db)
meta = MetaData()
meta.reflect(bind=engine)

class Q(BaseQ):
def run(self):
op = syn_to_op(self.syn, meta)
sql = op_to_sql(op)
with engine.connect() as conn:
res = conn.execute(sql)
return [row[0] for row in res.fetchall()]
return execute(self, meta, engine)

q = Q(None) # NOQA

Expand Down

0 comments on commit 219f2f1

Please sign in to comment.