AlchemyReflection 0.1.2__tar.gz

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.
@@ -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,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ AlchemyReflection.egg-info/PKG-INFO
5
+ AlchemyReflection.egg-info/SOURCES.txt
6
+ AlchemyReflection.egg-info/dependency_links.txt
7
+ AlchemyReflection.egg-info/requires.txt
8
+ AlchemyReflection.egg-info/top_level.txt
9
+ alchemy_reflection/__init__.py
10
+ alchemy_reflection/database.py
11
+ alchemy_reflection/execution.py
12
+ alchemy_reflection/reflection.py
@@ -0,0 +1,9 @@
1
+ sqlalchemy<3.0,>=2.0
2
+ pandas<4.0,>=2.0
3
+ polars<3.0,>=1.0
4
+
5
+ [arrow]
6
+ pyarrow<27.0,>=15.0
7
+
8
+ [pyodbc]
9
+ pyodbc<6.0,>=5.0
@@ -0,0 +1 @@
1
+ alchemy_reflection
@@ -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,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,218 @@
1
+ # AlchemyReflection
2
+ A lightweight Python package built on SQLAlchemy for database connection management, table reflection, schema inspection, and query result retrieval.
3
+
4
+ Designed with an emphasis on API ergonomics and method chaining, the object-oriented interface extends SQLAlchemy functionality while preserving native interoperability.
5
+
6
+ ## Installation
7
+
8
+ **Install from PyPI**
9
+
10
+ ```bash
11
+ pip install AlchemyReflection
12
+ ```
13
+
14
+ **Install from GitHub**
15
+
16
+ ```bash
17
+ pip install git+https://github.com/mirabelleding/AlchemyReflection.git
18
+ ```
19
+
20
+ ## Connection
21
+
22
+ `Database` accepts SQLAlchemy connection URLs for supported database dialects. Raw ODBC connection strings are also accepted for SQL Server.
23
+
24
+ **SQLAlchemy URL:**
25
+
26
+ ```python
27
+ from alchemy_reflection import Database
28
+
29
+ db = Database("postgresql+psycopg://user:password@localhost:5432/database_name")
30
+ ```
31
+
32
+ **Raw SQL Server ODBC connection string:**<br>
33
+ *Install the optional pyodbc dependency*
34
+ ```bash
35
+ pip install "AlchemyReflection[pyodbc]"
36
+ ```
37
+ ```text
38
+ DRIVER={ODBC Driver 18 for SQL Server};
39
+ SERVER=server_name;
40
+ DATABASE=database_name;
41
+ UID=username;
42
+ PWD=password;
43
+ ```
44
+ ```python
45
+ import os
46
+ from alchemy_reflection import Database
47
+
48
+ db = Database(os.environ["DB_ODBC"])
49
+ ```
50
+ Each `Database` instance maintains its own SQLAlchemy engine and reflected metadata. </br>
51
+
52
+ ## Basic Usage
53
+ ```python
54
+ import os
55
+
56
+ from sqlalchemy import select
57
+ from alchemy_reflection import Database
58
+
59
+ # Initialize database connection
60
+ db = Database(os.environ["DB_ODBC"])
61
+
62
+ # Search and pretty-print matching tables and views
63
+ db.catalogue("some keywords", pprint=True)
64
+
65
+ # Instantiate a ReflectedTable
66
+ table = db.reflect("schemaname.tablename")
67
+
68
+ # Inspect table metadata
69
+ table.inspect()
70
+ ```
71
+
72
+ ## Native SQLAlchemy Interoperability
73
+
74
+ `ReflectedTable` provides access to native SQLAlchemy `Table` attributes and methods, alongside `QueryExecutor` methods for query execution and result retrieval.
75
+ Native SQLAlchemy expressions such as `select(reflected_table)` are also supported.
76
+
77
+ ```python
78
+ reflected_table.name
79
+ reflected_table.schema
80
+ reflected_table.columns.keys()
81
+ reflected_table.primary_key
82
+ reflected_table.alias("t")
83
+ reflected_table.select()
84
+ ```
85
+
86
+ ## Query Execution and Result Retrieval
87
+
88
+ `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.
89
+
90
+ | Method | Return Type |
91
+ | --- | --- |
92
+ | `to_pd()` | pandas `DataFrame`, or `Series` for single-column queries |
93
+ | `to_pl()` | Polars `DataFrame`, or `Series` for single-column queries |
94
+ | `to_numpy(dtype=None)` | 2D NumPy array, or 1D for single-column queries; dtype inferred unless specified |
95
+ | `to_arrow()` | PyArrow `Table`, or `Array` for single-column queries; *requires the optional `pyarrow` dependency.* |
96
+ | `to_records()` | List of dictionaries with column names as keys |
97
+ | `fetch(n_rows=None)` | List of SQLAlchemy `Row` objects; all rows are retrieved by default |
98
+ | `to_scalar()` | Scalar value from a single-row, single-column query |
99
+
100
+
101
+ ```python
102
+ from sqlalchemy import func, select
103
+
104
+ stmt = select(table.c.some_column)
105
+
106
+ series = db.query(stmt).to_pd()
107
+ array = db.query(stmt).to_numpy()
108
+ rows = db.query(stmt).fetch(7)
109
+
110
+ count_stmt = select(func.count()).select_from(table)
111
+ count = db.query(count_stmt).to_scalar()
112
+ ```
113
+
114
+ ## Advanced SQLAlchemy Queries
115
+
116
+ SQL construction remains entirely native to SQLAlchemy. Below are examples of advanced query expressions and with DataFrame operations.
117
+ ```python
118
+ import hashlib
119
+ from sqlalchemy import select, func, exists, or_
120
+
121
+ en_cours = (
122
+ (e := db.reflect("mi77_lab.experiments").alias("e"))
123
+ .select()
124
+ .where(
125
+ e.c.status.in_(["unfinished", "in_exploration"]),
126
+ ~exists().where(
127
+ db.reflect("mi77_lab.archives").c.experiment_id
128
+ == e.c.experiment_id
129
+ ),
130
+ )
131
+ .add_columns(
132
+ func.row_number().over(
133
+ partition_by=e.c.inspiration_id,
134
+ order_by=e.c.updated_at.desc(),
135
+ ).label("rn")
136
+ )
137
+ .cte("en_cours")
138
+ )
139
+
140
+ # Now the art of composition
141
+ next_inventions = (
142
+ db.query(
143
+ select(
144
+ (i := db.reflect("mi77_lab.inspirations").alias("i"))
145
+ .c.name.label("inspiration"),
146
+ i.c.category,
147
+ en_cours.c.name.label("invention"),
148
+ en_cours.c.updated_at,
149
+ )
150
+ .join(en_cours, en_cours.c.inspiration_id == i.c.inspiration_id)
151
+ .where(
152
+ en_cours.c.rn == 1,
153
+ or_(
154
+ i.c.source.in_(["some magic", "and more..."]),
155
+ i.c.intrigue >= 7,
156
+ ),
157
+ )
158
+ )
159
+ .to_pd()
160
+ .pipe(refactor_atelier)
161
+ .groupby("category")
162
+ .get_group("nouveau")
163
+ .astype({"introspection": "string"})
164
+ .sort_values(
165
+ ["updated_at", "essence"],
166
+ ascending=[False, False],
167
+ )
168
+ .assign(
169
+ imprint=lambda df: (
170
+ df.astype(str)
171
+ .agg("-".join, axis=1)
172
+ .map(
173
+ lambda value: hashlib.blake2s(
174
+ value.encode(),
175
+ digest_size=7,
176
+ ).hexdigest()
177
+ )
178
+ )
179
+ )
180
+ .loc[:, cols]
181
+ .to_numpy()
182
+ )
183
+ ```
184
+
185
+ ## Multiple Database Connections
186
+
187
+ ```python
188
+ dev = Database(os.environ["DEV_ODBC"])
189
+ test = Database(os.environ["TEST_ODBC"])
190
+
191
+ dev_df = dev.reflect("schemaname.tablename").to_pd()
192
+ test_df = test.reflect("schemaname.tablename").to_pl()
193
+
194
+ dev.dispose()
195
+ test.dispose()
196
+ ```
197
+
198
+ ## Interface
199
+
200
+ | Class | Attributes / Methods |
201
+ | --- | --- |
202
+ | `Database` | `engine`, `metadata`, `reflect()`, `catalogue()`, `query()` |
203
+ | `ReflectedTable` | `sa`, `engine`, native SQLAlchemy `Table` attributes and methods, `inspect()`, delegated `QueryExecutor` methods |
204
+ | `QueryExecutor` | `statement`, `engine`, `to_pd()`, `to_pl()`, `to_numpy()`, `to_arrow()`, `to_records()`, `fetch()`, `to_scalar()` |
205
+
206
+ `Database.reflect()` returns a `ReflectedTable`, while `Database.query()` returns a `QueryExecutor`.
207
+
208
+ `ReflectedTable.__getattr__()` forwards unresolved attributes to the underlying SQLAlchemy `Table` first, then to `QueryExecutor`.
209
+
210
+ `ReflectedTable.__clause_element__()` enables SQLAlchemy expression coercion. The explicit `.sa` attribute exposes the underlying SQLAlchemy `Table` when a native table object is required.
211
+
212
+
213
+ ## Design Philosophy
214
+
215
+ 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.
216
+
217
+ ## License
218
+ MIT License © MI77-LAB
@@ -0,0 +1,6 @@
1
+ from .database import Database
2
+
3
+
4
+ __all__ = [
5
+ "Database",
6
+ ]
@@ -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,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "AlchemyReflection"
7
+ version = "0.1.2"
8
+
9
+ description = """An object-oriented interface for SQLAlchemy, \
10
+ designed for database reflection, query execution, and result retrieval, \
11
+ built around method chaining and native interoperability."""
12
+
13
+ readme = "README.md"
14
+ requires-python = ">=3.10"
15
+ license = "MIT"
16
+ license-files = ["LICENSE"]
17
+
18
+ authors = [
19
+ { name = "MI77-LAB" }
20
+ ]
21
+
22
+ classifiers = [
23
+ "Development Status :: 3 - Alpha",
24
+ "Intended Audience :: Developers",
25
+ "Operating System :: OS Independent",
26
+ "Programming Language :: Python :: 3",
27
+ "Topic :: Database",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ ]
30
+
31
+ dependencies = [
32
+ "sqlalchemy>=2.0,<3.0",
33
+ "pandas>=2.0,<4.0",
34
+ "polars>=1.0,<3.0",
35
+ ]
36
+
37
+ [project.optional-dependencies]
38
+ arrow = ["pyarrow>=15.0,<27.0"]
39
+ pyodbc = ["pyodbc>=5.0,<6.0"]
40
+
41
+ [project.urls]
42
+ Repository = "https://github.com/mirabelleding/AlchemyReflection"
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["."]
46
+ include = ["alchemy_reflection*"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+