0
# Database Management
1
2
Core database lifecycle operations including creation, configuration, information retrieval, and cleanup operations for PouchDB databases.
3
4
## Capabilities
5
6
### Database Constructor
7
8
Creates a new PouchDB database instance with configurable options for different environments and use cases.
9
10
```javascript { .api }
11
/**
12
* Creates a new PouchDB database instance
13
* @param name - Database name or remote URL
14
* @param options - Configuration options for the database
15
* @returns PouchDB instance
16
*/
17
new PouchDB(name: string, options?: PouchDBOptions): PouchDB;
18
19
interface PouchDBOptions {
20
adapter?: string; // Storage adapter ('leveldb', 'idb', 'http', etc.)
21
auto_compaction?: boolean; // Enable automatic compaction
22
revs_limit?: number; // Maximum number of revisions to store
23
view_adapter?: string; // Adapter for view storage
24
purged_infos_limit?: number; // Limit for purged info storage (default: 1000)
25
[key: string]: any; // Additional adapter-specific options
26
}
27
```
28
29
**Usage Examples:**
30
31
```javascript
32
// Local database with default adapter
33
const localDb = new PouchDB('my-local-db');
34
35
// Remote database
36
const remoteDb = new PouchDB('http://localhost:5984/my-remote-db');
37
38
// Database with specific adapter
39
const memoryDb = new PouchDB('temp-db', { adapter: 'memory' });
40
41
// Database with custom options
42
const db = new PouchDB('my-db', {
43
adapter: 'leveldb',
44
auto_compaction: true,
45
revs_limit: 10
46
});
47
```
48
49
### Database Information
50
51
Retrieves comprehensive information about the database including document count, storage size, and metadata.
52
53
```javascript { .api }
54
/**
55
* Get database information and statistics
56
* @returns Promise resolving to database information
57
*/
58
db.info(): Promise<DatabaseInfo>;
59
60
interface DatabaseInfo {
61
db_name: string; // Database name
62
doc_count: number; // Number of documents
63
update_seq: number | string; // Current update sequence
64
purge_seq?: number | string; // Current purge sequence
65
compact_running: boolean; // Whether compaction is running
66
disk_size?: number; // Database size on disk (bytes)
67
data_size?: number; // Actual data size (bytes)
68
instance_start_time: string; // When database instance was created
69
host: string; // Host information
70
auto_compaction?: boolean; // Auto-compaction status
71
}
72
```
73
74
**Usage Examples:**
75
76
```javascript
77
// Get basic database information
78
const info = await db.info();
79
console.log(`Database: ${info.db_name}`);
80
console.log(`Documents: ${info.doc_count}`);
81
console.log(`Size: ${info.disk_size} bytes`);
82
83
// Check if compaction is running
84
if (info.compact_running) {
85
console.log('Database compaction in progress');
86
}
87
```
88
89
### Database Destruction
90
91
Permanently deletes a database and all its data. This operation cannot be undone.
92
93
```javascript { .api }
94
/**
95
* Destroy the database and all its data permanently
96
* @param options - Destruction options
97
* @returns Promise resolving when destruction is complete
98
*/
99
db.destroy(options?: DestroyOptions): Promise<void>;
100
101
interface DestroyOptions {
102
[key: string]: any; // Adapter-specific options
103
}
104
```
105
106
**Usage Examples:**
107
108
```javascript
109
// Destroy a database
110
await db.destroy();
111
console.log('Database destroyed');
112
113
// Destroy with options (adapter-specific)
114
await db.destroy({
115
force: true // Example adapter-specific option
116
});
117
```
118
119
### Database Closure
120
121
Closes the database connection and releases resources. The database can be reopened by creating a new instance.
122
123
```javascript { .api }
124
/**
125
* Close the database connection and release resources
126
* @returns Promise resolving when database is closed
127
*/
128
db.close(): Promise<void>;
129
```
130
131
**Usage Examples:**
132
133
```javascript
134
// Close database connection
135
await db.close();
136
console.log('Database connection closed');
137
138
// Proper cleanup pattern
139
try {
140
// Use database
141
await db.put({ _id: 'doc1', data: 'value' });
142
} finally {
143
// Always close when done
144
await db.close();
145
}
146
```
147
148
### Database Compaction
149
150
Reduces database size by removing old document revisions and reclaiming space from deleted documents.
151
152
```javascript { .api }
153
/**
154
* Compact the database to reduce size and improve performance
155
* @param options - Compaction options
156
* @returns Promise resolving to compaction result
157
*/
158
db.compact(options?: CompactOptions): Promise<CompactResponse>;
159
160
interface CompactOptions {
161
interval?: number; // Compaction interval for continuous compaction
162
[key: string]: any; // Adapter-specific options
163
}
164
165
interface CompactResponse {
166
ok: boolean; // Whether compaction succeeded
167
[key: string]: any; // Additional adapter-specific response data
168
}
169
```
170
171
**Usage Examples:**
172
173
```javascript
174
// Basic compaction
175
const result = await db.compact();
176
console.log('Compaction completed:', result.ok);
177
178
// Compaction with options
179
const result = await db.compact({
180
interval: 5000 // Compact every 5 seconds
181
});
182
183
// Check database size before and after
184
const infoBefore = await db.info();
185
await db.compact();
186
const infoAfter = await db.info();
187
console.log(`Size reduced from ${infoBefore.disk_size} to ${infoAfter.disk_size}`);
188
```
189
190
### Static Configuration Methods
191
192
Global configuration methods for setting up PouchDB defaults and preferences.
193
194
```javascript { .api }
195
/**
196
* Create a PouchDB constructor with default options
197
* @param options - Default options to apply to all instances
198
* @returns New PouchDB constructor with defaults
199
*/
200
PouchDB.defaults(options: PouchDBOptions): typeof PouchDB;
201
202
/**
203
* Database name prefix for local databases
204
*/
205
PouchDB.prefix: string; // Default: '_pouch_'
206
207
/**
208
* Array of preferred adapters in order of preference
209
*/
210
PouchDB.preferredAdapters: string[];
211
```
212
213
**Usage Examples:**
214
215
```javascript
216
// Create PouchDB constructor with defaults
217
const CustomPouchDB = PouchDB.defaults({
218
adapter: 'memory',
219
auto_compaction: true
220
});
221
222
// All instances created with CustomPouchDB will use these defaults
223
const db1 = new CustomPouchDB('db1'); // Uses memory adapter
224
const db2 = new CustomPouchDB('db2'); // Uses memory adapter
225
226
// Change database prefix
227
PouchDB.prefix = 'myapp_';
228
const db = new PouchDB('test'); // Actually creates 'myapp_test'
229
230
// Check preferred adapters
231
console.log(PouchDB.preferredAdapters); // ['idb', 'leveldb', 'websql']
232
```
233
234
## Error Handling
235
236
Database management operations can fail for various reasons. Handle errors appropriately:
237
238
```javascript
239
try {
240
const info = await db.info();
241
console.log('Database is accessible');
242
} catch (error) {
243
if (error.status === 404) {
244
console.log('Database does not exist');
245
} else if (error.status === 401) {
246
console.log('Authentication required');
247
} else {
248
console.log('Database error:', error.message);
249
}
250
}
251
```
252
253
Common error codes:
254
- `404` - Database not found
255
- `401` - Authentication required
256
- `403` - Permission denied
257
- `500` - Internal server error (for remote databases)