Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /TrueSelph_jvspatial /jvspatial /db /factory.py
| """Simplified database creation utilities. | |
| This module provides simple utilities for creating database instances, | |
| replacing the complex factory pattern with direct instantiation. | |
| Includes integration with DatabaseManager for multi-database support. | |
| Supports custom database registration for seamless extension. | |
| """ | |
| from typing import Any, Callable, Dict, Optional | |
| from ._cache import CachingDatabase | |
| from ._observable import DEFAULT_SLOW_QUERY_MS, ObservableDatabase | |
| from .database import Database | |
| from .jsondb import JsonDB | |
| from .manager import get_database_manager | |
| try: # Optional dependency (requires aiosqlite) | |
| from .sqlite import SQLiteDB # noqa: F401 | |
| _SQLITE_AVAILABLE = True | |
| except ImportError: # pragma: no cover - dependency missing | |
| SQLiteDB = None # type: ignore[misc,assignment] | |
| _SQLITE_AVAILABLE = False | |
| try: # Optional dependency (requires aioboto3) | |
| from .dynamodb import DynamoDB # noqa: F401 | |
| _DYNAMODB_AVAILABLE = True | |
| except ImportError: # pragma: no cover - dependency missing | |
| DynamoDB = None # type: ignore[misc,assignment] | |
| _DYNAMODB_AVAILABLE = False | |
| try: # Optional dependency (requires asyncpg) | |
| from .postgres import PostgresDB # noqa: F401 | |
| _POSTGRES_AVAILABLE = True | |
| except ImportError: # pragma: no cover - dependency missing | |
| PostgresDB = None # type: ignore[misc,assignment] | |
| _POSTGRES_AVAILABLE = False | |
| # Registry for custom database implementations | |
| _DATABASE_REGISTRY: Dict[str, Callable[..., Database]] = {} | |
| def register_database_type(db_type: str, factory: Callable[..., Database]) -> None: | |
| """Register a custom database type for use with create_database(). | |
| This allows you to seamlessly integrate custom database implementations | |
| into the jvspatial factory system. Once registered, your custom database | |
| can be created using create_database() just like built-in types. | |
| Args: | |
| db_type: Unique identifier for the database type (e.g., 'redis', 'postgresql') | |
| factory: Factory function that creates a Database instance. | |
| Should accept **kwargs and return a Database instance. | |
| Example: | |
| ```python | |
| from jvspatial.db import Database, register_database_type, create_database | |
| class MyCustomDB(Database): | |
| def __init__(self, connection_string: str): | |
| self.connection_string = connection_string | |
| # ... implement abstract methods ... | |
| def create_my_custom_db(**kwargs): | |
| return MyCustomDB(kwargs.get("connection_string", "default://")) | |
| # Register the custom database | |
| register_database_type("my_custom", create_my_custom_db) | |
| # Now use it like built-in types | |
| db = create_database("my_custom", connection_string="custom://example") | |
| ``` | |
| Raises: | |
| ValueError: If db_type is already registered or conflicts with built-in types | |
| """ | |
| if db_type in ("json", "mongodb", "sqlite", "dynamodb", "postgres", "postgresql"): | |
| raise ValueError(f"Cannot register '{db_type}' - it's a built-in database type") | |
| if db_type in _DATABASE_REGISTRY: | |
| raise ValueError( | |
| f"Database type '{db_type}' is already registered. " | |
| "Use unregister_database_type() first to replace it." | |
| ) | |
| _DATABASE_REGISTRY[db_type] = factory | |
| def unregister_database_type(db_type: str) -> None: | |
| """Unregister a custom database type. | |
| Args: | |
| db_type: Database type identifier to unregister | |
| Raises: | |
| ValueError: If db_type is not registered or is a built-in type | |
| """ | |
| if db_type in ("json", "mongodb", "sqlite", "dynamodb", "postgres", "postgresql"): | |
| raise ValueError( | |
| f"Cannot unregister '{db_type}' - it's a built-in database type" | |
| ) | |
| if db_type not in _DATABASE_REGISTRY: | |
| raise ValueError(f"Database type '{db_type}' is not registered") | |
| del _DATABASE_REGISTRY[db_type] | |
| def list_database_types() -> Dict[str, str]: | |
| """List all available database types (built-in and registered). | |
| Returns: | |
| Dictionary mapping database type names to their descriptions | |
| """ | |
| types = { | |
| "json": "JSON file-based database (built-in)", | |
| "mongodb": "MongoDB database (built-in)", | |
| } | |
| if _SQLITE_AVAILABLE: | |
| types["sqlite"] = "SQLite database (built-in)" | |
| else: | |
| types["sqlite"] = "SQLite database (requires aiosqlite)" | |
| if _DYNAMODB_AVAILABLE: | |
| types["dynamodb"] = "DynamoDB database (built-in, for AWS Lambda)" | |
| else: | |
| types["dynamodb"] = "DynamoDB database (requires aioboto3)" | |
| if _POSTGRES_AVAILABLE: | |
| types["postgres"] = ( | |
| "PostgreSQL database (built-in, recommended high-performance backend)" | |
| ) | |
| types["postgresql"] = "Alias for 'postgres'" | |
| else: | |
| types["postgres"] = "PostgreSQL database (requires asyncpg)" | |
| for db_type, factory in _DATABASE_REGISTRY.items(): | |
| types[db_type] = f"Custom database: {factory.__name__}" | |
| return types | |
| def _instantiate_builtin_database( | |
| db_type: str, | |
| **kwargs: Any, | |
| ) -> Database: | |
| """Create a built-in database backend from env/defaults merged with ``kwargs``.""" | |
| from jvspatial.env import env, resolve_db_paths | |
| if db_type == "json": | |
| jsondb_path, _ = resolve_db_paths() | |
| base_path = kwargs.get("base_path") or kwargs.get("db_path") or jsondb_path | |
| return JsonDB(str(base_path)) | |
| if db_type == "mongodb": | |
| from .mongodb import MongoDB | |
| kw = dict(kwargs) | |
| if "uri" not in kw: | |
| kw["uri"] = kw.pop("connection_string", None) or kw.pop( | |
| "db_connection_string", None | |
| ) | |
| if "db_name" not in kw: | |
| kw["db_name"] = kw.pop("database_name", None) | |
| if "uri" not in kw: | |
| kw["uri"] = env( | |
| "JVSPATIAL_MONGODB_URI", default="mongodb://localhost:27017" | |
| ) | |
| if "db_name" not in kw: | |
| kw["db_name"] = env("JVSPATIAL_MONGODB_DB_NAME", default="jvdb") | |
| if "max_pool_size" not in kw: | |
| kw["max_pool_size"] = env("JVSPATIAL_MONGODB_MAX_POOL_SIZE", parse=int) | |
| if "min_pool_size" not in kw: | |
| kw["min_pool_size"] = env("JVSPATIAL_MONGODB_MIN_POOL_SIZE", parse=int) | |
| return MongoDB(**kw) | |
| if db_type == "sqlite": | |
| if not _SQLITE_AVAILABLE: | |
| raise ImportError( | |
| "aiosqlite is required for SQLite support. Install it with: pip install aiosqlite" | |
| ) | |
| sqlite_kwargs = dict(kwargs) | |
| _, sqlite_default = resolve_db_paths() | |
| db_path = ( | |
| sqlite_kwargs.pop("db_path", None) | |
| or sqlite_kwargs.pop("path", None) | |
| or sqlite_default | |
| ) | |
| return SQLiteDB(db_path=db_path, **sqlite_kwargs) | |
| if db_type == "dynamodb": | |
| if not _DYNAMODB_AVAILABLE: | |
| raise ImportError( | |
| "aioboto3 is required for DynamoDB support. Install it with: pip install jvspatial[lambda]" | |
| ) | |
| from .dynamodb import DynamoDB | |
| dynamodb_kwargs = dict(kwargs) | |
| if "table_name" not in dynamodb_kwargs: | |
| dynamodb_kwargs["table_name"] = env( | |
| "JVSPATIAL_DYNAMODB_TABLE_NAME", default="jvspatial" | |
| ) | |
| if "region_name" not in dynamodb_kwargs: | |
| dynamodb_kwargs["region_name"] = env( | |
| "JVSPATIAL_DYNAMODB_REGION", default="us-east-1" | |
| ) | |
| if "endpoint_url" not in dynamodb_kwargs: | |
| dynamodb_kwargs["endpoint_url"] = env("JVSPATIAL_DYNAMODB_ENDPOINT_URL") | |
| if "aws_access_key_id" not in dynamodb_kwargs: | |
| dynamodb_kwargs["aws_access_key_id"] = env("AWS_ACCESS_KEY_ID") | |
| if "aws_secret_access_key" not in dynamodb_kwargs: | |
| dynamodb_kwargs["aws_secret_access_key"] = env("AWS_SECRET_ACCESS_KEY") | |
| return DynamoDB(**dynamodb_kwargs) | |
| if db_type in ("postgres", "postgresql"): | |
| if not _POSTGRES_AVAILABLE: | |
| raise ImportError( | |
| "asyncpg is required for PostgreSQL support. " | |
| "Install it with: pip install jvspatial[postgres]" | |
| ) | |
| from .postgres import PostgresDB | |
| pg_kwargs = dict(kwargs) | |
| if "dsn" not in pg_kwargs: | |
| pg_kwargs["dsn"] = pg_kwargs.pop( | |
| "connection_string", None | |
| ) or pg_kwargs.pop("db_connection_string", None) | |
| if "dsn" not in pg_kwargs or pg_kwargs.get("dsn") is None: | |
| pg_kwargs["dsn"] = env( | |
| "JVSPATIAL_POSTGRES_DSN", | |
| default="postgresql://postgres:postgres@localhost:5432/jvdb", # pragma: allowlist secret | |
| ) | |
| if "min_size" not in pg_kwargs: | |
| pg_kwargs["min_size"] = env("JVSPATIAL_POSTGRES_MIN_POOL_SIZE", parse=int) | |
| if "max_size" not in pg_kwargs: | |
| pg_kwargs["max_size"] = env("JVSPATIAL_POSTGRES_MAX_POOL_SIZE", parse=int) | |
| if "pooler_mode" not in pg_kwargs: | |
| pg_kwargs["pooler_mode"] = env( | |
| "JVSPATIAL_POSTGRES_POOLER_MODE", default="session" | |
| ) | |
| # Drop any None entries so PostgresDB defaults take effect. | |
| pg_kwargs = {k: v for k, v in pg_kwargs.items() if v is not None} | |
| return PostgresDB(**pg_kwargs) | |
| raise ValueError(f"Not a built-in database type: {db_type!r}") | |
| def create_database( | |
| db_type: str = "json", | |
| register: bool = False, | |
| name: Optional[str] = None, | |
| cache_get_size: int = 0, | |
| cache_get_ttl: float = 60.0, | |
| observe: bool = False, | |
| slow_query_ms: float = DEFAULT_SLOW_QUERY_MS, | |
| metrics: Optional[Any] = None, | |
| **kwargs: Any, | |
| ) -> Database: | |
| """Create a database instance with direct instantiation. | |
| Supports both built-in database types ('json', 'sqlite', 'mongodb', 'dynamodb') and custom | |
| database types registered via register_database_type(). | |
| Args: | |
| db_type: Database type ('json', 'mongodb', 'sqlite', 'dynamodb', or a registered custom type) | |
| register: If True, register the database with DatabaseManager | |
| name: Database name for registration (required if register=True) | |
| cache_get_size: Optional opt-in read-through cache for ``get()`` | |
| calls. Pass ``> 0`` to wrap the backend in a | |
| :class:`~jvspatial.db._cache.CachingDatabase` with that LRU cap. | |
| Default ``0`` disables caching (current behavior). Skipped at | |
| runtime under serverless mode -- per-process caches are not | |
| useful across cold starts. | |
| cache_get_ttl: TTL in seconds for cached ``get()`` results when | |
| ``cache_get_size > 0``. Default ``60``. Set to ``0`` for no | |
| TTL (LRU eviction only). | |
| observe: When ``True``, wrap the database in an | |
| :class:`~jvspatial.db._observable.ObservableDatabase` that | |
| emits a structured log line and one metric per operation. | |
| Defaults to ``False`` (no behavior change for existing | |
| callers). | |
| slow_query_ms: Threshold above which the per-op log line is | |
| elevated to WARNING. Only meaningful when | |
| ``observe=True``. Defaults to 100ms. | |
| metrics: Optional :class:`~jvspatial.observability.metrics.MetricsRecorder` | |
| implementation. Defaults to | |
| :class:`~jvspatial.observability.metrics.NullMetricsRecorder` | |
| (zero overhead). For OpenTelemetry, install | |
| ``pip install jvspatial[otel]`` and pass an | |
| :class:`~jvspatial.observability.otel.OpenTelemetryMetricsRecorder`. | |
| **kwargs: Database-specific configuration passed to the database constructor | |
| Returns: | |
| Database instance | |
| Examples: | |
| # JSON database (not registered) | |
| db = create_database("json", base_path="./data") | |
| # MongoDB database (registered with manager) | |
| db = create_database("mongodb", uri="mongodb://localhost:27017", | |
| register=True, name="app_db") | |
| # SQLite database (file-based storage) | |
| db = create_database("sqlite", db_path="./data/app.db") | |
| # DynamoDB database | |
| db = create_database("dynamodb", table_name="myapp", region_name="us-east-1") | |
| # JSON database with read-through cache (opt-in) | |
| db = create_database( | |
| "json", base_path="./data", | |
| cache_get_size=2048, cache_get_ttl=30.0, | |
| ) | |
| # Custom database (after registration) | |
| db = create_database("my_custom", connection_string="custom://", | |
| register=True, name="custom_db") | |
| # Create and auto-register as current database | |
| db = create_database("json", base_path="./app_data", | |
| register=True, name="app") | |
| manager = get_database_manager() | |
| manager.set_current_database("app") | |
| Raises: | |
| ValueError: If db_type is not supported or registration fails | |
| """ | |
| db: Database | |
| if db_type in ("json", "mongodb", "sqlite", "dynamodb", "postgres", "postgresql"): | |
| db = _instantiate_builtin_database(db_type, **kwargs) | |
| elif db_type in _DATABASE_REGISTRY: | |
| factory = _DATABASE_REGISTRY[db_type] | |
| db = factory(**kwargs) | |
| else: | |
| available = ", ".join(list_database_types().keys()) | |
| raise ValueError( | |
| f"Unsupported database type: '{db_type}'. " f"Available types: {available}" | |
| ) | |
| # Optional read-through cache (off by default). | |
| if cache_get_size and cache_get_size > 0: | |
| db = CachingDatabase(db, max_entries=cache_get_size, ttl_seconds=cache_get_ttl) | |
| # Optional observability layer (off by default). Applied AFTER the | |
| # cache so the structured log line measures user-visible latency | |
| # including cache hits/misses -- which is what SLO calculations | |
| # need. | |
| if observe: | |
| db = ObservableDatabase(db, metrics=metrics, slow_query_ms=slow_query_ms) | |
| # Register with manager if requested | |
| if register: | |
| if name is None: | |
| raise ValueError("Database name is required when register=True") | |
| manager = get_database_manager() | |
| manager.register_database(name, db) | |
| return db | |
| def create_default_database() -> Database: | |
| """Create the default database based on environment. | |
| This creates the prime database used for core persistence operations | |
| such as authentication and session management. | |
| Returns: | |
| Configured database instance (prime database) | |
| """ | |
| manager = get_database_manager() | |
| return manager.get_prime_database() | |
| def get_prime_database() -> Database: | |
| """Get the prime database instance. | |
| The prime database is always used for core persistence operations | |
| such as authentication, session management, and system-level data. | |
| Returns: | |
| Prime database instance | |
| """ | |
| manager = get_database_manager() | |
| return manager.get_prime_database() | |
| def get_current_database() -> Database: | |
| """Get the current active database instance. | |
| Returns: | |
| Current database instance (defaults to prime if not set) | |
| """ | |
| manager = get_database_manager() | |
| return manager.get_current_database() | |
| def switch_database(name: str) -> Database: | |
| """Switch to a different database by name. | |
| Args: | |
| name: Database name to switch to | |
| Returns: | |
| The database instance that was switched to | |
| Raises: | |
| ValueError: If database is not registered | |
| """ | |
| manager = get_database_manager() | |
| manager.set_current_database(name) | |
| return manager.get_current_database() | |
| def unregister_database(name: str) -> None: | |
| """Unregister a non-prime database instance. | |
| Removes a database from the DatabaseManager. If the database being | |
| removed is the current database, automatically switches back to prime. | |
| Args: | |
| name: Database name to unregister | |
| Raises: | |
| ValueError: If name is "prime" (cannot unregister prime database) | |
| or database is not registered | |
| Example: | |
| ```python | |
| from jvspatial.db import create_database, unregister_database | |
| # Register a database | |
| db = create_database("json", base_path="./temp_data", register=True, name="temp") | |
| # Later, unregister it | |
| unregister_database("temp") | |
| ``` | |
| """ | |
| manager = get_database_manager() | |
| manager.unregister_database(name) | |
Xet Storage Details
- Size:
- 16.4 kB
- Xet hash:
- 24a22bed69699c56cd1f0296ef59bc9286f9a2fbf3624307ccb3672bd8ba9203
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.