-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathhelpers.ts
209 lines (188 loc) · 6.28 KB
/
helpers.ts
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
import { readFile } from 'node:fs/promises'
import { createStorage } from 'unstorage'
import fsDriver from 'unstorage/drivers/fs'
import overlayDriver from 'unstorage/drivers/overlay'
import { join } from 'pathe'
import type { HubConfig } from '../../../../../features'
// #region Migrations
export function useDatabaseMigrationsStorage(hub: HubConfig) {
// .data/hub/database/migrations
return createStorage({
driver: fsDriver({
base: join(hub.dir!, 'database/migrations')
})
})
}
export async function getDatabaseMigrationFiles(hub: HubConfig) {
const fileKeys = await useDatabaseMigrationsStorage(hub).getKeys()
return fileKeys.filter(file => file.endsWith('.sql'))
}
export async function copyDatabaseMigrationsToHubDir(hub: HubConfig) {
const srcStorage = createStorage({
driver: overlayDriver({
layers: hub.databaseMigrationsDirs!.map(dir => fsDriver({
base: dir,
ignore: ['.DS_Store']
}))
})
})
const destStorage = useDatabaseMigrationsStorage(hub)
await destStorage.clear()
const migrationFiles = (await srcStorage.getKeys()).filter(file => file.endsWith('.sql'))
await Promise.all(migrationFiles.map(async (file) => {
const sql = await srcStorage.getItem(file)
await destStorage.setItem(file, sql)
}))
}
export const CreateDatabaseMigrationsTableQuery = `CREATE TABLE IF NOT EXISTS _hub_migrations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT UNIQUE,
applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);`
export const AppliedDatabaseMigrationsQuery = 'select "id", "name", "applied_at" from "_hub_migrations" order by "_hub_migrations"."id"'
// #endregion
// #region Queries
export function useDatabaseQueriesStorage(hub: HubConfig) {
// .data/hub/database/migrations
return createStorage({
driver: fsDriver({
base: join(hub.dir!, 'database/queries')
})
})
}
export async function getDatabaseQueryFiles(hub: HubConfig) {
const fileKeys = await useDatabaseQueriesStorage(hub).getKeys()
return fileKeys.filter(file => file.endsWith('.sql'))
}
export async function copyDatabaseQueriesToHubDir(hub: HubConfig) {
const destStorage = useDatabaseQueriesStorage(hub)
await destStorage.clear()
await Promise.all(hub.databaseQueriesPaths!.map(async (path) => {
try {
const filename = path.split('/').pop()!
const sql = await readFile(path, 'utf-8')
await destStorage.setItem(filename, sql)
} catch (error: any) {
console.error(`Failed to read database query file ${path}: ${error.message}`)
}
}))
}
// #endregion
// #region Utils
/**
* Split a string containing SQL queries into an array of individual queries after removing comments
*/
export function splitSqlQueries(sqlFileContent: string): string[] {
const queries: string[] = []
let inString = false
let stringFence = ''
let result = ''
let currentGeneralWord = ''
let previousGeneralWord = ''
let inTrigger = false
let currentTriggerWord = ''
let triggerBlockNestingLevel = 0
for (let i = 0; i < sqlFileContent.length; i += 1) {
const char = sqlFileContent[i]
const nextChar = sqlFileContent[i + 1]
// Handle string literals
if ((char === '\'' || char === '"') && (i === 0 || sqlFileContent[i - 1] !== '\\')) {
if (!inString) {
inString = true
stringFence = char
} else if (char === stringFence) {
inString = false
}
}
// Only remove comments when not inside a string
if (!inString) {
// Handle -- comments
if (char === '-' && nextChar === '-') {
while (i < sqlFileContent.length && sqlFileContent[i] !== '\n') {
i += 1
}
continue
}
// Handle /* */ comments
if (char === '/' && nextChar === '*') {
i += 2
while (i < sqlFileContent.length && !(sqlFileContent[i] === '*' && sqlFileContent[i + 1] === '/')) {
i += 1
}
i += 2
continue
}
// Track general keywords for CREATE TRIGGER detection
if (/\w/.test(char)) {
currentGeneralWord += char.toLowerCase()
} else {
// Check if previous word was 'create' and current is 'trigger'
if (previousGeneralWord === 'create' && currentGeneralWord === 'trigger') {
inTrigger = true
}
previousGeneralWord = currentGeneralWord
currentGeneralWord = ''
}
// If in trigger, track BEGIN/END
if (inTrigger) {
if (/\w/.test(char)) {
currentTriggerWord += char.toLowerCase()
} else {
if (currentTriggerWord === 'begin') {
triggerBlockNestingLevel++
} else if (currentTriggerWord === 'end') {
triggerBlockNestingLevel = Math.max(triggerBlockNestingLevel - 1, 0)
}
currentTriggerWord = ''
}
}
// Handle semicolon
if (char === ';' && sqlFileContent[i - 1] !== '\\') {
if (inTrigger) {
if (triggerBlockNestingLevel === 0) {
// End of trigger, split here
result += char
const trimmedResult = result.trim()
if (trimmedResult !== '') {
queries.push(trimmedResult)
}
result = ''
inTrigger = false
triggerBlockNestingLevel = 0
continue
} else {
// Inside trigger, do not split
result += char
}
} else {
// Not in trigger, split as usual
result += char
const trimmedResult = result.trim()
if (trimmedResult !== '') {
queries.push(trimmedResult)
}
result = ''
continue
}
}
}
result += char
}
// Add any remaining content as a query
const finalTrimmed = result.trim()
if (finalTrimmed !== '') {
queries.push(finalTrimmed)
}
// Process each query to ensure it ends with a single semicolon and filter out empty/semicolon-only
return queries
.map((query) => {
// Handle semicolons in trigger bodies
if (query.includes('TRIGGER') && query.includes('BEGIN')) {
// First, handle the statements inside the trigger
query = query.replace(/;+(?=\s+(?:END|\S|$))/g, ';')
}
return query.replace(/;+$/, ';')
})
.filter(query => query !== ';' && query.trim() !== '')
}
// #endregion