jupyter-duckdb 1.2.0.6__py3-none-any.whl → 1.2.100__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,10 +19,14 @@ class RAParser:
19
19
  tokens = tuple(Tokenizer.tokenize(tokens[0]))
20
20
 
21
21
  # binary operators
22
- for operator in RA_BINARY_OPERATORS:
22
+ for operator_symbols in RA_BINARY_SYMBOLS:
23
23
  # iterate tokens and match symbol
24
24
  for i in range(1, len(tokens) + 1):
25
- if tokens[-i].lower() in operator.symbols():
25
+ lower_token = tokens[-i].lower()
26
+
27
+ if lower_token in operator_symbols:
28
+ operator = operator_symbols[lower_token]
29
+
26
30
  # raise error if left or right operand missing
27
31
  if i == 1:
28
32
  raise RAParserError(f'right operand missing after {tokens[-i]}', depth)
@@ -9,7 +9,7 @@ from .RAOperator import RAOperator
9
9
  from .RABinaryOperator import RABinaryOperator
10
10
  from .RAUnaryOperator import RAUnaryOperator
11
11
  from .RAOperand import RAOperand
12
- from .binary import RA_BINARY_OPERATORS
12
+ from .binary import RA_BINARY_OPERATORS, RA_BINARY_SYMBOLS
13
13
  from .unary import RA_UNARY_OPERATORS
14
14
 
15
15
  from .DCOperand import DCOperand
@@ -8,7 +8,7 @@ from ...util.RenamableColumnList import RenamableColumnList
8
8
  class Difference(RABinaryOperator):
9
9
  @staticmethod
10
10
  def symbols() -> Tuple[str, ...]:
11
- return '\\',
11
+ return '-', '\\'
12
12
 
13
13
  def to_sql(self, tables: Dict[str, Table]) -> Tuple[str, RenamableColumnList]:
14
14
  # execute subqueries
@@ -8,7 +8,7 @@ class Divide(LogicOperator):
8
8
 
9
9
  @staticmethod
10
10
  def symbols() -> Tuple[str, ...]:
11
- return '÷', '/'
11
+ return '/', '÷'
12
12
 
13
13
  @property
14
14
  def sql_symbol(self) -> str:
@@ -27,10 +27,6 @@ class Division(RABinaryOperator):
27
27
  # inter_name_left = ', '.join(l.current_name for l, _ in inter_cols)
28
28
  inter_name_right = ', '.join(r.current_name for _, r in inter_cols)
29
29
 
30
- print('-', diff_name)
31
- print(inter_name)
32
- print(inter_name_right)
33
-
34
30
  # create sql
35
31
  return f'''
36
32
  SELECT {diff_name}
@@ -0,0 +1,37 @@
1
+ from typing import Optional
2
+ from typing import Tuple, Dict
3
+
4
+ from duckdb_kernel.db import Table
5
+ from ..RABinaryOperator import RABinaryOperator
6
+ from ...util.RenamableColumn import RenamableColumn
7
+ from ...util.RenamableColumnList import RenamableColumnList
8
+
9
+
10
+ class FullOuterJoin(RABinaryOperator):
11
+ @staticmethod
12
+ def symbols() -> Tuple[str, ...]:
13
+ return chr(10199), 'fjoin', 'ojoin'
14
+
15
+ @staticmethod
16
+ def _coalesce(c1: RenamableColumn, c2: Optional[RenamableColumn]) -> str:
17
+ if c2 is not None:
18
+ return f'COALESCE({c1.current_name}, {c2.current_name}) AS {c1.current_name}'
19
+ else:
20
+ return c1.current_name
21
+
22
+ def to_sql(self, tables: Dict[str, Table]) -> Tuple[str, RenamableColumnList]:
23
+ # execute subqueries
24
+ lq, lcols = self.left.to_sql(tables)
25
+ rq, rcols = self.right.to_sql(tables)
26
+
27
+ # find matching columns
28
+ join_cols, all_cols = lcols.intersect(rcols)
29
+
30
+ replacements = {c1: c2 for c1, c2 in join_cols}
31
+ select_cols = [self._coalesce(c, replacements.get(c)) for c in all_cols]
32
+ select_clause = ', '.join(select_cols)
33
+
34
+ on_clause = ' AND '.join(f'{l.current_name} = {r.current_name}' for l, r in join_cols)
35
+
36
+ # create sql
37
+ return f'SELECT {select_clause} FROM ({lq}) {self._name()} FULL OUTER JOIN ({rq}) {self._name()} ON {on_clause}', all_cols
@@ -0,0 +1,24 @@
1
+ from typing import Tuple, Dict
2
+
3
+ from duckdb_kernel.db import Table
4
+ from ..RABinaryOperator import RABinaryOperator
5
+ from ...util.RenamableColumnList import RenamableColumnList
6
+
7
+
8
+ class LeftOuterJoin(RABinaryOperator):
9
+ @staticmethod
10
+ def symbols() -> Tuple[str, ...]:
11
+ return chr(10197), 'ljoin'
12
+
13
+ def to_sql(self, tables: Dict[str, Table]) -> Tuple[str, RenamableColumnList]:
14
+ # execute subqueries
15
+ lq, lcols = self.left.to_sql(tables)
16
+ rq, rcols = self.right.to_sql(tables)
17
+
18
+ # find matching columns
19
+ join_cols, all_cols = lcols.intersect(rcols)
20
+
21
+ on_clause = ' AND '.join(f'{l.current_name} = {r.current_name}' for l, r in join_cols)
22
+
23
+ # create sql
24
+ return f'SELECT {all_cols.list} FROM ({lq}) {self._name()} LEFT OUTER JOIN ({rq}) {self._name()} ON {on_clause}', all_cols
@@ -0,0 +1,24 @@
1
+ from typing import Tuple, Dict
2
+
3
+ from duckdb_kernel.db import Table
4
+ from ..RABinaryOperator import RABinaryOperator
5
+ from ...util.RenamableColumnList import RenamableColumnList
6
+
7
+
8
+ class RightOuterJoin(RABinaryOperator):
9
+ @staticmethod
10
+ def symbols() -> Tuple[str, ...]:
11
+ return chr(10198), 'rjoin'
12
+
13
+ def to_sql(self, tables: Dict[str, Table]) -> Tuple[str, RenamableColumnList]:
14
+ # execute subqueries
15
+ lq, lcols = self.left.to_sql(tables)
16
+ rq, rcols = self.right.to_sql(tables)
17
+
18
+ # find matching columns
19
+ join_cols, all_cols = lcols.intersect(rcols, prefer_right=True)
20
+
21
+ on_clause = ' AND '.join(f'{l.current_name} = {r.current_name}' for l, r in join_cols)
22
+
23
+ # create sql
24
+ return f'SELECT {all_cols.list} FROM ({lq}) {self._name()} RIGHT OUTER JOIN ({rq}) {self._name()} ON {on_clause}', all_cols
@@ -2,6 +2,9 @@ from .Cross import Cross
2
2
  from .Difference import Difference
3
3
  from .Intersection import Intersection
4
4
  from .Join import Join
5
+ from .LeftOuterJoin import LeftOuterJoin
6
+ from .RightOuterJoin import RightOuterJoin
7
+ from .FullOuterJoin import FullOuterJoin
5
8
  from .Union import Union
6
9
 
7
10
  from .Add import Add
@@ -30,12 +33,22 @@ LOGIC_BINARY_OPERATORS = sorted([
30
33
  ], key=lambda x: x.order, reverse=True)
31
34
 
32
35
  RA_BINARY_OPERATORS = [
33
- Difference,
34
- Union,
35
- Intersection,
36
- Join,
37
- Cross,
38
- Division
36
+ [Difference],
37
+ [Union],
38
+ [Intersection],
39
+ [Join],
40
+ [LeftOuterJoin, RightOuterJoin, FullOuterJoin],
41
+ [Cross],
42
+ [Division]
43
+ ]
44
+
45
+ RA_BINARY_SYMBOLS = [
46
+ {
47
+ symbol: operator
48
+ for operator in level
49
+ for symbol in operator.symbols()
50
+ }
51
+ for level in RA_BINARY_OPERATORS
39
52
  ]
40
53
 
41
54
  DC_SET = ConditionalSet
@@ -73,18 +73,26 @@ class RenamableColumnList(list[RenamableColumn]):
73
73
 
74
74
  return RenamableColumnList(cols.values())
75
75
 
76
- def intersect(self, other: 'RenamableColumnList') \
76
+ def intersect(self, other: 'RenamableColumnList', prefer_right: bool = False) \
77
77
  -> Tuple[List[Tuple[RenamableColumn, RenamableColumn]], 'RenamableColumnList']:
78
78
  self_cols: Dict[str, RenamableColumn] = {col.name: col for col in self}
79
79
  other_cols: Dict[str, RenamableColumn] = {col.name: col for col in other}
80
80
 
81
+ replacements: Dict[RenamableColumn, RenamableColumn] = {}
81
82
  intersection: List[Tuple[RenamableColumn, RenamableColumn]] = []
83
+
82
84
  for name in tuple(self_cols.keys()):
83
85
  if name in other_cols:
86
+ if prefer_right:
87
+ replacements[self_cols[name]] = other_cols[name]
88
+
84
89
  intersection.append((self_cols[name], other_cols[name]))
85
90
  del other_cols[name]
86
91
 
87
92
  # if len(intersection) == 0:
88
93
  # raise AssertionError('no common attributes found for join')
89
94
 
90
- return intersection, RenamableColumnList(self_cols.values(), other_cols.values())
95
+ return intersection, RenamableColumnList(
96
+ (replacements.get(x, x) for x in self_cols.values()),
97
+ other_cols.values()
98
+ )
@@ -0,0 +1,76 @@
1
+ import os
2
+ from typing import Dict, List, Tuple
3
+
4
+ from duckdb_kernel.db import Connection as DB, Table
5
+ from duckdb_kernel.db.error import EmptyResultError
6
+ from duckdb_kernel.parser.elements import RAElement
7
+ from duckdb_kernel.parser.elements.binary import ConditionalSet
8
+
9
+ with open('examples/tables.sql', 'r', encoding='utf-8') as file:
10
+ EXAMPLE_STMTS = [stmt
11
+ for stmt in file.read().split(';')
12
+ if stmt.strip()]
13
+
14
+
15
+ class Connection:
16
+ def __enter__(self):
17
+ db_type = os.environ.get('DB_TYPE')
18
+ if db_type == 'postgres':
19
+ host = os.environ.get('POSTGRES_HOST', 'localhost')
20
+ port = int(os.environ.get('POSTGRES_PORT', 5432))
21
+ username = os.environ.get('POSTGRES_USER', 'postgres')
22
+ password = os.environ.get('POSTGRES_PASSWORD', 'postgres')
23
+
24
+ from duckdb_kernel.db.implementation.postgres import Connection as PostgreSQL
25
+ self.con: DB = PostgreSQL(host, port, username, password, None)
26
+ elif db_type == 'sqlite':
27
+ from duckdb_kernel.db.implementation.sqlite import Connection as SQLite
28
+ self.con: DB = SQLite(':memory:')
29
+ else:
30
+ from duckdb_kernel.db.implementation.duckdb import Connection as DuckDB
31
+ self.con: DB = DuckDB(':memory:')
32
+
33
+ for stmt in EXAMPLE_STMTS:
34
+ try:
35
+ self.con.execute(stmt)
36
+ except EmptyResultError:
37
+ pass
38
+
39
+ return self
40
+
41
+ def __exit__(self, exc_type, exc_val, exc_tb):
42
+ self.con.close()
43
+
44
+ @property
45
+ def tables(self) -> Dict[str, Table]:
46
+ return self.con.analyze()
47
+
48
+ def execute_sql_return_cols(self, query: str) -> Tuple[List, List]:
49
+ return self.con.execute(query)
50
+
51
+ def execute_sql(self, query: str) -> List:
52
+ _, rows = self.execute_sql_return_cols(query)
53
+ return rows
54
+
55
+ def execute_ra_return_cols(self, root: RAElement) -> Tuple[List, List]:
56
+ sql = root.to_sql_with_renamed_columns(self.tables)
57
+ cols, rows = self.execute_sql_return_cols(sql)
58
+
59
+ return cols, sorted(rows, key=lambda t: tuple(-1 if x is None else x for x in t))
60
+
61
+ def execute_ra(self, root: RAElement) -> List:
62
+ _, rows = self.execute_ra_return_cols(root)
63
+ return rows
64
+
65
+ def execute_dc_return_cols(self, root: ConditionalSet) -> Tuple[List, List]:
66
+ sql, cnm = root.to_sql_with_renamed_columns(self.tables)
67
+ cols, rows = self.execute_sql_return_cols(sql)
68
+
69
+ return [cnm.get(c, c) for c in cols], sorted(rows)
70
+
71
+ def execute_dc(self, root: ConditionalSet) -> List:
72
+ _, rows = self.execute_dc_return_cols(root)
73
+ return rows
74
+
75
+
76
+ __all__ = ['Connection']