or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

authentication.mdchange-feeds.mddatabase-management.mddocument-operations.mderror-handling.mdhttp-adapters.mdindex.mdquery-indexing.mdreplication.mdscheduler-monitoring.mdsecurity-document.mdviews-design-documents.md

database-management.mddocs/

0

# Database Management

1

2

Create, delete, and manage databases with comprehensive support for both CouchDB and Cloudant-specific features including partitioned databases, shard information, and database sharing.

3

4

## Capabilities

5

6

### Database Access

7

8

Access databases through dict-like interface on the client.

9

10

```python { .api }

11

class CouchDB(dict):

12

"""Dict-like interface for database access."""

13

14

def all_dbs(self):

15

"""

16

List all database names on the server.

17

18

Returns:

19

list[str]: Database names

20

"""

21

22

def create_database(self, dbname, partitioned=False, **kwargs):

23

"""

24

Create a new database.

25

26

Parameters:

27

- dbname (str): Database name

28

- partitioned (bool): Create as partitioned database (Cloudant only)

29

- **kwargs: Additional database creation options

30

31

Returns:

32

CouchDatabase | CloudantDatabase: Database instance

33

34

Raises:

35

CloudantDatabaseException: Database creation failed

36

"""

37

38

def delete_database(self, dbname):

39

"""

40

Delete a database.

41

42

Parameters:

43

- dbname (str): Database name to delete

44

45

Returns:

46

dict: Deletion response

47

48

Raises:

49

CloudantDatabaseException: Database deletion failed

50

"""

51

52

def keys(self, remote=False):

53

"""

54

Get database names.

55

56

Parameters:

57

- remote (bool): Fetch from server (default: False, uses cache)

58

59

Returns:

60

list[str]: Database names

61

"""

62

63

def __getitem__(self, key):

64

"""

65

Access database by name.

66

67

Parameters:

68

- key (str): Database name

69

70

Returns:

71

CouchDatabase | CloudantDatabase: Database instance

72

"""

73

74

def get(self, key, default=None, remote=False):

75

"""

76

Safe database access.

77

78

Parameters:

79

- key (str): Database name

80

- default: Default value if database not found

81

- remote (bool): Check existence on server

82

83

Returns:

84

CouchDatabase | CloudantDatabase | default: Database instance or default

85

"""

86

87

def __delitem__(self, key):

88

"""

89

Delete database by name.

90

91

Parameters:

92

- key (str): Database name

93

"""

94

```

95

96

### Database Class

97

98

Core database operations and metadata management.

99

100

```python { .api }

101

class CouchDatabase(dict):

102

"""

103

Represents a CouchDB database with document and view operations.

104

"""

105

106

def __init__(self, client, database_name, fetch_limit=100, partitioned=False):

107

"""

108

Initialize database instance.

109

110

Parameters:

111

- client (CouchDB | Cloudant): Parent client

112

- database_name (str): Database name

113

- fetch_limit (int): Default result limit for queries

114

- partitioned (bool): Whether database is partitioned

115

"""

116

117

def exists(self):

118

"""

119

Check if database exists on server.

120

121

Returns:

122

bool: True if database exists

123

"""

124

125

def create(self, throw_on_exists=False):

126

"""

127

Create database on server.

128

129

Parameters:

130

- throw_on_exists (bool): Raise exception if database exists

131

132

Returns:

133

dict: Database creation response

134

135

Raises:

136

CloudantDatabaseException: Creation failed or database exists (if throw_on_exists=True)

137

"""

138

139

def delete(self):

140

"""

141

Delete database from server.

142

143

Returns:

144

dict: Deletion response

145

146

Raises:

147

CloudantDatabaseException: Deletion failed

148

"""

149

150

def metadata(self):

151

"""

152

Get database metadata and statistics.

153

154

Returns:

155

dict: Database metadata including doc_count, disk_size, etc.

156

"""

157

158

def doc_count(self):

159

"""

160

Get total document count in database.

161

162

Returns:

163

int: Number of documents

164

"""

165

166

def partition_metadata(self, partition_key):

167

"""

168

Get metadata for a specific partition (partitioned databases only).

169

170

Parameters:

171

- partition_key (str): Partition identifier

172

173

Returns:

174

dict: Partition metadata and statistics

175

176

Raises:

177

CloudantDatabaseException: Database not partitioned or partition not found

178

"""

179

180

def get_revision_limit(self):

181

"""

182

Get the revision limit for documents.

183

184

Returns:

185

int: Maximum number of revisions kept per document

186

"""

187

188

def set_revision_limit(self, limit):

189

"""

190

Set the revision limit for documents.

191

192

Parameters:

193

- limit (int): Maximum revisions to keep (minimum 1)

194

195

Returns:

196

dict: Response confirming limit change

197

"""

198

199

def view_cleanup(self):

200

"""

201

Clean up old view files and indexes.

202

203

Returns:

204

dict: Cleanup response

205

"""

206

207

@property

208

def database_url(self):

209

"""Database URL endpoint"""

210

211

@property

212

def r_session(self):

213

"""HTTP request session"""

214

215

@property

216

def admin_party(self):

217

"""Whether in Admin Party mode"""

218

219

@property

220

def creds(self):

221

"""Authentication credentials"""

222

```

223

224

### Cloudant Database Extensions

225

226

Additional features specific to Cloudant databases.

227

228

```python { .api }

229

class CloudantDatabase(CouchDatabase):

230

"""

231

Cloudant-specific database with additional cloud features.

232

"""

233

234

def shards(self):

235

"""

236

Get shard information for the database.

237

238

Returns:

239

dict: Sharding configuration and node distribution

240

"""

241

242

def share_database(self, username, roles=None):

243

"""

244

Share database with another user.

245

246

Parameters:

247

- username (str): Username to share with

248

- roles (list[str]): Roles to grant (_reader, _writer, _admin, _replicator)

249

250

Returns:

251

dict: Sharing response

252

253

Raises:

254

CloudantDatabaseException: Sharing failed

255

"""

256

257

def unshare_database(self, username):

258

"""

259

Remove database sharing for a user.

260

261

Parameters:

262

- username (str): Username to remove access for

263

264

Returns:

265

dict: Unsharing response

266

267

Raises:

268

CloudantDatabaseException: Unsharing failed

269

"""

270

271

@property

272

def security_url(self):

273

"""Security document URL"""

274

```

275

276

### Server Information

277

278

Access server metadata and capabilities.

279

280

```python { .api }

281

class CouchDB(dict):

282

"""Server information methods."""

283

284

def metadata(self):

285

"""

286

Get server metadata and version information.

287

288

Returns:

289

dict: Server metadata including version, features, vendor

290

"""

291

292

def features(self):

293

"""

294

Get server features and capabilities.

295

296

Returns:

297

list[str]: Available server features

298

"""

299

300

def db_updates(self, raw_data=False, **kwargs):

301

"""

302

Get database updates feed.

303

304

Parameters:

305

- raw_data (bool): Return raw response data

306

- **kwargs: Feed options (heartbeat, timeout, since, etc.)

307

308

Returns:

309

Feed: Database updates iterator

310

"""

311

312

class Cloudant(CouchDB):

313

"""Cloudant server information."""

314

315

def infinite_db_updates(self, **kwargs):

316

"""

317

Get infinite database updates feed.

318

319

Parameters:

320

- **kwargs: Feed options

321

322

Returns:

323

InfiniteFeed: Perpetual database updates iterator

324

"""

325

326

def shared_databases(self):

327

"""

328

List databases shared with the current user.

329

330

Returns:

331

list[str]: Shared database names

332

"""

333

334

def generate_api_key(self):

335

"""

336

Generate a new API key for authentication.

337

338

Returns:

339

dict: API key and password

340

"""

341

342

def bill(self, year=None, month=None):

343

"""

344

Get billing information.

345

346

Parameters:

347

- year (int): Year for billing data

348

- month (int): Month for billing data

349

350

Returns:

351

dict: Billing data and usage statistics

352

"""

353

354

def volume_usage(self, year=None, month=None):

355

"""

356

Get volume usage statistics.

357

358

Parameters:

359

- year (int): Year for usage data

360

- month (int): Month for usage data

361

362

Returns:

363

dict: Volume usage data

364

"""

365

366

def requests_usage(self, year=None, month=None):

367

"""

368

Get request usage statistics.

369

370

Parameters:

371

- year (int): Year for usage data

372

- month (int): Month for usage data

373

374

Returns:

375

dict: Request usage data

376

"""

377

```

378

379

## Usage Examples

380

381

### Basic Database Operations

382

383

```python

384

from cloudant import cloudant

385

386

with cloudant('user', 'pass', account='myaccount') as client:

387

# List all databases

388

databases = client.all_dbs()

389

print(f"Databases: {databases}")

390

391

# Create database

392

db = client.create_database('my_new_db')

393

print(f"Created database: {db.database_url}")

394

395

# Access existing database

396

db = client['existing_db']

397

398

# Check if database exists

399

if db.exists():

400

print("Database exists")

401

402

# Get database metadata

403

metadata = db.metadata()

404

print(f"Documents: {metadata['doc_count']}")

405

print(f"Size: {metadata['disk_size']} bytes")

406

407

# Delete database

408

client.delete_database('old_db')

409

```

410

411

### Partitioned Databases (Cloudant)

412

413

```python

414

from cloudant import cloudant

415

416

with cloudant('user', 'pass', account='myaccount') as client:

417

# Create partitioned database

418

db = client.create_database('partitioned_db', partitioned=True)

419

420

# Get partition metadata

421

partition_info = db.partition_metadata('user123')

422

print(f"Partition docs: {partition_info['doc_count']}")

423

```

424

425

### Database Sharing (Cloudant)

426

427

```python

428

from cloudant import cloudant

429

430

with cloudant('user', 'pass', account='myaccount') as client:

431

db = client['my_database']

432

433

# Share database with read/write access

434

db.share_database('other_user', roles=['_reader', '_writer'])

435

436

# Remove sharing

437

db.unshare_database('other_user')

438

439

# List shared databases

440

shared = client.shared_databases()

441

print(f"Shared databases: {shared}")

442

```

443

444

### Database Maintenance

445

446

```python

447

from cloudant import cloudant

448

449

with cloudant('user', 'pass', account='myaccount') as client:

450

db = client['my_database']

451

452

# Get current revision limit

453

limit = db.get_revision_limit()

454

print(f"Current revision limit: {limit}")

455

456

# Set revision limit to save disk space

457

db.set_revision_limit(10)

458

459

# Clean up old view files

460

cleanup_result = db.view_cleanup()

461

print(f"Cleanup result: {cleanup_result}")

462

```

463

464

### Server Information

465

466

```python

467

from cloudant import cloudant

468

469

with cloudant('user', 'pass', account='myaccount') as client:

470

# Get server metadata

471

server_info = client.metadata()

472

print(f"Server version: {server_info['version']}")

473

print(f"Vendor: {server_info['vendor']}")

474

475

# Get server features

476

features = client.features()

477

print(f"Features: {features}")

478

479

# Monitor database updates

480

for update in client.db_updates():

481

print(f"Database update: {update}")

482

break # Stop after first update

483

```

484

485

### Usage Statistics (Cloudant)

486

487

```python

488

from cloudant import cloudant

489

490

with cloudant('user', 'pass', account='myaccount') as client:

491

# Get current month billing

492

billing = client.bill()

493

print(f"Monthly cost: ${billing.get('total_cost', 0)}")

494

495

# Get volume usage

496

usage = client.volume_usage()

497

print(f"Storage used: {usage.get('storage', {}).get('used')} bytes")

498

499

# Get request usage

500

requests = client.requests_usage()

501

print(f"Requests made: {requests.get('requests', {}).get('count', 0)}")

502

```

503

504

## Error Handling

505

506

Database operations can raise `CloudantDatabaseException`:

507

508

```python

509

from cloudant import cloudant

510

from cloudant.error import CloudantDatabaseException

511

512

with cloudant('user', 'pass', account='myaccount') as client:

513

try:

514

# Try to create database that already exists

515

db = client.create_database('existing_db', throw_on_exists=True)

516

except CloudantDatabaseException as e:

517

print(f"Database operation failed: {e}")

518

519

try:

520

# Try to delete non-existent database

521

client.delete_database('non_existent_db')

522

except CloudantDatabaseException as e:

523

print(f"Database deletion failed: {e}")

524

```