33from contextlib import asynccontextmanager
44from dataclasses import dataclass , field
55from pathlib import Path
6- from typing import Any , AsyncIterator , Self
6+ from typing import AsyncIterator , Self
77
88import sqlalchemy as sa
99from sqlalchemy .engine import Engine , create_engine
1010from sqlalchemy .engine .url import make_url
1111from sqlalchemy .ext .asyncio import AsyncConnection , AsyncEngine , create_async_engine
1212
1313from fluid import settings
14+ from fluid .utils .data import compact_dict
1415
1516from .migration import Migration
1617
@@ -31,30 +32,50 @@ class Database:
3132 Currently, only `postgresql+asyncpg` is supported, but other databases may
3233 be supported in the future.
3334 """
34- echo : bool = settings .DBECHO
35+ echo : bool = field ( default_factory = lambda : settings .DBECHO )
3536 """Echo SQL queries to stdout
3637
3738 It defaults to the `DBECHO` setting in the settings module
3839 """
39- pool_size : int = settings .DBPOOL_MAX_SIZE
40- max_overflow : int = settings .DBPOOL_MAX_OVERFLOW
40+ pool_size : int = field ( default_factory = lambda : settings .DBPOOL_MAX_SIZE )
41+ max_overflow : int = field ( default_factory = lambda : settings .DBPOOL_MAX_OVERFLOW )
4142 metadata : sa .MetaData = field (default_factory = sa .MetaData )
4243 migration_path : str | Path = ""
4344 """Path to the directory containing migration files. If empty, migrations will
4445 be stored in the default location `migrations` in the current working directory.
4546 """
46- app_name : str = settings .APP_NAME
47+ app_name : str = field ( default_factory = lambda : settings .APP_NAME )
4748 _engine : AsyncEngine | None = None
4849
4950 @classmethod
5051 def from_env (
5152 cls ,
5253 * ,
53- dsn : str = settings .DATABASE ,
54- schema : str | None = settings .DATABASE_SCHEMA ,
55- ** kwargs : Any ,
54+ dsn : str | None = None ,
55+ schema : str | None = None ,
56+ migration_path : str | Path | None = None ,
57+ app_name : str | None = None ,
58+ max_overflow : int | None = None ,
59+ pool_size : int | None = None ,
60+ db_name : str | None = None ,
5661 ) -> Self :
5762 """Create a new database container from environment variables as defaults"""
63+ if dsn is None :
64+ dsn = settings .DATABASE
65+ if schema is None :
66+ schema = settings .DATABASE_SCHEMA
67+ kwargs = compact_dict (
68+ migration_path = migration_path ,
69+ app_name = app_name ,
70+ max_overflow = max_overflow ,
71+ pool_size = pool_size ,
72+ )
73+ if db_name :
74+ dsn = (
75+ make_url (dsn )
76+ .set (database = db_name )
77+ .render_as_string (hide_password = False )
78+ )
5879 return cls (dsn = dsn , metadata = sa .MetaData (schema = schema ), ** kwargs )
5980
6081 @property
0 commit comments