Skip to content

Database Providers

Database providers abstract the underlying persistence technology, allowing Protean to support various databases without changing domain or application logic. Each provider implements DatabasePort and declares the capabilities it supports.

Overview

The Database port in Protean provides a unified interface for different database technologies. Each provider adapter implements this interface while exposing the unique features of its underlying technology. Protean ships a memory provider that is active by default, so you can develop and test your entire domain model without running any external services.

Available Providers

Memory

The memory provider stores data in Python dictionaries. It is the default provider and requires no external dependencies.

  • Use cases: Development, testing, prototyping
  • Capabilities: Basic storage, simulated transactions, optimistic locking, raw queries
  • No external dependencies required

Memory provider reference

PostgreSQL

The postgresql provider uses SQLAlchemy to communicate with PostgreSQL databases.

  • Use cases: Production environments requiring full relational capabilities
  • Capabilities: Full relational set including native JSON and array columns
  • Requires: psycopg 3 (protean[postgresql]) or psycopg2 (protean[postgresql-psycopg2])

PostgreSQL provider reference

SQLite

The sqlite provider uses SQLAlchemy with Python's built-in sqlite3 module.

  • Use cases: Local development, testing with real SQL semantics
  • Capabilities: Full relational set (excluding native JSON and array)
  • No external dependencies required (SQLite is part of the Python standard library)

SQLite provider reference

MSSQL

The mssql provider uses SQLAlchemy with pyodbc to communicate with Microsoft SQL Server.

  • Use cases: Production environments on SQL Server
  • Capabilities: Full relational set, including JSON and array columns
  • Requires: pyodbc and a Microsoft ODBC driver installed on the machine

MSSQL provider reference

MySQL

The mysql provider uses SQLAlchemy with PyMySQL to communicate with MySQL and MariaDB. One provider serves both servers.

  • Use cases: Production environments on MySQL or MariaDB
  • Capabilities: Full relational set plus JSON columns. MySQL has no array type, so a List field is stored as JSON
  • Requires: pymysql, which installs from a wheel everywhere

MySQL provider reference

Elasticsearch

The elasticsearch provider uses the DSL bundled with the Elasticsearch client for document store operations.

  • Use cases: Search and analytics workloads, document-oriented storage
  • Capabilities: Basic storage, schema management, optimistic locking
  • Requires: elasticsearch (8.18 or newer, which ships elasticsearch.dsl)

Elasticsearch provider reference

Configuration

Providers are configured in your domain configuration file (domain.toml or .domain.toml):

# Default database configuration (required)
[databases.default]
provider = "memory"

# Additional named databases
[databases.analytics]
provider = "elasticsearch"
database_uri = { hosts = ["${ELASTICSEARCH_HOST|http://localhost:9200}"] }

[databases.reporting]
provider = "postgresql"
database_uri = "${DATABASE_URL|postgresql://postgres:postgres@localhost:5432/reports}"

${ELASTICSEARCH_HOST|...} and ${DATABASE_URL|...} read the host and the URI from those environment variables, and use the value after | when a variable is not set.

Each database configuration must specify:

  • provider: The provider adapter to use (memory, postgresql, sqlite, mssql, mysql, elasticsearch, or a third-party provider name)
  • Additional provider-specific options (like database_uri for non-memory providers)

Important

You must define a default database in your configuration. This database will be used for all aggregates unless a specific database is requested.

Database Capabilities

Providers declare their capabilities through a flag-based system. Broker capabilities form hierarchical tiers, but database capabilities are orthogonal: each provider declares any subset of capabilities it supports. You can combine individual flags freely.

Capability Flags

Capabilities are organized into five tiers, plus a group of claim and delete flags:

Tier 1: Universal Foundation, Every provider supports these.

Flag Description
CRUD Create, Read, Update, Delete single records
FILTER Query/filter records with lookup criteria
BULK_OPERATIONS update_all(), delete_all()
ORDERING Server-side ORDER BY support

Tier 2: Data Integrity

Flag Description
TRANSACTIONS Real commit/rollback atomicity (database-level ACID)
SIMULATED_TRANSACTIONS Copy-on-write UoW semantics (no true rollback)
OPTIMISTIC_LOCKING Version-based concurrency control

Tier 3: Query Power

Flag Description
RAW_QUERIES Execute raw/native queries (SQL, JSON criteria, DSL)

Tier 4: Infrastructure

Flag Description
SCHEMA_MANAGEMENT Create/drop tables, indices, or storage structures
CONNECTION_POOLING Connection pool management
SCHEMA_MIGRATIONS Versioned schema migrations, kept in the folder protean db init creates

Tier 5: Type System

Flag Description
NATIVE_JSON Native JSON column support (e.g. PostgreSQL JSONB)
NATIVE_ARRAY Native array column support (e.g. PostgreSQL ARRAY)

Claim, delete and insert-if-absent

No convenience set includes these flags. Each provider declares them on its own.

Flag Description
NATIVE_CLAIM Claims rows in one statement
BOUNDED_DELETE Deletes up to limit rows in one operation, without a separate read of their ids
FILTERED_CLAIM_CANDIDATES Leaves held rows out of a claim's candidates
INSERT_IF_ABSENT Writes a row only when no other row holds its unique key, in one atomic step

Convenience Sets

Common capability combinations are bundled as convenience sets:

Set Included Flags
BASIC_STORAGE CRUD, FILTER, BULK_OPERATIONS, ORDERING
IN_MEMORY BASIC_STORAGE, SIMULATED_TRANSACTIONS, OPTIMISTIC_LOCKING, RAW_QUERIES
RELATIONAL BASIC_STORAGE, TRANSACTIONS, OPTIMISTIC_LOCKING, RAW_QUERIES, SCHEMA_MANAGEMENT, CONNECTION_POOLING
DOCUMENT_STORE BASIC_STORAGE, SCHEMA_MANAGEMENT, OPTIMISTIC_LOCKING

Checking Capabilities at Runtime

You can check provider capabilities with in and & on provider.capabilities. in with one flag, or with a set of flags joined by |, is true when the provider declares all of them. & with a set of flags is true when the provider declares at least one of them:

from protean import Domain
from protean.fields import Integer, String
from protean.port.database import DatabaseCapabilities

domain = Domain(name="Capabilities")


@domain.aggregate
class User:
    name: String(max_length=50, required=True)
    age: Integer(required=True)


domain.init(traverse=False)

with domain.domain_context():
    domain.repository_for(User).add(User(name="Ada", age=36))
    domain.repository_for(User).add(User(name="Tim", age=17))

    # Get the default provider
    provider = domain.databases["default"]

    # Check for a single capability
    if DatabaseCapabilities.RAW_QUERIES in provider.capabilities:
        # The query language is the provider's own. The memory provider
        # takes JSON filter criteria; a SQL provider takes SQL.
        results = provider.raw('{"age__gt": 21}')

    # Check for all of multiple capabilities (AND logic)
    if (
        DatabaseCapabilities.NATIVE_JSON | DatabaseCapabilities.NATIVE_ARRAY
    ) in provider.capabilities:
        # Use native JSON and array columns
        ...

    # Check for any of multiple capabilities (OR logic)
    if provider.capabilities & (
        DatabaseCapabilities.TRANSACTIONS | DatabaseCapabilities.SIMULATED_TRANSACTIONS
    ):
        # Some form of transaction support is available
        ...

On the memory provider, results holds one record, Ada's.

Note

QuerySet.raw() reads through the DAO service's raw(), which checks for RAW_QUERIES and raises NotSupportedError when the provider does not declare it. A provider without its own raw(), such as Elasticsearch, raises NotSupportedError from provider.raw(). You only need to check capabilities explicitly when writing code that adapts its behavior based on what is available.

Provider Capability Matrix

| | Memory | SQLite | PostgreSQL | MSSQL | MySQL | Elasticsearch | |— |:------:|:------:|:----------:|:-----:|:-----:|:-------------:| | CRUD | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | FILTER | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | BULK_OPERATIONS | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | ORDERING | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | TRANSACTIONS | | ✅ | ✅ | ✅ | ✅ | | | SIMULATED_TRANSACTIONS | ✅ | | | | | | | OPTIMISTIC_LOCKING | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | RAW_QUERIES | ✅ | ✅ | ✅ | ✅ | ✅ | | | SCHEMA_MANAGEMENT | | ✅ | ✅ | ✅ | ✅ | ✅ | | CONNECTION_POOLING | | ✅ | ✅ | ✅ | ✅ | | | SCHEMA_MIGRATIONS | | ✅ | ✅ | ✅ | ✅ | | | NATIVE_JSON | | | ✅ | ✅ | ✅ | | | NATIVE_ARRAY | | | ✅ | ✅ | | | | NATIVE_CLAIM | | | ✅ | | | | | BOUNDED_DELETE | ✅ | ✅ | ✅ | ✅ | | ✅ | | FILTERED_CLAIM_CANDIDATES | | ✅ | ✅ | ✅ | ✅ | | | INSERT_IF_ABSENT | ✅ | ✅ | ✅ | ✅ | ✅ | |

Provider Registry

Providers register themselves through Python entry points under the protean.databases group. This means third-party database adapters can be pip-installed and automatically discovered by Protean without any source code changes.

Built-in Entry Points

Protean's built-in providers are registered in pyproject.toml:

# fragment
[project.entry-points."protean.databases"]
memory = "protean.adapters.database.memory:register"
postgresql = "protean.adapters.database.sqlalchemy:register_postgresql"
sqlite = "protean.adapters.database.sqlalchemy:register_sqlite"
mssql = "protean.adapters.database.sqlalchemy:register_mssql"
mysql = "protean.adapters.database.sqlalchemy:register_mysql"
elasticsearch = "protean.adapters.database.elasticsearch:register"

Each entry point maps a provider name to a register() function. The function is called on first access and registers the provider class path with protean.infra.registry.databases, the AdapterRegistry for database providers. A register() function for a provider with optional dependencies imports them inside try/except, so it silently skips registering that provider when those dependencies are not installed.

Third-Party Providers

External packages can register their own providers by adding an entry point in their pyproject.toml:

# fragment
[project.entry-points."protean.databases"]
dynamodb = "my_package:register"

After pip install my-package, the provider becomes available:

# fragment
[databases.default]
provider = "dynamodb"
database_uri = "dynamodb://localhost:8000"

See Building Custom Database Adapters for a complete guide.

Required Lookups

Every provider must register a minimum set of 12 standard lookups that power Protean's filtering API. Protean checks these lookups when it first loads a provider, and raises ConfigurationError naming the missing lookups when the provider class lacks any of them. It raises ConfigurationError too when a required lookup is registered as a class that does not subclass LookupPort. A filter that uses a lookup the provider does not register raises NotImplementedError.

Lookup Example
exact name='John'
iexact name__iexact='john'
contains name__contains='oh'
icontains name__icontains='oh'
startswith name__startswith='Jo'
endswith name__endswith='hn'
gt age__gt=21
gte age__gte=21
lt age__lt=65
lte age__lte=65
in status__in=['active', 'pending']
isnull status__isnull=True / status__isnull=False

The isnull lookup resolves to IS NULL / IS NOT NULL predicates (or the adapter's equivalent, such as Elasticsearch's exists query). It is required because core framework machinery, including the outbox poll path, depends on it.

Providers may register additional lookups beyond this required set.

Choosing and configuring a provider

  1. A default database is required, even if it is only the memory provider for development.

  2. Start with in-memory, switch later: Develop and test with the memory provider, then switch to a production database by changing configuration only.

  3. Check capabilities before using advanced features: Not all providers support raw queries, native JSON, or native array columns.

  4. Use appropriate providers for different concerns:

    • Memory for fast unit tests
    • SQLite for local development with real SQL
    • PostgreSQL for production
    • Elasticsearch for search-heavy read models
  5. Let Protean auto-generate database models: Only supply a custom @domain.database_model when you need to customize column types, indices, or other database-specific details.

  6. Monitor provider health: Use provider.ping() to verify connectivity during health checks.

Indexes

Aggregates and entities declare the indexes their query paths need with the indexes= option (see Indexes). The portable subset (composite, descending, unique, and named indexes) is honored by every SQL provider; opt-in features degrade gracefully where a dialect cannot support them:

Feature PostgreSQL SQLite SQL Server Memory Elasticsearch
Composite / unique / desc ✅ ✅ ✅ advisory —
Partial (where=) ✅ ✅ ⚠️ advisory —
Covering (include=) ✅ ⚠️ ✅ advisory —

⚠️ = falls back to a full index with a logged warning. The memory provider validates declarations but does not enforce them.

Read the tables a SQL provider owns

Every SQL provider (PostgreSQL, SQLite, MSSQL, MySQL) has a metadata property. It returns the SQLAlchemy MetaData object that holds the table of every aggregate, entity and projection the provider owns. Tools such as a schema migration tool read it to compare the tables your domain declares with the tables in the database.

from protean import Domain
from protean.fields import String

domain = Domain(name="Tables")
domain.config["databases"]["default"] = {
    "provider": "sqlite",
    "database_uri": "sqlite:///:memory:",
}


@domain.aggregate
class Customer:
    name: String(max_length=50, required=True)


domain.init(traverse=False)

with domain.domain_context():
    provider = domain.databases["default"]
    for table in provider.metadata.sorted_tables:
        print(table.schema, table.name)  # None customer

The property holds:

  • a table for each aggregate, entity and projection stored by this provider;
  • the outbox table, when the domain uses the outbox;
  • the processed_message table, when a projector or subscriber is declared with idempotent=True.

It holds no table for an event-sourced aggregate or its entities, a projection stored in a cache, an element registered with abstract=True, or an element assigned to another provider. A provider with managed = false has no outbox or processed_message table in it, because Protean does not create those tables on an unmanaged database.

Each table takes the schema set by the provider's schema key. Without the key, tables take public on PostgreSQL, dbo on MSSQL, and no schema on SQLite and MySQL.

Reading the property builds the table definitions without connecting to the database. It returns the same list after domain.drop_database(). Read it after domain.init().

The returned object is the one the provider's models use. Do not add tables to it or remove tables from it.