0
# Database Operations
1
2
Database connection management, schema operations, transaction support, and administrative functions for maintaining Neo4j database state in neomodel. Includes both synchronous and asynchronous database interfaces.
3
4
## Capabilities
5
6
### Database Connection Classes
7
8
Core database interface classes providing connection management and query execution.
9
10
```python { .api }
11
class Database:
12
"""
13
Main database interface for synchronous operations.
14
15
Provides connection management, query execution, and transaction support.
16
"""
17
18
def cypher_query(self, query, params=None, resolve_objects=False):
19
"""
20
Execute a raw Cypher query.
21
22
Args:
23
query (str): Cypher query string
24
params (dict, optional): Query parameters
25
resolve_objects (bool): Whether to resolve results to neomodel objects
26
27
Returns:
28
tuple: (results, meta) - query results and metadata
29
"""
30
31
def transaction(self):
32
"""
33
Start a new database transaction.
34
35
Returns:
36
Transaction: Transaction context manager
37
"""
38
39
def set_connection(self, url):
40
"""
41
Set database connection URL.
42
43
Args:
44
url (str): Neo4j connection URL (bolt://...)
45
"""
46
47
def close_connection(self):
48
"""Close current database connection."""
49
50
class AsyncDatabase:
51
"""
52
Main database interface for asynchronous operations.
53
54
Same interface as Database but all methods are async.
55
"""
56
57
async def cypher_query(self, query, params=None, resolve_objects=False):
58
"""Asynchronously execute a raw Cypher query."""
59
60
async def transaction(self):
61
"""Start a new async database transaction."""
62
63
async def set_connection(self, url):
64
"""Asynchronously set database connection URL."""
65
66
async def close_connection(self):
67
"""Asynchronously close current database connection."""
68
69
# Global database instances
70
db: Database
71
adb: AsyncDatabase
72
```
73
74
### Database Utility Functions
75
76
Administrative functions for database schema management and maintenance.
77
78
```python { .api }
79
def change_neo4j_password(new_password):
80
"""
81
Change the Neo4j database password.
82
83
Args:
84
new_password (str): New password for Neo4j user
85
86
Returns:
87
bool: True if password change was successful
88
"""
89
90
def clear_neo4j_database():
91
"""
92
Clear all nodes and relationships from the database.
93
94
Warning: This permanently deletes all data in the database.
95
96
Returns:
97
bool: True if database was cleared successfully
98
"""
99
100
def drop_constraints():
101
"""
102
Drop all database constraints.
103
104
Removes unique constraints, existence constraints, and other schema constraints.
105
106
Returns:
107
bool: True if constraints were dropped successfully
108
"""
109
110
def drop_indexes():
111
"""
112
Drop all database indexes.
113
114
Removes all property indexes, fulltext indexes, and vector indexes.
115
116
Returns:
117
bool: True if indexes were dropped successfully
118
"""
119
120
def install_all_labels():
121
"""
122
Install constraints and indexes for all defined node models.
123
124
Scans all StructuredNode subclasses and creates appropriate
125
database constraints and indexes based on property definitions.
126
127
Returns:
128
bool: True if installation was successful
129
"""
130
131
def install_labels(*models):
132
"""
133
Install constraints and indexes for specific node models.
134
135
Args:
136
*models: StructuredNode classes to install labels for
137
138
Returns:
139
bool: True if installation was successful
140
"""
141
142
def remove_all_labels():
143
"""
144
Remove all constraints and indexes from the database.
145
146
Equivalent to calling both drop_constraints() and drop_indexes().
147
148
Returns:
149
bool: True if removal was successful
150
"""
151
```
152
153
### Transaction Management
154
155
Classes and functions for managing database transactions.
156
157
```python { .api }
158
class Transaction:
159
"""
160
Database transaction context manager for synchronous operations.
161
162
Provides commit and rollback functionality for grouped operations.
163
"""
164
165
def __enter__(self):
166
"""Enter transaction context."""
167
return self
168
169
def __exit__(self, exc_type, exc_val, exc_tb):
170
"""Exit transaction context with automatic commit/rollback."""
171
172
def commit(self):
173
"""Commit the current transaction."""
174
175
def rollback(self):
176
"""Rollback the current transaction."""
177
178
class AsyncTransaction:
179
"""
180
Database transaction context manager for asynchronous operations.
181
"""
182
183
async def __aenter__(self):
184
"""Enter async transaction context."""
185
return self
186
187
async def __aexit__(self, exc_type, exc_val, exc_tb):
188
"""Exit async transaction context with automatic commit/rollback."""
189
190
async def commit(self):
191
"""Asynchronously commit the current transaction."""
192
193
async def rollback(self):
194
"""Asynchronously rollback the current transaction."""
195
```
196
197
## Usage Examples
198
199
### Database Connection and Configuration
200
201
```python
202
from neomodel import config, db
203
204
# Set database connection
205
config.DATABASE_URL = 'bolt://neo4j:password@localhost:7687'
206
207
# Alternative: set specific database name
208
config.DATABASE_NAME = 'myapp'
209
210
# Use custom driver settings
211
config.DRIVER = {
212
'max_connection_lifetime': 1000,
213
'max_connection_pool_size': 50,
214
'connection_acquisition_timeout': 60
215
}
216
217
# Test connection
218
try:
219
db.set_connection(config.DATABASE_URL)
220
print("Connected to Neo4j successfully")
221
except Exception as e:
222
print(f"Connection failed: {e}")
223
```
224
225
### Raw Cypher Queries
226
227
```python
228
from neomodel import db
229
230
# Execute raw Cypher query
231
query = "MATCH (n:Person) WHERE n.age > $age RETURN n.name, n.age"
232
results, meta = db.cypher_query(query, {'age': 30})
233
234
print(f"Found {len(results)} results")
235
for row in results:
236
name, age = row
237
print(f"{name}: {age} years old")
238
239
# Query with object resolution
240
query = "MATCH (n:Person) RETURN n"
241
results, meta = db.cypher_query(query, resolve_objects=True)
242
243
# Results are now Person instances
244
for person in results:
245
print(f"Person: {person.name}")
246
```
247
248
### Transaction Management
249
250
```python
251
from neomodel import db, StructuredNode, StringProperty
252
253
class Person(StructuredNode):
254
name = StringProperty(required=True)
255
256
# Synchronous transaction
257
with db.transaction():
258
person1 = Person(name="Alice").save()
259
person2 = Person(name="Bob").save()
260
# Both saves committed together
261
262
# Manual transaction control
263
tx = db.transaction()
264
try:
265
person = Person(name="Charlie").save()
266
# Do more operations...
267
tx.commit()
268
except Exception as e:
269
tx.rollback()
270
print(f"Transaction failed: {e}")
271
```
272
273
### Async Database Operations
274
275
```python
276
from neomodel import adb, AsyncStructuredNode, StringProperty
277
278
class AsyncPerson(AsyncStructuredNode):
279
name = StringProperty(required=True)
280
281
async def database_operations():
282
# Async raw query
283
query = "MATCH (n:Person) RETURN count(n) as total"
284
results, meta = await adb.cypher_query(query)
285
total_people = results[0][0]
286
287
# Async transaction
288
async with adb.transaction():
289
person1 = await AsyncPerson(name="Dave").save()
290
person2 = await AsyncPerson(name="Eve").save()
291
# Both saves committed together
292
293
return total_people
294
```
295
296
### Schema Management
297
298
```python
299
from neomodel import (
300
install_all_labels, install_labels, drop_constraints,
301
drop_indexes, clear_neo4j_database
302
)
303
304
# Install constraints and indexes for all models
305
install_all_labels()
306
307
# Install for specific models only
308
from myapp.models import Person, Company
309
install_labels(Person, Company)
310
311
# Clean up schema
312
drop_constraints() # Remove all constraints
313
drop_indexes() # Remove all indexes
314
315
# Nuclear option - clear everything
316
# WARNING: This deletes all data!
317
clear_neo4j_database()
318
```
319
320
### Database Administration
321
322
```python
323
from neomodel import change_neo4j_password, db
324
325
# Change database password
326
try:
327
change_neo4j_password("new_secure_password")
328
print("Password changed successfully")
329
except Exception as e:
330
print(f"Password change failed: {e}")
331
332
# Check database status
333
try:
334
results, meta = db.cypher_query("CALL dbms.components()")
335
for component in results:
336
print(f"Component: {component}")
337
except Exception as e:
338
print(f"Status check failed: {e}")
339
340
# Get database statistics
341
stats_query = """
342
MATCH (n)
343
RETURN labels(n) as label, count(n) as count
344
ORDER BY count DESC
345
"""
346
results, meta = db.cypher_query(stats_query)
347
print("Node counts by label:")
348
for label, count in results:
349
print(f" {label}: {count}")
350
```
351
352
### Connection Management
353
354
```python
355
from neomodel import db, config
356
357
# Multiple database connections
358
def switch_database(db_name):
359
"""Switch to a different database."""
360
original_url = config.DATABASE_URL
361
362
# Parse and modify URL for different database
363
base_url = original_url.rsplit('/', 1)[0]
364
new_url = f"{base_url}/{db_name}"
365
366
# Close current connection and connect to new database
367
db.close_connection()
368
db.set_connection(new_url)
369
370
return original_url
371
372
# Usage
373
original = switch_database("testdb")
374
# ... work with test database ...
375
db.set_connection(original) # Switch back
376
```
377
378
### Error Handling and Debugging
379
380
```python
381
from neomodel import db
382
from neomodel.exceptions import (
383
DoesNotExist, UniqueProperty, ConstraintValidationFailed
384
)
385
386
def safe_database_operation():
387
try:
388
# Potentially failing operation
389
results, meta = db.cypher_query(
390
"MATCH (n:Person {name: $name}) RETURN n",
391
{'name': 'NonexistentPerson'}
392
)
393
394
if not results:
395
raise DoesNotExist("Person not found")
396
397
except ConstraintValidationFailed as e:
398
print(f"Constraint violation: {e}")
399
except UniqueProperty as e:
400
print(f"Unique constraint violated: {e}")
401
except Exception as e:
402
print(f"Database error: {e}")
403
# Log error details
404
print(f"Query meta: {meta}")
405
```
406
407
## Types
408
409
```python { .api }
410
# Database result types
411
CypherResult = Tuple[List[List[Any]], Dict[str, Any]]
412
QueryParams = Dict[str, Any]
413
414
# Transaction types
415
TransactionContext = Union[Transaction, AsyncTransaction]
416
417
# Connection types
418
DatabaseURL = str
419
DriverConfig = Dict[str, Any]
420
```