@type32/tauri-sqlite-orm 0.2.13 → 0.3.0

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.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,26 @@
1
- import Database from '@tauri-apps/plugin-sql';
1
+ import { Dialect, DialectAdapter, Driver, Kysely, DatabaseIntrospector, QueryCompiler, Expression, SqlBool } from 'kysely';
2
+ export { Expression, sql } from 'kysely';
3
+
4
+ /**
5
+ * Minimal interface that any SQLite-over-Tauri (or compatible mock) database must satisfy.
6
+ * Using this instead of the concrete `@tauri-apps/plugin-sql` type keeps the dialect
7
+ * portable and testable outside a Tauri runtime.
8
+ */
9
+ interface DatabaseLike {
10
+ select<T>(query: string, params?: any[]): Promise<T>;
11
+ execute(query: string, params?: any[]): Promise<{
12
+ lastInsertId: number;
13
+ rowsAffected: number;
14
+ }>;
15
+ }
16
+ declare class TauriDialect implements Dialect {
17
+ private readonly db;
18
+ constructor(db: DatabaseLike);
19
+ createAdapter(): DialectAdapter;
20
+ createDriver(): Driver;
21
+ createIntrospector(db: Kysely<any>): DatabaseIntrospector;
22
+ createQueryCompiler(): QueryCompiler;
23
+ }
2
24
 
3
25
  type ColumnDataType = 'TEXT' | 'INTEGER' | 'REAL' | 'BLOB' | 'BOOLEAN' | 'NUMERIC';
4
26
  type Mode = 'default' | 'timestamp' | 'timestamp_ms' | 'json' | 'boolean' | 'bigint';
@@ -13,6 +35,8 @@ interface ColumnOptions<TData, TEnum extends readonly string[] = readonly string
13
35
  references?: {
14
36
  table: AnyTable;
15
37
  column: AnySQLiteColumn;
38
+ onDelete?: 'cascade' | 'set null' | 'set default' | 'restrict' | 'no action';
39
+ onUpdate?: 'cascade' | 'set null' | 'set default' | 'restrict' | 'no action';
16
40
  };
17
41
  mode?: Mode;
18
42
  $onUpdateFn?: () => TData;
@@ -28,69 +52,97 @@ type AnyTable = Table<Record<string, AnySQLiteColumn>, string>;
28
52
  type InferSelectModel<T extends AnyTable> = {
29
53
  [K in keyof T['_']['columns']]: ExtractColumnType<T['_']['columns'][K]>;
30
54
  };
31
- type RelationType = 'one' | 'many' | 'manyToMany';
55
+ type RelationType = 'one' | 'many';
32
56
  interface RelationConfig {
33
57
  type: RelationType;
34
58
  foreignTable: AnyTable;
59
+ /** For one: local FK columns. For many (v2): foreign table's FK columns. */
35
60
  fields?: AnySQLiteColumn[];
61
+ /** For one: foreign PK columns. For many (v2): parent table's PK columns. */
36
62
  references?: AnySQLiteColumn[];
63
+ /** For many-to-many via through(): junction table between parent and foreign */
37
64
  junctionTable?: AnyTable;
38
- junctionFields?: AnySQLiteColumn[];
39
- junctionReferences?: AnySQLiteColumn[];
40
- }
41
-
42
- declare class BaseQueryBuilder {
43
- protected db: Database;
44
- protected query: string;
45
- protected params: any[];
46
- constructor(db: Database);
47
- where(condition: SQLCondition): this;
48
- orderBy(column: AnySQLiteColumn | {
49
- sql: string;
50
- params: any[];
51
- }, direction?: "ASC" | "DESC"): this;
52
- limit(count: number): this;
53
- offset(count: number): this;
54
- build(): {
55
- sql: string;
56
- params: any[];
65
+ /** Parent column -> junction column (parent PK = junction FK to parent) */
66
+ fromJunction?: {
67
+ column: AnySQLiteColumn;
68
+ junctionColumn: AnySQLiteColumn;
57
69
  };
58
- toSQL(): {
59
- sql: string;
60
- params: any[];
70
+ /** Junction column -> foreign column (junction FK to foreign = foreign PK) */
71
+ toJunction?: {
72
+ junctionColumn: AnySQLiteColumn;
73
+ column: AnySQLiteColumn;
61
74
  };
75
+ /** When false, one relation is required (type-level: T not T | null) */
76
+ optional?: boolean;
77
+ /** Alias for the relation (e.g. for self-referential disambiguation) */
78
+ alias?: string;
79
+ /** Predefined filter for many relations: (alias) => Condition. Receives the joined table alias. */
80
+ where?: (alias: string) => unknown;
62
81
  }
63
82
 
83
+ type Condition = Expression<SqlBool>;
84
+ declare const eq: <T>(column: AnySQLiteColumn, value: T, tableAlias?: string) => Condition;
85
+ declare const ne: <T>(column: AnySQLiteColumn, value: T, tableAlias?: string) => Condition;
86
+ declare const and: (...conditions: Condition[]) => Condition;
87
+ declare const or: (...conditions: Condition[]) => Condition;
88
+ declare const not: (condition: Condition) => Condition;
89
+ declare const gt: <T>(column: AnySQLiteColumn, value: T) => Condition;
90
+ declare const gte: <T>(column: AnySQLiteColumn, value: T) => Condition;
91
+ declare const lt: <T>(column: AnySQLiteColumn, value: T) => Condition;
92
+ declare const lte: <T>(column: AnySQLiteColumn, value: T) => Condition;
93
+ declare const like: (column: AnySQLiteColumn, pattern: string) => Condition;
94
+ declare const ilike: (column: AnySQLiteColumn, pattern: string) => Condition;
95
+ declare const startsWith: (column: AnySQLiteColumn, value: string) => Condition;
96
+ declare const endsWith: (column: AnySQLiteColumn, value: string) => Condition;
97
+ declare const contains: (column: AnySQLiteColumn, value: string) => Condition;
98
+ declare const isNull: (column: AnySQLiteColumn) => Condition;
99
+ declare const isNotNull: (column: AnySQLiteColumn) => Condition;
100
+ declare const exists: (subquery: Expression<any>) => Condition;
101
+ declare const notExists: (subquery: Expression<any>) => Condition;
102
+ declare const eqSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
103
+ declare const neSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
104
+ declare const gtSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
105
+ declare const gteSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
106
+ declare const ltSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
107
+ declare const lteSubquery: (column: AnySQLiteColumn, subquery: Expression<any>) => Condition;
108
+ declare const inArray: <T>(column: AnySQLiteColumn, values: T[] | Expression<any>) => Condition;
109
+ declare const notIn: <T>(column: AnySQLiteColumn, values: T[] | Expression<any>) => Condition;
110
+ declare const between: <T>(column: AnySQLiteColumn, min: T, max: T) => Condition;
111
+
64
112
  type NestedInclude = boolean | {
113
+ columns?: string[] | Record<string, boolean>;
65
114
  with?: Record<string, NestedInclude>;
66
115
  };
67
116
  type ExtractRelationNames<T extends AnyTable> = T['relations'] extends Record<string, any> ? keyof T['relations'] & string : never;
68
117
  type IncludeRelations<T extends AnyTable> = T['relations'] extends Record<string, any> ? Partial<Record<ExtractRelationNames<T>, NestedInclude>> : Record<string, never>;
69
- declare class SelectQueryBuilder<TTable extends AnyTable, TSelectedColumns extends (keyof TTable['_']['columns'])[] | undefined = undefined> extends BaseQueryBuilder {
70
- private table;
71
- private columns?;
72
- private isDistinct;
73
- private groupByColumns;
74
- private havingCondition;
75
- private joins;
76
- private includeRelations;
77
- private selectedTableAlias;
78
- private selectedColumns;
79
- constructor(db: Database, table: TTable, columns?: TSelectedColumns | undefined);
118
+ declare class SelectQueryBuilder<TTable extends AnyTable, TSelectedColumns extends (keyof TTable['_']['columns'])[] | undefined = undefined> {
119
+ private readonly kysely;
120
+ private _builder;
121
+ private _table;
122
+ private _columns?;
123
+ private _includeRelations;
124
+ private _manualJoins;
125
+ private _isDistinct;
126
+ private _includedColumnAliases;
127
+ constructor(kysely: Kysely<any>, table: TTable, columns?: TSelectedColumns);
80
128
  distinct(): this;
129
+ where(condition: Condition): this;
130
+ orderBy(column: AnySQLiteColumn | Expression<any>, direction?: 'asc' | 'desc'): this;
131
+ limit(count: number): this;
132
+ offset(count: number): this;
81
133
  groupBy(...columns: AnySQLiteColumn[]): this;
82
- having(condition: SQLCondition): this;
83
- leftJoin<T extends AnyTable>(table: T, condition: SQLCondition, alias: string): this;
84
- innerJoin<T extends AnyTable>(table: T, condition: SQLCondition, alias: string): this;
134
+ having(condition: Condition): this;
135
+ leftJoin<T extends AnyTable>(table: T, condition: Expression<SqlBool>, alias: string): this;
136
+ innerJoin<T extends AnyTable>(table: T, condition: Expression<SqlBool>, alias: string): this;
85
137
  include(relations: IncludeRelations<TTable>): this;
86
- private buildJoins;
138
+ private applyIncludes;
87
139
  execute(): Promise<InferSelectModel<TTable>[]>;
88
140
  private processRelationResults;
89
141
  all(): Promise<InferSelectModel<TTable>[]>;
90
142
  get(): Promise<InferSelectModel<TTable> | undefined>;
143
+ first(): Promise<InferSelectModel<TTable> | undefined>;
91
144
  exists(): Promise<boolean>;
92
145
  count(): Promise<number>;
93
- first(): Promise<InferSelectModel<TTable> | undefined>;
94
146
  pluck<K extends keyof TTable['_']['columns']>(column: K): Promise<InferSelectModel<TTable>[K][]>;
95
147
  paginate(page?: number, pageSize?: number): Promise<{
96
148
  data: InferSelectModel<TTable>[];
@@ -105,23 +157,27 @@ declare class SelectQueryBuilder<TTable extends AnyTable, TSelectedColumns exten
105
157
  sql: string;
106
158
  params: any[];
107
159
  };
160
+ toKyselyExpression(): Expression<any>;
108
161
  }
109
162
 
110
- declare class UpdateQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
111
- private table;
112
- private updateData;
113
- private returningColumns;
114
- private hasWhereClause;
115
- private allowGlobal;
116
- private incrementDecrementOps;
117
- constructor(db: Database, table: T);
163
+ declare class UpdateQueryBuilder<T extends AnyTable> {
164
+ private readonly kysely;
165
+ private _builder;
166
+ private _table;
167
+ private _updateData;
168
+ private _returningColumns;
169
+ private _hasWhereClause;
170
+ private _allowGlobal;
171
+ private _incrementDecrementOps;
172
+ constructor(kysely: Kysely<any>, table: T);
118
173
  set(data: Partial<InferInsertModel<T>>): this;
119
- where(condition: any): this;
120
- increment(column: keyof T["_"]["columns"], value?: number): this;
121
- decrement(column: keyof T["_"]["columns"], value?: number): this;
174
+ where(condition: Condition): this;
175
+ increment(column: keyof T['_']['columns'], value?: number): this;
176
+ decrement(column: keyof T['_']['columns'], value?: number): this;
122
177
  allowGlobalOperation(): this;
123
- returning(...columns: (keyof T["_"]["columns"])[]): this;
124
- private buildUpdateClause;
178
+ returning(...columns: (keyof T['_']['columns'])[]): this;
179
+ private mapReturningRows;
180
+ private buildSetClause;
125
181
  execute(): Promise<T extends AnyTable ? (InferSelectModel<T> & Record<string, any>)[] : never>;
126
182
  returningAll(): Promise<InferSelectModel<T>[]>;
127
183
  returningFirst(): Promise<InferSelectModel<T> | undefined>;
@@ -131,23 +187,26 @@ declare class UpdateQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
131
187
  };
132
188
  }
133
189
 
134
- declare class InsertQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
135
- private table;
136
- private dataSets;
137
- private returningColumns;
138
- private onConflictAction;
139
- private conflictTarget;
140
- private updateSet;
141
- constructor(db: Database, table: T);
190
+ declare class InsertQueryBuilder<T extends AnyTable> {
191
+ private readonly kysely;
192
+ private _builder;
193
+ private _table;
194
+ private _dataSets;
195
+ private _returningColumns;
196
+ private _onConflictAction;
197
+ private _conflictTarget;
198
+ private _updateSet;
199
+ constructor(kysely: Kysely<any>, table: T);
142
200
  values(data: InferInsertModel<T> | InferInsertModel<T>[]): this;
143
- returning(...columns: (keyof T["_"]["columns"])[]): this;
201
+ returning(...columns: (keyof T['_']['columns'])[]): this;
144
202
  onConflictDoNothing(target?: AnySQLiteColumn | AnySQLiteColumn[]): this;
145
203
  onConflictDoUpdate(config: {
146
204
  target: AnySQLiteColumn | AnySQLiteColumn[];
147
205
  set: Partial<InferInsertModel<T>>;
148
206
  }): this;
149
- private processDefaultValues;
150
- private buildConflictClause;
207
+ private processDefaults;
208
+ private mapReturningRows;
209
+ private serializeDataSet;
151
210
  execute(): Promise<T extends AnyTable ? (InferSelectModel<T> & Record<string, any>)[] : never>;
152
211
  returningAll(): Promise<InferSelectModel<T>[]>;
153
212
  returningFirst(): Promise<InferSelectModel<T> | undefined>;
@@ -157,13 +216,16 @@ declare class InsertQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
157
216
  };
158
217
  }
159
218
 
160
- declare class DeleteQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
161
- private table;
162
- private returningColumns;
163
- private hasWhereClause;
164
- private allowGlobal;
165
- constructor(db: Database, table: T);
166
- where(condition: any): this;
219
+ declare class DeleteQueryBuilder<T extends AnyTable> {
220
+ private readonly kysely;
221
+ private _builder;
222
+ private _table;
223
+ private _returningColumns;
224
+ private _hasWhereClause;
225
+ private _allowGlobal;
226
+ constructor(kysely: Kysely<any>, table: T);
227
+ private mapReturningRows;
228
+ where(condition: Condition): this;
167
229
  allowGlobalOperation(): this;
168
230
  returning(...columns: (keyof T['_']['columns'])[]): this;
169
231
  execute(): Promise<T extends AnyTable ? (InferSelectModel<T> & Record<string, any>)[] : never>;
@@ -176,31 +238,25 @@ declare class DeleteQueryBuilder<T extends AnyTable> extends BaseQueryBuilder {
176
238
  }
177
239
 
178
240
  declare class WithQueryBuilder {
179
- private db;
180
- private ctes;
181
- constructor(db: Database);
182
- with(alias: string, query: {
183
- sql: string;
184
- params: any[];
185
- }): this;
186
- select<T extends AnyTable, C extends (keyof T["_"]["columns"])[] | undefined = undefined>(table: T, columns?: C): SelectQueryBuilder<T, C>;
241
+ private readonly kysely;
242
+ private _ctes;
243
+ constructor(kysely: Kysely<any>);
244
+ with(alias: string, query: SelectQueryBuilder<any, any>): this;
245
+ private applyWith;
246
+ select<T extends AnyTable, C extends (keyof T['_']['columns'])[] | undefined = undefined>(table: T, columns?: C): SelectQueryBuilder<T, C>;
187
247
  insert<T extends AnyTable>(table: T): InsertQueryBuilder<T>;
188
248
  update<T extends AnyTable>(table: T): UpdateQueryBuilder<T>;
189
249
  delete<T extends AnyTable>(table: T): DeleteQueryBuilder<T>;
190
- private applyWithClause;
191
250
  }
192
251
 
193
252
  type RelationsBuilder = {
194
253
  one: <U extends AnyTable>(table: U, config?: {
195
254
  fields: AnySQLiteColumn[];
196
255
  references: AnySQLiteColumn[];
256
+ optional?: boolean;
257
+ alias?: string;
197
258
  }) => OneRelation<U>;
198
259
  many: <U extends AnyTable>(table: U) => ManyRelation<U>;
199
- manyToMany: <U extends AnyTable>(table: U, config: {
200
- junctionTable: AnyTable;
201
- junctionFields: AnySQLiteColumn[];
202
- junctionReferences: AnySQLiteColumn[];
203
- }) => ManyToManyRelation<U>;
204
260
  };
205
261
 
206
262
  declare class SQLiteColumn<TName extends string = string, TType extends ColumnDataType = ColumnDataType, TMode extends Mode = 'default', TNotNull extends boolean = false, THasDefault extends boolean = false, TAutoincrement extends boolean = false, TEnum extends readonly string[] = never, TCustomType = never> {
@@ -223,7 +279,10 @@ declare class SQLiteColumn<TName extends string = string, TType extends ColumnDa
223
279
  primaryKey(): SQLiteColumn<TName, TType, TMode, true, THasDefault, TAutoincrement, TEnum, TCustomType>;
224
280
  autoincrement(): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, true, TEnum, TCustomType>;
225
281
  unique(): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, TCustomType>;
226
- references<T extends AnyTable, K extends keyof T['_']['columns'] & string>(ref: T, column: K | T['_']['columns'][K]): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, TCustomType>;
282
+ references<T extends AnyTable, K extends keyof T['_']['columns'] & string>(ref: T, column: K | T['_']['columns'][K], options?: {
283
+ onDelete?: 'cascade' | 'set null' | 'set default' | 'restrict' | 'no action';
284
+ onUpdate?: 'cascade' | 'set null' | 'set default' | 'restrict' | 'no action';
285
+ }): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, TCustomType>;
227
286
  $onUpdateFn(fn: () => ColumnValueTypes<TType, TMode>): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, TCustomType>;
228
287
  $type<T>(): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, T>;
229
288
  as(alias: string): SQLiteColumn<TName, TType, TMode, TNotNull, THasDefault, TAutoincrement, TEnum, TCustomType>;
@@ -254,37 +313,16 @@ declare class Table<TColumns extends Record<string, AnySQLiteColumn>, TTableName
254
313
  constructor(name: TTableName, columns: TColumns);
255
314
  }
256
315
  declare const sqliteTable: <TTableName extends string, TColumns extends Record<string, AnySQLiteColumn>>(tableName: TTableName, columns: TColumns) => Table<TColumns, TTableName>;
257
- type SQLCondition = {
258
- sql: string;
259
- params: any[];
260
- };
261
- type SQLAggregate<T = number> = {
262
- sql: string;
263
- params: any[];
264
- _type?: T;
265
- };
266
- type SQLSubquery = {
267
- sql: string;
268
- params: any[];
269
- _isSubquery: true;
270
- };
271
- declare const asc: (column: AnySQLiteColumn) => {
272
- sql: string;
273
- params: never[];
274
- };
275
- declare const desc: (column: AnySQLiteColumn) => {
276
- sql: string;
277
- params: never[];
278
- };
279
- declare const sql: <T = unknown>(strings: TemplateStringsArray, ...values: any[]) => {
280
- sql: string;
281
- params: any[];
282
- mapWith?: (value: any) => T;
283
- };
316
+ type SQLCondition = Expression<SqlBool>;
317
+ type SQLAggregate<T = number> = Expression<T>;
318
+ type SQLSubquery = Expression<any>;
319
+ declare const asc: (column: AnySQLiteColumn) => Expression<any>;
320
+ declare const desc: (column: AnySQLiteColumn) => Expression<any>;
284
321
  declare class TauriORM {
285
322
  private db;
286
323
  private tables;
287
- constructor(db: Database, schema?: Record<string, AnyTable | Record<string, Relation>> | undefined);
324
+ private kysely;
325
+ constructor(db: DatabaseLike, schema?: Record<string, AnyTable | Record<string, Relation>> | undefined);
288
326
  private buildColumnDefinition;
289
327
  checkMigration(): Promise<{
290
328
  safe: boolean;
@@ -314,10 +352,7 @@ declare class TauriORM {
314
352
  rowsAffected: number;
315
353
  }[] : never>;
316
354
  $with(alias: string): {
317
- as: (query: {
318
- sql: string;
319
- params: any[];
320
- }) => WithQueryBuilder;
355
+ as: (query: SelectQueryBuilder<any, any>) => WithQueryBuilder;
321
356
  };
322
357
  transaction<T>(callback: (tx: TauriORM) => Promise<T>): Promise<T>;
323
358
  rollback(): never;
@@ -348,78 +383,71 @@ declare class OneRelation<T extends AnyTable = AnyTable> extends Relation<T> {
348
383
  config?: {
349
384
  fields: AnySQLiteColumn[];
350
385
  references: AnySQLiteColumn[];
386
+ optional?: boolean;
387
+ alias?: string;
351
388
  } | undefined;
352
389
  constructor(foreignTable: T, config?: {
353
390
  fields: AnySQLiteColumn[];
354
391
  references: AnySQLiteColumn[];
392
+ optional?: boolean;
393
+ alias?: string;
355
394
  } | undefined);
356
395
  }
357
396
  declare class ManyRelation<T extends AnyTable = AnyTable> extends Relation<T> {
358
- constructor(foreignTable: T);
359
- }
360
- declare class ManyToManyRelation<T extends AnyTable = AnyTable> extends Relation<T> {
361
- config: {
362
- junctionTable: AnyTable;
363
- junctionFields: AnySQLiteColumn[];
364
- junctionReferences: AnySQLiteColumn[];
365
- };
366
- constructor(foreignTable: T, config: {
367
- junctionTable: AnyTable;
368
- junctionFields: AnySQLiteColumn[];
369
- junctionReferences: AnySQLiteColumn[];
370
- });
397
+ config?: {
398
+ from?: AnySQLiteColumn[];
399
+ to?: AnySQLiteColumn[];
400
+ through?: {
401
+ junctionTable: AnyTable;
402
+ fromRef: {
403
+ column: AnySQLiteColumn;
404
+ junctionColumn: AnySQLiteColumn;
405
+ };
406
+ toRef: {
407
+ column: AnySQLiteColumn;
408
+ junctionColumn: AnySQLiteColumn;
409
+ };
410
+ };
411
+ optional?: boolean;
412
+ alias?: string;
413
+ where?: (alias: string) => unknown;
414
+ } | undefined;
415
+ constructor(foreignTable: T, config?: {
416
+ from?: AnySQLiteColumn[];
417
+ to?: AnySQLiteColumn[];
418
+ through?: {
419
+ junctionTable: AnyTable;
420
+ fromRef: {
421
+ column: AnySQLiteColumn;
422
+ junctionColumn: AnySQLiteColumn;
423
+ };
424
+ toRef: {
425
+ column: AnySQLiteColumn;
426
+ junctionColumn: AnySQLiteColumn;
427
+ };
428
+ };
429
+ optional?: boolean;
430
+ alias?: string;
431
+ where?: (alias: string) => unknown;
432
+ } | undefined);
371
433
  }
372
434
  declare const relations: <T extends AnyTable, R extends Record<string, Relation>>(table: T, relationsCallback: (helpers: RelationsBuilder) => R) => R;
373
435
  declare const getTableColumns: <T extends AnyTable>(table: T) => Record<string, AnySQLiteColumn>;
374
436
  declare const alias: <T extends AnyTable>(table: T, alias: string) => Table<T["_"]["columns"], T["_"]["name"]>;
375
437
 
376
- declare const eq: <T>(column: AnySQLiteColumn, value: T, tableAlias?: string) => SQLCondition;
377
- declare const ne: <T>(column: AnySQLiteColumn, value: T, tableAlias?: string) => SQLCondition;
378
- declare const and: (...conditions: SQLCondition[]) => SQLCondition;
379
- declare const or: (...conditions: SQLCondition[]) => SQLCondition;
380
- declare const not: (condition: SQLCondition) => SQLCondition;
381
- declare const gt: <T>(column: AnySQLiteColumn, value: T) => SQLCondition;
382
- declare const gte: <T>(column: AnySQLiteColumn, value: T) => SQLCondition;
383
- declare const lt: <T>(column: AnySQLiteColumn, value: T) => SQLCondition;
384
- declare const lte: <T>(column: AnySQLiteColumn, value: T) => SQLCondition;
385
- declare const like: (column: AnySQLiteColumn, pattern: string) => SQLCondition;
386
- declare const ilike: (column: AnySQLiteColumn, pattern: string) => SQLCondition;
387
- declare const startsWith: (column: AnySQLiteColumn, value: string) => SQLCondition;
388
- declare const endsWith: (column: AnySQLiteColumn, value: string) => SQLCondition;
389
- declare const contains: (column: AnySQLiteColumn, value: string) => SQLCondition;
390
- declare const isNull: (column: AnySQLiteColumn) => SQLCondition;
391
- declare const isNotNull: (column: AnySQLiteColumn) => SQLCondition;
392
- declare const exists: (subquery: {
393
- sql: string;
394
- params: any[];
395
- }) => SQLCondition;
396
- declare const notExists: (subquery: {
397
- sql: string;
398
- params: any[];
399
- }) => SQLCondition;
400
- declare const eqSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
401
- declare const neSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
402
- declare const gtSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
403
- declare const gteSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
404
- declare const ltSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
405
- declare const lteSubquery: (column: AnySQLiteColumn, subquery: SQLSubquery) => SQLCondition;
406
- declare const inArray: <T>(column: AnySQLiteColumn, values: T[] | SQLSubquery) => SQLCondition;
407
- declare const notIn: <T>(column: AnySQLiteColumn, values: T[] | SQLSubquery) => SQLCondition;
408
- declare const between: <T>(column: AnySQLiteColumn, min: T, max: T) => SQLCondition;
409
-
410
- declare const count: (column?: AnySQLiteColumn) => SQLAggregate<number>;
411
- declare const countDistinct: (column: AnySQLiteColumn) => SQLAggregate<number>;
412
- declare const sum: (column: AnySQLiteColumn) => SQLAggregate<number>;
413
- declare const avg: (column: AnySQLiteColumn) => SQLAggregate<number>;
414
- declare const max: <T = any>(column: AnySQLiteColumn) => SQLAggregate<T>;
415
- declare const min: <T = any>(column: AnySQLiteColumn) => SQLAggregate<T>;
416
- declare const groupConcat: (column: AnySQLiteColumn, separator?: string) => SQLAggregate<string>;
417
- declare const as: <T>(aggregate: SQLAggregate<T>, alias: string) => SQLAggregate<T> & {
438
+ declare const count: (column?: AnySQLiteColumn) => Expression<number>;
439
+ declare const countDistinct: (column: AnySQLiteColumn) => Expression<number>;
440
+ declare const sum: (column: AnySQLiteColumn) => Expression<number>;
441
+ declare const avg: (column: AnySQLiteColumn) => Expression<number>;
442
+ declare const max: <T = any>(column: AnySQLiteColumn) => Expression<T>;
443
+ declare const min: <T = any>(column: AnySQLiteColumn) => Expression<T>;
444
+ declare const groupConcat: (column: AnySQLiteColumn, separator?: string) => Expression<string>;
445
+ declare const as: <T>(aggregate: Expression<T>, alias: string) => Expression<T> & {
418
446
  alias: string;
419
447
  };
420
448
 
421
- declare const subquery: <T extends AnyTable>(query: SelectQueryBuilder<T, any>) => SQLSubquery;
422
- declare const scalarSubquery: <T extends AnyTable>(query: SelectQueryBuilder<T, any>) => SQLSubquery;
449
+ declare const subquery: <T extends AnyTable>(query: SelectQueryBuilder<T, any>) => Expression<any>;
450
+ declare const scalarSubquery: <T extends AnyTable>(query: SelectQueryBuilder<T, any>) => Expression<any>;
423
451
 
424
452
  declare function text<TName extends string>(name: TName): SQLiteColumn<TName, 'TEXT', 'default', false, false, false, never, never>;
425
453
  declare function text<TName extends string, const TConfig extends {
@@ -442,6 +470,161 @@ declare function numeric<TName extends string, const TConfig extends {
442
470
  }>(name: TName, config: TConfig): SQLiteColumn<TName, 'NUMERIC', TConfig['mode'], false, false, false, never, never>;
443
471
  declare const enumType: <TName extends string, TValues extends readonly [string, ...string[]]>(name: TName, values: TValues) => SQLiteColumn<TName, "TEXT", "default", false, false, false, TValues extends readonly string[] ? TValues : never, never>;
444
472
 
473
+ /** Maps relations() return type to typed relation configs with foreign table preserved */
474
+ type InferRelationsMap<R extends Record<string, OneRelation | ManyRelation>> = {
475
+ [K in keyof R]: R[K] extends OneRelation<infer T> ? R[K] extends {
476
+ config?: {
477
+ optional?: infer O;
478
+ };
479
+ } ? {
480
+ type: 'one';
481
+ foreignTable: T;
482
+ optional: O;
483
+ } : {
484
+ type: 'one';
485
+ foreignTable: T;
486
+ optional?: true;
487
+ } : R[K] extends ManyRelation<infer T> ? {
488
+ type: 'many';
489
+ foreignTable: T;
490
+ } : never;
491
+ };
492
+ /** With/include object shape - matches NestedInclude from select builder */
493
+ type WithShape = boolean | {
494
+ columns?: string[] | Record<string, boolean>;
495
+ with?: Record<string, WithShape>;
496
+ };
497
+ /** Map of table name -> relations() return type, for nested with support */
498
+ type RelationsByTable = Record<string, Record<string, OneRelation | ManyRelation>>;
499
+ /** Get relations for a table from the all-relations map */
500
+ type GetRelationsForTable<TTable extends AnyTable, TAllRelations extends RelationsByTable> = TAllRelations[TTable['_']['name']] extends Record<string, OneRelation | ManyRelation> ? InferRelationsMap<TAllRelations[TTable['_']['name']]> : Record<string, never>;
501
+ /** Infer nested relation fields when TWith has a nested `with` */
502
+ type InferNestedFields<TForeignTable extends AnyTable, TWith extends WithShape, TAllRelations extends RelationsByTable> = TWith extends {
503
+ with?: infer TW;
504
+ } ? TW extends Record<string, WithShape> ? InferRelationFields<TForeignTable, GetRelationsForTable<TForeignTable, TAllRelations>, TAllRelations, TW> : unknown : unknown;
505
+ /** Recursively build relation fields from a with object */
506
+ type InferRelationFields<TTable extends AnyTable, TRelationsMap extends Record<string, {
507
+ type: 'one' | 'many';
508
+ foreignTable: AnyTable;
509
+ }>, TAllRelations extends RelationsByTable, TWith extends Record<string, WithShape>> = {
510
+ [K in keyof TWith & keyof TRelationsMap]: TWith[K] extends false | undefined ? never : TRelationsMap[K] extends {
511
+ type: 'one';
512
+ foreignTable: infer T;
513
+ optional?: infer O;
514
+ } ? T extends AnyTable ? ([O] extends [false] ? InferSelectModel<T> & InferNestedFields<T, TWith[K], TAllRelations> : (InferSelectModel<T> & InferNestedFields<T, TWith[K], TAllRelations>) | null) : never : TRelationsMap[K] extends {
515
+ type: 'many';
516
+ foreignTable: infer T;
517
+ } ? T extends AnyTable ? (InferSelectModel<T> & InferNestedFields<T, TWith[K], TAllRelations>)[] : never : never;
518
+ };
519
+ /**
520
+ * Infer the result type of a select query that includes relations via `.include(with)`.
521
+ *
522
+ * Use this to type variables that hold results from relational queries, e.g.:
523
+ *
524
+ * @example
525
+ * ```ts
526
+ * export type User = InferSelectModel<typeof schema.user>
527
+ *
528
+ * const withRelationalObject = { sessions: true, accounts: true } as const
529
+ * export type UserWithRelations = InferRelationalSelectModel<
530
+ * typeof schema.user,
531
+ * typeof schema.userRelations,
532
+ * typeof withRelationalObject
533
+ * >
534
+ * ```
535
+ *
536
+ * For nested includes, pass a map of table name -> relations as the fourth parameter:
537
+ *
538
+ * @example
539
+ * ```ts
540
+ * const withNested = { sessions: { with: { user: true } } } as const
541
+ * type UserWithSessionsAndUser = InferRelationalSelectModel<
542
+ * typeof schema.user,
543
+ * typeof schema.userRelations,
544
+ * typeof withNested,
545
+ * { user: typeof userRelations; session: typeof sessionRelations }
546
+ * >
547
+ * ```
548
+ *
549
+ * @param TTable - The table type (e.g. typeof schema.user)
550
+ * @param TRelations - The relations for this table (e.g. typeof schema.userRelations)
551
+ * @param TWith - The with/include object shape (use `as const` for literal inference)
552
+ * @param TAllRelations - Optional map of table name -> relations for nested `with` support
553
+ */
554
+ type InferRelationalSelectModel<TTable extends AnyTable, TRelations extends Record<string, OneRelation | ManyRelation>, TWith extends Record<string, WithShape>, TAllRelations extends RelationsByTable = {
555
+ [K in TTable['_']['name']]: TRelations;
556
+ }> = InferSelectModel<TTable> & InferRelationFields<TTable, InferRelationsMap<TRelations>, TAllRelations, TWith>;
557
+
558
+ /**
559
+ * Relations v2 API - Drizzle-style defineRelations with from/to and many-without-one.
560
+ * Use defineRelations() for a single place to define all relations, or defineRelationsPart() to split into parts.
561
+ */
562
+
563
+ /** Options for one() relation - from/to replace fields/references */
564
+ interface OneRelationOptions {
565
+ from: AnySQLiteColumn | AnySQLiteColumn[];
566
+ to: AnySQLiteColumn | AnySQLiteColumn[];
567
+ optional?: boolean;
568
+ alias?: string;
569
+ }
570
+ /** Reference for through() - column with junction column for many-to-many */
571
+ interface ThroughRef {
572
+ column: AnySQLiteColumn;
573
+ junctionColumn: AnySQLiteColumn;
574
+ junctionTable: AnyTable;
575
+ }
576
+ /** Create a through reference for many-to-many: through(column, junctionColumn, junctionTable) */
577
+ declare function through(column: AnySQLiteColumn, junctionColumn: AnySQLiteColumn, junctionTable: AnyTable): ThroughRef;
578
+ /** Options for many() relation - optional explicit from/to for many-without-one, or through() for many-to-many */
579
+ interface ManyRelationOptions {
580
+ from?: AnySQLiteColumn | AnySQLiteColumn[] | ThroughRef;
581
+ to?: AnySQLiteColumn | AnySQLiteColumn[] | ThroughRef;
582
+ optional?: boolean;
583
+ alias?: string;
584
+ /** Predefined filter: (alias) => Condition. Applied to the joined relation table. */
585
+ where?: (alias: string) => Condition;
586
+ }
587
+ /** Build the r object passed to defineRelations callback */
588
+ declare function buildR<Tables extends Record<string, AnyTable>>(tables: Tables): {
589
+ [K in keyof Tables]: Record<string, AnySQLiteColumn>;
590
+ } & {
591
+ one: {
592
+ [K in keyof Tables]: (opts: OneRelationOptions) => OneRelation<Tables[K]>;
593
+ };
594
+ many: {
595
+ [K in keyof Tables]: (opts?: ManyRelationOptions) => ManyRelation<Tables[K]>;
596
+ };
597
+ };
598
+ type DefineRelationsCallback<Tables extends Record<string, AnyTable>> = (r: ReturnType<typeof buildR>) => {
599
+ [K in keyof Tables]?: Record<string, OneRelation | ManyRelation>;
600
+ };
601
+ /**
602
+ * Define all relations for your schema in one place (v2 API).
603
+ * Uses from/to instead of fields/references, and supports many-without-one.
604
+ *
605
+ * @example
606
+ * ```ts
607
+ * import * as schema from './schema'
608
+ * import { defineRelations } from '@type32/tauri-sqlite-orm'
609
+ *
610
+ * export const relations = defineRelations(schema, (r) => ({
611
+ * users: {
612
+ * posts: r.many.posts({ from: r.users.id, to: r.posts.userId }),
613
+ * },
614
+ * posts: {
615
+ * user: r.one.users({ from: r.posts.userId, to: r.users.id }),
616
+ * postTags: r.many.postTags({ from: r.posts.id, to: r.postTags.postId }),
617
+ * },
618
+ * }))
619
+ * ```
620
+ */
621
+ declare function defineRelations<TSchema extends Record<string, unknown>>(schema: TSchema, callback: DefineRelationsCallback<Record<string, AnyTable>>): Record<string, Record<string, OneRelation | ManyRelation>>;
622
+ /**
623
+ * Define a part of relations - merge multiple parts when passing to TauriORM.
624
+ * Useful for splitting large schema definitions.
625
+ */
626
+ declare function defineRelationsPart<TSchema extends Record<string, unknown>>(schema: TSchema, callback: DefineRelationsCallback<Record<string, AnyTable>>): Record<string, Record<string, OneRelation | ManyRelation>>;
627
+
445
628
  declare class TauriORMError extends Error {
446
629
  constructor(message: string);
447
630
  }
@@ -473,4 +656,4 @@ declare class TableNotFoundError extends TauriORMError {
473
656
  constructor(tableName: string);
474
657
  }
475
658
 
476
- export { type AnySQLiteColumn, type AnyTable, BaseQueryBuilder, type ColumnDataType, ColumnNotFoundError, type ColumnOptions, type ColumnValueTypes, DeleteQueryBuilder, type ExtractColumnType, type InferInsertModel, type InferSelectModel, InsertQueryBuilder, InsertValidationError, ManyRelation, ManyToManyRelation, MigrationError, MissingWhereClauseError, type Mode, OneRelation, QueryBuilderError, Relation, type RelationConfig, RelationError, type RelationType, type RelationsBuilder, type SQLAggregate, type SQLCondition, type SQLSubquery, SQLiteColumn, SelectQueryBuilder, Table, TableNotFoundError, TauriORM, TauriORMError, UpdateQueryBuilder, UpdateValidationError, ValidationError, WithQueryBuilder, alias, and, as, asc, avg, between, blob, boolean, contains, count, countDistinct, desc, endsWith, enumType, eq, eqSubquery, exists, getTableColumns, groupConcat, gt, gtSubquery, gte, gteSubquery, ilike, inArray, integer, isNotNull, isNull, like, lt, ltSubquery, lte, lteSubquery, max, min, ne, neSubquery, not, notExists, notIn, numeric, or, real, relations, scalarSubquery, sql, sqliteTable, startsWith, subquery, sum, text };
659
+ export { type AnySQLiteColumn, type AnyTable, type ColumnDataType, ColumnNotFoundError, type ColumnOptions, type ColumnValueTypes, type Condition, type DatabaseLike, type DefineRelationsCallback, DeleteQueryBuilder, type ExtractColumnType, type InferInsertModel, type InferRelationalSelectModel, type InferRelationsMap, type InferSelectModel, InsertQueryBuilder, InsertValidationError, ManyRelation, type ManyRelationOptions, MigrationError, MissingWhereClauseError, type Mode, OneRelation, type OneRelationOptions, QueryBuilderError, Relation, type RelationConfig, RelationError, type RelationType, type RelationsBuilder, type SQLAggregate, type SQLCondition, type SQLSubquery, SQLiteColumn, SelectQueryBuilder, Table, TableNotFoundError, TauriDialect, TauriORM, TauriORMError, type ThroughRef, UpdateQueryBuilder, UpdateValidationError, ValidationError, WithQueryBuilder, alias, and, as, asc, avg, between, blob, boolean, contains, count, countDistinct, defineRelations, defineRelationsPart, desc, endsWith, enumType, eq, eqSubquery, exists, getTableColumns, groupConcat, gt, gtSubquery, gte, gteSubquery, ilike, inArray, integer, isNotNull, isNull, like, lt, ltSubquery, lte, lteSubquery, max, min, ne, neSubquery, not, notExists, notIn, numeric, or, real, relations, scalarSubquery, sqliteTable, startsWith, subquery, sum, text, through };