an5-adapters 0.2.0__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,277 @@
1
+ Metadata-Version: 2.4
2
+ Name: an5-adapters
3
+ Version: 0.2.0
4
+ Summary: Python adapter helpers for AN5 ORM.
5
+ Author: an5ORM
6
+ License: MIT
7
+ Keywords: an5,orm,adapter
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ Requires-Dist: pyodbc>=5.0
13
+ Requires-Dist: psycopg2-binary>=2.9
14
+
15
+ # an5Adapters
16
+
17
+ Standalone runtime adapters for AN5 ORM. Provides connection pooling, query execution, typed table clients in TypeScript, Python, .NET, and Google Sheets API.
18
+
19
+ Adapters are runtime packages only. They do not import generated `an5Client` artifacts; generated clients or applications can pass model metadata explicitly when table-name mapping or field type coercion is needed.
20
+
21
+ ## Features
22
+
23
+ - **Connection pooling** — Managed connection pools with configurable limits
24
+ - **Type-safe table clients** — Generic CRUD operations with type inference
25
+ - **Full query support** — WHERE, ORDER BY, pagination, aggregates
26
+ - **Vector search** — Cosine, euclidean, and dot product similarity
27
+ - **Transactions** — Begin/commit/rollback with automatic cleanup
28
+ - **Cross-language** — Same API in TypeScript, Python, and .NET
29
+ - **Google Sheets** — Use spreadsheets as a database with the same CRUD API
30
+
31
+ ## Installation
32
+
33
+ ### TypeScript
34
+
35
+ ```bash
36
+ npm install an5-adapters
37
+ ```
38
+
39
+ ### Python
40
+
41
+ ```bash
42
+ pip install an5-adapters
43
+ ```
44
+
45
+ ### .NET
46
+
47
+ ```bash
48
+ dotnet add package An5Adapters
49
+ ```
50
+
51
+ ## Usage
52
+
53
+ ### TypeScript
54
+
55
+ ```typescript
56
+ import { createAn5Adapter, setAdapterMetadata } from 'an5-adapters';
57
+
58
+ setAdapterMetadata({
59
+ modelToTable: { User: 'dbo.users' },
60
+ modelFields: {
61
+ User: {
62
+ id: { ts: 'string', sql: 'uniqueidentifier', isId: true },
63
+ active: { ts: 'boolean', sql: 'bit' },
64
+ },
65
+ },
66
+ });
67
+
68
+ const db = createAn5Adapter({
69
+ connectionString: 'sqlserver://localhost:1433;database=mydb;user=sa;password=pass',
70
+ });
71
+
72
+ // Table client
73
+ const users = db.table<User>('users');
74
+ await users.findMany({ where: { active: true }, take: 10 });
75
+
76
+ // Raw queries
77
+ const rows = await db.exec('SELECT * FROM users WHERE id = @id', { id: '123' });
78
+
79
+ // Transactions
80
+ await db.$transaction(async (tx) => {
81
+ await tx.table('users').create({ data: { name: 'John' } });
82
+ });
83
+ ```
84
+
85
+ ### Python
86
+
87
+ ```python
88
+ from an5_adapter import create_an5_adapter
89
+ from base.metadata import set_adapter_metadata
90
+
91
+ set_adapter_metadata({
92
+ "modelToTable": {"User": "dbo.users"},
93
+ "modelFields": {
94
+ "User": {
95
+ "id": {"py": "str", "sql": "uniqueidentifier", "isId": True},
96
+ "active": {"py": "bool", "sql": "bit"},
97
+ }
98
+ },
99
+ })
100
+
101
+ db = create_an5_adapter("sqlserver://localhost:1433;database=mydb;user=sa;password=pass")
102
+
103
+ # Table client
104
+ users = db.table("User")
105
+ users.find_many(where={"active": True}, take=10)
106
+
107
+ # Raw queries
108
+ rows = db.exec("SELECT * FROM users WHERE id = ?", params=["123"])
109
+
110
+ # Transactions
111
+ db.transaction(lambda tx: tx.table("User").create({"name": "John"}))
112
+ ```
113
+
114
+ ### .NET
115
+
116
+ ```csharp
117
+ using An5Orm;
118
+
119
+ var db = new An5Adapter(connectionString);
120
+
121
+ // Table client
122
+ var users = db.Table<User>("dbo.users");
123
+ var activeUsers = users.FindMany("IsActive = @p", new { p = true });
124
+
125
+ // Raw queries
126
+ var rows = db.QueryRaw("SELECT * FROM users WHERE Id = @id", new { id = "123" });
127
+
128
+ // Transactions
129
+ db.Transaction(tx => {
130
+ tx.Table<User>("dbo.users").Create(new User { Name = "John" });
131
+ });
132
+ ```
133
+
134
+ ### Google Sheets
135
+
136
+ ```typescript
137
+ import { createAn5SheetsAdapter } from 'an5-adapters';
138
+
139
+ const db = createAn5SheetsAdapter({
140
+ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
141
+ // Option 1: client email + private key
142
+ clientEmail: 'sa@project.iam.gserviceaccount.com',
143
+ privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
144
+ // Option 2: full service account JSON
145
+ // credentials: { client_email: '...', private_key: '...' },
146
+ // Optional: map model names to sheet names
147
+ sheetMapping: { users: 'UsersData', orders: 'OrdersData' },
148
+ });
149
+
150
+ // Table client (same API as SQL adapters)
151
+ const users = db.table<User>('users');
152
+ await users.findMany({ where: { active: true }, take: 10 });
153
+ await users.create({ data: { name: 'John', email: 'john@example.com' } });
154
+ await users.update({ where: { email: 'john@example.com' }, data: { name: 'Johnny' } });
155
+ await users.delete({ where: { email: 'john@example.com' } });
156
+
157
+ // Raw range access (Google Sheets specific)
158
+ const rawData = await db.readRange('Sheet1!A1:C10');
159
+ await db.writeRange('Sheet1!A1:B2', [['Name', 'Age'], ['Alice', '30']]);
160
+ await db.appendRange('Sheet1!A:A', [['Bob', '25']]);
161
+
162
+ // Auto-creates sheet + header row on first create()
163
+ await db.table('orders').create({ data: { id: '1', total: 100 } });
164
+
165
+ // List, delete sheets
166
+ const sheets = await db.listSheets();
167
+ await db.deleteSheet('OldSheet');
168
+
169
+ // Clear data (keeps headers) or delete all rows
170
+ await db.table('users').clear();
171
+ await db.table('users').deleteAll();
172
+ ```
173
+
174
+ ### Integrated factory (auto-detect adapter)
175
+
176
+ ```typescript
177
+ import { createAn5Adapter, createAdapter, An5Adapter } from 'an5-adapters';
178
+
179
+ // Auto-detects from connection string
180
+ const sqlDb = createAn5Adapter({ connectionString: 'sqlserver://localhost:1433;database=mydb;user=sa;password=pass' });
181
+
182
+ const sheetsDb = createAn5Adapter({
183
+ connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
184
+ });
185
+
186
+ // Or use the Sheets config object directly (also auto-detected)
187
+ const sheetsDb2 = createAdapter({
188
+ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
189
+ clientEmail: 'sa@project.iam.gserviceaccount.com',
190
+ privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
191
+ });
192
+
193
+ // Constructor form also delegates googlesheets:// to the Sheets adapter
194
+ const sheetsDb3 = new An5Adapter({
195
+ connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
196
+ });
197
+ ```
198
+
199
+ **Notes:**
200
+ - Each model/table maps to a **sheet tab** (first row = headers)
201
+ - Sheets without header rows get auto-created on first `create()`
202
+ - Type coercion can use optional adapter metadata (`setAdapterMetadata`) for field types and model-to-table mapping
203
+ - Numeric strings (without leading zeros) are auto-coerced; `"00123"` stays string
204
+ - Boolean strings `"true"` / `"false"` are auto-coerced
205
+ - Sheet names with spaces are automatically escaped (A1 notation)
206
+ - Supports service account JSON or individual `clientEmail`+`privateKey`
207
+ - Automatic retry with exponential backoff for rate limits (429/500/503)
208
+
209
+ ### Provider Imports
210
+
211
+ Use the package root for normal applications:
212
+
213
+ ```typescript
214
+ import { createAn5Adapter, createAn5SheetsAdapter } from 'an5-adapters';
215
+ ```
216
+
217
+ Provider folders are still available to source-level consumers through `typescript/*`, but the public factory in `typescript/an5Adapter.ts` is the preferred entry point. The old `unified.ts` entry point has been removed because the factory now lives directly in `An5Adapter`.
218
+
219
+ ## API Reference
220
+
221
+ ### An5Adapter / An5SheetsAdapter
222
+
223
+ | Method | Description |
224
+ |--------|-------------|
225
+ | `exec(query, params)` | Execute query, return rows (SQL only) |
226
+ | `table<T>(name)` | Get typed table client |
227
+ | `$transaction(fn)` | Execute in transaction |
228
+ | `$connect()` | Open connection / authenticate |
229
+ | `$disconnect()` | Close connection / clear auth |
230
+ | `readRange(range)` | Read raw sheet range (Sheets only) |
231
+ | `writeRange(range, values)` | Write raw sheet range (Sheets only) |
232
+ | `appendRange(range, values)` | Append rows to sheet (Sheets only) |
233
+ | `listSheets()` | List all sheet tab names (Sheets only) |
234
+ | `deleteSheet(name)` | Delete a sheet tab (Sheets only) |
235
+
236
+ ### AdapterTableClient / SheetsTableClient
237
+
238
+ | Method | Description |
239
+ |--------|-------------|
240
+ | `findMany(args)` | Query multiple rows |
241
+ | `findFirst(args)` | Query single row |
242
+ | `findUnique(where)` | Find by unique key |
243
+ | `count(where)` | Count rows |
244
+ | `create(data)` | Insert row |
245
+ | `createMany(data)` | Bulk insert |
246
+ | `update(where, data)` | Update row |
247
+ | `updateMany(where, data)` | Update multiple rows |
248
+ | `delete(where)` | Delete row |
249
+ | `deleteMany(where)` | Delete multiple rows |
250
+ | `upsert(where, create, update)` | Insert or update |
251
+ | `aggregate(args)` | SUM, AVG, MIN, MAX, COUNT |
252
+ | `groupBy(args)` | Group by fields |
253
+ | `vectorSearch(args)` | Semantic similarity search |
254
+ | `clear()` | Clear all data rows, keep headers (Sheets only) |
255
+ | `deleteAll()` | Delete all data rows including headers (Sheets only) |
256
+
257
+ ## Provider Layout
258
+
259
+ - TypeScript providers live under `typescript/{base,mssql,postgres,mysql,sqlite,googlesheets}`.
260
+ - Python providers live under `python/{base,mssql,postgres}`, with `python/an5_adapter.py` kept as the public facade.
261
+ - .NET providers live under `dotnet/{Base,Mssql,Postgres}`, with `dotnet/an5Adapter.cs` kept as the public facade.
262
+ - Adapters do not depend on generated `an5-client` artifacts; generated clients may pass metadata in explicitly when they need model/table mapping.
263
+
264
+ ## Testing
265
+
266
+ ```bash
267
+ # TypeScript/Node
268
+ node test/unit.test.js
269
+
270
+ # Python
271
+ python -m compileall python
272
+ python test/smoke.py
273
+ ```
274
+
275
+ ## License
276
+
277
+ MIT
@@ -0,0 +1,263 @@
1
+ # an5Adapters
2
+
3
+ Standalone runtime adapters for AN5 ORM. Provides connection pooling, query execution, typed table clients in TypeScript, Python, .NET, and Google Sheets API.
4
+
5
+ Adapters are runtime packages only. They do not import generated `an5Client` artifacts; generated clients or applications can pass model metadata explicitly when table-name mapping or field type coercion is needed.
6
+
7
+ ## Features
8
+
9
+ - **Connection pooling** — Managed connection pools with configurable limits
10
+ - **Type-safe table clients** — Generic CRUD operations with type inference
11
+ - **Full query support** — WHERE, ORDER BY, pagination, aggregates
12
+ - **Vector search** — Cosine, euclidean, and dot product similarity
13
+ - **Transactions** — Begin/commit/rollback with automatic cleanup
14
+ - **Cross-language** — Same API in TypeScript, Python, and .NET
15
+ - **Google Sheets** — Use spreadsheets as a database with the same CRUD API
16
+
17
+ ## Installation
18
+
19
+ ### TypeScript
20
+
21
+ ```bash
22
+ npm install an5-adapters
23
+ ```
24
+
25
+ ### Python
26
+
27
+ ```bash
28
+ pip install an5-adapters
29
+ ```
30
+
31
+ ### .NET
32
+
33
+ ```bash
34
+ dotnet add package An5Adapters
35
+ ```
36
+
37
+ ## Usage
38
+
39
+ ### TypeScript
40
+
41
+ ```typescript
42
+ import { createAn5Adapter, setAdapterMetadata } from 'an5-adapters';
43
+
44
+ setAdapterMetadata({
45
+ modelToTable: { User: 'dbo.users' },
46
+ modelFields: {
47
+ User: {
48
+ id: { ts: 'string', sql: 'uniqueidentifier', isId: true },
49
+ active: { ts: 'boolean', sql: 'bit' },
50
+ },
51
+ },
52
+ });
53
+
54
+ const db = createAn5Adapter({
55
+ connectionString: 'sqlserver://localhost:1433;database=mydb;user=sa;password=pass',
56
+ });
57
+
58
+ // Table client
59
+ const users = db.table<User>('users');
60
+ await users.findMany({ where: { active: true }, take: 10 });
61
+
62
+ // Raw queries
63
+ const rows = await db.exec('SELECT * FROM users WHERE id = @id', { id: '123' });
64
+
65
+ // Transactions
66
+ await db.$transaction(async (tx) => {
67
+ await tx.table('users').create({ data: { name: 'John' } });
68
+ });
69
+ ```
70
+
71
+ ### Python
72
+
73
+ ```python
74
+ from an5_adapter import create_an5_adapter
75
+ from base.metadata import set_adapter_metadata
76
+
77
+ set_adapter_metadata({
78
+ "modelToTable": {"User": "dbo.users"},
79
+ "modelFields": {
80
+ "User": {
81
+ "id": {"py": "str", "sql": "uniqueidentifier", "isId": True},
82
+ "active": {"py": "bool", "sql": "bit"},
83
+ }
84
+ },
85
+ })
86
+
87
+ db = create_an5_adapter("sqlserver://localhost:1433;database=mydb;user=sa;password=pass")
88
+
89
+ # Table client
90
+ users = db.table("User")
91
+ users.find_many(where={"active": True}, take=10)
92
+
93
+ # Raw queries
94
+ rows = db.exec("SELECT * FROM users WHERE id = ?", params=["123"])
95
+
96
+ # Transactions
97
+ db.transaction(lambda tx: tx.table("User").create({"name": "John"}))
98
+ ```
99
+
100
+ ### .NET
101
+
102
+ ```csharp
103
+ using An5Orm;
104
+
105
+ var db = new An5Adapter(connectionString);
106
+
107
+ // Table client
108
+ var users = db.Table<User>("dbo.users");
109
+ var activeUsers = users.FindMany("IsActive = @p", new { p = true });
110
+
111
+ // Raw queries
112
+ var rows = db.QueryRaw("SELECT * FROM users WHERE Id = @id", new { id = "123" });
113
+
114
+ // Transactions
115
+ db.Transaction(tx => {
116
+ tx.Table<User>("dbo.users").Create(new User { Name = "John" });
117
+ });
118
+ ```
119
+
120
+ ### Google Sheets
121
+
122
+ ```typescript
123
+ import { createAn5SheetsAdapter } from 'an5-adapters';
124
+
125
+ const db = createAn5SheetsAdapter({
126
+ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
127
+ // Option 1: client email + private key
128
+ clientEmail: 'sa@project.iam.gserviceaccount.com',
129
+ privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
130
+ // Option 2: full service account JSON
131
+ // credentials: { client_email: '...', private_key: '...' },
132
+ // Optional: map model names to sheet names
133
+ sheetMapping: { users: 'UsersData', orders: 'OrdersData' },
134
+ });
135
+
136
+ // Table client (same API as SQL adapters)
137
+ const users = db.table<User>('users');
138
+ await users.findMany({ where: { active: true }, take: 10 });
139
+ await users.create({ data: { name: 'John', email: 'john@example.com' } });
140
+ await users.update({ where: { email: 'john@example.com' }, data: { name: 'Johnny' } });
141
+ await users.delete({ where: { email: 'john@example.com' } });
142
+
143
+ // Raw range access (Google Sheets specific)
144
+ const rawData = await db.readRange('Sheet1!A1:C10');
145
+ await db.writeRange('Sheet1!A1:B2', [['Name', 'Age'], ['Alice', '30']]);
146
+ await db.appendRange('Sheet1!A:A', [['Bob', '25']]);
147
+
148
+ // Auto-creates sheet + header row on first create()
149
+ await db.table('orders').create({ data: { id: '1', total: 100 } });
150
+
151
+ // List, delete sheets
152
+ const sheets = await db.listSheets();
153
+ await db.deleteSheet('OldSheet');
154
+
155
+ // Clear data (keeps headers) or delete all rows
156
+ await db.table('users').clear();
157
+ await db.table('users').deleteAll();
158
+ ```
159
+
160
+ ### Integrated factory (auto-detect adapter)
161
+
162
+ ```typescript
163
+ import { createAn5Adapter, createAdapter, An5Adapter } from 'an5-adapters';
164
+
165
+ // Auto-detects from connection string
166
+ const sqlDb = createAn5Adapter({ connectionString: 'sqlserver://localhost:1433;database=mydb;user=sa;password=pass' });
167
+
168
+ const sheetsDb = createAn5Adapter({
169
+ connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
170
+ });
171
+
172
+ // Or use the Sheets config object directly (also auto-detected)
173
+ const sheetsDb2 = createAdapter({
174
+ spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
175
+ clientEmail: 'sa@project.iam.gserviceaccount.com',
176
+ privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
177
+ });
178
+
179
+ // Constructor form also delegates googlesheets:// to the Sheets adapter
180
+ const sheetsDb3 = new An5Adapter({
181
+ connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
182
+ });
183
+ ```
184
+
185
+ **Notes:**
186
+ - Each model/table maps to a **sheet tab** (first row = headers)
187
+ - Sheets without header rows get auto-created on first `create()`
188
+ - Type coercion can use optional adapter metadata (`setAdapterMetadata`) for field types and model-to-table mapping
189
+ - Numeric strings (without leading zeros) are auto-coerced; `"00123"` stays string
190
+ - Boolean strings `"true"` / `"false"` are auto-coerced
191
+ - Sheet names with spaces are automatically escaped (A1 notation)
192
+ - Supports service account JSON or individual `clientEmail`+`privateKey`
193
+ - Automatic retry with exponential backoff for rate limits (429/500/503)
194
+
195
+ ### Provider Imports
196
+
197
+ Use the package root for normal applications:
198
+
199
+ ```typescript
200
+ import { createAn5Adapter, createAn5SheetsAdapter } from 'an5-adapters';
201
+ ```
202
+
203
+ Provider folders are still available to source-level consumers through `typescript/*`, but the public factory in `typescript/an5Adapter.ts` is the preferred entry point. The old `unified.ts` entry point has been removed because the factory now lives directly in `An5Adapter`.
204
+
205
+ ## API Reference
206
+
207
+ ### An5Adapter / An5SheetsAdapter
208
+
209
+ | Method | Description |
210
+ |--------|-------------|
211
+ | `exec(query, params)` | Execute query, return rows (SQL only) |
212
+ | `table<T>(name)` | Get typed table client |
213
+ | `$transaction(fn)` | Execute in transaction |
214
+ | `$connect()` | Open connection / authenticate |
215
+ | `$disconnect()` | Close connection / clear auth |
216
+ | `readRange(range)` | Read raw sheet range (Sheets only) |
217
+ | `writeRange(range, values)` | Write raw sheet range (Sheets only) |
218
+ | `appendRange(range, values)` | Append rows to sheet (Sheets only) |
219
+ | `listSheets()` | List all sheet tab names (Sheets only) |
220
+ | `deleteSheet(name)` | Delete a sheet tab (Sheets only) |
221
+
222
+ ### AdapterTableClient / SheetsTableClient
223
+
224
+ | Method | Description |
225
+ |--------|-------------|
226
+ | `findMany(args)` | Query multiple rows |
227
+ | `findFirst(args)` | Query single row |
228
+ | `findUnique(where)` | Find by unique key |
229
+ | `count(where)` | Count rows |
230
+ | `create(data)` | Insert row |
231
+ | `createMany(data)` | Bulk insert |
232
+ | `update(where, data)` | Update row |
233
+ | `updateMany(where, data)` | Update multiple rows |
234
+ | `delete(where)` | Delete row |
235
+ | `deleteMany(where)` | Delete multiple rows |
236
+ | `upsert(where, create, update)` | Insert or update |
237
+ | `aggregate(args)` | SUM, AVG, MIN, MAX, COUNT |
238
+ | `groupBy(args)` | Group by fields |
239
+ | `vectorSearch(args)` | Semantic similarity search |
240
+ | `clear()` | Clear all data rows, keep headers (Sheets only) |
241
+ | `deleteAll()` | Delete all data rows including headers (Sheets only) |
242
+
243
+ ## Provider Layout
244
+
245
+ - TypeScript providers live under `typescript/{base,mssql,postgres,mysql,sqlite,googlesheets}`.
246
+ - Python providers live under `python/{base,mssql,postgres}`, with `python/an5_adapter.py` kept as the public facade.
247
+ - .NET providers live under `dotnet/{Base,Mssql,Postgres}`, with `dotnet/an5Adapter.cs` kept as the public facade.
248
+ - Adapters do not depend on generated `an5-client` artifacts; generated clients may pass metadata in explicitly when they need model/table mapping.
249
+
250
+ ## Testing
251
+
252
+ ```bash
253
+ # TypeScript/Node
254
+ node test/unit.test.js
255
+
256
+ # Python
257
+ python -m compileall python
258
+ python test/smoke.py
259
+ ```
260
+
261
+ ## License
262
+
263
+ MIT
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "an5-adapters"
7
+ version = "0.2.0"
8
+ description = "Python adapter helpers for AN5 ORM."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ authors = [{ name = "an5ORM" }]
12
+ license = { text = "MIT" }
13
+ keywords = ["an5", "orm", "adapter"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "License :: OSI Approved :: MIT License"
17
+ ]
18
+ dependencies = [
19
+ "pyodbc>=5.0",
20
+ "psycopg2-binary>=2.9"
21
+ ]
22
+
23
+ [tool.setuptools]
24
+ package-dir = {"" = "python"}
25
+ py-modules = ["an5_adapter", "table_client"]
26
+ packages = ["base", "mssql", "postgres"]
@@ -0,0 +1,97 @@
1
+ """Standalone Python runtime adapter for AN5 ORM."""
2
+
3
+ from typing import Dict, List, Optional
4
+
5
+ try:
6
+ from .base import DIALECT_MSSQL, DIALECT_POSTGRES, detect_dialect, set_adapter_metadata
7
+ from .mssql import connect as connect_mssql
8
+ from .postgres import connect as connect_postgres
9
+ from .table_client import AdapterTableClient
10
+ except ImportError:
11
+ from base import DIALECT_MSSQL, DIALECT_POSTGRES, detect_dialect, set_adapter_metadata
12
+ from mssql import connect as connect_mssql
13
+ from postgres import connect as connect_postgres
14
+ from table_client import AdapterTableClient
15
+
16
+ # Backward-compatible aliases used by tests and older imports.
17
+ _detect_dialect = detect_dialect
18
+ try:
19
+ from .mssql import parse_connection_string as _parse_connection_string
20
+ except ImportError:
21
+ from mssql import parse_connection_string as _parse_connection_string
22
+
23
+ class An5Adapter:
24
+ def __init__(self, connection_string: str):
25
+ self._dialect = detect_dialect(connection_string)
26
+ self._conn_str = connection_string
27
+
28
+ def _connect(self):
29
+ if self._dialect == DIALECT_POSTGRES:
30
+ return connect_postgres(self._conn_str)
31
+ return connect_mssql(self._conn_str)
32
+
33
+ def _to_dicts(self, cursor, query: str) -> List[Dict]:
34
+ if cursor.description:
35
+ cols = [col[0] for col in cursor.description]
36
+ rows = cursor.fetchall() if cursor.description else []
37
+ return [dict(zip(cols, row)) for row in rows]
38
+ return []
39
+
40
+ def exec(self, query: str, params: Optional[List] = None) -> List[Dict]:
41
+ conn = self._connect()
42
+ try:
43
+ cursor = conn.cursor()
44
+ cursor.execute(query, params or [])
45
+ return self._to_dicts(cursor, query)
46
+ finally:
47
+ conn.close()
48
+
49
+ def execute(self, query: str, params: Optional[List] = None) -> int:
50
+ conn = self._connect()
51
+ try:
52
+ cursor = conn.cursor()
53
+ cursor.execute(query, params or [])
54
+ return cursor.rowcount
55
+ finally:
56
+ conn.close()
57
+
58
+ def query_raw(self, query: str, *values) -> List[Dict]:
59
+ return self.exec(query, list(values))
60
+
61
+ def execute_raw(self, query: str, *values) -> int:
62
+ return self.execute(query, list(values))
63
+
64
+ def table(self, model_name: str) -> AdapterTableClient:
65
+ return AdapterTableClient(self, model_name)
66
+
67
+ def __getattr__(self, model_name: str) -> AdapterTableClient:
68
+ return self.table(model_name)
69
+
70
+ def transaction(self, fn):
71
+ conn = self._connect()
72
+ conn.autocommit = False
73
+ try:
74
+ result = fn(self)
75
+ conn.commit()
76
+ return result
77
+ except Exception:
78
+ conn.rollback()
79
+ raise
80
+ finally:
81
+ if self._dialect == DIALECT_POSTGRES:
82
+ conn.autocommit = True
83
+ conn.close()
84
+
85
+ def create_an5_adapter(connection_string: str) -> An5Adapter:
86
+ return An5Adapter(connection_string)
87
+
88
+ __all__ = [
89
+ "An5Adapter",
90
+ "AdapterTableClient",
91
+ "create_an5_adapter",
92
+ "DIALECT_MSSQL",
93
+ "DIALECT_POSTGRES",
94
+ "_detect_dialect",
95
+ "_parse_connection_string",
96
+ "set_adapter_metadata",
97
+ ]