0
# Enhanced Database Interface
1
2
Promise-based database interface with shortcut methods for common operations, eliminating the need for explicit transaction management in simple cases.
3
4
## Capabilities
5
6
### Transaction Creation
7
8
Create transactions with enhanced promise-based interfaces.
9
10
```typescript { .api }
11
/**
12
* Start a new transaction for a single store
13
* @param storeNames - The object store this transaction needs
14
* @param mode - Transaction mode (readonly, readwrite, versionchange)
15
* @param options - Transaction options including durability
16
* @returns Enhanced transaction interface
17
*/
18
transaction<Name extends StoreNames<DBTypes>, Mode extends IDBTransactionMode = 'readonly'>(
19
storeNames: Name,
20
mode?: Mode,
21
options?: IDBTransactionOptions
22
): IDBPTransaction<DBTypes, [Name], Mode>;
23
24
/**
25
* Start a new transaction for multiple stores
26
* @param storeNames - Array of object stores this transaction needs
27
* @param mode - Transaction mode (readonly, readwrite, versionchange)
28
* @param options - Transaction options including durability
29
* @returns Enhanced transaction interface
30
*/
31
transaction<Names extends ArrayLike<StoreNames<DBTypes>>, Mode extends IDBTransactionMode = 'readonly'>(
32
storeNames: Names,
33
mode?: Mode,
34
options?: IDBTransactionOptions
35
): IDBPTransaction<DBTypes, Names, Mode>;
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
// Single store transaction
42
const tx = db.transaction("users", "readwrite");
43
const userStore = tx.objectStore("users");
44
await userStore.add({ id: "1", name: "Alice" });
45
await tx.done; // Wait for transaction completion
46
47
// Multiple store transaction
48
const tx2 = db.transaction(["users", "posts"], "readwrite");
49
const userStore2 = tx2.objectStore("users");
50
const postStore = tx2.objectStore("posts");
51
await userStore2.add({ id: "1", name: "Bob" });
52
await postStore.add({ id: 1, authorId: "1", title: "Hello World" });
53
await tx2.done;
54
55
// Transaction with durability options
56
const tx3 = db.transaction("users", "readwrite", {
57
durability: "strict" // Ensure data is written to disk immediately
58
});
59
60
// Different durability options
61
const fastTx = db.transaction("cache", "readwrite", {
62
durability: "relaxed" // Better performance, less durability guarantees
63
});
64
65
const defaultTx = db.transaction("users", "readwrite", {
66
durability: "default" // Browser default behavior
67
});
68
```
69
70
### Object Store Management
71
72
Create and delete object stores during database upgrades.
73
74
```typescript { .api }
75
/**
76
* Creates a new object store
77
* Throws "InvalidStateError" if not called within an upgrade transaction
78
* @param name - Name of the object store
79
* @param optionalParameters - Store configuration options
80
* @returns Enhanced object store interface
81
*/
82
createObjectStore<Name extends StoreNames<DBTypes>>(
83
name: Name,
84
optionalParameters?: IDBObjectStoreParameters
85
): IDBPObjectStore<DBTypes, ArrayLike<StoreNames<DBTypes>>, Name, 'versionchange'>;
86
87
/**
88
* Deletes the object store with the given name
89
* Throws "InvalidStateError" if not called within an upgrade transaction
90
* @param name - Name of the object store to delete
91
*/
92
deleteObjectStore(name: StoreNames<DBTypes>): void;
93
```
94
95
**Usage Examples:**
96
97
```typescript
98
// During database upgrade
99
const db = await openDB("my-database", 2, {
100
upgrade(db, oldVersion) {
101
if (oldVersion < 1) {
102
// Create object store with auto-incrementing keys
103
const userStore = db.createObjectStore("users", {
104
keyPath: "id",
105
autoIncrement: true
106
});
107
108
// Create indexes
109
userStore.createIndex("email", "email", { unique: true });
110
userStore.createIndex("name", "name");
111
}
112
113
if (oldVersion < 2) {
114
// Create additional store
115
const postStore = db.createObjectStore("posts", {
116
keyPath: "id",
117
autoIncrement: true
118
});
119
postStore.createIndex("author", "authorId");
120
121
// Remove old store if needed
122
if (db.objectStoreNames.contains("old_store")) {
123
db.deleteObjectStore("old_store");
124
}
125
}
126
}
127
});
128
```
129
130
### Shortcut Methods
131
132
Direct database operations that automatically create and manage transactions.
133
134
#### Add Operations
135
136
```typescript { .api }
137
/**
138
* Add a value to a store
139
* Rejects if an item of a given key already exists in the store
140
* This creates a transaction automatically
141
* @param storeName - Name of the store
142
* @param value - Value to add
143
* @param key - Optional key (if not using keyPath)
144
* @returns Promise resolving to the key of the added item
145
*/
146
add<Name extends StoreNames<DBTypes>>(
147
storeName: Name,
148
value: StoreValue<DBTypes, Name>,
149
key?: StoreKey<DBTypes, Name> | IDBKeyRange
150
): Promise<StoreKey<DBTypes, Name>>;
151
```
152
153
#### Put Operations
154
155
```typescript { .api }
156
/**
157
* Put an item in the database
158
* Replaces any item with the same key
159
* This creates a transaction automatically
160
* @param storeName - Name of the store
161
* @param value - Value to put
162
* @param key - Optional key (if not using keyPath)
163
* @returns Promise resolving to the key of the stored item
164
*/
165
put<Name extends StoreNames<DBTypes>>(
166
storeName: Name,
167
value: StoreValue<DBTypes, Name>,
168
key?: StoreKey<DBTypes, Name> | IDBKeyRange
169
): Promise<StoreKey<DBTypes, Name>>;
170
```
171
172
#### Get Operations
173
174
```typescript { .api }
175
/**
176
* Retrieves the value of the first record in a store matching the query
177
* Resolves with undefined if no match is found
178
* This creates a transaction automatically
179
* @param storeName - Name of the store
180
* @param query - Key or key range to match
181
* @returns Promise resolving to the value or undefined
182
*/
183
get<Name extends StoreNames<DBTypes>>(
184
storeName: Name,
185
query: StoreKey<DBTypes, Name> | IDBKeyRange
186
): Promise<StoreValue<DBTypes, Name> | undefined>;
187
188
/**
189
* Retrieves the value of the first record in an index matching the query
190
* Resolves with undefined if no match is found
191
* This creates a transaction automatically
192
* @param storeName - Name of the store
193
* @param indexName - Name of the index within the store
194
* @param query - Index key or key range to match
195
* @returns Promise resolving to the value or undefined
196
*/
197
getFromIndex<Name extends StoreNames<DBTypes>, IndexName extends IndexNames<DBTypes, Name>>(
198
storeName: Name,
199
indexName: IndexName,
200
query: IndexKey<DBTypes, Name, IndexName> | IDBKeyRange
201
): Promise<StoreValue<DBTypes, Name> | undefined>;
202
203
/**
204
* Retrieves all values in a store that match the query
205
* This creates a transaction automatically
206
* @param storeName - Name of the store
207
* @param query - Key or key range to match (optional)
208
* @param count - Maximum number of values to return (optional)
209
* @returns Promise resolving to array of matching values
210
*/
211
getAll<Name extends StoreNames<DBTypes>>(
212
storeName: Name,
213
query?: StoreKey<DBTypes, Name> | IDBKeyRange | null,
214
count?: number
215
): Promise<StoreValue<DBTypes, Name>[]>;
216
217
/**
218
* Retrieves all values in an index that match the query
219
* This creates a transaction automatically
220
* @param storeName - Name of the store
221
* @param indexName - Name of the index within the store
222
* @param query - Index key or key range to match (optional)
223
* @param count - Maximum number of values to return (optional)
224
* @returns Promise resolving to array of matching values
225
*/
226
getAllFromIndex<Name extends StoreNames<DBTypes>, IndexName extends IndexNames<DBTypes, Name>>(
227
storeName: Name,
228
indexName: IndexName,
229
query?: IndexKey<DBTypes, Name, IndexName> | IDBKeyRange | null,
230
count?: number
231
): Promise<StoreValue<DBTypes, Name>[]>;
232
```
233
234
#### Key Operations
235
236
```typescript { .api }
237
/**
238
* Retrieves the key of the first record in a store that matches the query
239
* Resolves with undefined if no match is found
240
* @param storeName - Name of the store
241
* @param query - Key or key range to match
242
* @returns Promise resolving to the key or undefined
243
*/
244
getKey<Name extends StoreNames<DBTypes>>(
245
storeName: Name,
246
query: StoreKey<DBTypes, Name> | IDBKeyRange
247
): Promise<StoreKey<DBTypes, Name> | undefined>;
248
249
/**
250
* Retrieves the keys of records in a store matching the query
251
* @param storeName - Name of the store
252
* @param query - Key or key range to match (optional)
253
* @param count - Maximum number of keys to return (optional)
254
* @returns Promise resolving to array of matching keys
255
*/
256
getAllKeys<Name extends StoreNames<DBTypes>>(
257
storeName: Name,
258
query?: StoreKey<DBTypes, Name> | IDBKeyRange | null,
259
count?: number
260
): Promise<StoreKey<DBTypes, Name>[]>;
261
```
262
263
#### Delete and Clear Operations
264
265
```typescript { .api }
266
/**
267
* Deletes records in a store matching the given query
268
* This creates a transaction automatically
269
* @param storeName - Name of the store
270
* @param key - Key or key range to delete
271
* @returns Promise that resolves when deletion is complete
272
*/
273
delete<Name extends StoreNames<DBTypes>>(
274
storeName: Name,
275
key: StoreKey<DBTypes, Name> | IDBKeyRange
276
): Promise<void>;
277
278
/**
279
* Deletes all records in a store
280
* This creates a transaction automatically
281
* @param storeName - Name of the store
282
* @returns Promise that resolves when clearing is complete
283
*/
284
clear(name: StoreNames<DBTypes>): Promise<void>;
285
```
286
287
#### Count Operations
288
289
```typescript { .api }
290
/**
291
* Retrieves the number of records matching the given query in a store
292
* This creates a transaction automatically
293
* @param storeName - Name of the store
294
* @param key - Key or key range to count (optional)
295
* @returns Promise resolving to the count
296
*/
297
count<Name extends StoreNames<DBTypes>>(
298
storeName: Name,
299
key?: StoreKey<DBTypes, Name> | IDBKeyRange | null
300
): Promise<number>;
301
302
/**
303
* Retrieves the number of records matching the given query in an index
304
* This creates a transaction automatically
305
* @param storeName - Name of the store
306
* @param indexName - Name of the index within the store
307
* @param key - Index key or key range to count (optional)
308
* @returns Promise resolving to the count
309
*/
310
countFromIndex<Name extends StoreNames<DBTypes>, IndexName extends IndexNames<DBTypes, Name>>(
311
storeName: Name,
312
indexName: IndexName,
313
key?: IndexKey<DBTypes, Name, IndexName> | IDBKeyRange | null
314
): Promise<number>;
315
```
316
317
**Shortcut Method Usage Examples:**
318
319
```typescript
320
import { openDB } from "idb";
321
322
const db = await openDB("my-database");
323
324
// Simple operations with automatic transaction management
325
await db.add("users", { name: "Alice", email: "alice@example.com" });
326
await db.put("users", { id: 1, name: "Bob", email: "bob@example.com" });
327
328
// Get operations
329
const user = await db.get("users", 1);
330
const userByEmail = await db.getFromIndex("users", "email", "alice@example.com");
331
const allUsers = await db.getAll("users");
332
const activeUsers = await db.getAllFromIndex("users", "status", "active");
333
334
// Key operations
335
const userKey = await db.getKey("users", IDBKeyRange.bound(1, 10));
336
const allUserKeys = await db.getAllKeys("users");
337
338
// Count operations
339
const totalUsers = await db.count("users");
340
const activeUserCount = await db.countFromIndex("users", "status", "active");
341
342
// Delete operations
343
await db.delete("users", 1);
344
await db.clear("users"); // Delete all users
345
346
// Working with key ranges
347
const recentUsers = await db.getAll("users", IDBKeyRange.lowerBound(100));
348
const userRange = await db.getAll("users", IDBKeyRange.bound(1, 10));
349
```
350
351
### Database Properties
352
353
Enhanced database interface properties and metadata.
354
355
```typescript { .api }
356
/**
357
* The names of stores in the database
358
*/
359
readonly objectStoreNames: TypedDOMStringList<StoreNames<DBTypes>>;
360
```
361
362
**Property Usage:**
363
364
```typescript
365
const db = await openDB("my-database");
366
367
// Check available stores
368
console.log("Available stores:", [...db.objectStoreNames]);
369
370
// Check if specific store exists
371
if (db.objectStoreNames.contains("users")) {
372
const users = await db.getAll("users");
373
}
374
375
// Iterate over store names
376
for (const storeName of db.objectStoreNames) {
377
const count = await db.count(storeName);
378
console.log(`${storeName}: ${count} records`);
379
}
380
```