0
# Database Management
1
2
Database lifecycle management including connection handling, configuration, and database-wide operations. UnQLite supports both file-based and in-memory databases with flexible configuration options.
3
4
## Capabilities
5
6
### Database Connection
7
8
Initialize and manage database connections with various configuration options.
9
10
```python { .api }
11
def __init__(self, filename=':mem:', flags=UNQLITE_OPEN_CREATE, open_database=True, thread_safe=True):
12
"""Initialize UnQLite database connection.
13
14
Args:
15
filename: Database file path or ':mem:' for in-memory database
16
flags: Open mode flags (UNQLITE_OPEN_*)
17
open_database: Whether to open database immediately
18
thread_safe: Enable thread-safe operations
19
"""
20
...
21
22
def open(self):
23
"""Open database connection. Returns True if successful."""
24
...
25
26
def close(self):
27
"""Close database connection. Returns True if successful."""
28
...
29
30
def flush(self):
31
"""Synchronize database changes to disk. Only for file-based databases."""
32
...
33
```
34
35
**Usage Example:**
36
37
```python
38
import unqlite
39
40
# In-memory database (default)
41
db = unqlite.UnQLite()
42
43
# File-based database with automatic creation
44
db = unqlite.UnQLite('mydata.db')
45
46
# Read-only database
47
db = unqlite.UnQLite('readonly.db', flags=unqlite.UNQLITE_OPEN_READONLY)
48
49
# Manual connection management
50
db = unqlite.UnQLite('manual.db', open_database=False)
51
db.open()
52
# ... use database
53
db.close()
54
```
55
56
### Context Manager Support
57
58
Automatic resource management using Python context managers.
59
60
```python { .api }
61
def __enter__(self):
62
"""Enter context manager. Opens database if not already open."""
63
...
64
65
def __exit__(self, exc_type, exc_val, exc_tb):
66
"""Exit context manager. Closes database connection."""
67
...
68
```
69
70
**Usage Example:**
71
72
```python
73
# Automatic cleanup with context manager
74
with unqlite.UnQLite('data.db') as db:
75
db['key'] = 'value'
76
result = db['key']
77
# Database automatically closed when exiting context
78
79
# Context manager with error handling
80
try:
81
with unqlite.UnQLite('data.db') as db:
82
db['important_data'] = 'critical_value'
83
# If exception occurs, database is still properly closed
84
raise Exception("Something went wrong")
85
except Exception as e:
86
print(f"Error occurred: {e}")
87
# Database was properly closed despite the exception
88
```
89
90
### Database Information
91
92
Access database metadata and state information.
93
94
```python { .api }
95
@property
96
def is_memory(self):
97
"""Returns True if database is in-memory."""
98
...
99
100
@property
101
def is_open(self):
102
"""Returns True if database connection is open."""
103
...
104
105
@property
106
def filename(self):
107
"""Returns database filename."""
108
...
109
110
@property
111
def flags(self):
112
"""Returns open mode flags."""
113
...
114
115
def __len__(self):
116
"""Return total number of records in database. O(n) operation."""
117
...
118
```
119
120
**Usage Example:**
121
122
```python
123
db = unqlite.UnQLite('example.db')
124
125
print(f"Database file: {db.filename}")
126
print(f"Is in-memory: {db.is_memory}")
127
print(f"Is open: {db.is_open}")
128
print(f"Open flags: {db.flags}")
129
130
# Add some data
131
db['key1'] = 'value1'
132
db['key2'] = 'value2'
133
134
# Count records (expensive for large databases)
135
record_count = len(db)
136
print(f"Total records: {record_count}")
137
```
138
139
### Database Clearing
140
141
Remove all records from the database.
142
143
```python { .api }
144
def flush(self):
145
"""Remove all records from database. Returns number of deleted records.
146
147
Note: This is an O(n) operation requiring iteration through entire key-space.
148
"""
149
...
150
```
151
152
**Usage Example:**
153
154
```python
155
db = unqlite.UnQLite(':mem:')
156
157
# Add test data
158
for i in range(10):
159
db[f'key{i}'] = f'value{i}'
160
161
print(f"Records before flush: {len(db)}") # 10
162
163
# Clear all data
164
deleted_count = db.flush()
165
print(f"Deleted {deleted_count} records")
166
print(f"Records after flush: {len(db)}") # 0
167
```
168
169
## Open Mode Flags
170
171
Control database behavior with open mode flags:
172
173
```python
174
# Read-only access
175
unqlite.UNQLITE_OPEN_READONLY
176
177
# Read-write access
178
unqlite.UNQLITE_OPEN_READWRITE
179
180
# Create database if it doesn't exist (default)
181
unqlite.UNQLITE_OPEN_CREATE
182
183
# Exclusive access
184
unqlite.UNQLITE_OPEN_EXCLUSIVE
185
186
# Temporary database
187
unqlite.UNQLITE_OPEN_TEMP_DB
188
189
# Disable mutex locking
190
unqlite.UNQLITE_OPEN_NOMUTEX
191
192
# Disable journaling
193
unqlite.UNQLITE_OPEN_OMIT_JOURNALING
194
195
# Force in-memory mode
196
unqlite.UNQLITE_OPEN_IN_MEMORY
197
198
# Use memory mapping
199
unqlite.UNQLITE_OPEN_MMAP
200
```
201
202
**Usage Example:**
203
204
```python
205
# Combine multiple flags using bitwise OR
206
flags = unqlite.UNQLITE_OPEN_READWRITE | unqlite.UNQLITE_OPEN_NOMUTEX
207
db = unqlite.UnQLite('fast.db', flags=flags)
208
209
# Read-only database
210
readonly_db = unqlite.UnQLite('data.db', flags=unqlite.UNQLITE_OPEN_READONLY)
211
212
# High-performance in-memory database
213
memory_db = unqlite.UnQLite(':mem:', flags=unqlite.UNQLITE_OPEN_IN_MEMORY | unqlite.UNQLITE_OPEN_NOMUTEX)
214
```
215
216
## Thread Safety
217
218
UnQLite can be configured for thread-safe operations:
219
220
```python
221
# Thread-safe database (default)
222
db = unqlite.UnQLite('shared.db', thread_safe=True)
223
224
# Single-threaded optimization
225
db = unqlite.UnQLite('private.db', thread_safe=False)
226
```
227
228
Thread safety affects global library configuration and should be set consistently across all database instances in an application.
229
230
## Error Handling
231
232
Database management operations can raise various exceptions:
233
234
```python
235
try:
236
db = unqlite.UnQLite('/invalid/path/database.db')
237
except unqlite.UnQLiteError as e:
238
print(f"Failed to open database: {e}")
239
240
try:
241
db.open()
242
except unqlite.UnQLiteError as e:
243
print(f"Failed to open connection: {e}")
244
```