-
-
Notifications
You must be signed in to change notification settings - Fork 749
Expand file tree
/
Copy pathdatabase.ts
More file actions
202 lines (173 loc) · 7.38 KB
/
database.ts
File metadata and controls
202 lines (173 loc) · 7.38 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
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
import { mkdir } from 'node:fs/promises'
import type { Connector } from 'db0'
import type { Resolver } from '@nuxt/kit'
import cloudflareD1Connector from 'db0/connectors/cloudflare-d1'
import { isAbsolute, join, dirname } from 'pathe'
import { isWebContainer } from '@webcontainer/env'
import type { CacheEntry, D1DatabaseConfig, LocalDevelopmentDatabase, ResolvedCollection, SqliteDatabaseConfig } from '../types'
import type { ModuleOptions, SQLiteConnector } from '../types/module'
import { generateCollectionInsert, generateCollectionTableDefinition } from './collection'
import { isNodeSqliteAvailable, ensurePackageInstalled } from './dependencies'
/**
* Database version is used to identify schema changes
* and drop the info table when the version is not supported
*/
export const databaseVersion = 'v3.5.0'
export async function refineDatabaseConfig(database: ModuleOptions['database'], opts: { rootDir: string, updateSqliteFileName?: boolean }) {
if (database.type === 'd1') {
if (!('bindingName' in database)) {
// @ts-expect-error bindingName
database.bindingName = database.binding
}
}
if (database.type === 'sqlite') {
const path = isAbsolute(database.filename)
? database.filename
: join(opts.rootDir, database.filename)
await mkdir(dirname(path), { recursive: true }).catch(() => {})
if (opts.updateSqliteFileName) {
database.filename = path
}
}
}
export async function resolveDatabaseAdapter(adapter: 'sqlite' | 'bunsqlite' | 'postgres' | 'postgresql' | 'libsql' | 'd1' | 'nodesqlite' | 'pglite', opts: { resolver: Resolver, sqliteConnector?: SQLiteConnector }) {
const databaseConnectors = {
nodesqlite: 'db0/connectors/node-sqlite',
bunsqlite: opts.resolver.resolve('./runtime/internal/connectors/bun-sqlite'),
postgres: 'db0/connectors/postgresql', // legacy
postgresql: 'db0/connectors/postgresql',
libsql: 'db0/connectors/libsql/node',
d1: 'db0/connectors/cloudflare-d1',
pglite: 'db0/connectors/pglite',
}
adapter = adapter || 'sqlite'
if (adapter === 'sqlite') {
return await findBestSqliteAdapter({ sqliteConnector: opts.sqliteConnector, resolver: opts.resolver })
}
return databaseConnectors[adapter]
}
async function getDatabase(database: SqliteDatabaseConfig | D1DatabaseConfig, opts: { sqliteConnector?: SQLiteConnector }): Promise<Connector> {
if (database.type === 'd1') {
return cloudflareD1Connector({ bindingName: database.bindingName })
}
return import(await findBestSqliteAdapter(opts))
.then((m) => {
const connector = (m.default || m) as (config: unknown) => Connector
return connector({ path: database.filename })
})
}
const _localDatabase: Record<string, Connector> = {}
export async function getLocalDatabase(database: SqliteDatabaseConfig | D1DatabaseConfig, { connector, sqliteConnector }: { connector?: Connector, nativeSqlite?: boolean, sqliteConnector?: SQLiteConnector } = {}): Promise<LocalDevelopmentDatabase> {
const databaseLocation = database.type === 'sqlite' ? database.filename : database.bindingName
const db = _localDatabase[databaseLocation] || connector || await getDatabase(database, { sqliteConnector })
const cacheCollection = {
tableName: '_development_cache',
extendedSchema: {
$schema: 'http://json-schema.org/draft-07/schema#',
$ref: '#/definitions/cache',
definitions: {
cache: {
type: 'object',
properties: {
id: { type: 'string' },
value: { type: 'string' },
checksum: { type: 'string' },
},
required: ['id', 'value', 'checksum'],
},
},
},
fields: {
id: 'string',
value: 'string',
checksum: 'string',
},
} as unknown as ResolvedCollection
// If the database is already initialized, we need to drop the cache table
if (!_localDatabase[databaseLocation]) {
_localDatabase[databaseLocation] = db
let dropCacheTable = false
try {
dropCacheTable = await db.prepare('SELECT * FROM _development_cache WHERE id = ?')
.get('__DATABASE_VERSION__').then(row => (row as unknown as { value: string })?.value !== databaseVersion)
}
catch {
dropCacheTable = true
}
const initQueries = generateCollectionTableDefinition(cacheCollection, { drop: Boolean(dropCacheTable) })
for (const query of initQueries.split('\n')) {
await db.exec(query)
}
// Initialize the database version
if (dropCacheTable) {
await db.exec(generateCollectionInsert(cacheCollection, { id: '__DATABASE_VERSION__', value: databaseVersion, checksum: databaseVersion }).queries[0]!)
}
}
const fetchDevelopmentCache = async () => {
const result = await db.prepare('SELECT * FROM _development_cache').all() as CacheEntry[]
return result.reduce((acc, cur) => ({ ...acc, [cur.id]: cur }), {} as Record<string, CacheEntry>)
}
const fetchDevelopmentCacheForKey = async (id: string) => {
return await db.prepare('SELECT * FROM _development_cache WHERE id = ?').get(id) as CacheEntry | undefined
}
const insertDevelopmentCache = async (id: string, value: string, checksum: string) => {
deleteDevelopmentCache(id)
const insert = generateCollectionInsert(cacheCollection, { id, value, checksum })
for (const query of insert.queries) {
await db.exec(query)
}
}
const deleteDevelopmentCache = async (id: string) => {
db.prepare(`DELETE FROM _development_cache WHERE id = ?`).run(id)
}
const dropContentTables = async () => {
const tables = await db.prepare('SELECT name FROM sqlite_master WHERE type = ? AND name LIKE ?')
.all('table', '_content_%') as { name: string }[]
for (const { name } of tables) {
db.exec(`DROP TABLE ${name}`)
}
}
return {
database: db,
async exec(sql: string) {
db.exec(sql)
},
close() {
Reflect.deleteProperty(_localDatabase, databaseLocation)
},
fetchDevelopmentCache,
fetchDevelopmentCacheForKey,
insertDevelopmentCache,
deleteDevelopmentCache,
dropContentTables,
supportsTransactions: database.type !== 'd1', // D1 uses batch() instead
}
}
async function findBestSqliteAdapter(opts: { sqliteConnector?: SQLiteConnector, resolver?: Resolver }) {
if (opts.sqliteConnector === 'bun') {
if (!process.versions.bun) {
console.warn('[nuxt/content] `sqliteConnector: \'bun\'` targets Bun runtime — the build-time database will use a Node.js-compatible fallback.')
}
return opts.resolver ? opts.resolver.resolve('./runtime/internal/connectors/bun-sqlite') : 'db0/connectors/bun-sqlite'
}
if (opts.sqliteConnector === 'native' && isNodeSqliteAvailable()) {
return opts.resolver ? opts.resolver.resolve('./runtime/internal/connectors/node-sqlite') : 'db0/connectors/node-sqlite'
}
if (opts.sqliteConnector === 'sqlite3') {
return 'db0/connectors/sqlite3'
}
if (opts.sqliteConnector === 'better-sqlite3') {
await ensurePackageInstalled('better-sqlite3')
return 'db0/connectors/better-sqlite3'
}
// Auto-detect Bun runtime when no explicit connector is set
if (process.versions.bun) {
return opts.resolver ? opts.resolver.resolve('./runtime/internal/connectors/bun-sqlite') : 'db0/connectors/bun-sqlite'
}
if (isWebContainer()) {
await ensurePackageInstalled('sqlite3')
return 'db0/connectors/sqlite3'
}
await ensurePackageInstalled('better-sqlite3')
return 'db0/connectors/better-sqlite3'
}