AlchemyReflection 0.1.2__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.
- alchemy_reflection/__init__.py +6 -0
- alchemy_reflection/database.py +123 -0
- alchemy_reflection/execution.py +130 -0
- alchemy_reflection/reflection.py +95 -0
- alchemyreflection-0.1.2.dist-info/METADATA +243 -0
- alchemyreflection-0.1.2.dist-info/RECORD +9 -0
- alchemyreflection-0.1.2.dist-info/WHEEL +5 -0
- alchemyreflection-0.1.2.dist-info/licenses/LICENSE +21 -0
- alchemyreflection-0.1.2.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pprint import pprint as _pprint
|
|
5
|
+
|
|
6
|
+
from sqlalchemy import (
|
|
7
|
+
URL,
|
|
8
|
+
Engine,
|
|
9
|
+
MetaData,
|
|
10
|
+
Selectable,
|
|
11
|
+
Table,
|
|
12
|
+
create_engine,
|
|
13
|
+
inspect,
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
from .execution import QueryExecutor
|
|
17
|
+
from .reflection import ReflectedTable
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Database:
|
|
21
|
+
"""
|
|
22
|
+
The main interface of AlchemyReflection for database reflection and query execution.
|
|
23
|
+
Accepts SQLAlchemy connection URLs for supported database dialects,
|
|
24
|
+
as well as raw ODBC connection strings for SQL Server.
|
|
25
|
+
"""
|
|
26
|
+
def __init__(self, conn: str | URL):
|
|
27
|
+
if (
|
|
28
|
+
isinstance(conn, str)
|
|
29
|
+
and not re.match(r"^[a-zA-Z][a-zA-Z0-9+.-]*://", conn)
|
|
30
|
+
):
|
|
31
|
+
conn = URL.create(
|
|
32
|
+
"mssql+pyodbc",
|
|
33
|
+
query={"odbc_connect": conn},
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
self._engine = create_engine(
|
|
37
|
+
conn,
|
|
38
|
+
pool_pre_ping=True,
|
|
39
|
+
)
|
|
40
|
+
self.metadata = MetaData()
|
|
41
|
+
|
|
42
|
+
@property
|
|
43
|
+
def engine(self) -> Engine:
|
|
44
|
+
return self._engine
|
|
45
|
+
|
|
46
|
+
def reflect(self,source: str) -> ReflectedTable:
|
|
47
|
+
"""
|
|
48
|
+
Reflect a database table or view into a ReflectedTable instance.
|
|
49
|
+
Requires a schema-qualified table or view name.
|
|
50
|
+
--------
|
|
51
|
+
e.g.
|
|
52
|
+
>>> db.reflect("someschema.sometable")
|
|
53
|
+
"""
|
|
54
|
+
schema, separator, tablename = source.rpartition(".")
|
|
55
|
+
|
|
56
|
+
if not separator or not schema or not tablename:
|
|
57
|
+
raise ValueError("A schema-qualified table or view name is required")
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
ReflectedTable(
|
|
61
|
+
Table(
|
|
62
|
+
tablename,
|
|
63
|
+
self.metadata,
|
|
64
|
+
schema=schema,
|
|
65
|
+
autoload_with=self.engine,
|
|
66
|
+
),
|
|
67
|
+
self.engine,
|
|
68
|
+
)
|
|
69
|
+
)
|
|
70
|
+
|
|
71
|
+
def query(
|
|
72
|
+
self,
|
|
73
|
+
statement: Selectable | ReflectedTable | str,
|
|
74
|
+
) -> QueryExecutor:
|
|
75
|
+
"""
|
|
76
|
+
Create a QueryExecutor for query execution, row retrieval, and
|
|
77
|
+
result conversion to pandas, Polars, NumPy, PyArrow, etc...
|
|
78
|
+
Accepts raw SQL statements, SQLAlchemy selectables, and ReflectedTable instances.
|
|
79
|
+
"""
|
|
80
|
+
return QueryExecutor(statement, self.engine)
|
|
81
|
+
|
|
82
|
+
def catalogue(
|
|
83
|
+
self,
|
|
84
|
+
keyword: str | None = None,
|
|
85
|
+
pprint: bool = False,
|
|
86
|
+
) -> dict[str, dict[str, list[str]]]:
|
|
87
|
+
"""
|
|
88
|
+
Return a dictionary of all schemas, tables, and views in the database.
|
|
89
|
+
Supports keyword filtering and optional pretty-printing of the results.
|
|
90
|
+
"""
|
|
91
|
+
inspector = inspect(self.engine)
|
|
92
|
+
catalogue = {
|
|
93
|
+
schema: {
|
|
94
|
+
"tables": inspector.get_table_names(schema=schema),
|
|
95
|
+
"views": inspector.get_view_names(schema=schema),
|
|
96
|
+
}
|
|
97
|
+
for schema in inspector.get_schema_names()
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if keyword is not None:
|
|
101
|
+
keyword = keyword.lower()
|
|
102
|
+
catalogue = {
|
|
103
|
+
schema: {
|
|
104
|
+
obj_type: [
|
|
105
|
+
obj
|
|
106
|
+
for obj in objects
|
|
107
|
+
if keyword in obj.lower()
|
|
108
|
+
]
|
|
109
|
+
for obj_type, objects in content.items()
|
|
110
|
+
}
|
|
111
|
+
for schema, content in catalogue.items()
|
|
112
|
+
if any(
|
|
113
|
+
keyword in obj.lower()
|
|
114
|
+
for objects in content.values()
|
|
115
|
+
for obj in objects
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
if pprint:
|
|
119
|
+
_pprint(catalogue)
|
|
120
|
+
return catalogue
|
|
121
|
+
|
|
122
|
+
def dispose(self) -> None:
|
|
123
|
+
self.engine.dispose()
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import polars as pl
|
|
8
|
+
from sqlalchemy import Engine, FromClause, Selectable, select, text
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
import pyarrow as pa
|
|
12
|
+
|
|
13
|
+
from .reflection import ReflectedTable
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class QueryExecutor:
|
|
17
|
+
"""
|
|
18
|
+
Execute SQL statements and retrieve results in multiple formats.
|
|
19
|
+
|
|
20
|
+
Supports SQLAlchemy selectable constructs, ReflectedTable, and raw
|
|
21
|
+
SQL strings. Table-like inputs are converted into SQLAlchemy Select
|
|
22
|
+
objects, while SQL strings are converted into TextClause objects.
|
|
23
|
+
|
|
24
|
+
Execution is deferred until a result retrieval method is called.
|
|
25
|
+
"""
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
statement: Selectable | ReflectedTable | str,
|
|
29
|
+
engine: Engine,
|
|
30
|
+
) -> None:
|
|
31
|
+
if isinstance(statement, str):
|
|
32
|
+
statement = text(statement)
|
|
33
|
+
elif hasattr(statement, "__clause_element__"):
|
|
34
|
+
statement = statement.__clause_element__()
|
|
35
|
+
|
|
36
|
+
if isinstance(statement, FromClause):
|
|
37
|
+
statement = select(statement)
|
|
38
|
+
|
|
39
|
+
self.statement = statement
|
|
40
|
+
self.engine = engine
|
|
41
|
+
|
|
42
|
+
def to_pd(self) -> pd.DataFrame | pd.Series:
|
|
43
|
+
"""
|
|
44
|
+
Returns query result as a pandas DataFrame or Series.
|
|
45
|
+
A single-column query returns a Series; otherwise, a DataFrame.
|
|
46
|
+
--------
|
|
47
|
+
e.g.
|
|
48
|
+
>>> type(db.query(select(table.c.amount)).to_pd()).__name__
|
|
49
|
+
'Series'
|
|
50
|
+
>>> type(db.query(select(table)).to_pd()).__name__
|
|
51
|
+
'DataFrame'
|
|
52
|
+
"""
|
|
53
|
+
with self.engine.connect() as conn:
|
|
54
|
+
df = pd.read_sql_query(self.statement, conn)
|
|
55
|
+
|
|
56
|
+
return df.iloc[:, 0] if df.shape[1] == 1 else df
|
|
57
|
+
|
|
58
|
+
def to_pl(self) -> pl.DataFrame | pl.Series:
|
|
59
|
+
"""
|
|
60
|
+
Returns query result as a Polars DataFrame or Series.
|
|
61
|
+
Similar to to_pd(), a single-column query returns a Series.
|
|
62
|
+
"""
|
|
63
|
+
with self.engine.connect() as conn:
|
|
64
|
+
df = pl.read_database(self.statement, conn)
|
|
65
|
+
|
|
66
|
+
return df.to_series(0) if df.width == 1 else df
|
|
67
|
+
|
|
68
|
+
def to_numpy(self, dtype: Any = None) -> np.ndarray:
|
|
69
|
+
"""
|
|
70
|
+
Returns query results as a NumPy array.
|
|
71
|
+
Single-column results are returned as 1D arrays, while multi-column
|
|
72
|
+
results retain their 2D structure.
|
|
73
|
+
The dtype is inferred by default and can be explicitly specified
|
|
74
|
+
to control type conversion or preserve mixed types.
|
|
75
|
+
"""
|
|
76
|
+
with self.engine.connect() as conn:
|
|
77
|
+
result = conn.execute(self.statement)
|
|
78
|
+
|
|
79
|
+
array = np.asarray(
|
|
80
|
+
[tuple(row) for row in result],
|
|
81
|
+
dtype=dtype,
|
|
82
|
+
).reshape(-1, len(result.keys()))
|
|
83
|
+
|
|
84
|
+
return array[:, 0] if array.shape[1] == 1 else array
|
|
85
|
+
|
|
86
|
+
def to_arrow(self) -> pa.Table | pa.Array:
|
|
87
|
+
"""
|
|
88
|
+
Returns query results as a PyArrow Table or Array.
|
|
89
|
+
Similar to to_pd(), single-column results are returned as an Array.
|
|
90
|
+
Requires the optional PyArrow dependency.
|
|
91
|
+
"""
|
|
92
|
+
return self.to_pl().to_arrow()
|
|
93
|
+
|
|
94
|
+
def to_records(self) -> list[dict[str, Any]]:
|
|
95
|
+
"""
|
|
96
|
+
Returns query results as a list of dictionaries, with each dictionary
|
|
97
|
+
representing a row and column names as keys.
|
|
98
|
+
"""
|
|
99
|
+
return [row._asdict() for row in self.fetch()]
|
|
100
|
+
|
|
101
|
+
def to_scalar(self) -> Any:
|
|
102
|
+
"""
|
|
103
|
+
Returns the scalar value from a query yielding exactly one row and column.
|
|
104
|
+
Unlike SQLAlchemy's Result.scalar(), this method enforces both
|
|
105
|
+
row and column cardinality.
|
|
106
|
+
--------
|
|
107
|
+
e.g.
|
|
108
|
+
>>> db.query(select(func.count()).select_from(sometable)).to_scalar()
|
|
109
|
+
77
|
|
110
|
+
"""
|
|
111
|
+
with self.engine.connect() as conn:
|
|
112
|
+
result = conn.execute(self.statement)
|
|
113
|
+
|
|
114
|
+
if len(result.keys()) != 1:
|
|
115
|
+
raise ValueError("Multiple columns were found when exactly one was required")
|
|
116
|
+
|
|
117
|
+
return result.scalar_one()
|
|
118
|
+
|
|
119
|
+
def fetch(self, n_rows: int | None = None) -> list:
|
|
120
|
+
"""
|
|
121
|
+
Retrieves query results as a list of SQLAlchemy Row objects.
|
|
122
|
+
All rows are retrieved by default. Specify n_rows to limit the
|
|
123
|
+
number of rows returned.
|
|
124
|
+
"""
|
|
125
|
+
if n_rows is not None and (type(n_rows) is not int or n_rows < 0):
|
|
126
|
+
raise ValueError("n_rows must be a non-negative integer")
|
|
127
|
+
|
|
128
|
+
with self.engine.connect() as conn:
|
|
129
|
+
result = conn.execute(self.statement)
|
|
130
|
+
return result.all() if n_rows is None else result.fetchmany(n_rows)
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from pprint import pprint
|
|
4
|
+
|
|
5
|
+
from sqlalchemy import (
|
|
6
|
+
CheckConstraint,
|
|
7
|
+
Engine,
|
|
8
|
+
ForeignKeyConstraint,
|
|
9
|
+
Table,
|
|
10
|
+
)
|
|
11
|
+
|
|
12
|
+
from .execution import QueryExecutor
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ReflectedTable:
|
|
16
|
+
"""
|
|
17
|
+
Extends the SQLAlchemy Table interface with query execution and result
|
|
18
|
+
retrieval methods from QueryExecutor.
|
|
19
|
+
|
|
20
|
+
Unresolved attributes are delegated to the underlying SQLAlchemy Table
|
|
21
|
+
first, then to QueryExecutor.
|
|
22
|
+
"""
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
table: Table,
|
|
26
|
+
engine: Engine,
|
|
27
|
+
) -> None:
|
|
28
|
+
self.sa = table
|
|
29
|
+
self.engine = engine
|
|
30
|
+
|
|
31
|
+
is_clause_element = False
|
|
32
|
+
|
|
33
|
+
def __clause_element__(self) -> Table:
|
|
34
|
+
return self.sa
|
|
35
|
+
|
|
36
|
+
def __getattr__(self, name: str):
|
|
37
|
+
try:
|
|
38
|
+
return getattr(self.sa, name)
|
|
39
|
+
except AttributeError:
|
|
40
|
+
return getattr(QueryExecutor(self.sa, self.engine), name)
|
|
41
|
+
|
|
42
|
+
def __dir__(self):
|
|
43
|
+
return sorted(
|
|
44
|
+
set(super().__dir__())
|
|
45
|
+
| set(dir(self.sa))
|
|
46
|
+
| set(dir(QueryExecutor(self.sa, self.engine)))
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
def inspect(self) -> None:
|
|
50
|
+
"""
|
|
51
|
+
Pretty-print the reflected table's metadata and structural information,
|
|
52
|
+
including its columns, constraints, and other table properties.
|
|
53
|
+
"""
|
|
54
|
+
meta = {
|
|
55
|
+
"schema": self.sa.schema,
|
|
56
|
+
"table": self.sa.name,
|
|
57
|
+
"columns": [
|
|
58
|
+
{
|
|
59
|
+
"name": c.name,
|
|
60
|
+
"type": str(c.type),
|
|
61
|
+
"nullable": c.nullable,
|
|
62
|
+
"primary_key": c.primary_key,
|
|
63
|
+
}
|
|
64
|
+
for c in self.sa.columns
|
|
65
|
+
],
|
|
66
|
+
"foreign_keys": [
|
|
67
|
+
{
|
|
68
|
+
"column": fk.parent.name,
|
|
69
|
+
"references": fk.target_fullname,
|
|
70
|
+
}
|
|
71
|
+
for fk in self.sa.foreign_keys
|
|
72
|
+
],
|
|
73
|
+
"indexes": [
|
|
74
|
+
{
|
|
75
|
+
"name": index.name,
|
|
76
|
+
"columns": [c.name for c in index.columns],
|
|
77
|
+
"unique": index.unique,
|
|
78
|
+
}
|
|
79
|
+
for index in self.sa.indexes
|
|
80
|
+
],
|
|
81
|
+
"constraints": [
|
|
82
|
+
{
|
|
83
|
+
"type": type(constraint).__name__,
|
|
84
|
+
"name": constraint.name,
|
|
85
|
+
"details": (
|
|
86
|
+
str(constraint.sqltext)
|
|
87
|
+
if isinstance(constraint, CheckConstraint)
|
|
88
|
+
else [c.name for c in constraint.columns]
|
|
89
|
+
),
|
|
90
|
+
}
|
|
91
|
+
for constraint in self.sa.constraints
|
|
92
|
+
if not isinstance(constraint, ForeignKeyConstraint)
|
|
93
|
+
],
|
|
94
|
+
}
|
|
95
|
+
pprint(meta, sort_dicts=False)
|
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: AlchemyReflection
|
|
3
|
+
Version: 0.1.2
|
|
4
|
+
Summary: An object-oriented interface for SQLAlchemy, designed for database reflection, query execution, and result retrieval, built around method chaining and native interoperability.
|
|
5
|
+
Author: MI77-LAB
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Repository, https://github.com/mirabelleding/AlchemyReflection
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Topic :: Database
|
|
13
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
14
|
+
Requires-Python: >=3.10
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
License-File: LICENSE
|
|
17
|
+
Requires-Dist: sqlalchemy<3.0,>=2.0
|
|
18
|
+
Requires-Dist: pandas<4.0,>=2.0
|
|
19
|
+
Requires-Dist: polars<3.0,>=1.0
|
|
20
|
+
Provides-Extra: arrow
|
|
21
|
+
Requires-Dist: pyarrow<27.0,>=15.0; extra == "arrow"
|
|
22
|
+
Provides-Extra: pyodbc
|
|
23
|
+
Requires-Dist: pyodbc<6.0,>=5.0; extra == "pyodbc"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# AlchemyReflection
|
|
27
|
+
A lightweight Python package built on SQLAlchemy for database connection management, table reflection, schema inspection, and query result retrieval.
|
|
28
|
+
|
|
29
|
+
Designed with an emphasis on API ergonomics and method chaining, the object-oriented interface extends SQLAlchemy functionality while preserving native interoperability.
|
|
30
|
+
|
|
31
|
+
## Installation
|
|
32
|
+
|
|
33
|
+
**Install from PyPI**
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install AlchemyReflection
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
**Install from GitHub**
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install git+https://github.com/mirabelleding/AlchemyReflection.git
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## Connection
|
|
46
|
+
|
|
47
|
+
`Database` accepts SQLAlchemy connection URLs for supported database dialects. Raw ODBC connection strings are also accepted for SQL Server.
|
|
48
|
+
|
|
49
|
+
**SQLAlchemy URL:**
|
|
50
|
+
|
|
51
|
+
```python
|
|
52
|
+
from alchemy_reflection import Database
|
|
53
|
+
|
|
54
|
+
db = Database("postgresql+psycopg://user:password@localhost:5432/database_name")
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**Raw SQL Server ODBC connection string:**<br>
|
|
58
|
+
*Install the optional pyodbc dependency*
|
|
59
|
+
```bash
|
|
60
|
+
pip install "AlchemyReflection[pyodbc]"
|
|
61
|
+
```
|
|
62
|
+
```text
|
|
63
|
+
DRIVER={ODBC Driver 18 for SQL Server};
|
|
64
|
+
SERVER=server_name;
|
|
65
|
+
DATABASE=database_name;
|
|
66
|
+
UID=username;
|
|
67
|
+
PWD=password;
|
|
68
|
+
```
|
|
69
|
+
```python
|
|
70
|
+
import os
|
|
71
|
+
from alchemy_reflection import Database
|
|
72
|
+
|
|
73
|
+
db = Database(os.environ["DB_ODBC"])
|
|
74
|
+
```
|
|
75
|
+
Each `Database` instance maintains its own SQLAlchemy engine and reflected metadata. </br>
|
|
76
|
+
|
|
77
|
+
## Basic Usage
|
|
78
|
+
```python
|
|
79
|
+
import os
|
|
80
|
+
|
|
81
|
+
from sqlalchemy import select
|
|
82
|
+
from alchemy_reflection import Database
|
|
83
|
+
|
|
84
|
+
# Initialize database connection
|
|
85
|
+
db = Database(os.environ["DB_ODBC"])
|
|
86
|
+
|
|
87
|
+
# Search and pretty-print matching tables and views
|
|
88
|
+
db.catalogue("some keywords", pprint=True)
|
|
89
|
+
|
|
90
|
+
# Instantiate a ReflectedTable
|
|
91
|
+
table = db.reflect("schemaname.tablename")
|
|
92
|
+
|
|
93
|
+
# Inspect table metadata
|
|
94
|
+
table.inspect()
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Native SQLAlchemy Interoperability
|
|
98
|
+
|
|
99
|
+
`ReflectedTable` provides access to native SQLAlchemy `Table` attributes and methods, alongside `QueryExecutor` methods for query execution and result retrieval.
|
|
100
|
+
Native SQLAlchemy expressions such as `select(reflected_table)` are also supported.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
reflected_table.name
|
|
104
|
+
reflected_table.schema
|
|
105
|
+
reflected_table.columns.keys()
|
|
106
|
+
reflected_table.primary_key
|
|
107
|
+
reflected_table.alias("t")
|
|
108
|
+
reflected_table.select()
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Query Execution and Result Retrieval
|
|
112
|
+
|
|
113
|
+
`QueryExecutor` supports query execution and result retrieval for raw SQL statements, SQLAlchemy `Selectable`, and `ReflectedTable` instances. Its methods are accessible through `Database.query()` or directly through `ReflectedTable` interface.
|
|
114
|
+
|
|
115
|
+
| Method | Return Type |
|
|
116
|
+
| --- | --- |
|
|
117
|
+
| `to_pd()` | pandas `DataFrame`, or `Series` for single-column queries |
|
|
118
|
+
| `to_pl()` | Polars `DataFrame`, or `Series` for single-column queries |
|
|
119
|
+
| `to_numpy(dtype=None)` | 2D NumPy array, or 1D for single-column queries; dtype inferred unless specified |
|
|
120
|
+
| `to_arrow()` | PyArrow `Table`, or `Array` for single-column queries; *requires the optional `pyarrow` dependency.* |
|
|
121
|
+
| `to_records()` | List of dictionaries with column names as keys |
|
|
122
|
+
| `fetch(n_rows=None)` | List of SQLAlchemy `Row` objects; all rows are retrieved by default |
|
|
123
|
+
| `to_scalar()` | Scalar value from a single-row, single-column query |
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
```python
|
|
127
|
+
from sqlalchemy import func, select
|
|
128
|
+
|
|
129
|
+
stmt = select(table.c.some_column)
|
|
130
|
+
|
|
131
|
+
series = db.query(stmt).to_pd()
|
|
132
|
+
array = db.query(stmt).to_numpy()
|
|
133
|
+
rows = db.query(stmt).fetch(7)
|
|
134
|
+
|
|
135
|
+
count_stmt = select(func.count()).select_from(table)
|
|
136
|
+
count = db.query(count_stmt).to_scalar()
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## Advanced SQLAlchemy Queries
|
|
140
|
+
|
|
141
|
+
SQL construction remains entirely native to SQLAlchemy. Below are examples of advanced query expressions and with DataFrame operations.
|
|
142
|
+
```python
|
|
143
|
+
import hashlib
|
|
144
|
+
from sqlalchemy import select, func, exists, or_
|
|
145
|
+
|
|
146
|
+
en_cours = (
|
|
147
|
+
(e := db.reflect("mi77_lab.experiments").alias("e"))
|
|
148
|
+
.select()
|
|
149
|
+
.where(
|
|
150
|
+
e.c.status.in_(["unfinished", "in_exploration"]),
|
|
151
|
+
~exists().where(
|
|
152
|
+
db.reflect("mi77_lab.archives").c.experiment_id
|
|
153
|
+
== e.c.experiment_id
|
|
154
|
+
),
|
|
155
|
+
)
|
|
156
|
+
.add_columns(
|
|
157
|
+
func.row_number().over(
|
|
158
|
+
partition_by=e.c.inspiration_id,
|
|
159
|
+
order_by=e.c.updated_at.desc(),
|
|
160
|
+
).label("rn")
|
|
161
|
+
)
|
|
162
|
+
.cte("en_cours")
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
# Now the art of composition
|
|
166
|
+
next_inventions = (
|
|
167
|
+
db.query(
|
|
168
|
+
select(
|
|
169
|
+
(i := db.reflect("mi77_lab.inspirations").alias("i"))
|
|
170
|
+
.c.name.label("inspiration"),
|
|
171
|
+
i.c.category,
|
|
172
|
+
en_cours.c.name.label("invention"),
|
|
173
|
+
en_cours.c.updated_at,
|
|
174
|
+
)
|
|
175
|
+
.join(en_cours, en_cours.c.inspiration_id == i.c.inspiration_id)
|
|
176
|
+
.where(
|
|
177
|
+
en_cours.c.rn == 1,
|
|
178
|
+
or_(
|
|
179
|
+
i.c.source.in_(["some magic", "and more..."]),
|
|
180
|
+
i.c.intrigue >= 7,
|
|
181
|
+
),
|
|
182
|
+
)
|
|
183
|
+
)
|
|
184
|
+
.to_pd()
|
|
185
|
+
.pipe(refactor_atelier)
|
|
186
|
+
.groupby("category")
|
|
187
|
+
.get_group("nouveau")
|
|
188
|
+
.astype({"introspection": "string"})
|
|
189
|
+
.sort_values(
|
|
190
|
+
["updated_at", "essence"],
|
|
191
|
+
ascending=[False, False],
|
|
192
|
+
)
|
|
193
|
+
.assign(
|
|
194
|
+
imprint=lambda df: (
|
|
195
|
+
df.astype(str)
|
|
196
|
+
.agg("-".join, axis=1)
|
|
197
|
+
.map(
|
|
198
|
+
lambda value: hashlib.blake2s(
|
|
199
|
+
value.encode(),
|
|
200
|
+
digest_size=7,
|
|
201
|
+
).hexdigest()
|
|
202
|
+
)
|
|
203
|
+
)
|
|
204
|
+
)
|
|
205
|
+
.loc[:, cols]
|
|
206
|
+
.to_numpy()
|
|
207
|
+
)
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## Multiple Database Connections
|
|
211
|
+
|
|
212
|
+
```python
|
|
213
|
+
dev = Database(os.environ["DEV_ODBC"])
|
|
214
|
+
test = Database(os.environ["TEST_ODBC"])
|
|
215
|
+
|
|
216
|
+
dev_df = dev.reflect("schemaname.tablename").to_pd()
|
|
217
|
+
test_df = test.reflect("schemaname.tablename").to_pl()
|
|
218
|
+
|
|
219
|
+
dev.dispose()
|
|
220
|
+
test.dispose()
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## Interface
|
|
224
|
+
|
|
225
|
+
| Class | Attributes / Methods |
|
|
226
|
+
| --- | --- |
|
|
227
|
+
| `Database` | `engine`, `metadata`, `reflect()`, `catalogue()`, `query()` |
|
|
228
|
+
| `ReflectedTable` | `sa`, `engine`, native SQLAlchemy `Table` attributes and methods, `inspect()`, delegated `QueryExecutor` methods |
|
|
229
|
+
| `QueryExecutor` | `statement`, `engine`, `to_pd()`, `to_pl()`, `to_numpy()`, `to_arrow()`, `to_records()`, `fetch()`, `to_scalar()` |
|
|
230
|
+
|
|
231
|
+
`Database.reflect()` returns a `ReflectedTable`, while `Database.query()` returns a `QueryExecutor`.
|
|
232
|
+
|
|
233
|
+
`ReflectedTable.__getattr__()` forwards unresolved attributes to the underlying SQLAlchemy `Table` first, then to `QueryExecutor`.
|
|
234
|
+
|
|
235
|
+
`ReflectedTable.__clause_element__()` enables SQLAlchemy expression coercion. The explicit `.sa` attribute exposes the underlying SQLAlchemy `Table` when a native table object is required.
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
## Design Philosophy
|
|
239
|
+
|
|
240
|
+
Built on the belief that abstractions should eliminate repetitive operations without obscuring the underlying framework or introducing unnecessary complexity. The package simplifies common database operations while retaining SQLAlchemy's native capabilities.
|
|
241
|
+
|
|
242
|
+
## License
|
|
243
|
+
MIT License © MI77-LAB
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
alchemy_reflection/__init__.py,sha256=CXomw4I9nGjHslHxH2_bFqM9UT1FKLcud7YAplyOnXs,62
|
|
2
|
+
alchemy_reflection/database.py,sha256=oM6qdf93ne2TcPcOwEdfxJuX1ABUg4Y616q46ZpUn-8,3607
|
|
3
|
+
alchemy_reflection/execution.py,sha256=8Wy7yeG34zToQvIf6JjmCv4WMfJjGnrKf29NWFvb9UQ,4536
|
|
4
|
+
alchemy_reflection/reflection.py,sha256=l8CC3yEIxeOQGaB7bXur7gMMmy1w4QmaWwNO3cCZObs,2758
|
|
5
|
+
alchemyreflection-0.1.2.dist-info/licenses/LICENSE,sha256=CVTJbyGzb7xAhtYnS24hh69XSuly05GKGOhULRCQxs4,1065
|
|
6
|
+
alchemyreflection-0.1.2.dist-info/METADATA,sha256=8z7v4oVeoL0UjzyplUSmrWRLggHgNOTBrA9MqASXlks,7670
|
|
7
|
+
alchemyreflection-0.1.2.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
8
|
+
alchemyreflection-0.1.2.dist-info/top_level.txt,sha256=sUAJdgyhMr17pRw5Z5wIJ_mGk1pJr8AqU8jN7IsLIaM,19
|
|
9
|
+
alchemyreflection-0.1.2.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MI77-LAB
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
alchemy_reflection
|