@an5/adapters 0.2.5 → 0.2.9

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.
Files changed (99) hide show
  1. package/README.md +283 -305
  2. package/dist/an5Adapter.d.ts +142 -7
  3. package/dist/an5Adapter.js +998 -68
  4. package/dist/base/metadata.d.ts +10 -0
  5. package/dist/base/metadata.js +107 -0
  6. package/dist/base/sql.d.ts +19 -1
  7. package/dist/base/sql.js +152 -24
  8. package/dist/base/types.d.ts +10 -1
  9. package/dist/browser.d.ts +4 -1
  10. package/dist/browser.js +9 -2
  11. package/dist/googlesheets/adapter.d.ts +1 -0
  12. package/dist/googlesheets/adapter.js +9 -2
  13. package/dist/googlesheets/config.d.ts +4 -4
  14. package/dist/googlesheets/helpers.js +2 -0
  15. package/dist/googlesheets/parseConnectionString.js +5 -2
  16. package/dist/googlesheets/sqlExecutor.js +29 -24
  17. package/dist/googlesheets/tableClient.js +14 -5
  18. package/dist/index.d.ts +5 -1
  19. package/dist/index.js +15 -1
  20. package/dist/mssql/engine.js +8 -4
  21. package/dist/mysql/engine.js +1 -1
  22. package/dist/nbase/client.d.ts +92 -0
  23. package/dist/nbase/client.js +147 -0
  24. package/dist/nbase/index.d.ts +47 -0
  25. package/dist/nbase/index.js +80 -0
  26. package/dist/postgres/engine.js +1 -1
  27. package/dist/sqlite/browserEngine.d.ts +27 -0
  28. package/dist/sqlite/browserEngine.js +161 -0
  29. package/dist/sqlite/engine.js +15 -3
  30. package/dist/sqlite/index.d.ts +1 -0
  31. package/dist/sqlite/index.js +1 -0
  32. package/dist/typed.d.ts +5 -0
  33. package/dist/typed.js +2 -0
  34. package/dotnet/An5Adapter.cs +1112 -275
  35. package/dotnet/Base/Core.cs +380 -82
  36. package/dotnet/Mssql/MssqlEngine.cs +145 -144
  37. package/dotnet/Postgres/PostgresEngine.cs +149 -121
  38. package/dotnet/Sqlite/SqliteEngine.cs +214 -0
  39. package/golang/an5_adapter.go +314 -0
  40. package/golang/base/base.go +100 -0
  41. package/golang/base/metadata.go +116 -0
  42. package/golang/base/where.go +311 -0
  43. package/golang/go.mod +3 -0
  44. package/golang/mssql/mssql.go +32 -0
  45. package/golang/postgres/postgres.go +37 -0
  46. package/golang/sqlite/sqlite.go +14 -0
  47. package/golang/sqlite_test.go +42 -0
  48. package/golang/table_client.go +1329 -0
  49. package/package.json +26 -9
  50. package/python/an5_adapter.py +184 -97
  51. package/python/base/__init__.py +3 -3
  52. package/python/base/dialects.py +11 -8
  53. package/python/base/metadata.py +59 -10
  54. package/python/base/sql.py +202 -121
  55. package/python/mssql/__init__.py +1 -1
  56. package/python/mssql/provider.py +62 -62
  57. package/python/postgres/__init__.py +1 -1
  58. package/python/postgres/provider.py +15 -15
  59. package/python/sqlite/__init__.py +3 -0
  60. package/python/sqlite/provider.py +83 -0
  61. package/python/table_client.py +636 -216
  62. package/rust/Cargo.toml +31 -0
  63. package/rust/README.md +71 -0
  64. package/rust/src/adapter.rs +1312 -0
  65. package/rust/src/base/dialect.rs +172 -0
  66. package/rust/src/base/metadata.rs +134 -0
  67. package/rust/src/base/mod.rs +17 -0
  68. package/rust/src/base/where_builder.rs +405 -0
  69. package/rust/src/lib.rs +75 -0
  70. package/typescript/src/an5Adapter.ts +1515 -505
  71. package/typescript/src/base/index.ts +3 -3
  72. package/typescript/src/base/metadata.ts +148 -28
  73. package/typescript/src/base/sql.ts +264 -98
  74. package/typescript/src/base/types.ts +33 -24
  75. package/typescript/src/browser.ts +10 -6
  76. package/typescript/src/config.ts +95 -95
  77. package/typescript/src/googlesheets/adapter.ts +269 -259
  78. package/typescript/src/googlesheets/an5SheetsAdapter.ts +3 -3
  79. package/typescript/src/googlesheets/config.ts +47 -47
  80. package/typescript/src/googlesheets/helpers.ts +144 -143
  81. package/typescript/src/googlesheets/index.ts +3 -3
  82. package/typescript/src/googlesheets/parseConnectionString.ts +48 -46
  83. package/typescript/src/googlesheets/retry.ts +126 -126
  84. package/typescript/src/googlesheets/sqlExecutor.ts +304 -301
  85. package/typescript/src/googlesheets/tableClient.ts +461 -455
  86. package/typescript/src/googlesheets/types.ts +6 -6
  87. package/typescript/src/index.ts +48 -27
  88. package/typescript/src/mssql/engine.ts +134 -132
  89. package/typescript/src/mssql/index.ts +1 -1
  90. package/typescript/src/mysql/engine.ts +80 -80
  91. package/typescript/src/mysql/index.ts +1 -1
  92. package/typescript/src/nbase/client.ts +214 -0
  93. package/typescript/src/nbase/index.ts +104 -0
  94. package/typescript/src/postgres/engine.ts +87 -87
  95. package/typescript/src/postgres/index.ts +1 -1
  96. package/typescript/src/sqlite/browserEngine.ts +192 -0
  97. package/typescript/src/sqlite/engine.ts +66 -55
  98. package/typescript/src/sqlite/index.ts +3 -1
  99. package/typescript/src/typed.ts +52 -0
package/README.md CHANGED
@@ -1,305 +1,283 @@
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 System.Collections.Generic;
104
- using An5Orm;
105
-
106
- var db = new An5Adapter("sqlserver://localhost:1433;database=mydb;user=sa;password=pass");
107
-
108
- // Table client
109
- var users = db.Table<User>("dbo.users");
110
- var activeUsers = users.FindMany(
111
- "IsActive = @p",
112
- new Dictionary<string, object> { ["p"] = true });
113
-
114
- // Raw queries
115
- var rows = db.QueryRaw("SELECT * FROM users WHERE Id = @id",
116
- new Dictionary<string, object> { ["id"] = "123" });
117
-
118
- // Create / Update / Delete
119
- users.Create(new User { Name = "John", IsActive = true });
120
- users.Update(existingUser); // uses the Id property as the key
121
- users.Delete("123");
122
-
123
- // Transactions (must return a value; use db.Transaction<int> for void-style)
124
- db.Transaction(tx =>
125
- {
126
- tx.Table<User>("dbo.users").Create(new User { Name = "John" });
127
- return 0;
128
- });
129
- ```
130
-
131
- Note: `QueryRaw`/`FindMany` take parameters as a `Dictionary<string, object>`,
132
- not anonymous objects. See `dotnet/An5Adapter.cs` for the full API.
133
-
134
- ### Google Sheets
135
-
136
- ```typescript
137
- import { createAn5SheetsAdapter } from '@an5/adapters/googlesheets';
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
- ### Browser Mode (Google Sheets)
175
-
176
- For browser environments (React, Vue, Svelte, Next.js client components), import from `@an5/adapters/browser` and configure `accessToken` or `apiKey`. In browser mode, the adapter uses native `fetch()` without importing Node.js modules (`googleapis`, `crypto`, `fs`).
177
-
178
- ```typescript
179
- import { createAn5SheetsAdapter } from '@an5/adapters/browser';
180
-
181
- // Option 1: OAuth2 Access Token (e.g. from Firebase Auth or Google Sign-In)
182
- const db = createAn5SheetsAdapter({
183
- spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
184
- accessToken: userOAuthAccessToken,
185
- });
186
-
187
- // Option 2: Google API Key
188
- const db2 = createAn5SheetsAdapter({
189
- spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
190
- apiKey: 'AIzaSy...',
191
- });
192
- ```
193
-
194
- ### Integrated factory (auto-detect adapter)
195
-
196
- ```typescript
197
- import { createAn5Adapter, An5Adapter } from '@an5/adapters';
198
-
199
- // Auto-detects from connection string
200
- const sqlDb = createAn5Adapter({ connectionString: 'sqlserver://localhost:1433;database=mydb;user=sa;password=pass' });
201
-
202
- const sheetsDb = createAn5Adapter({
203
- connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
204
- });
205
-
206
- // Or use the Sheets config object directly (also auto-detected)
207
- const sheetsDb2 = createAn5Adapter({
208
- spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgVE2upms',
209
- clientEmail: 'sa@project.iam.gserviceaccount.com',
210
- privateKey: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
211
- });
212
-
213
- // Constructor form also delegates googlesheets:// to the Sheets adapter
214
- const sheetsDb3 = new An5Adapter({
215
- connectionString: 'googlesheets://spreadsheetId;clientEmail=sa@project.iam.gserviceaccount.com;privateKey=...',
216
- });
217
- ```
218
-
219
- **Notes:**
220
- - Each model/table maps to a **sheet tab** (first row = headers)
221
- - Sheets without header rows get auto-created on first `create()`
222
- - Type coercion can use optional adapter metadata (`setAdapterMetadata`) for field types and model-to-table mapping
223
- - Numeric strings (without leading zeros) are auto-coerced; `"00123"` stays string
224
- - Boolean strings `"true"` / `"false"` are auto-coerced
225
- - Sheet names with spaces are automatically escaped (A1 notation)
226
- - Supports service account JSON or individual `clientEmail`+`privateKey`
227
- - Automatic retry with exponential backoff for rate limits (429/500/503)
228
-
229
- ### Provider Imports
230
-
231
- Use the package root for normal SQL applications:
232
-
233
- ```typescript
234
- import { createAn5Adapter, An5Adapter } from '@an5/adapters';
235
- ```
236
-
237
- The Sheets adapter is exposed from the package root and through its own subpath:
238
-
239
- ```typescript
240
- import { createAn5SheetsAdapter, An5SheetsAdapter, SheetsTableClient, parseSheetsConnectionString } from '@an5/adapters';
241
- import { An5SheetsAdapter, createAn5SheetsAdapter } from '@an5/adapters/googlesheets';
242
- import { parseSheetsConnectionString } from '@an5/adapters/googlesheets';
243
- ```
244
-
245
- Browser builds (no Node.js modules) use `@an5/adapters/browser`. The public SQL factory `createAn5Adapter` lives in `typescript/src/an5Adapter.ts` and auto-detects `googlesheets://` connection strings.
246
-
247
- ## API Reference
248
-
249
- ### An5Adapter / An5SheetsAdapter
250
-
251
- | Method | Description |
252
- |--------|-------------|
253
- | `exec(query, params)` | Execute query, return rows (SQL only) |
254
- | `table<T>(name)` | Get typed table client |
255
- | `$transaction(fn)` | Execute in transaction |
256
- | `$connect()` | Open connection / authenticate |
257
- | `$disconnect()` | Close connection / clear auth |
258
- | `readRange(range)` | Read raw sheet range (Sheets only) |
259
- | `writeRange(range, values)` | Write raw sheet range (Sheets only) |
260
- | `appendRange(range, values)` | Append rows to sheet (Sheets only) |
261
- | `listSheets()` | List all sheet tab names (Sheets only) |
262
- | `deleteSheet(name)` | Delete a sheet tab (Sheets only) |
263
-
264
- ### AdapterTableClient / SheetsTableClient
265
-
266
- | Method | Description |
267
- |--------|-------------|
268
- | `findMany(args)` | Query multiple rows |
269
- | `findFirst(args)` | Query single row |
270
- | `findUnique(where)` | Find by unique key |
271
- | `count(where)` | Count rows |
272
- | `create(data)` | Insert row |
273
- | `createMany(data)` | Bulk insert |
274
- | `update(where, data)` | Update row |
275
- | `updateMany(where, data)` | Update multiple rows |
276
- | `delete(where)` | Delete row |
277
- | `deleteMany(where)` | Delete multiple rows |
278
- | `upsert(where, create, update)` | Insert or update |
279
- | `aggregate(args)` | SUM, AVG, MIN, MAX, COUNT |
280
- | `groupBy(args)` | Group by fields |
281
- | `vectorSearch(args)` | Semantic similarity search |
282
- | `clear()` | Clear all data rows, keep headers (Sheets only) |
283
- | `deleteAll()` | Delete all data rows including headers (Sheets only) |
284
-
285
- ## Provider Layout
286
-
287
- - TypeScript source providers live under `typescript/src/{base,mssql,postgres,mysql,sqlite,googlesheets}`; `npm run build` compiles them into `dist/` (also exposed via `@an5/adapters/base`, `@an5/adapters/mssql`, … subpaths).
288
- - Python providers live under `python/{base,mssql,postgres}`, with `python/an5_adapter.py` kept as the public facade. `npm run build:python` (or `python -m build --outdir dist-py`) builds the package into `dist-py/`.
289
- - .NET providers live under `dotnet/{Base,Mssql,Postgres}`, with `dotnet/an5Adapter.cs` kept as the public facade.
290
- - Adapters do not depend on generated `an5-client` artifacts; generated clients may pass metadata in explicitly when they need model/table mapping.
291
-
292
- ## Testing
293
-
294
- ```bash
295
- # TypeScript/Node
296
- node test/unit.test.js
297
-
298
- # Python
299
- python -m compileall python
300
- python test/smoke.py
301
- ```
302
-
303
- ## License
304
-
305
- MIT
1
+ # @an5/adapters
2
+
3
+ Standalone runtime database adapter and query engine for AN5 ORM. Provides connection pooling, SQL dialect query building (`parseWhere`, `buildOrderBy`, `quote`), dynamic model proxy access, eager loading (`include`), nested writes, vector search, transactions, and typed table clients across TypeScript, Python, .NET (C#), Golang, and Google Sheets.
4
+
5
+ ## Features
6
+
7
+ - **Dynamic Model Access** — Access models directly via `db.user.findMany()` or `db.User.create()` (proxy resolves casing/plurals via metadata); `db.table('User')` is the escape hatch for runtime-known model names
8
+ - **Typed Model Access** — Bind generated delegates for full type-safety: `createAn5Adapter<{ user: UserTableClient }>({...})`, plus the `TypedAn5Adapter` / `AdapterAPI` helper types
9
+ - **Relations & Eager Loading** — Query nested relations with `include`, relation-level `select`, `where`, `orderBy`, pagination, and `_count`
10
+ - **Nested Writes** — Create and update records with nested relation writes (`create`, `update`, `disconnect`)
11
+ - **Query Builder & Dialects** — Dialect-aware SQL formatting for MSSQL, PostgreSQL, MySQL, and SQLite
12
+ - **Aggregations & GroupBy** — Standard ORM aggregates (`_count`, `_sum`, `_avg`, `_min`, `_max`) and `groupBy`
13
+ - **Field Math Operators** — Atomic updates with `increment`, `decrement`, `multiply`, `divide`, `set`
14
+ - **Vector Search** — Similarity search using NBase, pgvector (PostgreSQL), `VECTOR_DISTANCE` (MSSQL), or in-memory cosine/euclidean/dot similarity
15
+ - **Real Transactions** — Interactive and callback transactions (`$transaction(async tx => ...)` and `$begin()/$commit()/$rollback()`)
16
+ - **Cross-Language** — Unified API in TypeScript, Python, .NET (C#), Golang, and Rust
17
+ - **Google Sheets Database** — Use spreadsheets as a live database with full CRUD and SQL syntax support
18
+
19
+ ---
20
+
21
+ ## Installation
22
+
23
+ ### TypeScript
24
+
25
+ ```bash
26
+ npm install @an5/adapters
27
+ ```
28
+
29
+ ### Python
30
+
31
+ ```bash
32
+ pip install an5-adapters
33
+ ```
34
+
35
+ ### .NET
36
+
37
+ ```bash
38
+ dotnet add package An5Adapters
39
+ ```
40
+
41
+ ### Go
42
+
43
+ ```bash
44
+ # Included in the npm package under golang/ or via go module
45
+ ```
46
+
47
+ ### Rust
48
+
49
+ ```bash
50
+ cargo add an5-adapters
51
+ ```
52
+
53
+ The crate is driver-agnostic — it depends on `sqlx` with `any`, so the app enables the driver it needs. See [crates.io](https://crates.io/crates/an5-adapters) and [docs.rs](https://docs.rs/an5-adapters).
54
+
55
+ ---
56
+
57
+ ## NBase — Neural Vector Database
58
+
59
+ [NBase](https://github.com/N2FlowJS/nbase) is a partitioned vector database with
60
+ HNSW, LSH and KNN indexing behind a REST API. an5 can run vector search there
61
+ instead of loading every row into memory, which matters once a table holds
62
+ millions of embeddings.
63
+
64
+ The rows stay in your relational table: only the vectors move to NBase, each one
65
+ tagged with its row id, and search results are hydrated from the table.
66
+
67
+ ### Configure
68
+
69
+ NBase is configured through the connection string, like every other backend:
70
+
71
+ ```ts
72
+ import { createAn5Adapter } from '@an5/adapters';
73
+
74
+ const db = createAn5Adapter({ connectionString: 'nbase://localhost:1307' });
75
+ await db.$connect(); // probes NBase
76
+ ```
77
+
78
+ Accepted forms:
79
+
80
+ | Form | Result |
81
+ |------|--------|
82
+ | `nbase://localhost:1307` | `http://localhost:1307` |
83
+ | `nbase:localhost:1307` | `http://localhost:1307` |
84
+ | `nbase:http://localhost:1307` | `http://localhost:1307` |
85
+ | `nbase:https://vectors.example.com` | `https://vectors.example.com` |
86
+ | `nbase://localhost:1307?token=t&timeoutMs=500&method=hnsw` | options applied |
87
+
88
+ `?token`, `?timeoutMs`, `?method`, `?idField` and `?modelField` are read from the
89
+ query string, and a path is kept as a base path for deployments behind a
90
+ reverse proxy.
91
+
92
+ This adapter is **vector-only**: it has no relational database, so a search
93
+ returns the NBase hits — id, metadata and `distance` — instead of table rows.
94
+
95
+ ### Search
96
+
97
+ With an `nbase://` connection string, search returns the hits themselves:
98
+
99
+ ```ts
100
+ const hits = await db.table('Article').vectorSearch({ vector: queryEmbedding, take: 5 });
101
+ // hits[0] = { id: 'Article:42', an5Id: '42', an5Model: 'Article', distance: 0.11 }
102
+ ```
103
+
104
+ ### Search rows from your own table
105
+
106
+ To get real rows back, keep your database connection string and point it at the
107
+ same NBase instance. NBase is still configured with a connection string, never a
108
+ params object:
109
+
110
+ ```ts
111
+ const db = createAn5Adapter({
112
+ connectionString: 'sqlserver://localhost:1433;database=mydb',
113
+ nbase: 'nbase://localhost:1307',
114
+ });
115
+
116
+ await db.table('Article').indexVectorsInNBase({ vectorField: 'embedding' });
117
+ // → { indexed: 1200 }
118
+
119
+ const hits = await db.table('Article').vectorSearch({ vector: queryEmbedding, take: 5 });
120
+ // hits[0] = { id, title, ..., distance }
121
+ ```
122
+
123
+ Vectors are tagged with their row id, so a hit is hydrated from the table by
124
+ that id and the result keeps the `{ ...row, distance }` shape the other engines
125
+ return.
126
+
127
+ ### Standalone client
128
+
129
+ ```ts
130
+ import { createNBaseVectorClient } from '@an5/adapters/nbase';
131
+
132
+ const nbase = createNBaseVectorClient({ url: 'http://localhost:1307' });
133
+ await nbase.health();
134
+ await nbase.addVectors([{ id: 'a:1', vector: [0.1, 0.2], metadata: { an5Id: '1' } }]);
135
+ const { results } = await nbase.search([0.1, 0.2], { k: 5, distanceMetric: 'cosine' });
136
+ ```
137
+
138
+ If NBase is unreachable, `vectorSearch` logs a warning and falls back to the
139
+ database's native vector support, then to in-memory similarity, so an outage
140
+ degrades performance rather than breaking queries.
141
+
142
+
143
+ ## Usage
144
+
145
+ ### TypeScript
146
+
147
+ ```typescript
148
+ import { createAn5Adapter } from '@an5/adapters';
149
+
150
+ const db = createAn5Adapter({
151
+ connectionString: process.env.DATABASE_URL!,
152
+ });
153
+
154
+ // Dynamic model access
155
+ const users = await db.user.findMany({
156
+ where: { active: true },
157
+ include: {
158
+ orders: {
159
+ where: { status: 'paid' },
160
+ orderBy: { total: 'desc' },
161
+ take: 5,
162
+ },
163
+ _count: true,
164
+ },
165
+ take: 10,
166
+ });
167
+
168
+ // Nested writes
169
+ const created = await db.user.create({
170
+ data: {
171
+ email: 'alpha@example.com',
172
+ name: 'Alpha',
173
+ orders: {
174
+ create: [
175
+ { total: 100, status: 'open' },
176
+ { total: 250, status: 'paid' },
177
+ ],
178
+ },
179
+ },
180
+ include: { orders: true, _count: true },
181
+ });
182
+
183
+ // Atomic updates
184
+ await db.user.update({
185
+ where: { id: created.id },
186
+ data: {
187
+ score: { increment: 10 },
188
+ },
189
+ });
190
+
191
+ // Aggregations
192
+ const stats = await db.order.aggregate({
193
+ _count: true,
194
+ _sum: { total: true },
195
+ _avg: { total: true },
196
+ });
197
+ console.log(stats._count._all, stats._sum.total, stats._avg.total);
198
+
199
+ // Transactions
200
+ await db.$transaction(async (tx) => {
201
+ await tx.user.update({
202
+ where: { id: created.id },
203
+ data: { score: { increment: 5 } },
204
+ });
205
+ await tx.order.create({
206
+ data: { userId: created.id, total: 50, status: 'paid' },
207
+ });
208
+ });
209
+
210
+ // Raw query
211
+ const rawRows = await db.$queryRawUnsafe('SELECT * FROM users WHERE active = @p_0', 1);
212
+
213
+ // Disconnect
214
+ await db.$disconnect();
215
+ ```
216
+
217
+ ### Python
218
+
219
+ ```python
220
+ from an5_adapter import create_an5_adapter
221
+
222
+ db = create_an5_adapter("sqlserver://localhost:1433;database=mydb;user=sa;password=pass")
223
+
224
+ # Dynamic model access
225
+ users = db.user.find_many(where={"active": True}, take=10)
226
+
227
+ # Nested create
228
+ created = db.user.create({
229
+ "data": {
230
+ "email": "alpha@example.com",
231
+ "name": "Alpha",
232
+ }
233
+ })
234
+
235
+ # Transactions
236
+ def perform_transfer(tx):
237
+ tx.user.update({"where": {"id": "u1"}, "data": {"score": {"increment": 10}}})
238
+
239
+ db.transaction(perform_transfer)
240
+ ```
241
+
242
+ ---
243
+
244
+ ## API Reference
245
+
246
+ ### `An5Adapter`
247
+
248
+ | Method / Property | Description |
249
+ |-------------------|-------------|
250
+ | `db[modelName]` | Dynamic proxy returning `AdapterTableClient` for the model |
251
+ | `table<T>(name)` | Explicitly returns `AdapterTableClient<T>` |
252
+ | `exec(query, params)` | Execute raw parameterized query returning rows |
253
+ | `$queryRawUnsafe(sql, ...args)` | Positional raw query |
254
+ | `$executeRaw(sql, ...args)` | Raw DML execution returning affected count |
255
+ | `$transaction(fn)` | Callback transaction with automatic commit/rollback |
256
+ | `$begin()` | Interactive transaction returning `An5AdapterTx` |
257
+ | `$connect()` | Open connection / pool |
258
+ | `$disconnect()` | Close connections |
259
+
260
+ ### `AdapterTableClient`
261
+
262
+ | Method | Description |
263
+ |--------|-------------|
264
+ | `findMany(args)` | Query multiple records with `where`, `orderBy`, `skip`, `take`, `select`, `include` |
265
+ | `findFirst(args)` | Query first matching record |
266
+ | `findUnique(args)` | Query unique record by unique filter |
267
+ | `create(args)` | Insert a record with support for nested relation writes |
268
+ | `createMany(args)` | Bulk insert records |
269
+ | `update(args)` | Update record with field math operations & nested relation writes |
270
+ | `updateMany(args)` | Update multiple records |
271
+ | `delete(args)` | Delete a single record |
272
+ | `deleteMany(args)` | Delete multiple records |
273
+ | `upsert(args)` | Insert or update a record |
274
+ | `count(args)` | Count matching records |
275
+ | `aggregate(args)` | Compute `_count`, `_sum`, `_avg`, `_min`, `_max` |
276
+ | `groupBy(args)` | Group by fields with aggregations and pagination |
277
+ | `vectorSearch(args)` | Semantic vector similarity search |
278
+
279
+ ---
280
+
281
+ ## License
282
+
283
+ MIT