-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathindex.ts
More file actions
119 lines (107 loc) · 2.69 KB
/
Copy pathindex.ts
File metadata and controls
119 lines (107 loc) · 2.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import type { ConnectionType } from '@conar/shared/enums/connection-type'
import type { connections } from '~/drizzle'
import { Store } from '@tanstack/react-store'
import { formatSql } from '~/lib/formatter'
export * from './constraints'
export * from './delete-rows'
export * from './drop-table'
export * from './enums'
export * from './indexes'
export * from './rename-table'
export * from './rows'
export * from './select'
export * from './set'
export * from './tables-and-schemas'
export * from './total'
export function executeSql({
type,
connectionString,
sql,
values = [],
}: {
type: ConnectionType
connectionString: string
sql: string
values?: unknown[]
}) {
if (!window.electron) {
throw new Error('Electron is not available')
}
return window.electron.query[type]({ connectionString, sql, values })
}
export function executeAndLogSql({ connection, sql, values = [] }: {
connection: typeof connections.$inferSelect
sql: string
values?: unknown[]
}) {
const promise = executeSql({ type: connection.type, connectionString: connection.connectionString, sql, values })
logSql(connection, promise, { sql, values })
return promise
}
export interface SqlLog {
id: string
sql: string
createdAt: Date
result: unknown | null
duration: number | null
values: unknown[]
error: string | null
}
export const sqlLogsStore = new Store<Record<string, Record<string, SqlLog>>>({})
export async function logSql(
connection: typeof connections.$inferSelect,
promise: Promise<{ result: unknown, duration: number }>,
{
sql,
values = [],
}: {
sql: string
values?: unknown[]
},
) {
const id = crypto.randomUUID()
sqlLogsStore.setState(state => ({
...state,
[connection.id]: {
...(state[connection.id] || {}),
[id]: {
id,
createdAt: new Date(),
sql: formatSql(sql, connection.type)
.split('\n')
.filter(str => !str.startsWith('--'))
.join(' '),
values,
result: null,
duration: null,
error: null,
},
},
} satisfies typeof state))
try {
const { result, duration } = await promise
sqlLogsStore.setState(state => ({
...state,
[connection.id]: {
...state[connection.id],
[id]: {
...state[connection.id]![id]!,
result,
duration,
},
},
} satisfies typeof state))
}
catch (error) {
sqlLogsStore.setState(state => ({
...state,
[connection.id]: {
...state[connection.id],
[id]: {
...state[connection.id]![id]!,
error: error instanceof Error ? error.message : String(error),
},
},
} satisfies typeof state))
}
}