model.py 14 KB

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