@an5/adapters 0.2.10 → 0.2.13

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 (109) hide show
  1. package/README.md +163 -2
  2. package/dist/an5Adapter.d.ts +37 -0
  3. package/dist/an5Adapter.js +190 -65
  4. package/dist/base/metadata.d.ts +2 -0
  5. package/dist/base/metadata.js +10 -0
  6. package/dist/base/sql.d.ts +2 -0
  7. package/dist/base/sql.js +24 -25
  8. package/dist/base/types.d.ts +14 -0
  9. package/dist/googlesheets/adapter.js +16 -8
  10. package/dist/googlesheets/config.d.ts +13 -0
  11. package/dist/googlesheets/config.js +5 -1
  12. package/dist/googlesheets/oauth.d.ts +3 -0
  13. package/dist/googlesheets/oauth.js +43 -0
  14. package/dist/googlesheets/parseConnectionString.js +12 -0
  15. package/dist/googlesheets/tableClient.js +5 -23
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +8 -1
  18. package/dist/sqlite/browserEngine.d.ts +13 -0
  19. package/dist/sqlite/browserEngine.js +13 -0
  20. package/dist/sqlite/engine.d.ts +5 -0
  21. package/dist/sqlite/engine.js +10 -0
  22. package/dist/sqlite/index.d.ts +1 -0
  23. package/dist/sqlite/index.js +1 -0
  24. package/dist/sqlite/vector.d.ts +155 -0
  25. package/dist/sqlite/vector.js +436 -0
  26. package/dotnet/An5Adapter.cs +85 -27
  27. package/dotnet/Base/Core.cs +14 -0
  28. package/dotnet/Mssql/MssqlEngine.cs +44 -1
  29. package/dotnet/Postgres/PostgresEngine.cs +2 -0
  30. package/dotnet/Sqlite/SqliteEngine.cs +82 -2
  31. package/dotnet/Sqlite/SqliteVectors.cs +401 -0
  32. package/golang/an5_adapter.go +84 -32
  33. package/golang/base/vectors.go +263 -0
  34. package/golang/sqlite/vector.go +248 -0
  35. package/golang/sqlite_vector_test.go +288 -0
  36. package/golang/table_client.go +67 -3
  37. package/java/pom.xml +177 -0
  38. package/java/src/main/java/an5/adapters/An5Adapter.java +374 -0
  39. package/java/src/main/java/an5/adapters/An5Aggregate.java +116 -0
  40. package/java/src/main/java/an5/adapters/An5GroupBy.java +97 -0
  41. package/java/src/main/java/an5/adapters/An5Query.java +100 -0
  42. package/java/src/main/java/an5/adapters/An5TableClient.java +1031 -0
  43. package/java/src/main/java/an5/adapters/An5ViewClient.java +107 -0
  44. package/java/src/main/java/an5/adapters/base/Dialect.java +103 -0
  45. package/java/src/main/java/an5/adapters/base/FieldMeta.java +42 -0
  46. package/java/src/main/java/an5/adapters/base/JdbcUrls.java +201 -0
  47. package/java/src/main/java/an5/adapters/base/Metadata.java +195 -0
  48. package/java/src/main/java/an5/adapters/base/RelationDef.java +26 -0
  49. package/java/src/main/java/an5/adapters/base/SqlBuilder.java +422 -0
  50. package/java/src/main/java/an5/adapters/base/SqliteVectors.java +375 -0
  51. package/java/src/main/java/an5/adapters/base/Vectors.java +123 -0
  52. package/java/src/test/java/An5AdaptersSmoke.java +733 -0
  53. package/java/src/test/java/Json.java +174 -0
  54. package/java/src/test/java/QuerySemantics.java +111 -0
  55. package/kotlin/build.gradle.kts +145 -0
  56. package/kotlin/settings.gradle.kts +10 -0
  57. package/kotlin/src/main/kotlin/an5/adapters/Aggregate.kt +89 -0
  58. package/kotlin/src/main/kotlin/an5/adapters/An5.kt +91 -0
  59. package/kotlin/src/main/kotlin/an5/adapters/Query.kt +130 -0
  60. package/kotlin/src/main/kotlin/an5/adapters/Rows.kt +166 -0
  61. package/kotlin/src/main/kotlin/an5/adapters/TableClient.kt +169 -0
  62. package/kotlin/src/main/kotlin/an5/adapters/Types.kt +77 -0
  63. package/kotlin/src/test/kotlin/an5/adapters/An5Smoke.kt +329 -0
  64. package/native/sqlite/CMakeLists.txt +12 -0
  65. package/native/sqlite/README.md +117 -0
  66. package/native/sqlite/an5_vector.c +209 -0
  67. package/package.json +40 -9
  68. package/python/an5_adapter.py +37 -6
  69. package/python/base/__init__.py +15 -0
  70. package/python/base/vectors.py +434 -0
  71. package/python/sqlite/__init__.py +2 -2
  72. package/python/sqlite/provider.py +21 -1
  73. package/python/table_client.py +129 -59
  74. package/rust/src/adapter.rs +342 -24
  75. package/rust/src/base/mod.rs +7 -0
  76. package/rust/src/base/vectors.rs +293 -0
  77. package/rust/src/lib.rs +3 -3
  78. package/scripts/sqlite-native-build.js +32 -0
  79. package/swift/Package.swift +22 -0
  80. package/swift/Sources/An5Adapters/An5Adapter.swift +160 -0
  81. package/swift/Sources/An5Adapters/Metadata.swift +183 -0
  82. package/swift/Sources/An5Adapters/Query.swift +105 -0
  83. package/swift/Sources/An5Adapters/Row+Accessors.swift +129 -0
  84. package/swift/Sources/An5Adapters/SQLBuilder.swift +359 -0
  85. package/swift/Sources/An5Adapters/SQLiteDriver.swift +301 -0
  86. package/swift/Sources/An5Adapters/SqliteVectors.swift +243 -0
  87. package/swift/Sources/An5Adapters/TableClient.swift +671 -0
  88. package/swift/Sources/An5Adapters/Types.swift +127 -0
  89. package/swift/Sources/An5Adapters/Vectors.swift +86 -0
  90. package/swift/Sources/An5Adapters/ViewClient.swift +50 -0
  91. package/swift/Sources/CSQLite/module.modulemap +8 -0
  92. package/swift/Sources/CSQLite/shim.h +9 -0
  93. package/swift/Tests/An5AdaptersTests/QuerySemanticsTests.swift +51 -0
  94. package/swift/Tests/An5AdaptersTests/RuntimeSmokeTests.swift +488 -0
  95. package/typescript/src/an5Adapter.ts +200 -58
  96. package/typescript/src/base/metadata.ts +8 -0
  97. package/typescript/src/base/sql.ts +23 -16
  98. package/typescript/src/base/types.ts +15 -0
  99. package/typescript/src/googlesheets/adapter.ts +17 -8
  100. package/typescript/src/googlesheets/config.ts +10 -1
  101. package/typescript/src/googlesheets/oauth.ts +31 -0
  102. package/typescript/src/googlesheets/parseConnectionString.ts +8 -0
  103. package/typescript/src/googlesheets/tableClient.ts +5 -19
  104. package/typescript/src/index.ts +13 -0
  105. package/typescript/src/sqlite/browserEngine.ts +24 -0
  106. package/typescript/src/sqlite/engine.ts +13 -0
  107. package/typescript/src/sqlite/index.ts +1 -1
  108. package/typescript/src/sqlite/vector.ts +541 -0
  109. package/golang/sqlite/sqlite.go +0 -14
package/README.md CHANGED
@@ -13,7 +13,7 @@ Standalone runtime database adapter and query engine for AN5 ORM. Provides conne
13
13
  - **Field Math Operators** — Atomic updates with `increment`, `decrement`, `multiply`, `divide`, `set`
14
14
  - **Vector Search** — Similarity search using NBase, pgvector (PostgreSQL), `VECTOR_DISTANCE` (MSSQL), or in-memory cosine/euclidean/dot similarity
15
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
16
+ - **Cross-Language** — Unified API in TypeScript, Python, .NET (C#), Golang, Rust, Java, Kotlin, and Swift
17
17
  - **Google Sheets Database** — Use spreadsheets as a live database with full CRUD and SQL syntax support
18
18
 
19
19
  ---
@@ -52,6 +52,78 @@ cargo add an5-adapters
52
52
 
53
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
54
 
55
+ ### Java
56
+
57
+ ```bash
58
+ # Included in the npm package under java/, which ships its own pom.xml
59
+ ```
60
+
61
+ `java/` is a Maven module with **no dependencies**: the adapter speaks JDBC through
62
+ `java.sql`, so the app picks the driver it already has — `org.xerial:sqlite-jdbc`,
63
+ `org.postgresql:postgresql` or `com.microsoft.sqlserver:mssql-jdbc`. That is what lets one
64
+ runtime serve all three engines and what keeps it usable on Android, where an adapter that
65
+ dragged in three drivers would not fit.
66
+
67
+ ```xml
68
+ <dependency>
69
+ <groupId>io.github.an5orm</groupId>
70
+ <artifactId>an5-adapters-java</artifactId>
71
+ <version>0.2.13</version>
72
+ </dependency>
73
+ ```
74
+
75
+ From a checkout the same module is built and installed into `~/.m2`:
76
+
77
+ ```bash
78
+ mvn -f java/pom.xml install
79
+ mvn -f java/pom.xml test
80
+ ```
81
+
82
+ ### Kotlin
83
+
84
+ ```bash
85
+ # Included in the npm package under kotlin/, which ships build.gradle.kts
86
+ ```
87
+
88
+ Gradle rather than Maven, because Kotlin on Android is built with Gradle and a runtime a
89
+ phone app cannot resolve is not a mobile runtime. The Kotlin runtime depends on the Java one
90
+ rather than reimplementing it, so the dialect rules and the where builder exist once:
91
+
92
+ ```kotlin
93
+ dependencies {
94
+ implementation("io.github.an5orm:an5-adapters-kotlin:0.2.13")
95
+ }
96
+ ```
97
+
98
+ From a checkout the Kotlin module resolves its Java sibling from `~/.m2` — declared as
99
+ `mavenLocal()` in `build.gradle.kts`, so the checkout builds without publishing anything
100
+ first:
101
+
102
+ ```bash
103
+ mvn -f java/pom.xml install
104
+ gradle -p kotlin build
105
+ ```
106
+
107
+ Both JVM modules publish to Maven Central, and each release ships both
108
+ `io.github.an5orm:an5-adapters-java:<version>` and
109
+ `io.github.an5orm:an5-adapters-kotlin:<version>`: a `v*` tag runs the
110
+ `publish-maven` job in `.github/workflows/publish.yml` (`mvn -Prelease deploy` and
111
+ `gradle publish`), and a manual run is available through the workflow's `publish-maven`
112
+ input. It needs the repository secrets `MAVEN_CENTRAL_USERNAME` and `MAVEN_CENTRAL_TOKEN`
113
+ (a Central Portal token), `MAVEN_GPG_PRIVATE_KEY` and `MAVEN_GPG_PASSPHRASE`.
114
+
115
+ ### Swift
116
+
117
+ ```swift
118
+ .package(url: "https://github.com/an5ORM/an5Adapters.git", from: "0.2.13")
119
+ ```
120
+
121
+ A SwiftPM package that links the **system** SQLite — the database every Apple platform
122
+ already ships, so there is no bundled engine and the same file works on device and in the
123
+ simulator. Building it needs SQLite's headers (`apt-get install libsqlite3-dev` on Linux).
124
+ The runtime takes a `SQLDriver`, so an app that already has a database layer can put GRDB or
125
+ SQLite.swift underneath instead.
126
+
55
127
  ---
56
128
 
57
129
  ## NBase — Neural Vector Database
@@ -139,6 +211,65 @@ If NBase is unreachable, `vectorSearch` logs a warning and falls back to the
139
211
  database's native vector support, then to in-memory similarity, so an outage
140
212
  degrades performance rather than breaking queries.
141
213
 
214
+ ---
215
+
216
+ ## SQLite — vector search without a vector database
217
+
218
+ For host-language-free distance calculation, build the shared
219
+ [AN5 C extension](native/sqlite/README.md) with
220
+ `npm run build:sqlite:native` and pass the printed library path as `sqliteVec`.
221
+ It runs cosine, Euclidean and dot-product distances natively, with SSE2 on
222
+ x86-64 and query-vector caching. The existing fallback remains available when
223
+ an extension is not loaded.
224
+
225
+ SQLite has no vector type, so a `VECTOR(n)` column stores a **BLOB of
226
+ little-endian float32** — 4 bytes per dimension. Write a plain array of numbers
227
+ and the adapter encodes it; read it back and you get the same array. A column
228
+ that already holds JSON text (`'[0.1, 0.2]'`) keeps working, so nothing has to
229
+ be migrated.
230
+
231
+ ```ts
232
+ await db.table('Article').create({ data: { title: '…', embedding: queryEmbedding } });
233
+
234
+ const row = await db.table('Article').findFirst({ where: { title: '…' } });
235
+ row.embedding; // number[]
236
+ ```
237
+
238
+ The search is ranked **inside the database**, trying four strategies in order:
239
+
240
+ | Order | Strategy | Needs | Reaches |
241
+ |-------|----------|-------|---------|
242
+ | 1 | `sqlite-vec` | The extension loaded | Scalar distances over ordinary tables |
243
+ | 2 | `udf` | A driver that can register a function | `BLOB` and legacy text columns |
244
+ | 3 | `sql` | JSON1 (built in since SQLite 3.38) | Legacy text columns |
245
+ | 4 | `memory` | Nothing | Any column, whole table loaded |
246
+
247
+ Strategies 1-3 transfer only the rows that match, which is the reason to prefer
248
+ them. A row whose stored vector cannot be scored is left out rather than returned
249
+ with a null distance.
250
+
251
+ [sqlite-vec](https://github.com/asg017/sqlite-vec) supplies native vector distance
252
+ functions for exact search. The adapter scans an ordinary table with those
253
+ functions; it does not create or synchronize a `vec0` virtual table:
254
+
255
+ ```ts
256
+ const db = createAn5Adapter({
257
+ connectionString: 'sqlite:///app.db',
258
+ sqliteVec: require('sqlite-vec').getLoadablePath(),
259
+ });
260
+ ```
261
+
262
+ `vectorStrategy` pins one strategy instead of probing — `'auto'` (the default),
263
+ `'sqlite-vec'`, `'udf'`, `'sql'` or `'memory'`. Every other runtime implements
264
+ the same four strategies with the same order; `sqlx` (Rust) and JDBC (Java,
265
+ Kotlin) use `sql` for JSON text and `memory` for BLOB columns without
266
+ driver-specific vector functions.
267
+
268
+ ```python
269
+ from an5_adapter import create_an5_adapter
270
+ db = create_an5_adapter("sqlite:///app.db", sqlite_vec="vec0", vector_strategy="auto")
271
+ ```
272
+
142
273
 
143
274
  ## Usage
144
275
 
@@ -274,10 +405,40 @@ db.transaction(perform_transfer)
274
405
  | `count(args)` | Count matching records |
275
406
  | `aggregate(args)` | Compute `_count`, `_sum`, `_avg`, `_min`, `_max` |
276
407
  | `groupBy(args)` | Group by fields with aggregations and pagination |
277
- | `vectorSearch(args)` | Semantic vector similarity search |
408
+ | `vectorSearch(args)` | Semantic vector similarity search; SQLite ranks it in the database (sqlite-vec, `an5_vec_*`, `json_each`), everything else uses the engine's native support or scores in memory |
409
+
410
+ Generated TypeScript field metadata marks schema primary keys with `isId: true`.
411
+ SQL and Google Sheets `create` use this marker to identify custom primary-key
412
+ names before falling back to `id` or `...Id` for older metadata. Regenerate the
413
+ client to enable this behavior for existing custom-key schemas.
414
+
415
+ `createMany` uses a bulk statement when every row supplies the same columns.
416
+ Rows with different column sets or missing generated UUID keys are inserted
417
+ individually so omitted columns retain their defaults and UUID keys are assigned. Bulk failures are propagated without retrying
418
+ individual rows. Wrap mixed-column inserts in `$transaction` when they must
419
+ succeed or roll back together.
420
+
421
+ For SQL adapters, `skipDuplicates: true` skips only unique or primary-key
422
+ violations. Connection failures and other constraint errors are propagated.
423
+ Google Sheets does not enforce unique constraints; this flag does not deduplicate
424
+ sheet rows, and failed batch appends are propagated without individual retries.
425
+
426
+ For SQL adapters, `findMany` and `groupBy` accept `skip` without `take` to
427
+ return all remaining rows or groups. Supply `orderBy` for stable row pagination;
428
+ `groupBy` orders by its grouping fields when pagination has no explicit ordering.
429
+ With relation metadata configured, `groupBy.where` supports the same relation
430
+ filters as `findMany.where`, including `some`, `none`, `every`, `is`, and `isNot`.
278
431
 
279
432
  ---
280
433
 
281
434
  ## License
282
435
 
283
436
  MIT
437
+
438
+ ### Google Sheets desktop OAuth
439
+
440
+ Google Sheets connections accept `accessToken`, `refreshToken`, `oauthClientId`, optional `oauthClientSecret`, and `tokenExpiresAt` (Unix milliseconds). The VS Code connection UI can generate and store this URI after browser sign-in and spreadsheet selection. Values in the semicolon-delimited URI must be URL encoded. Keep offline credentials in secure storage; do not commit them.
441
+
442
+ The adapter refreshes expired access tokens before requests, shares concurrent refresh requests, and retries authentication failures once after refreshing. Revoked credentials report a reconnect error. Existing service account, API key and access-token-only configurations remain supported.
443
+
444
+ For web applications, use a Google Web OAuth client and per-user access tokens. The browser adapter rejects offline desktop credentials and service account private keys. A browser connection manager must handle account selection, token reacquisition and SQLite persistence; see the [browser connection design](https://an5orm.github.io/docs/guides/browser-connections/).
@@ -1,6 +1,7 @@
1
1
  import { An5SheetsAdapter, An5SheetsAdapterConfig, SheetsTableClient } from './googlesheets';
2
2
  import type { An5AdapterConfig, Dialect, TransactionHandle } from './base/types';
3
3
  import { type NBaseAdapterConfig, type NBaseVectorClient } from './nbase';
4
+ import { type SqliteVectorSupport, type VectorStrategyPreference } from './sqlite/vector';
4
5
  export type { An5AdapterConfig, Dialect, QueryEngine, TransactionHandle } from './base/types';
5
6
  export { setAdapterMetadata, createAdapterProxy, type AdapterMetadata } from './base/metadata';
6
7
  export type { TypedAn5Adapter, AdapterAPI } from './typed';
@@ -36,6 +37,14 @@ export declare class An5Adapter {
36
37
  private requireEngine;
37
38
  private requireSheetsAdapter;
38
39
  exec<T = any>(query: string, params?: Record<string, any>): Promise<T[]>;
40
+ /**
41
+ * The SQLite engine's vector hooks, or null when this is not a SQLite adapter.
42
+ * `vectorSearch` needs them to load sqlite-vec and register the distance
43
+ * functions; a connection with no hooks still searches in memory.
44
+ */
45
+ sqliteVectorSupport(): Promise<SqliteVectorSupport | null>;
46
+ /** `vectorStrategy` from the config, so a project can pin one strategy. */
47
+ get vectorStrategy(): VectorStrategyPreference | undefined;
39
48
  /** INTERNAL: used by AdapterTableClient for DML statements needing row count */
40
49
  _executeRaw(query: string, params?: Record<string, any>): Promise<number>;
41
50
  /** Execute a raw query with positional values → @p_0, @p_1, ... per dialect */
@@ -141,11 +150,30 @@ export declare class AdapterTableClient<T = any> {
141
150
  constructor(adapter: An5Adapter | An5AdapterTx, modelName: string);
142
151
  get dialect(): Dialect;
143
152
  get tableName(): string;
153
+ /** The table name this model maps to, before any quoting is applied. */
154
+ private get mappedTableName();
155
+ /**
156
+ * The bare table name, for helpers that take a string literal. `@@map` values
157
+ * may be pre-quoted or schema-qualified, neither of which `pragma_table_info`
158
+ * accepts, so the last segment is unwrapped here.
159
+ */
160
+ get rawTableName(): string;
144
161
  private get nolock();
145
162
  /** Build the shared context used by parseWhere to resolve relations and self references. */
146
163
  private whereContext;
147
164
  private doExec;
148
165
  private doExecuteRaw;
166
+ /**
167
+ * Encode every `VECTOR(n)` value on its way into SQLite.
168
+ *
169
+ * The column holds a float32 BLOB, which is a third of the size of the JSON
170
+ * text it replaces and is what sqlite-vec reads. Values that already arrived
171
+ * as text or bytes are left alone, so rows written by an older version stay
172
+ * readable.
173
+ */
174
+ private encodeVectorFields;
175
+ /** Decode `VECTOR(n)` columns back into `number[]` after a read. */
176
+ private decodeVectorFields;
149
177
  findMany(args?: {
150
178
  where?: any;
151
179
  orderBy?: any;
@@ -246,6 +274,15 @@ export declare class AdapterTableClient<T = any> {
246
274
  }): Promise<(T & {
247
275
  distance: number;
248
276
  })[]>;
277
+ /**
278
+ * Rank the vector column in the client. This is the last resort for every
279
+ * provider, and the only option on SQLite connections that offer neither
280
+ * sqlite-vec, a driver function nor JSON1.
281
+ *
282
+ * The whole table is loaded, so it is only reasonable for a table small
283
+ * enough to fit in memory.
284
+ */
285
+ private scoreVectorsInMemory;
249
286
  }
250
287
  export declare function createAn5Adapter(config: AnyAdapterConfig): AnyAdapter;
251
288
  export declare function createAn5Adapter<TModels extends object>(config: AnyAdapterConfig): import('./typed').TypedAn5Adapter<TModels>;