Skip to main content

Schema-driven MongoDB database module with auto-generated repositories

Project description

tc-db-base - Schema-Driven Database Service

A flexible, schema-driven database module that auto-generates repositories with CRUD operations, search functions, and index management based on a JSON schema.

Installation

# Install from PyPI
pip install tc-db-base

# Or with Flask support
pip install tc-db-base[flask]

Features

  • Schema-Driven: Define collections in dbs.json, get auto-generated methods
  • Auto-Generated Finders: find_by_{field}() for unique/searchable fields
  • Validation: Automatic validation against schema
  • Soft Delete: Optional soft delete support per collection
  • Timestamps: Auto-managed created_at / updated_at
  • Index Management: Auto-create indexes from schema
  • Search: Built-in search across searchable fields

Quick Start

from tc_db_base import init_db, get_repository

# Initialize and connect
db = init_db()

# Get auto-generated repository
users = get_repository('users')

# Create (with auto-validation and timestamps)
user_id = users.create({
    'user_key': 'usr_123',
    'account_key': 'acc_456',
    'email': 'john@example.com',
    'password': 'hashed_password',
    'name': 'John Doe'
})

# Auto-generated finders (from unique_fields)
user = users.find_by_user_key('usr_123')
user = users.find_by_email('john@example.com')

# Auto-generated finders (from searchable_fields)
users_list = users.find_by_account_key('acc_456')

# Search across searchable fields
results = users.search('john', limit=10)

# Standard CRUD
user = users.find_by_id(user_id)
users.update_by_id(user_id, {'name': 'John Smith'})
users.delete_by_id(user_id)  # Soft delete if enabled

Schema Definition (dbs.json)

{
  "dbs": {
    "user_db": {
      "users": {
        "description": "User accounts",
        "fields": {
          "user_key": {"type": "string", "required": true},
          "email": {"type": "string", "required": true, "format": "email"},
          "name": {"type": "string"},
          "status": {"type": "string", "enum": ["active", "inactive"], "default": "active"},
          "created_at": {"type": "datetime", "auto": "create"},
          "updated_at": {"type": "datetime", "auto": "update"}
        },
        "unique_fields": ["user_key", "email"],
        "indexes": {
          "user_key_idx": {"fields": ["user_key"], "unique": true},
          "email_idx": {"fields": ["email"], "unique": true}
        },
        "searchable_fields": ["user_key", "email", "name"],
        "soft_delete": true,
        "timestamps": true
      }
    }
  }
}

Auto-Generated Methods

For each collection, these methods are auto-generated:

CRUD Operations

repo.create(data)                    # Insert with validation
repo.create_many(documents)          # Bulk insert
repo.find_by_id(id)                  # Find by _id
repo.find_one(query)                 # Find single
repo.find_many(query, skip, limit)   # Find multiple
repo.update_one(query, data)         # Update single
repo.update_by_id(id, data)          # Update by ID
repo.delete_one(query)               # Delete (soft if enabled)
repo.delete_by_id(id)                # Delete by ID
repo.hard_delete(query)              # Permanent delete
repo.restore(query)                  # Restore soft-deleted
repo.count(query)                    # Count documents
repo.exists(query)                   # Check existence

Dynamic Finders (auto-generated from schema)

# For unique_fields: ["user_key", "email"]
repo.find_by_user_key(value)         # Returns single doc
repo.find_by_email(value)            # Returns single doc

# For searchable_fields: ["account_key", "name"]
repo.find_by_account_key(value)      # Returns list
repo.find_by_name(value)             # Returns list

Search & Aggregation

repo.search(text, fields, limit)     # Search searchable_fields
repo.search_by_fields(field=value)   # Multi-field search
repo.aggregate(pipeline)             # Run aggregation
repo.group_by(field, match)          # Group by field
repo.count_by(field)                 # Count grouped
repo.distinct(field, query)          # Distinct values

Index Management

repo.ensure_indexes()                # Create indexes from schema
repo.get_indexes()                   # List current indexes

Field Types

Type Python Type Description
string str Text values
number int/float Numeric values
boolean bool True/False
array list Lists
object dict Nested objects
datetime datetime Timestamps

Field Options

Option Description
required Field is mandatory
default Default value
enum Allowed values list
format Validation format (email, url, phone)
sensitive Excluded from query results
auto Auto-set: "create" or "update"

REST API (Standalone Server)

# Using module
python -m tc_db_base.server --port 5002

# Or using installed command
tc-db-server --port 5002

Endpoints

GET  /health                         # Health check
GET  /schema                         # Full schema
GET  /schema/{collection}            # Collection schema

GET  /api/v1/{collection}            # List documents
GET  /api/v1/{collection}/{id}       # Get by ID
POST /api/v1/{collection}            # Create
PUT  /api/v1/{collection}/{id}       # Update
DELETE /api/v1/{collection}/{id}     # Delete

GET  /api/v1/{collection}/search?q=text  # Search
POST /api/v1/{collection}/aggregate      # Aggregation
GET  /api/v1/{collection}/count-by/{field}  # Count by field

Project Structure

tc_db_base/
├── __init__.py          # Package exports
├── client.py            # MongoDB client
├── service.py           # DatabaseService
├── repository.py        # DynamicRepository
├── server.py            # REST API server
└── schema/
    ├── __init__.py      # SchemaLoader
    ├── validator.py     # SchemaValidator
    └── dbs.json         # Database schema

Configuration

Uses task_circuit_base for configuration (if available), otherwise falls back to environment variables.

Schema files are loaded from (in priority order):

  1. SCHEMA_PATH environment variable
  2. {cwd}/resources/schema/
  3. Parent directories /resources/schema/
  4. Package default tc_db_base/schema/
# Via environment variables
MONGO_URI=mongodb://localhost:27017
SCHEMA_PATH=/path/to/custom/schema

# Via resources/config.yaml (if using task_circuit_base)
database:
  mongo_uri: mongodb://localhost:27017
  connection:
    max_pool_size: 100

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tc_db_base-0.0.2.tar.gz (20.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tc_db_base-0.0.2-py3-none-any.whl (19.7 kB view details)

Uploaded Python 3

File details

Details for the file tc_db_base-0.0.2.tar.gz.

File metadata

  • Download URL: tc_db_base-0.0.2.tar.gz
  • Upload date:
  • Size: 20.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tc_db_base-0.0.2.tar.gz
Algorithm Hash digest
SHA256 0316c16619ef7a76840f89704bdbe9f80d94a3425fcdb0afb6c5b2a803ec6c2e
MD5 8480bce9b8acdc46f4e3b3ed331ad810
BLAKE2b-256 fc7d17444c8772feb8e67b332f1cfed0a3d730e1a14251dad68437f17dca5eae

See more details on using hashes here.

Provenance

The following attestation bundles were made for tc_db_base-0.0.2.tar.gz:

Publisher: publish.yml on task-circuit/tc-db-base

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file tc_db_base-0.0.2-py3-none-any.whl.

File metadata

  • Download URL: tc_db_base-0.0.2-py3-none-any.whl
  • Upload date:
  • Size: 19.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for tc_db_base-0.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 001a7a40f725c154edddaa32c7417446376349990656c24c33b35acd1e262ca1
MD5 f59b0791bc0e87d330f7d90f6aecf491
BLAKE2b-256 9417373007f536412905edcbedbcd038e6e32e29ea461b2a05c3ffcd5f5b545d

See more details on using hashes here.

Provenance

The following attestation bundles were made for tc_db_base-0.0.2-py3-none-any.whl:

Publisher: publish.yml on task-circuit/tc-db-base

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page