model.py 13 KB

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