Skip to content

Memory Provider

The Memory provider is an in-memory database adapter that stores data in Python dictionaries. It is the default provider in Protean and requires no external dependencies.

Overview

The Memory provider is designed for:

  • Development environments where simplicity and speed are key
  • Testing scenarios where deterministic behavior is required
  • Prototyping when you want to defer technology decisions
  • CI pipelines that should run without external services

The Memory provider stores data using Python dictionaries protected by threading locks:

  • Records are kept in defaultdict(dict) keyed by entity class name
  • Thread-safe access via Lock for concurrent operations
  • All data is lost when the process terminates

Because it is the default provider, no configuration is needed at all: a fresh domain uses the Memory provider automatically.

Configuration

[databases.default]
provider = "memory"

Configuration Options

Option Default Description
provider Required Must be "memory" for the Memory provider

No other options are needed. There is no connection URI, no pool size, no schema, just provider = "memory".

Capabilities

The Memory provider supports the following capabilities:

  • ✅ CRUD: Create, Read, Update, Delete single records
  • ✅ FILTER: Query/filter records with lookup criteria
  • ✅ BULK_OPERATIONS: update_all(), delete_all()
  • ✅ ORDERING: Server-side ordering of results
  • ✅ SIMULATED_TRANSACTIONS: Copy-on-write UoW semantics
  • ✅ OPTIMISTIC_LOCKING: Version-based concurrency control
  • ✅ RAW_QUERIES: JSON-string query criteria
  • ❌ TRANSACTIONS: No real database-level atomicity
  • ❌ SCHEMA_MANAGEMENT: No tables or indices to manage
  • ❌ CONNECTION_POOLING: No external connections
  • ❌ SCHEMA_MIGRATIONS: No schema to migrate
  • ❌ NATIVE_JSON: No native JSON column type
  • ❌ NATIVE_ARRAY: No native array column type
  • ✅ BOUNDED_DELETE: Deletes up to limit rows in one operation, without a separate read of their ids
  • ❌ NATIVE_CLAIM: Claims rows in one statement
  • ❌ 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

Note

The Memory provider uses simulated transactions, not real ones. Within a Unit of Work, changes are tracked and applied on commit, but a rollback only discards uncommitted changes. It cannot undo side effects that already happened in the Python process.

Indexes

The memory provider accepts Index declarations and validates them for shape at Domain.init(). Non-unique indexes are advisory, because the in-memory store performs no index-backed lookups. Unique indexes (Index(..., unique=True)), however, are enforced: a duplicate insert or update that violates a single-column or composite unique index raises ValidationError. Protean raises the same error for a field-level unique=True. A SQL backend rejects the duplicate at the database instead. NULLs are treated as distinct (PostgreSQL/SQLite semantics). Because the memory provider accepts these index declarations, you can declare the indexes your aggregates need, develop against the memory provider, and switch to a SQL backend without changing the domain.

Raw Queries

The Memory provider supports raw queries through JSON-string criteria that are evaluated against in-memory records:

from protean import Domain
from protean.fields import Integer, String

domain = Domain(name="MemoryRaw")


@domain.aggregate
class User:
    name: String(max_length=50, required=True)
    age: Integer(required=True)
    status: String(max_length=10, default="active")


domain.init(traverse=False)

with domain.domain_context():
    repo = domain.repository_for(User)
    repo.add(User(name="Ada", age=36))
    repo.add(User(name="Tim", age=17))
    repo.add(User(name="Lin", age=40, status="inactive"))

    results = domain.databases["default"].raw('{"age__gt": 21, "status": "active"}')

results holds one record, Ada's. Tim is too young and Lin is inactive.

The query string is parsed as JSON and interpreted as filter criteria using the same lookup syntax as the QuerySet API.

Datetime lookups

exact, in, lt, lte, gt, gte, any and overlap compare two datetimes as UTC instants, so 12:00+00:00 equals 14:00+02:00. A naive datetime on either side is read as UTC. contains, startswith and endswith compare the string form, and so does a datetime filtered with a string.

Limitations

  • No Persistence: Data is lost on process restart. The Memory provider is purely ephemeral.
  • No Real Transactions: Simulated transactions commit atomically and roll back uncommitted changes, but only within one Python process, and nothing is durable.
  • No Distribution: All data lives in a single Python process. Cannot scale across multiple processes or machines.
  • No Schema Management: There are no tables or indices to create or drop. create_schema() and drop_schema() are no-ops.
  • No Native JSON/Array: Complex fields are stored as serialized Python objects, not as native database types.

Migration Path

The Memory provider is designed to be easily replaced with production-ready providers:

# Development configuration (default)
[databases.default]
provider = "memory"

In production, switch the provider:

[databases.default]
provider = "postgresql"
database_uri = "${DATABASE_URL|postgresql://user:pass@db.example.com:5432/myapp}"

${DATABASE_URL|...} reads the URI from the DATABASE_URL environment variable, and uses the value after | when it is not set.

All providers implement the same DatabasePort protocol, so your domain code stays the same when you switch providers. To switch, update the configuration, and Protean uses the new provider.