Skip to content

Commit

Permalink
add support for the "select one" operator
Browse files Browse the repository at this point in the history
  • Loading branch information
imryche committed Jun 30, 2024
1 parent 0be685a commit 22d22b8
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
8 changes: 6 additions & 2 deletions litequery/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

class Op(str, Enum):
SELECT = ""
SELECT_ONE = "^"
MODIFY = "!"
INSERT_RETURNING = "<!"

Expand All @@ -24,8 +25,9 @@ def parse_queries(path):
raw_queries = re.findall(r"-- name: (.+)\n([\s\S]*?);", content)
queries = []
for query_name, sql in raw_queries:
op_pattern = "|".join(op.value for op in Op)
match = re.match(rf"^([a-z_][a-z0-9_-]*)({op_pattern})?$", query_name)
op_pattern = "|".join("\\" + "\\".join(list(op.value)) for op in Op if op.value)
pattern = rf"^([a-z_][a-z0-9_-]*)({op_pattern})?$"
match = re.match(pattern, query_name)
if not match:
raise NameError(f'Invalid query name: "{query_name}"')
query_name = match.group(1)
Expand Down Expand Up @@ -61,6 +63,8 @@ async def query_method(**kwargs):
async with conn.execute(query.sql, kwargs) as cur:
if query.op == Op.SELECT:
return await cur.fetchall()
if query.op == Op.SELECT_ONE:
return await cur.fetchone()
if query.op == Op.MODIFY:
await conn.commit()
return cur.rowcount
Expand Down
2 changes: 1 addition & 1 deletion queries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ select
from
users;

-- name: users_first
-- name: users_first^
select
*
from
Expand Down

0 comments on commit 22d22b8

Please sign in to comment.