Database Backend
Database-per-Tenant Backend Module
This module implements the Database-per-Tenant isolation strategy where each tenant gets its own separate PostgreSQL database within the same or different database servers.
Isolation Strategy
Each tenant is completely isolated in a separate database. This provides strong isolation at the cost of managing multiple databases.
Architecture
- Tenant configuration specifies database credentials (NAME, USER, PASSWORD, HOST, PORT)
- Each tenant's database is registered dynamically in Django's DATABASES setting
- TenantContext manages switching between databases during request processing
- The public/shared database holds the Tenant and Domain models
Database Configuration
Tenant configuration should include a 'db_config' dictionary:
tenant.config = {
'db_config': {
'NAME': 'tenant_acme_db', # Database name
'USER': 'tenant_acme_user', # Database user
'PASSWORD': 'secret_password', # Database password
'HOST': 'db.example.com', # Database host
'PORT': 5432, # Database port
'ENGINE': 'django.db.backends.postgresql', # Optional, defaults to master
'ALIAS': 'acme_db', # Optional, defaults to NAME or MASTER_DB_ALIAS
}
}
Lifecycle
- create() - Creates new database, binds to Django settings, runs migrations
- activate() - Switches database connection when entering tenant context
- deactivate() - Restores previous database when exiting context
- delete() - Drops database and removes from Django settings
- bind() - Manually attaches database to settings for connections
Connection Management
- Uses Django's DATABASES setting for multi-database support
- TenantContext maintains stack of active database aliases
- Each request or explicit context switch changes active database
- Schema management ensures no cross-tenant data leakage
PostgreSQL Support
- Compatible with both psycopg2 and psycopg3 drivers
- Detects available driver and uses appropriate SQL construction API
- Handles PostgreSQL-specific operations (CREATE DATABASE, DROP DATABASE)
Performance Considerations
- Database creation can be slow (especially over network)
- Connection pooling per database (see CONN_MAX_AGE setting)
- Index and query optimization must happen per database
- Migrations run per database (can be parallelized)
Security Considerations
- Each tenant needs separate database credentials
- Strongly isolate databases at DB server level
- Use firewalls/security groups to restrict access
- Monitor for cross-database queries (security bug)
- Regular backups per database
Usage Example
from django_omnitenant.backends.database_backend import DatabaseTenantBackend
from myapp.models import Tenant
# Create new tenant
tenant = Tenant.objects.create(
tenant_id='acme',
name='Acme Corporation',
config={
'db_config': {
'NAME': 'tenant_acme_db',
'USER': 'acme_user',
'PASSWORD': 'secret',
'HOST': 'db.example.com',
}
}
)
# Provision database
backend = DatabaseTenantBackend(tenant)
backend.create(run_migrations=True)
# Use tenant
with TenantContext.use_tenant(tenant):
# Queries automatically route to tenant's database
User.objects.create(username='john')
# Cleanup
backend.delete(drop_db=True)
DatabaseTenantBackend
Bases: BaseTenantBackend
Database-per-Tenant isolation backend.
Implements the database-per-tenant isolation strategy where each tenant gets its own separate PostgreSQL database.
Each tenant's database is created and configured dynamically. The backend manages database creation, connection routing, migrations, and cleanup.
Key Features
- Complete data isolation between tenants
- Independent database credentials per tenant
- Dynamic database registration in Django
- Automatic migration handling
- PostgreSQL native database management
Configuration
Tenants must have 'db_config' in their config dictionary containing: - NAME: Database name (required) - USER: Database username (required) - PASSWORD: Database password (required) - HOST: Database host (required) - PORT: Database port (required) - ENGINE: Database engine (optional, defaults to master) - ALIAS: Database alias (optional, defaults to NAME) - TIME_ZONE: Database timezone (optional, inherits from settings)
Attributes:
| Name | Type | Description |
|---|---|---|
tenant |
BaseTenant
|
The tenant instance |
db_config |
CaseInsensitiveDict
|
Tenant's database configuration |
previous_schema |
str
|
Stores schema before activation (for deactivation) |
Source code in django_omnitenant/backends/database_backend.py
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 | |
create(run_migrations=False, **kwargs)
Provision a new database for the tenant.
This method creates the tenant's database on the configured database server, registers it with Django, and optionally runs initial migrations.
Process
- Get tenant's database alias and resolved configuration
- Create the database on the database server using PostgreSQL
- Call parent create() which:
- Calls bind() to register database in Django settings
- Emits tenant_created signal
- Optionally runs migrations if run_migrations=True
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
bool
|
Whether to run migrations after creation |
False
|
|
Additional arguments passed to parent create() |
{}
|
Raises:
| Type | Description |
|---|---|
Exception
|
If database creation fails (already exists, permission denied, etc.) |
Error
|
If database server connection fails |
Database Creation
Uses the psycopg driver (psycopg2 or psycopg3) to connect directly to PostgreSQL server and execute CREATE DATABASE statement.
Configuration
Database details from tenant.config['db_config']: - NAME: Database name to create - USER: Database user credentials for creation - PASSWORD: Database password - HOST: Database server host - PORT: Database server port
Workflow
- _create_database() → Creates DB on PostgreSQL server
- bind() → Registers in Django's DATABASES setting
- tenant_created signal → Notifies listeners
- migrate() → Runs initial schema if run_migrations=True
Error Handling
If database already exists or other errors occur:
try:
backend.create(run_migrations=True)
except Exception as e:
logger.error(f"Failed to create tenant database: {e}")
# Database may be partially created
# May need manual cleanup
Example
tenant = Tenant.objects.create(
tenant_id='acme',
config={
'db_config': {
'NAME': 'tenant_acme_db',
'USER': 'acme_user',
'PASSWORD': 'secret',
'HOST': 'db.example.com',
'PORT': 5432,
}
}
)
backend = DatabaseTenantBackend(tenant)
backend.create(run_migrations=True)
Performance
Database creation can take several seconds especially over network. Consider running in background task for large number of tenants.
See Also
- delete(): Remove tenant database
- bind(): Register database in Django
- migrate(): Run database migrations
Source code in django_omnitenant/backends/database_backend.py
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 | |
migrate(*args, **kwargs)
Run database migrations for the tenant's database.
This method executes Django's migrate management command within the tenant's database context, applying any pending migrations to the tenant's schema.
Process
- Get tenant's database alias and configuration
- Activate tenant context (switches to tenant's database)
- Run Django migrate command for that specific database
- Call parent migrate() which emits tenant_migrated signal
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
Positional arguments passed to migrate command - app_label: Migrate specific app (e.g., 'myapp') - migration_name: Migrate to specific migration (e.g., '0005_custom') |
()
|
|
|
Keyword arguments passed to migrate command - verbosity: Output verbosity (0-3) - interactive: Allow interactive prompts (default True) - run_syncdb: Create tables for apps without migrations (default False) |
{}
|
Raises:
| Type | Description |
|---|---|
Exception
|
If migration fails (syntax errors, conflicts, etc.) |
Signals
Emits: tenant_migrated(sender=Tenant, tenant=instance) Handlers can perform post-migration setup
Database Context
Uses TenantContext.use_tenant() to ensure all migration operations run against the tenant's specific database, not the master database.
Error Handling
If migration fails, the exception is caught and logged before re-raising. This ensures the failure is visible while still propagating the error.
try:
backend.migrate()
except Exception as e:
logger.error(f"Migration failed for {tenant.tenant_id}: {e}")
# Tenant database may be in inconsistent state
# May need to rollback or manual intervention
Usage Examples
backend = DatabaseTenantBackend(tenant)
# Run all pending migrations
backend.migrate()
# Migrate specific app
backend.migrate('myapp')
# Migrate to specific migration
backend.migrate(app_label='myapp', migration_name='0005_custom')
# With verbosity
backend.migrate(verbosity=2)
Management Command
Typically invoked via Django management command:
python manage.py migratetenant acme
python manage.py migratetenants
Workflow
- Get database alias for tenant
- Enter TenantContext for that tenant
- Call migrate command for that database only
- Emit tenant_migrated signal
- Exit context and return
Performance
- Large migrations may take significant time
- Database locks during migration
- Consider running during maintenance window
- Can migrate multiple tenants in parallel
See Also
- create(): Provision database and optionally migrate
- management commands: migratetenant, migratetenants
- tenant_migrated signal: For post-migration handlers
Source code in django_omnitenant/backends/database_backend.py
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |
delete(drop_db=False)
Tear down and optionally drop the tenant's database.
This method removes the tenant's database from Django settings and optionally drops it from the PostgreSQL server.
Process
- Get tenant's database alias and configuration
- Optionally drop the database from PostgreSQL server
- Remove database from Django's DATABASES setting
- Call parent delete() which emits tenant_deleted signal
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
bool
|
Whether to actually drop the database from PostgreSQL. Default is False (only remove from Django settings). Set to True to permanently delete the database. |
False
|
Raises:
| Type | Description |
|---|---|
Exception
|
If database drop fails (permission denied, active connections, etc.) |
Error
|
If PostgreSQL connection fails |
Destructive Operation
This operation CANNOT be recovered without backups! Always archive tenant data before deletion if compliance requires it.
Two-Step Deletion
The method supports soft and hard deletion:
- drop_db=False (default):
- Removes from Django settings
- Database remains on PostgreSQL server (can manually restore)
-
Allows recovery if deletion was accidental
-
drop_db=True:
- Actually drops database from PostgreSQL
- Data is gone (unless you have backups)
- Frees disk space and resources
Workflow
- Get database alias and configuration
- If drop_db=True: _drop_database() removes from PostgreSQL
- Remove from Django's DATABASES setting
- Emit tenant_deleted signal for cleanup handlers
Error Handling
Handle errors carefully during deletion:
try:
# First try soft delete (keeps data)
backend.delete(drop_db=False)
except Exception as e:
logger.error(f"Error removing from Django: {e}")
# Later, after confirming no issues:
try:
# Hard delete (remove data)
backend.delete(drop_db=True)
except Exception as e:
logger.error(f"Error dropping database: {e}")
# May need manual intervention
notify_administrators()
Active Connections
If the database has active connections, DROP DATABASE may fail. The implementation uses CASCADE or disconnects active sessions first.
Common causes of failures: - Applications still connecting to database - Open transactions - Scheduled jobs using database - IDE connections
Examples:
tenant = Tenant.objects.get(tenant_id='acme')
backend = DatabaseTenantBackend(tenant)
# Soft delete (for safety)
backend.delete(drop_db=False)
# Data remains, can be restored
# Later, hard delete (after confirming)
backend.delete(drop_db=True)
# Database is gone permanently
# Clean up model
tenant.delete()
Compliance & Archival: For GDPR/compliance requirements:
```python
# 1. Archive tenant data
archive_tenant_data(tenant)
# 2. Soft delete from Django
backend.delete(drop_db=False)
# 3. Verify no issues for X days
schedule_hard_delete.delay(tenant.id, delay=30)
# 4. Later, hard delete
def hard_delete_tenant(tenant_id):
tenant = Tenant.objects.get(id=tenant_id)
backend = DatabaseTenantBackend(tenant)
backend.delete(drop_db=True)
tenant.delete()
```
See Also
- create(): Provision database
- tenant_deleted signal: For cleanup handlers
- Archival strategies: For compliance
Source code in django_omnitenant/backends/database_backend.py
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 | |
bind()
Register tenant's database in Django's DATABASES setting.
This method makes the tenant's database available to Django for queries. After bind() is called, the database alias is registered and can be used with Django's database router and multi-database features.
Process
- Get tenant's database alias and resolved configuration
- Add/register database in Django's DATABASES setting
- Print confirmation message for logging
Configuration Resolution
The configuration is built by: 1. Getting tenant's db_config from tenant.config['db_config'] 2. Merging with master database settings as defaults 3. Respecting tenant-specific overrides
Example merged config: - ENGINE: Tenant-specific or master's - NAME: Tenant database name - USER: Tenant database user - PASSWORD: Tenant password - HOST: Tenant host or master's - PORT: Tenant port or master's - Options: Merged from both
Lifecycle
bind() is called: - During create() to register new database - During activate() to ensure database is available - Manually to update database settings
Effect
After bind() completes: - Database is in settings.DATABASES[db_alias] - Can be used with Django ORM (e.g., Model.objects.using(db_alias)) - Router can direct queries to it - Connections can be established to it
Examples:
tenant = Tenant.objects.get(tenant_id='acme')
backend = DatabaseTenantBackend(tenant)
# Bind the database
backend.bind()
# Now database is available in settings
assert 'acme_db' in settings.DATABASES
# Can use it with explicit routing
User.objects.using('acme_db').create(username='john')
# Or within TenantContext (automatic routing)
with TenantContext.use_tenant(tenant):
User.objects.create(username='john')
Dynamic Registration
Unlike static DATABASES configuration in settings.py, bind() registers databases at runtime. This allows: - Adding tenants without restarting application - Dynamically changing database credentials - Supporting unlimited number of tenants
Idempotency
Calling bind() multiple times is safe: - Later calls overwrite previous registration - No errors if database alias already exists - Can be used to update database configuration
See Also
- activate(): Switches connection to use this database
- get_alias_and_config(): Builds resolved configuration
- DatabaseTenantBackend: Full database lifecycle
Source code in django_omnitenant/backends/database_backend.py
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 | |
activate()
Switch to the tenant's database for the current context.
This method activates the tenant's database by: 1. Ensuring the database is bound (registered in Django settings) 2. Pushing the database alias onto the context stack 3. Saving current schema state for restoration on deactivate 4. Setting schema to 'public' to ensure consistency
Process
- Get database alias from tenant config
- If database not yet in Django settings, bind it
- Push database alias onto TenantContext stack
- Save current PostgreSQL schema name
- Set schema to 'public' for consistency
Lifecycle
Called when: - Entering TenantContext context manager - Request middleware starts request processing - Explicitly switching tenant
Database Alias Resolution
The alias is determined in order: 1. tenant.config['db_config']['ALIAS'] (explicit alias) 2. tenant.config['db_config']['NAME'] (use database name) 3. settings.MASTER_DB_ALIAS (fallback to master)
This allows flexibility in configuration.
Lazy Binding
If the database isn't already in DATABASES, activate() calls bind() to register it. This allows databases to be registered on-demand rather than all at startup.
Schema Management
When using database-per-tenant with PostgreSQL: - Each database has its own schemas - Setting schema to 'public' ensures consistency - Prevents cross-tenant data if schema-backend tenant exists - Saves previous schema for restoration on deactivate
Example scenario: - Request enters with schema 'tenant1_schema' - Tenant1 context activates (switches database) - Sets schema to 'public' in tenant1's database - On exit, restores previous schema
Context Stack
Uses TenantContext.push_db_alias() to maintain stack: - Supports nested tenant contexts - Proper cleanup on context exit - Thread-local so safe for concurrent requests
Examples:
from django_omnitenant.tenant_context import TenantContext
tenant = Tenant.objects.get(tenant_id='acme')
backend = DatabaseTenantBackend(tenant)
# Automatic via context manager (preferred)
with TenantContext.use_tenant(tenant):
# activate() called automatically
User.objects.all() # Queries tenant's database
# deactivate() called automatically
# Manual usage
backend.activate()
try:
User.objects.all()
finally:
backend.deactivate()
Performance
activate() is called for every request. Should be fast: - Only pushes alias onto context stack - Lazy binds database only if needed (usually cached) - Schema switching is fast PostgreSQL operation
Thread Safety
TenantContext uses thread-local storage so: - Each request thread has independent context - Concurrent requests don't interfere - Safe for multi-threaded application servers
Errors
If database connection fails: - Exception will be raised - Context is not fully activated - deactivate() won't be called - Caller must handle error
See Also
- deactivate(): Exit tenant context
- TenantContext: Context manager for activation
- bind(): Register database if not already done
Source code in django_omnitenant/backends/database_backend.py
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 | |
deactivate()
Exit the tenant's database context and restore previous state.
This method deactivates the tenant's database by: 1. Popping the database alias from the context stack 2. Restoring the previous PostgreSQL schema
Process
- Pop database alias from TenantContext stack
- Restore previous schema that was saved on activate
Lifecycle
Called when: - Exiting TenantContext context manager - Request middleware completes request processing - Explicitly exiting tenant context
Context Stack Management
Pops the database alias from the context stack maintained by TenantContext. This allows: - Nested contexts to work properly - Previous database to be restored - Proper cleanup even if multiple activations
Schema Restoration
Restores the PostgreSQL schema that was active before activate() was called. This is important for: - Proper isolation between operations - Preventing cross-tenant data leakage - Consistency when switching between databases
Examples:
from django_omnitenant.tenant_context import TenantContext
# Automatic via context manager (preferred)
with TenantContext.use_tenant(tenant):
# activate() called
User.objects.all()
# deactivate() called automatically, even on exception
# Manual usage
try:
backend.activate()
User.objects.all()
finally:
backend.deactivate() # Always called
Exception Safety
deactivate() should always be called, even if errors occur during the context. Similar to try/finally semantics:
backend.activate()
try:
# May raise exception
dangerous_operation()
finally:
# Guaranteed to run
backend.deactivate()
Error Handling
If deactivate() itself fails (database error, etc.): - Exception is raised but context is partially cleaned up - Previous schema restoration attempt was made - Database alias was removed from stack
Handle gracefully:
try:
backend.deactivate()
except Exception as e:
logger.error(f"Error deactivating tenant: {e}")
# Context is still partially cleaned up
Nested Contexts
With nested tenant contexts:
with TenantContext.use_tenant(tenant1):
# Activates tenant1's database
with TenantContext.use_tenant(tenant2):
# Activates tenant2's database
# Deactivates, back to tenant1
# Deactivates, back to master database
Each deactivate() restores the context from the previous level.
Performance
deactivate() is called for every request. Should be fast: - Only pops from context stack - Restores saved schema name - No expensive operations
Thread Safety
Thread-local TenantContext ensures: - Each thread maintains independent context - deactivate() in one thread doesn't affect others - Safe for concurrent request processing
See Also
- activate(): Enter tenant context
- TenantContext: Context manager for activation/deactivation
- Schema management: For consistent isolation
Source code in django_omnitenant/backends/database_backend.py
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 | |
get_alias_and_config(tenant)
classmethod
Build and return the database alias and fully resolved configuration for a tenant.
This method merges tenant-specific database configuration with master database settings to create a complete, ready-to-use Django database configuration.
Process
- Extract tenant's db_config from tenant.config['db_config']
- Determine database alias (from ALIAS, NAME, or MASTER_DB_ALIAS)
- Get base configuration from master database
- Merge tenant config with base, with tenant overrides taking precedence
- Handle special fields (TEST, OPTIONS, etc.)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
BaseTenant
|
Tenant instance to get configuration for |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
(db_alias, resolved_config) |
|
|
||
|
Configuration Precedence
For each setting, resolved config uses: 1. Tenant's db_config value if present 2. Master database value if tenant doesn't override 3. Django default if neither specified
Example:
TENANT db_config: {'NAME': 'tenant_db', 'HOST': 'db.example.com'}
MASTER DATABASES: {'NAME': 'master_db', 'HOST': 'localhost', 'PORT': 5432}
RESULT: {'NAME': 'tenant_db', 'HOST': 'db.example.com', 'PORT': 5432}
Alias Determination
Database alias is resolved in order: 1. tenant.config['db_config']['ALIAS'] - Explicit alias (preferred) 2. tenant.config['db_config']['NAME'] - Use database name as alias 3. settings.MASTER_DB_ALIAS - Fallback to master (shouldn't happen)
Configuration Fields
The resolved config includes all Django database settings:
- ENGINE: Database backend module
- NAME: Database name (required)
- USER: Database user
- PASSWORD: Database password
- HOST: Database host
- PORT: Database port
- OPTIONS: Database-specific options
- TIME_ZONE: Timezone for this database
- ATOMIC_REQUESTS: Atomic request wrapping
- AUTOCOMMIT: Autocommit mode
- CONN_MAX_AGE: Connection pool age
- CONN_HEALTH_CHECKS: Enable health checks
- TEST: Test database configuration
Test Database Configuration
The TEST dictionary is special: - Merged from both tenant and master configs - Default NAME is set to resolved['NAME'] if not specified - Allows per-tenant test database customization
Examples:
from myapp.models import Tenant
from django_omnitenant.backends.database_backend import DatabaseTenantBackend
tenant = Tenant.objects.create(
tenant_id='acme',
config={
'db_config': {
'NAME': 'acme_db',
'USER': 'acme_user',
'PASSWORD': 'secret',
'HOST': 'db.example.com',
'ALIAS': 'acme', # Optional
}
}
)
alias, config = DatabaseTenantBackend.get_alias_and_config(tenant)
# Returns: ('acme', {'ENGINE': ..., 'NAME': 'acme_db', ...})
# Without explicit ALIAS
alias, config = DatabaseTenantBackend.get_alias_and_config(tenant)
# Returns: ('acme_db', {...}) # Uses NAME as alias
# With minimal config (uses master defaults)
tenant.config = {'db_config': {'NAME': 'minimal_db'}}
alias, config = DatabaseTenantBackend.get_alias_and_config(tenant)
# Returns: ('minimal_db', {
# 'ENGINE': 'django.db.backends.postgresql', # From master
# 'NAME': 'minimal_db',
# 'HOST': 'localhost', # From master
# 'PORT': 5432, # From master
# ...
# })
Error Handling
If required fields are missing: - NAME is required but will be missing if not in tenant or master config - USER, PASSWORD, HOST, PORT should come from master if not overridden - Missing values will cause connection errors later
Performance
This is a fast operation (dict merging): - Called frequently during request processing - Cached implicitly by TenantContext - No database queries
See Also
- init(): Uses get_alias_and_config for initial setup
- create(): Uses to get database name for creation
- bind(): Uses to register database in Django
- activate(): Uses to get database alias for routing
Source code in django_omnitenant/backends/database_backend.py
873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 | |