@type32/tauri-sqlite-orm 0.3.0 → 0.4.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.
Files changed (41) hide show
  1. package/dist/aggregates.d.ts +12 -0
  2. package/dist/aggregates.js +9 -0
  3. package/dist/builders/delete.d.ts +23 -0
  4. package/dist/builders/delete.js +73 -0
  5. package/dist/builders/index.d.ts +7 -0
  6. package/dist/builders/index.js +7 -0
  7. package/dist/builders/insert.d.ts +31 -0
  8. package/dist/builders/insert.js +141 -0
  9. package/dist/builders/query-base.d.ts +1 -0
  10. package/dist/builders/query-base.js +1 -0
  11. package/dist/builders/relations.d.ts +11 -0
  12. package/dist/builders/relations.js +1 -0
  13. package/dist/builders/select.d.ts +54 -0
  14. package/dist/builders/select.js +427 -0
  15. package/dist/builders/update.d.ts +30 -0
  16. package/dist/builders/update.js +124 -0
  17. package/dist/builders/with.d.ts +17 -0
  18. package/dist/builders/with.js +34 -0
  19. package/dist/column-helpers.d.ts +22 -0
  20. package/dist/column-helpers.js +17 -0
  21. package/dist/dialect.d.ts +21 -0
  22. package/dist/dialect.js +67 -0
  23. package/dist/errors.d.ts +30 -0
  24. package/dist/errors.js +66 -0
  25. package/dist/index.d.mts +11 -6
  26. package/dist/index.d.ts +11 -6
  27. package/dist/operators.d.ts +30 -0
  28. package/dist/operators.js +84 -0
  29. package/dist/orm.d.ts +180 -0
  30. package/dist/orm.js +556 -0
  31. package/dist/relational-types.d.ts +87 -0
  32. package/dist/relational-types.js +1 -0
  33. package/dist/relations-v2.d.ts +77 -0
  34. package/dist/relations-v2.js +157 -0
  35. package/dist/serialization.d.ts +14 -0
  36. package/dist/serialization.js +135 -0
  37. package/dist/subquery.d.ts +5 -0
  38. package/dist/subquery.js +6 -0
  39. package/dist/types.d.ts +58 -0
  40. package/dist/types.js +1 -0
  41. package/package.json +2 -1
@@ -0,0 +1,12 @@
1
+ import { Expression } from 'kysely';
2
+ import { AnySQLiteColumn } from './types';
3
+ export declare const count: (column?: AnySQLiteColumn) => Expression<number>;
4
+ export declare const countDistinct: (column: AnySQLiteColumn) => Expression<number>;
5
+ export declare const sum: (column: AnySQLiteColumn) => Expression<number>;
6
+ export declare const avg: (column: AnySQLiteColumn) => Expression<number>;
7
+ export declare const max: <T = any>(column: AnySQLiteColumn) => Expression<T>;
8
+ export declare const min: <T = any>(column: AnySQLiteColumn) => Expression<T>;
9
+ export declare const groupConcat: (column: AnySQLiteColumn, separator?: string) => Expression<string>;
10
+ export declare const as: <T>(aggregate: Expression<T>, alias: string) => Expression<T> & {
11
+ alias: string;
12
+ };
@@ -0,0 +1,9 @@
1
+ import { sql } from 'kysely';
2
+ export const count = (column) => sql `COUNT(${column ? sql.ref(column._.name) : sql.raw('*')})`;
3
+ export const countDistinct = (column) => sql `COUNT(DISTINCT ${sql.ref(column._.name)})`;
4
+ export const sum = (column) => sql `SUM(${sql.ref(column._.name)})`;
5
+ export const avg = (column) => sql `AVG(${sql.ref(column._.name)})`;
6
+ export const max = (column) => sql `MAX(${sql.ref(column._.name)})`;
7
+ export const min = (column) => sql `MIN(${sql.ref(column._.name)})`;
8
+ export const groupConcat = (column, separator = ',') => sql `GROUP_CONCAT(${sql.ref(column._.name)}, ${sql.val(separator)})`;
9
+ export const as = (aggregate, alias) => Object.assign(aggregate, { alias });
@@ -0,0 +1,23 @@
1
+ import { Kysely } from 'kysely';
2
+ import { AnyTable, InferSelectModel } from '../types';
3
+ import { Condition } from '../operators';
4
+ export declare class DeleteQueryBuilder<T extends AnyTable> {
5
+ private readonly kysely;
6
+ private _builder;
7
+ private _table;
8
+ private _returningColumns;
9
+ private _hasWhereClause;
10
+ private _allowGlobal;
11
+ constructor(kysely: Kysely<any>, table: T);
12
+ private mapReturningRows;
13
+ where(condition: Condition): this;
14
+ allowGlobalOperation(): this;
15
+ returning(...columns: (keyof T['_']['columns'])[]): this;
16
+ execute(): Promise<T extends AnyTable ? (InferSelectModel<T> & Record<string, any>)[] : never>;
17
+ returningAll(): Promise<InferSelectModel<T>[]>;
18
+ returningFirst(): Promise<InferSelectModel<T> | undefined>;
19
+ toSQL(): {
20
+ sql: string;
21
+ params: any[];
22
+ };
23
+ }
@@ -0,0 +1,73 @@
1
+ import { MissingWhereClauseError } from '../errors';
2
+ import { deserializeValue } from '../serialization';
3
+ export class DeleteQueryBuilder {
4
+ kysely;
5
+ _builder;
6
+ _table;
7
+ _returningColumns = [];
8
+ _hasWhereClause = false;
9
+ _allowGlobal = false;
10
+ constructor(kysely, table) {
11
+ this.kysely = kysely;
12
+ this._table = table;
13
+ this._builder = kysely.deleteFrom(table._.name);
14
+ }
15
+ mapReturningRows(rows) {
16
+ const dbNameToTs = {};
17
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
18
+ dbNameToTs[col._.name] = tsName;
19
+ }
20
+ const norm = (k) => (k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k);
21
+ return rows.map((row) => {
22
+ const out = {};
23
+ for (const [dbKey, value] of Object.entries(row)) {
24
+ const logicalKey = norm(dbKey);
25
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
26
+ const column = this._table._.columns[tsName];
27
+ out[tsName] = column ? deserializeValue(value, column) : value;
28
+ }
29
+ return out;
30
+ });
31
+ }
32
+ where(condition) {
33
+ this._hasWhereClause = true;
34
+ this._builder = this._builder.where(condition);
35
+ return this;
36
+ }
37
+ allowGlobalOperation() {
38
+ this._allowGlobal = true;
39
+ return this;
40
+ }
41
+ returning(...columns) {
42
+ this._returningColumns.push(...columns);
43
+ return this;
44
+ }
45
+ async execute() {
46
+ if (!this._hasWhereClause && !this._allowGlobal) {
47
+ throw new MissingWhereClauseError('DELETE', this._table._.name);
48
+ }
49
+ if (this._returningColumns.length > 0) {
50
+ const cols = this._returningColumns.map((k) => this._table._.columns[k]._.name);
51
+ const rows = await this._builder.returning(cols).execute();
52
+ return this.mapReturningRows(rows);
53
+ }
54
+ const result = await this._builder.executeTakeFirst();
55
+ return [{ rowsAffected: Number(result?.numDeletedRows ?? 0) }];
56
+ }
57
+ async returningAll() {
58
+ const allCols = Object.keys(this._table._.columns);
59
+ return this.returning(...allCols).execute();
60
+ }
61
+ async returningFirst() {
62
+ const results = await this.returningAll();
63
+ return results[0];
64
+ }
65
+ toSQL() {
66
+ let builder = this._builder;
67
+ if (this._returningColumns.length > 0) {
68
+ builder = builder.returning(this._returningColumns.map((k) => this._table._.columns[k]._.name));
69
+ }
70
+ const compiled = builder.compile();
71
+ return { sql: compiled.sql, params: [...compiled.parameters] };
72
+ }
73
+ }
@@ -0,0 +1,7 @@
1
+ export * from './query-base';
2
+ export * from './select';
3
+ export * from './update';
4
+ export * from './insert';
5
+ export * from './delete';
6
+ export * from './with';
7
+ export * from './relations';
@@ -0,0 +1,7 @@
1
+ export * from './query-base';
2
+ export * from './select';
3
+ export * from './update';
4
+ export * from './insert';
5
+ export * from './delete';
6
+ export * from './with';
7
+ export * from './relations';
@@ -0,0 +1,31 @@
1
+ import { Kysely } from 'kysely';
2
+ import { InferInsertModel } from '../orm';
3
+ import { AnySQLiteColumn, AnyTable, InferSelectModel } from '../types';
4
+ export declare class InsertQueryBuilder<T extends AnyTable> {
5
+ private readonly kysely;
6
+ private _builder;
7
+ private _table;
8
+ private _dataSets;
9
+ private _returningColumns;
10
+ private _onConflictAction;
11
+ private _conflictTarget;
12
+ private _updateSet;
13
+ constructor(kysely: Kysely<any>, table: T);
14
+ values(data: InferInsertModel<T> | InferInsertModel<T>[]): this;
15
+ returning(...columns: (keyof T['_']['columns'])[]): this;
16
+ onConflictDoNothing(target?: AnySQLiteColumn | AnySQLiteColumn[]): this;
17
+ onConflictDoUpdate(config: {
18
+ target: AnySQLiteColumn | AnySQLiteColumn[];
19
+ set: Partial<InferInsertModel<T>>;
20
+ }): this;
21
+ private processDefaults;
22
+ private mapReturningRows;
23
+ private serializeDataSet;
24
+ execute(): Promise<T extends AnyTable ? (InferSelectModel<T> & Record<string, any>)[] : never>;
25
+ returningAll(): Promise<InferSelectModel<T>[]>;
26
+ returningFirst(): Promise<InferSelectModel<T> | undefined>;
27
+ toSQL(): {
28
+ sql: string;
29
+ params: any[];
30
+ };
31
+ }
@@ -0,0 +1,141 @@
1
+ import { InsertValidationError } from '../errors';
2
+ import { serializeValue, deserializeValue } from '../serialization';
3
+ export class InsertQueryBuilder {
4
+ kysely;
5
+ _builder;
6
+ _table;
7
+ _dataSets = [];
8
+ _returningColumns = [];
9
+ _onConflictAction = null;
10
+ _conflictTarget = [];
11
+ _updateSet = {};
12
+ constructor(kysely, table) {
13
+ this.kysely = kysely;
14
+ this._table = table;
15
+ this._builder = kysely.insertInto(table._.name);
16
+ }
17
+ values(data) {
18
+ const arr = Array.isArray(data) ? data : [data];
19
+ this._dataSets.push(...arr);
20
+ return this;
21
+ }
22
+ returning(...columns) {
23
+ this._returningColumns.push(...columns);
24
+ return this;
25
+ }
26
+ onConflictDoNothing(target) {
27
+ this._onConflictAction = 'nothing';
28
+ if (target) {
29
+ this._conflictTarget = Array.isArray(target) ? target : [target];
30
+ }
31
+ return this;
32
+ }
33
+ onConflictDoUpdate(config) {
34
+ this._onConflictAction = 'update';
35
+ this._conflictTarget = Array.isArray(config.target) ? config.target : [config.target];
36
+ this._updateSet = config.set;
37
+ return this;
38
+ }
39
+ processDefaults(data) {
40
+ const out = { ...data };
41
+ for (const [key, column] of Object.entries(this._table._.columns)) {
42
+ if (out[key] === undefined && column.options.$defaultFn) {
43
+ ;
44
+ out[key] = column.options.$defaultFn();
45
+ }
46
+ }
47
+ return out;
48
+ }
49
+ mapReturningRows(rows) {
50
+ const dbNameToTs = {};
51
+ for (const [tsName, col] of Object.entries(this._table._.columns)) {
52
+ dbNameToTs[col._.name] = tsName;
53
+ }
54
+ const norm = (k) => (k.startsWith('"') && k.endsWith('"') ? k.slice(1, -1) : k);
55
+ return rows.map((row) => {
56
+ const out = {};
57
+ for (const [dbKey, value] of Object.entries(row)) {
58
+ const logicalKey = norm(dbKey);
59
+ const tsName = dbNameToTs[logicalKey] ?? logicalKey;
60
+ const column = this._table._.columns[tsName];
61
+ out[tsName] = column ? deserializeValue(value, column) : value;
62
+ }
63
+ return out;
64
+ });
65
+ }
66
+ serializeDataSet(data) {
67
+ const out = {};
68
+ for (const [key, value] of Object.entries(data)) {
69
+ const column = this._table._.columns[key];
70
+ out[column ? column._.name : key] = column ? serializeValue(value, column) : value;
71
+ }
72
+ return out;
73
+ }
74
+ async execute() {
75
+ if (this._dataSets.length === 0) {
76
+ throw new InsertValidationError('No data provided for insert. Use .values() to provide data.');
77
+ }
78
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
79
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
80
+ if (this._onConflictAction === 'nothing') {
81
+ if (this._conflictTarget.length > 0) {
82
+ const targetCols = this._conflictTarget.map((c) => c._.name);
83
+ builder = builder.onConflict((oc) => oc.columns(targetCols).doNothing());
84
+ }
85
+ else {
86
+ builder = builder.onConflict((oc) => oc.doNothing());
87
+ }
88
+ }
89
+ else if (this._onConflictAction === 'update') {
90
+ const targetCols = this._conflictTarget.map((c) => c._.name);
91
+ const updateData = this.serializeDataSet(this._updateSet);
92
+ builder = builder.onConflict((oc) => oc.columns(targetCols).doUpdateSet(updateData));
93
+ }
94
+ if (this._returningColumns.length > 0) {
95
+ const cols = this._returningColumns.map((k) => this._table._.columns[k]._.name);
96
+ const rows = await builder.returning(cols).execute();
97
+ return this.mapReturningRows(rows);
98
+ }
99
+ const result = await builder.executeTakeFirst();
100
+ return [
101
+ {
102
+ lastInsertId: Number(result?.insertId ?? 0),
103
+ rowsAffected: Number(result?.numInsertedOrUpdatedRows ?? 0),
104
+ },
105
+ ];
106
+ }
107
+ async returningAll() {
108
+ const allCols = Object.keys(this._table._.columns);
109
+ return this.returning(...allCols).execute();
110
+ }
111
+ async returningFirst() {
112
+ const results = await this.returningAll();
113
+ return results[0];
114
+ }
115
+ toSQL() {
116
+ if (this._dataSets.length === 0) {
117
+ throw new InsertValidationError('No data provided for insert. Use .values() to provide data.');
118
+ }
119
+ const processed = this._dataSets.map((d) => this.serializeDataSet(this.processDefaults(d)));
120
+ let builder = this._builder.values(processed.length === 1 ? processed[0] : processed);
121
+ if (this._onConflictAction === 'nothing') {
122
+ if (this._conflictTarget.length > 0) {
123
+ builder = builder.onConflict((oc) => oc.columns(this._conflictTarget.map((c) => c._.name)).doNothing());
124
+ }
125
+ else {
126
+ builder = builder.onConflict((oc) => oc.doNothing());
127
+ }
128
+ }
129
+ else if (this._onConflictAction === 'update') {
130
+ const updateData = this.serializeDataSet(this._updateSet);
131
+ builder = builder.onConflict((oc) => oc
132
+ .columns(this._conflictTarget.map((c) => c._.name))
133
+ .doUpdateSet(updateData));
134
+ }
135
+ if (this._returningColumns.length > 0) {
136
+ builder = builder.returning(this._returningColumns.map((k) => this._table._.columns[k]._.name));
137
+ }
138
+ const compiled = builder.compile();
139
+ return { sql: compiled.sql, params: [...compiled.parameters] };
140
+ }
141
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,11 @@
1
+ import { ManyRelation, OneRelation } from '../orm';
2
+ import { AnySQLiteColumn, AnyTable } from '../types';
3
+ export type RelationsBuilder = {
4
+ one: <U extends AnyTable>(table: U, config?: {
5
+ fields: AnySQLiteColumn[];
6
+ references: AnySQLiteColumn[];
7
+ optional?: boolean;
8
+ alias?: string;
9
+ }) => OneRelation<U>;
10
+ many: <U extends AnyTable>(table: U) => ManyRelation<U>;
11
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,54 @@
1
+ import { Expression, Kysely, SqlBool } from 'kysely';
2
+ import { Condition } from '../operators';
3
+ import { AnySQLiteColumn, AnyTable, InferSelectModel } from '../types';
4
+ type NestedInclude = boolean | {
5
+ columns?: string[] | Record<string, boolean>;
6
+ with?: Record<string, NestedInclude>;
7
+ };
8
+ type ExtractRelationNames<T extends AnyTable> = T['relations'] extends Record<string, any> ? keyof T['relations'] & string : never;
9
+ type IncludeRelations<T extends AnyTable> = T['relations'] extends Record<string, any> ? Partial<Record<ExtractRelationNames<T>, NestedInclude>> : Record<string, never>;
10
+ export declare class SelectQueryBuilder<TTable extends AnyTable, TSelectedColumns extends (keyof TTable['_']['columns'])[] | undefined = undefined> {
11
+ private readonly kysely;
12
+ private _builder;
13
+ private _table;
14
+ private _columns?;
15
+ private _includeRelations;
16
+ private _manualJoins;
17
+ private _isDistinct;
18
+ private _includedColumnAliases;
19
+ constructor(kysely: Kysely<any>, table: TTable, columns?: TSelectedColumns);
20
+ distinct(): this;
21
+ where(condition: Condition): this;
22
+ orderBy(column: AnySQLiteColumn | Expression<any>, direction?: 'asc' | 'desc'): this;
23
+ limit(count: number): this;
24
+ offset(count: number): this;
25
+ groupBy(...columns: AnySQLiteColumn[]): this;
26
+ having(condition: Condition): this;
27
+ leftJoin<T extends AnyTable>(table: T, condition: Expression<SqlBool>, alias: string): this;
28
+ innerJoin<T extends AnyTable>(table: T, condition: Expression<SqlBool>, alias: string): this;
29
+ include(relations: IncludeRelations<TTable>): this;
30
+ private applyIncludes;
31
+ execute(): Promise<InferSelectModel<TTable>[]>;
32
+ private processRelationResults;
33
+ all(): Promise<InferSelectModel<TTable>[]>;
34
+ get(): Promise<InferSelectModel<TTable> | undefined>;
35
+ first(): Promise<InferSelectModel<TTable> | undefined>;
36
+ exists(): Promise<boolean>;
37
+ count(): Promise<number>;
38
+ pluck<K extends keyof TTable['_']['columns']>(column: K): Promise<InferSelectModel<TTable>[K][]>;
39
+ paginate(page?: number, pageSize?: number): Promise<{
40
+ data: InferSelectModel<TTable>[];
41
+ total: number;
42
+ page: number;
43
+ pageSize: number;
44
+ totalPages: number;
45
+ hasNextPage: boolean;
46
+ hasPrevPage: boolean;
47
+ }>;
48
+ toSQL(): {
49
+ sql: string;
50
+ params: any[];
51
+ };
52
+ toKyselyExpression(): Expression<any>;
53
+ }
54
+ export {};