0
# Database Operations
1
2
Core database lifecycle management including opening databases with upgrade callbacks, deleting databases, and handling database events.
3
4
## Capabilities
5
6
### Opening Databases
7
8
Opens a database and returns a promise-based enhanced IDBDatabase interface.
9
10
```typescript { .api }
11
/**
12
* Opens a database and returns a promise for an enhanced IDBDatabase
13
* @param name - Name of the database
14
* @param version - Schema version, or undefined to open current version
15
* @param callbacks - Additional callbacks for database events
16
* @returns Promise resolving to enhanced database interface
17
*/
18
function openDB<DBTypes extends DBSchema | unknown = unknown>(
19
name: string,
20
version?: number,
21
{ blocked, upgrade, blocking, terminated }: OpenDBCallbacks<DBTypes> = {}
22
): Promise<IDBPDatabase<DBTypes>>;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { openDB } from "idb";
29
30
// Simple database opening
31
const db = await openDB("my-database");
32
33
// Database with version and upgrade
34
const db = await openDB("my-database", 2, {
35
upgrade(db, oldVersion, newVersion) {
36
if (oldVersion < 1) {
37
db.createObjectStore("users", { keyPath: "id" });
38
}
39
if (oldVersion < 2) {
40
const store = db.createObjectStore("posts", { keyPath: "id" });
41
store.createIndex("author", "authorId");
42
}
43
}
44
});
45
46
// Database with typed schema
47
interface MyDB {
48
users: {
49
key: string;
50
value: { id: string; name: string; email: string };
51
};
52
posts: {
53
key: number;
54
value: { id: number; title: string; authorId: string };
55
indexes: { author: string };
56
};
57
}
58
59
const typedDB = await openDB<MyDB>("my-database", 1, {
60
upgrade(db) {
61
const userStore = db.createObjectStore("users", { keyPath: "id" });
62
const postStore = db.createObjectStore("posts", { keyPath: "id", autoIncrement: true });
63
postStore.createIndex("author", "authorId");
64
}
65
});
66
67
// Error handling for database opening
68
try {
69
const db = await openDB("my-database", 2, {
70
upgrade(db, oldVersion) {
71
if (oldVersion < 1) {
72
db.createObjectStore("users", { keyPath: "id" });
73
}
74
},
75
blocked() {
76
console.log("Database blocked - close other tabs");
77
}
78
});
79
} catch (error) {
80
if (error.name === "VersionError") {
81
console.error("Invalid version specified");
82
} else {
83
console.error("Database opening failed:", error);
84
}
85
}
86
```
87
88
### Deleting Databases
89
90
Deletes a database entirely.
91
92
```typescript { .api }
93
/**
94
* Deletes a database
95
* @param name - Name of the database to delete
96
* @param callbacks - Additional callbacks for deletion events
97
* @returns Promise that resolves when deletion is complete
98
*/
99
function deleteDB(
100
name: string,
101
{ blocked }: DeleteDBCallbacks = {}
102
): Promise<void>;
103
```
104
105
**Usage Examples:**
106
107
```typescript
108
import { deleteDB } from "idb";
109
110
// Simple database deletion
111
await deleteDB("my-database");
112
113
// Deletion with blocked callback
114
await deleteDB("my-database", {
115
blocked(currentVersion, event) {
116
console.log("Database deletion blocked by open connections");
117
}
118
});
119
120
// Error handling for database operations
121
try {
122
await deleteDB("my-database");
123
} catch (error) {
124
if (error.name === "NotFoundError") {
125
console.log("Database doesn't exist");
126
} else {
127
console.error("Deletion failed:", error);
128
}
129
}
130
```
131
132
### Database Event Callbacks
133
134
Configuration for handling database lifecycle events during opening and deletion.
135
136
```typescript { .api }
137
interface OpenDBCallbacks<DBTypes extends DBSchema | unknown> {
138
/**
139
* Called if this version of the database has never been opened before.
140
* Use it to specify the schema for the database.
141
* @param database - Enhanced database instance for schema changes
142
* @param oldVersion - Last version of the database opened by the user
143
* @param newVersion - New version being opened
144
* @param transaction - The transaction for this upgrade
145
* @param event - The event object for the associated 'upgradeneeded' event
146
*/
147
upgrade?(
148
database: IDBPDatabase<DBTypes>,
149
oldVersion: number,
150
newVersion: number | null,
151
transaction: IDBPTransaction<DBTypes, StoreNames<DBTypes>[], 'versionchange'>,
152
event: IDBVersionChangeEvent
153
): void;
154
155
/**
156
* Called if there are older versions of the database open on the origin,
157
* so this version cannot open.
158
* @param currentVersion - Version of the database that's blocking this one
159
* @param blockedVersion - The version being blocked
160
* @param event - The event object for the associated 'blocked' event
161
*/
162
blocked?(
163
currentVersion: number,
164
blockedVersion: number | null,
165
event: IDBVersionChangeEvent
166
): void;
167
168
/**
169
* Called if this connection is blocking a future version of the database
170
* from opening.
171
* @param currentVersion - Version of the open database
172
* @param blockedVersion - The version being blocked
173
* @param event - The event object for the associated 'versionchange' event
174
*/
175
blocking?(
176
currentVersion: number,
177
blockedVersion: number | null,
178
event: IDBVersionChangeEvent
179
): void;
180
181
/**
182
* Called if the browser abnormally terminates the connection.
183
* This is not called when db.close() is called.
184
*/
185
terminated?(): void;
186
}
187
188
interface DeleteDBCallbacks {
189
/**
190
* Called if there are connections to this database open,
191
* so it cannot be deleted.
192
* @param currentVersion - Version of the database blocking deletion
193
* @param event - The event object for the associated 'blocked' event
194
*/
195
blocked?(currentVersion: number, event: IDBVersionChangeEvent): void;
196
}
197
```
198
199
**Database Event Usage:**
200
201
```typescript
202
const db = await openDB("my-database", 3, {
203
upgrade(db, oldVersion, newVersion, transaction, event) {
204
console.log(`Upgrading from ${oldVersion} to ${newVersion}`);
205
206
if (oldVersion < 1) {
207
db.createObjectStore("users", { keyPath: "id" });
208
}
209
if (oldVersion < 2) {
210
db.createObjectStore("settings", { keyPath: "key" });
211
}
212
if (oldVersion < 3) {
213
const userStore = transaction.objectStore("users");
214
userStore.createIndex("email", "email", { unique: true });
215
}
216
},
217
218
blocked(currentVersion, blockedVersion, event) {
219
console.log("Database opening blocked - close other tabs");
220
},
221
222
blocking(currentVersion, blockedVersion, event) {
223
console.log("This database connection is blocking a newer version");
224
// Consider closing the database
225
db.close();
226
},
227
228
terminated() {
229
console.log("Database connection terminated unexpectedly");
230
}
231
});
232
```
233
234
### Database Schema Types
235
236
Type definitions for defining strongly-typed database schemas.
237
238
```typescript { .api }
239
/**
240
* Base interface for defining database schema types
241
*/
242
interface DBSchema {
243
[storeName: string]: DBSchemaValue;
244
}
245
246
/**
247
* Schema definition for an object store
248
*/
249
interface DBSchemaValue {
250
/** Type of keys used in this store */
251
key: IDBValidKey;
252
/** Type of values stored in this store */
253
value: any;
254
/** Optional index definitions */
255
indexes?: IndexKeys;
256
}
257
258
/**
259
* Index key mappings for an object store
260
*/
261
interface IndexKeys {
262
[indexName: string]: IDBValidKey;
263
}
264
```
265
266
**Schema Definition Examples:**
267
268
```typescript
269
// Simple schema with string keys
270
interface SimpleDB {
271
users: {
272
key: string;
273
value: { name: string; email: string };
274
};
275
}
276
277
// Complex schema with multiple stores and indexes
278
interface BlogDB {
279
users: {
280
key: string;
281
value: {
282
id: string;
283
username: string;
284
email: string;
285
createdAt: Date;
286
};
287
indexes: {
288
email: string;
289
username: string;
290
};
291
};
292
293
posts: {
294
key: number;
295
value: {
296
id: number;
297
title: string;
298
content: string;
299
authorId: string;
300
publishedAt: Date;
301
tags: string[];
302
};
303
indexes: {
304
author: string;
305
published: Date;
306
tag: string;
307
};
308
};
309
310
comments: {
311
key: number;
312
value: {
313
id: number;
314
postId: number;
315
authorId: string;
316
content: string;
317
createdAt: Date;
318
};
319
indexes: {
320
post: number;
321
author: string;
322
};
323
};
324
}
325
```