model.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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, Optional
  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. import sqlmodel
  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. 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. class Model(Base, sqlmodel.SQLModel):
  44. """Base class to define a table in the database."""
  45. # The primary key for the table.
  46. id: Optional[int] = sqlmodel.Field(default=None, primary_key=True)
  47. def __init_subclass__(cls):
  48. """Drop the default primary key field if any primary key field is defined."""
  49. non_default_primary_key_fields = [
  50. field_name
  51. for field_name, field in cls.model_fields.items()
  52. if field_name != "id"
  53. and getattr(field.field_info, "primary_key", None) is True
  54. ]
  55. if non_default_primary_key_fields:
  56. cls.model_fields.pop("id", None)
  57. super().__init_subclass__()
  58. @classmethod
  59. def _dict_recursive(cls, value):
  60. """Recursively serialize the relationship object(s).
  61. Args:
  62. value: The value to serialize.
  63. Returns:
  64. The serialized value.
  65. """
  66. if hasattr(value, "dict"):
  67. return value.dict()
  68. elif isinstance(value, list):
  69. return [cls._dict_recursive(item) for item in value]
  70. return value
  71. def dict(self, **kwargs):
  72. """Convert the object to a dictionary.
  73. Args:
  74. kwargs: Ignored but needed for compatibility.
  75. Returns:
  76. The object as a dictionary.
  77. """
  78. base_fields = {name: getattr(self, name) for name in self.model_fields}
  79. relationships = {}
  80. # SQLModel relationships do not appear in model_fields, but should be included if present.
  81. for name in self.__sqlmodel_relationships__:
  82. try:
  83. relationships[name] = self._dict_recursive(getattr(self, name))
  84. except sqlalchemy.orm.exc.DetachedInstanceError:
  85. # This happens when the relationship was never loaded and the session is closed.
  86. continue
  87. return {
  88. **base_fields,
  89. **relationships,
  90. }
  91. @staticmethod
  92. def create_all():
  93. """Create all the tables."""
  94. engine = get_engine()
  95. sqlmodel.SQLModel.metadata.create_all(engine)
  96. @staticmethod
  97. def get_db_engine():
  98. """Get the database engine.
  99. Returns:
  100. The database engine.
  101. """
  102. return get_engine()
  103. @staticmethod
  104. def _alembic_config():
  105. """Get the alembic configuration and script_directory.
  106. Returns:
  107. tuple of (config, script_directory)
  108. """
  109. config = alembic.config.Config(constants.ALEMBIC_CONFIG)
  110. return config, alembic.script.ScriptDirectory(
  111. config.get_main_option("script_location", default="version"),
  112. )
  113. @staticmethod
  114. def _alembic_render_item(
  115. type_: str,
  116. obj: Any,
  117. autogen_context: "alembic.autogenerate.api.AutogenContext",
  118. ):
  119. """Alembic render_item hook call.
  120. This method is called to provide python code for the given obj,
  121. but currently it is only used to add `sqlmodel` to the import list
  122. when generating migration scripts.
  123. See https://alembic.sqlalchemy.org/en/latest/api/runtime.html
  124. Args:
  125. type_: One of "schema", "table", "column", "index",
  126. "unique_constraint", or "foreign_key_constraint".
  127. obj: The object being rendered.
  128. autogen_context: Shared AutogenContext passed to each render_item call.
  129. Returns:
  130. False - Indicating that the default rendering should be used.
  131. """
  132. autogen_context.imports.add("import sqlmodel")
  133. return False
  134. @classmethod
  135. def alembic_init(cls):
  136. """Initialize alembic for the project."""
  137. alembic.command.init(
  138. config=alembic.config.Config(constants.ALEMBIC_CONFIG),
  139. directory=str(Path(constants.ALEMBIC_CONFIG).parent / "alembic"),
  140. )
  141. @classmethod
  142. def alembic_autogenerate(
  143. cls,
  144. connection: sqlalchemy.engine.Connection,
  145. message: str | None = None,
  146. write_migration_scripts: bool = True,
  147. ) -> bool:
  148. """Generate migration scripts for alembic-detectable changes.
  149. Args:
  150. connection: SQLAlchemy connection to use when detecting changes.
  151. message: Human readable identifier describing the generated revision.
  152. write_migration_scripts: If True, write autogenerated revisions to script directory.
  153. Returns:
  154. True when changes have been detected.
  155. """
  156. if not Path(constants.ALEMBIC_CONFIG).exists():
  157. return False
  158. config, script_directory = cls._alembic_config()
  159. revision_context = alembic.autogenerate.api.RevisionContext(
  160. config=config,
  161. script_directory=script_directory,
  162. command_args=defaultdict(
  163. lambda: None,
  164. autogenerate=True,
  165. head="head",
  166. message=message,
  167. ),
  168. )
  169. writer = alembic.autogenerate.rewriter.Rewriter()
  170. @writer.rewrites(alembic.operations.ops.AddColumnOp)
  171. def render_add_column_with_server_default(context, revision, op):
  172. # Carry the sqlmodel default as server_default so that newly added
  173. # columns get the desired default value in existing rows.
  174. if op.column.default is not None and op.column.server_default is None:
  175. op.column.server_default = sqlalchemy.DefaultClause(
  176. sqlalchemy.sql.expression.literal(op.column.default.arg),
  177. )
  178. return op
  179. def run_autogenerate(rev, context):
  180. revision_context.run_autogenerate(rev, context)
  181. return []
  182. with alembic.runtime.environment.EnvironmentContext(
  183. config=config,
  184. script=script_directory,
  185. fn=run_autogenerate,
  186. ) as env:
  187. env.configure(
  188. connection=connection,
  189. target_metadata=sqlmodel.SQLModel.metadata,
  190. render_item=cls._alembic_render_item,
  191. process_revision_directives=writer, # type: ignore
  192. compare_type=False,
  193. )
  194. env.run_migrations()
  195. changes_detected = False
  196. if revision_context.generated_revisions:
  197. upgrade_ops = revision_context.generated_revisions[-1].upgrade_ops
  198. if upgrade_ops is not None:
  199. changes_detected = bool(upgrade_ops.ops)
  200. if changes_detected and write_migration_scripts:
  201. # Must iterate the generator to actually write the scripts.
  202. _ = tuple(revision_context.generate_scripts())
  203. return changes_detected
  204. @classmethod
  205. def _alembic_upgrade(
  206. cls,
  207. connection: sqlalchemy.engine.Connection,
  208. to_rev: str = "head",
  209. ) -> None:
  210. """Apply alembic migrations up to the given revision.
  211. Args:
  212. connection: SQLAlchemy connection to use when performing upgrade.
  213. to_rev: Revision to migrate towards.
  214. """
  215. config, script_directory = cls._alembic_config()
  216. def run_upgrade(rev, context):
  217. return script_directory._upgrade_revs(to_rev, rev)
  218. with alembic.runtime.environment.EnvironmentContext(
  219. config=config,
  220. script=script_directory,
  221. fn=run_upgrade,
  222. ) as env:
  223. env.configure(connection=connection)
  224. env.run_migrations()
  225. @classmethod
  226. def migrate(cls, autogenerate: bool = False) -> bool | None:
  227. """Execute alembic migrations for all sqlmodel Model classes.
  228. If alembic is not installed or has not been initialized for the project,
  229. then no action is performed.
  230. If there are no revisions currently tracked by alembic, then
  231. an initial revision will be created based on sqlmodel metadata.
  232. If models in the app have changed in incompatible ways that alembic
  233. cannot automatically generate revisions for, the app may not be able to
  234. start up until migration scripts have been corrected by hand.
  235. Args:
  236. autogenerate: If True, generate migration script and use it to upgrade schema
  237. (otherwise, just bring the schema to current "head" revision).
  238. Returns:
  239. True - indicating the process was successful.
  240. None - indicating the process was skipped.
  241. """
  242. if not Path(constants.ALEMBIC_CONFIG).exists():
  243. return
  244. with cls.get_db_engine().connect() as connection:
  245. cls._alembic_upgrade(connection=connection)
  246. if autogenerate:
  247. changes_detected = cls.alembic_autogenerate(connection=connection)
  248. if changes_detected:
  249. cls._alembic_upgrade(connection=connection)
  250. connection.commit()
  251. return True
  252. @classmethod
  253. @property
  254. def select(cls):
  255. """Select rows from the table.
  256. Returns:
  257. The select statement.
  258. """
  259. return sqlmodel.select(cls)
  260. def session(url: str | None = None) -> sqlmodel.Session:
  261. """Get a session to interact with the database.
  262. Args:
  263. url: The database url.
  264. Returns:
  265. A database session.
  266. """
  267. return sqlmodel.Session(get_engine(url))