model.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. """Database built into Reflex."""
  2. from __future__ import annotations
  3. import re
  4. from collections import defaultdict
  5. from contextlib import suppress
  6. from typing import Any, ClassVar
  7. import alembic.autogenerate
  8. import alembic.command
  9. import alembic.config
  10. import alembic.operations.ops
  11. import alembic.runtime.environment
  12. import alembic.script
  13. import alembic.util
  14. import sqlalchemy
  15. import sqlalchemy.exc
  16. import sqlalchemy.ext.asyncio
  17. import sqlalchemy.orm
  18. from alembic.runtime.migration import MigrationContext
  19. from reflex.base import Base
  20. from reflex.config import environment, get_config
  21. from reflex.utils import console
  22. from reflex.utils.compat import sqlmodel, sqlmodel_field_has_primary_key
  23. _ENGINE: dict[str, sqlalchemy.engine.Engine] = {}
  24. _ASYNC_ENGINE: dict[str, sqlalchemy.ext.asyncio.AsyncEngine] = {}
  25. _AsyncSessionLocal: dict[str | None, sqlalchemy.ext.asyncio.async_sessionmaker] = {}
  26. # Import AsyncSession _after_ reflex.utils.compat
  27. from sqlmodel.ext.asyncio.session import AsyncSession # noqa: E402
  28. def _safe_db_url_for_logging(url: str) -> str:
  29. """Remove username and password from the database URL for logging.
  30. Args:
  31. url: The database URL.
  32. Returns:
  33. The database URL with the username and password removed.
  34. """
  35. return re.sub(r"://[^@]+@", "://<username>:<password>@", url)
  36. def get_engine_args(url: str | None = None) -> dict[str, Any]:
  37. """Get the database engine arguments.
  38. Args:
  39. url: The database url.
  40. Returns:
  41. The database engine arguments as a dict.
  42. """
  43. kwargs: dict[str, Any] = {
  44. # Print the SQL queries if the log level is INFO or lower.
  45. "echo": environment.SQLALCHEMY_ECHO.get(),
  46. # Check connections before returning them.
  47. "pool_pre_ping": environment.SQLALCHEMY_POOL_PRE_PING.get(),
  48. }
  49. conf = get_config()
  50. url = url or conf.db_url
  51. if url is not None and url.startswith("sqlite"):
  52. # Needed for the admin dash on sqlite.
  53. kwargs["connect_args"] = {"check_same_thread": False}
  54. return kwargs
  55. def get_engine(url: str | None = None) -> sqlalchemy.engine.Engine:
  56. """Get the database engine.
  57. Args:
  58. url: the DB url to use.
  59. Returns:
  60. The database engine.
  61. Raises:
  62. ValueError: If the database url is None.
  63. """
  64. conf = get_config()
  65. url = url or conf.db_url
  66. if url is None:
  67. raise ValueError("No database url configured")
  68. global _ENGINE
  69. if url in _ENGINE:
  70. return _ENGINE[url]
  71. if not environment.ALEMBIC_CONFIG.get().exists():
  72. console.warn(
  73. "Database is not initialized, run [bold]reflex db init[/bold] first."
  74. )
  75. _ENGINE[url] = sqlmodel.create_engine(
  76. url,
  77. **get_engine_args(url),
  78. )
  79. return _ENGINE[url]
  80. def get_async_engine(url: str | None) -> sqlalchemy.ext.asyncio.AsyncEngine:
  81. """Get the async database engine.
  82. Args:
  83. url: The database url.
  84. Returns:
  85. The async database engine.
  86. Raises:
  87. ValueError: If the async database url is None.
  88. """
  89. if url is None:
  90. conf = get_config()
  91. url = conf.async_db_url
  92. if url is not None and conf.db_url is not None:
  93. async_db_url_tail = url.partition("://")[2]
  94. db_url_tail = conf.db_url.partition("://")[2]
  95. if async_db_url_tail != db_url_tail:
  96. console.warn(
  97. f"async_db_url `{_safe_db_url_for_logging(url)}` "
  98. "should reference the same database as "
  99. f"db_url `{_safe_db_url_for_logging(conf.db_url)}`."
  100. )
  101. if url is None:
  102. raise ValueError("No async database url configured")
  103. global _ASYNC_ENGINE
  104. if url in _ASYNC_ENGINE:
  105. return _ASYNC_ENGINE[url]
  106. if not environment.ALEMBIC_CONFIG.get().exists():
  107. console.warn(
  108. "Database is not initialized, run [bold]reflex db init[/bold] first."
  109. )
  110. _ASYNC_ENGINE[url] = sqlalchemy.ext.asyncio.create_async_engine(
  111. url,
  112. **get_engine_args(url),
  113. )
  114. return _ASYNC_ENGINE[url]
  115. async def get_db_status() -> dict[str, bool]:
  116. """Checks the status of the database connection.
  117. Attempts to connect to the database and execute a simple query to verify connectivity.
  118. Returns:
  119. The status of the database connection.
  120. """
  121. status = True
  122. try:
  123. engine = get_engine()
  124. with engine.connect() as connection:
  125. connection.execute(sqlalchemy.text("SELECT 1"))
  126. except sqlalchemy.exc.OperationalError:
  127. status = False
  128. return {"db": status}
  129. SQLModelOrSqlAlchemy = type[sqlmodel.SQLModel] | type[sqlalchemy.orm.DeclarativeBase]
  130. class ModelRegistry:
  131. """Registry for all models."""
  132. models: ClassVar[set[SQLModelOrSqlAlchemy]] = set()
  133. # Cache the metadata to avoid re-creating it.
  134. _metadata: ClassVar[sqlalchemy.MetaData | None] = None
  135. @classmethod
  136. def register(cls, model: SQLModelOrSqlAlchemy):
  137. """Register a model. Can be used directly or as a decorator.
  138. Args:
  139. model: The model to register.
  140. Returns:
  141. The model passed in as an argument (Allows decorator usage)
  142. """
  143. cls.models.add(model)
  144. return model
  145. @classmethod
  146. def get_models(cls, include_empty: bool = False) -> set[SQLModelOrSqlAlchemy]:
  147. """Get registered models.
  148. Args:
  149. include_empty: If True, include models with empty metadata.
  150. Returns:
  151. The registered models.
  152. """
  153. if include_empty:
  154. return cls.models
  155. return {
  156. model for model in cls.models if not cls._model_metadata_is_empty(model)
  157. }
  158. @staticmethod
  159. def _model_metadata_is_empty(model: SQLModelOrSqlAlchemy) -> bool:
  160. """Check if the model metadata is empty.
  161. Args:
  162. model: The model to check.
  163. Returns:
  164. True if the model metadata is empty, False otherwise.
  165. """
  166. return len(model.metadata.tables) == 0
  167. @classmethod
  168. def get_metadata(cls) -> sqlalchemy.MetaData:
  169. """Get the database metadata.
  170. Returns:
  171. The database metadata.
  172. """
  173. if cls._metadata is not None:
  174. return cls._metadata
  175. models = cls.get_models(include_empty=False)
  176. if len(models) == 1:
  177. metadata = next(iter(models)).metadata
  178. else:
  179. # Merge the metadata from all the models.
  180. # This allows mixing bare sqlalchemy models with sqlmodel models in one database.
  181. metadata = sqlalchemy.MetaData()
  182. for model in cls.get_models():
  183. for table in model.metadata.tables.values():
  184. table.to_metadata(metadata)
  185. # Cache the metadata
  186. cls._metadata = metadata
  187. return metadata
  188. class Model(Base, sqlmodel.SQLModel): # pyright: ignore [reportGeneralTypeIssues,reportIncompatibleVariableOverride]
  189. """Base class to define a table in the database."""
  190. # The primary key for the table.
  191. id: int | None = sqlmodel.Field(default=None, primary_key=True)
  192. def __init_subclass__(cls):
  193. """Drop the default primary key field if any primary key field is defined."""
  194. non_default_primary_key_fields = [
  195. field_name
  196. for field_name, field in cls.__fields__.items()
  197. if field_name != "id" and sqlmodel_field_has_primary_key(field)
  198. ]
  199. if non_default_primary_key_fields:
  200. cls.__fields__.pop("id", None)
  201. super().__init_subclass__()
  202. @classmethod
  203. def _dict_recursive(cls, value: Any):
  204. """Recursively serialize the relationship object(s).
  205. Args:
  206. value: The value to serialize.
  207. Returns:
  208. The serialized value.
  209. """
  210. if hasattr(value, "dict"):
  211. return value.dict()
  212. elif isinstance(value, list):
  213. return [cls._dict_recursive(item) for item in value]
  214. return value
  215. def dict(self, **kwargs):
  216. """Convert the object to a dictionary.
  217. Args:
  218. kwargs: Ignored but needed for compatibility.
  219. Returns:
  220. The object as a dictionary.
  221. """
  222. base_fields = {name: getattr(self, name) for name in self.__fields__}
  223. relationships = {}
  224. # SQLModel relationships do not appear in __fields__, but should be included if present.
  225. for name in self.__sqlmodel_relationships__:
  226. with suppress(
  227. sqlalchemy.orm.exc.DetachedInstanceError # This happens when the relationship was never loaded and the session is closed.
  228. ):
  229. relationships[name] = self._dict_recursive(getattr(self, name))
  230. return {
  231. **base_fields,
  232. **relationships,
  233. }
  234. @staticmethod
  235. def create_all():
  236. """Create all the tables."""
  237. engine = get_engine()
  238. ModelRegistry.get_metadata().create_all(engine)
  239. @staticmethod
  240. def get_db_engine():
  241. """Get the database engine.
  242. Returns:
  243. The database engine.
  244. """
  245. return get_engine()
  246. @staticmethod
  247. def _alembic_config():
  248. """Get the alembic configuration and script_directory.
  249. Returns:
  250. tuple of (config, script_directory)
  251. """
  252. config = alembic.config.Config(environment.ALEMBIC_CONFIG.get())
  253. if not config.get_main_option("script_location"):
  254. config.set_main_option("script_location", "version")
  255. return config, alembic.script.ScriptDirectory.from_config(config)
  256. @staticmethod
  257. def _alembic_render_item(
  258. type_: str,
  259. obj: Any,
  260. autogen_context: alembic.autogenerate.api.AutogenContext,
  261. ):
  262. """Alembic render_item hook call.
  263. This method is called to provide python code for the given obj,
  264. but currently it is only used to add `sqlmodel` to the import list
  265. when generating migration scripts.
  266. See https://alembic.sqlalchemy.org/en/latest/api/runtime.html
  267. Args:
  268. type_: One of "schema", "table", "column", "index",
  269. "unique_constraint", or "foreign_key_constraint".
  270. obj: The object being rendered.
  271. autogen_context: Shared AutogenContext passed to each render_item call.
  272. Returns:
  273. False - Indicating that the default rendering should be used.
  274. """
  275. autogen_context.imports.add("import sqlmodel")
  276. return False
  277. @classmethod
  278. def alembic_init(cls):
  279. """Initialize alembic for the project."""
  280. alembic.command.init(
  281. config=alembic.config.Config(environment.ALEMBIC_CONFIG.get()),
  282. directory=str(environment.ALEMBIC_CONFIG.get().parent / "alembic"),
  283. )
  284. @classmethod
  285. def alembic_autogenerate(
  286. cls,
  287. connection: sqlalchemy.engine.Connection,
  288. message: str | None = None,
  289. write_migration_scripts: bool = True,
  290. ) -> bool:
  291. """Generate migration scripts for alembic-detectable changes.
  292. Args:
  293. connection: SQLAlchemy connection to use when detecting changes.
  294. message: Human readable identifier describing the generated revision.
  295. write_migration_scripts: If True, write autogenerated revisions to script directory.
  296. Returns:
  297. True when changes have been detected.
  298. """
  299. if not environment.ALEMBIC_CONFIG.get().exists():
  300. return False
  301. config, script_directory = cls._alembic_config()
  302. revision_context = alembic.autogenerate.api.RevisionContext(
  303. config=config,
  304. script_directory=script_directory,
  305. command_args=defaultdict(
  306. lambda: None,
  307. autogenerate=True,
  308. head="head",
  309. message=message,
  310. ),
  311. )
  312. writer = alembic.autogenerate.rewriter.Rewriter()
  313. @writer.rewrites(alembic.operations.ops.AddColumnOp)
  314. def render_add_column_with_server_default(
  315. context: MigrationContext,
  316. revision: str | None,
  317. op: Any,
  318. ):
  319. # Carry the sqlmodel default as server_default so that newly added
  320. # columns get the desired default value in existing rows.
  321. if op.column.default is not None and op.column.server_default is None:
  322. op.column.server_default = sqlalchemy.DefaultClause(
  323. sqlalchemy.sql.expression.literal(op.column.default.arg),
  324. )
  325. return op
  326. def run_autogenerate(rev: str, context: MigrationContext):
  327. revision_context.run_autogenerate(rev, context)
  328. return []
  329. with alembic.runtime.environment.EnvironmentContext(
  330. config=config,
  331. script=script_directory,
  332. fn=run_autogenerate,
  333. ) as env:
  334. env.configure(
  335. connection=connection,
  336. target_metadata=ModelRegistry.get_metadata(),
  337. render_item=cls._alembic_render_item,
  338. process_revision_directives=writer,
  339. compare_type=False,
  340. render_as_batch=True, # for sqlite compatibility
  341. )
  342. env.run_migrations()
  343. changes_detected = False
  344. if revision_context.generated_revisions:
  345. upgrade_ops = revision_context.generated_revisions[-1].upgrade_ops
  346. if upgrade_ops is not None:
  347. changes_detected = bool(upgrade_ops.ops)
  348. if changes_detected and write_migration_scripts:
  349. # Must iterate the generator to actually write the scripts.
  350. _ = tuple(revision_context.generate_scripts())
  351. return changes_detected
  352. @classmethod
  353. def _alembic_upgrade(
  354. cls,
  355. connection: sqlalchemy.engine.Connection,
  356. to_rev: str = "head",
  357. ) -> None:
  358. """Apply alembic migrations up to the given revision.
  359. Args:
  360. connection: SQLAlchemy connection to use when performing upgrade.
  361. to_rev: Revision to migrate towards.
  362. """
  363. config, script_directory = cls._alembic_config()
  364. def run_upgrade(rev: str, context: MigrationContext):
  365. return script_directory._upgrade_revs(to_rev, rev)
  366. with alembic.runtime.environment.EnvironmentContext(
  367. config=config,
  368. script=script_directory,
  369. fn=run_upgrade,
  370. ) as env:
  371. env.configure(connection=connection)
  372. env.run_migrations()
  373. @classmethod
  374. def migrate(cls, autogenerate: bool = False) -> bool | None:
  375. """Execute alembic migrations for all sqlmodel Model classes.
  376. If alembic is not installed or has not been initialized for the project,
  377. then no action is performed.
  378. If there are no revisions currently tracked by alembic, then
  379. an initial revision will be created based on sqlmodel metadata.
  380. If models in the app have changed in incompatible ways that alembic
  381. cannot automatically generate revisions for, the app may not be able to
  382. start up until migration scripts have been corrected by hand.
  383. Args:
  384. autogenerate: If True, generate migration script and use it to upgrade schema
  385. (otherwise, just bring the schema to current "head" revision).
  386. Returns:
  387. True - indicating the process was successful.
  388. None - indicating the process was skipped.
  389. """
  390. if not environment.ALEMBIC_CONFIG.get().exists():
  391. return
  392. with cls.get_db_engine().connect() as connection:
  393. cls._alembic_upgrade(connection=connection)
  394. if autogenerate:
  395. changes_detected = cls.alembic_autogenerate(connection=connection)
  396. if changes_detected:
  397. cls._alembic_upgrade(connection=connection)
  398. connection.commit()
  399. return True
  400. @classmethod
  401. def select(cls):
  402. """Select rows from the table.
  403. Returns:
  404. The select statement.
  405. """
  406. return sqlmodel.select(cls)
  407. ModelRegistry.register(Model)
  408. def session(url: str | None = None) -> sqlmodel.Session:
  409. """Get a sqlmodel session to interact with the database.
  410. Args:
  411. url: The database url.
  412. Returns:
  413. A database session.
  414. """
  415. return sqlmodel.Session(get_engine(url))
  416. def asession(url: str | None = None) -> AsyncSession:
  417. """Get an async sqlmodel session to interact with the database.
  418. async with rx.asession() as asession:
  419. ...
  420. Most operations against the `asession` must be awaited.
  421. Args:
  422. url: The database url.
  423. Returns:
  424. An async database session.
  425. """
  426. global _AsyncSessionLocal
  427. if url not in _AsyncSessionLocal:
  428. _AsyncSessionLocal[url] = sqlalchemy.ext.asyncio.async_sessionmaker(
  429. bind=get_async_engine(url),
  430. class_=AsyncSession,
  431. expire_on_commit=False,
  432. autocommit=False,
  433. autoflush=False,
  434. )
  435. return _AsyncSessionLocal[url]()
  436. def sqla_session(url: str | None = None) -> sqlalchemy.orm.Session:
  437. """Get a bare sqlalchemy session to interact with the database.
  438. Args:
  439. url: The database url.
  440. Returns:
  441. A database session.
  442. """
  443. return sqlalchemy.orm.Session(get_engine(url))