model.py 14 KB

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