|
| 1 | +import { NITRO_SQLITE_NULL } from '..' |
1 | 2 | import { HybridNitroSQLite } from '../nitro' |
2 | 3 | import type { NativeQueryResult } from '../specs/NativeQueryResult.nitro' |
3 | | -import type { QueryResult, SQLiteItem, SQLiteQueryParams } from '../types' |
| 4 | +import type { |
| 5 | + QueryResult, |
| 6 | + NativeSQLiteQueryParams, |
| 7 | + SQLiteQueryParams, |
| 8 | + QueryResultRow, |
| 9 | +} from '../types' |
4 | 10 |
|
5 | | -export function execute<Data extends SQLiteItem = never>( |
| 11 | +export function execute<Data extends QueryResultRow = never>( |
6 | 12 | dbName: string, |
7 | 13 | query: string, |
8 | 14 | params?: SQLiteQueryParams |
9 | 15 | ): QueryResult<Data> { |
10 | | - const nativeResult = HybridNitroSQLite.execute(dbName, query, params) |
| 16 | + const nativeResult = HybridNitroSQLite.execute( |
| 17 | + dbName, |
| 18 | + query, |
| 19 | + toNativeQueryParams(params) |
| 20 | + ) |
11 | 21 | const result = buildJsQueryResult<Data>(nativeResult) |
12 | 22 | return result |
13 | 23 | } |
14 | 24 |
|
15 | | -export async function executeAsync<Data extends SQLiteItem = never>( |
| 25 | +export async function executeAsync<Data extends QueryResultRow = never>( |
16 | 26 | dbName: string, |
17 | 27 | query: string, |
18 | 28 | params?: SQLiteQueryParams |
19 | 29 | ): Promise<QueryResult<Data>> { |
20 | 30 | const nativeResult = await HybridNitroSQLite.executeAsync( |
21 | 31 | dbName, |
22 | 32 | query, |
23 | | - params |
| 33 | + toNativeQueryParams(params) |
24 | 34 | ) |
25 | 35 | const result = buildJsQueryResult<Data>(nativeResult) |
26 | 36 | return result |
27 | 37 | } |
28 | 38 |
|
29 | | -function buildJsQueryResult<Data extends SQLiteItem = never>({ |
| 39 | +function toNativeQueryParams( |
| 40 | + params: SQLiteQueryParams | undefined |
| 41 | +): NativeSQLiteQueryParams | undefined { |
| 42 | + return params?.map((param) => { |
| 43 | + if (param === undefined || param === null) { |
| 44 | + return NITRO_SQLITE_NULL |
| 45 | + } |
| 46 | + return param |
| 47 | + }) |
| 48 | +} |
| 49 | + |
| 50 | +function buildJsQueryResult<Data extends QueryResultRow = never>({ |
30 | 51 | insertId, |
31 | 52 | rowsAffected, |
32 | 53 | results, |
33 | 54 | }: NativeQueryResult): QueryResult<Data> { |
34 | | - const data = results as Data[] |
| 55 | + const data = results.map((row) => |
| 56 | + Object.fromEntries( |
| 57 | + Object.entries(row).map(([key, value]) => { |
| 58 | + if (value === NITRO_SQLITE_NULL) { |
| 59 | + return [key, undefined] |
| 60 | + } |
| 61 | + return [key, value] |
| 62 | + }) |
| 63 | + ) |
| 64 | + ) as Data[] |
35 | 65 |
|
36 | 66 | return { |
37 | 67 | insertId, |
|
0 commit comments