model.py 17 KB

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