Compare commits

...

201 Commits

Author SHA1 Message Date
Sebastián Ramírez
6b562358fc 🔖 Release version 0.0.16 2024-02-17 14:53:16 +01:00
Sebastián Ramírez
3d483921fe 📝 Update release notes 2024-02-17 14:52:43 +01:00
github-actions
2abb798a22 📝 Update release notes 2024-02-17 13:49:59 +00:00
Sebastián Ramírez
fa12c5d87b Add new method sqlmodel_update() to update models in place, including an update parameter for extra data (#804) 2024-02-17 14:49:39 +01:00
Sebastián Ramírez
7fec884864 🔖 Release version 0.0.15 2024-02-17 14:36:12 +01:00
github-actions
d8fa545955 📝 Update release notes 2024-02-17 13:35:13 +00:00
Sebastián Ramírez
1b7b3aa668 🐛 Fix class initialization compatibility with Pydantic and SQLModel, fixing errors revealed by the latest Pydantic (#807) 2024-02-17 13:34:57 +00:00
github-actions
0c7def88b5 📝 Update release notes 2024-01-09 06:52:30 +00:00
dependabot[bot]
48b97f3d8e ⬆ Bump tiangolo/issue-manager from 0.4.0 to 0.4.1 (#775)
Bumps [tiangolo/issue-manager](https://github.com/tiangolo/issue-manager) from 0.4.0 to 0.4.1.
- [Release notes](https://github.com/tiangolo/issue-manager/releases)
- [Commits](https://github.com/tiangolo/issue-manager/compare/0.4.0...0.4.1)

---
updated-dependencies:
- dependency-name: tiangolo/issue-manager
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2024-01-09 07:49:37 +01:00
github-actions
fe497adf0c 📝 Update release notes 2023-12-10 20:20:18 +00:00
Sebastián Ramírez
8419545a3a 👷 Fix GitHub Actions build docs filter paths for GitHub workflows (#738)
* 👷 Fix GitHub Actions build docs filter paths for GitHub workflows

* 🎨 Update format of expression and conftest
2023-12-10 20:19:12 +00:00
Sebastián Ramírez
b892504141 🔖 Release version 0.0.14 2023-12-04 15:51:20 +01:00
github-actions
bd24013a26 📝 Update release notes 2023-12-04 14:42:57 +00:00
Sebastián Ramírez
fa2f178b8a Add support for Pydantic v2 (while keeping support for v1 if v2 is not available), including initial work by AntonDeMeester (#722)
Co-authored-by: Mohamed Farahat <farahats9@yahoo.com>
Co-authored-by: Stefan Borer <stefan.borer@gmail.com>
Co-authored-by: Peter Landry <peter.landry@gmail.com>
Co-authored-by: Anton De Meester <antondemeester+github@gmail.com>
2023-12-04 15:42:39 +01:00
Sebastián Ramírez
5b733b348d 🔖 Release version 0.0.13 2023-12-04 13:15:10 +01:00
github-actions
6770b9fd89 📝 Update release notes 2023-12-04 12:13:24 +00:00
Sebastián Ramírez
5c0fca1d96 ✏️ Fix typo, simplify single quote/apostrophe character in "Sister Margaret's" everywhere in the docs (#721) 2023-12-04 13:13:03 +01:00
github-actions
909286cc03 📝 Update release notes 2023-12-04 12:01:06 +00:00
Sebastián Ramírez
276bcf788c 🔧 Update docs build setup, add support for sponsors, add sponsor GOVCERT.LU (#720) 2023-12-04 13:00:47 +01:00
github-actions
cc11619c67 📝 Update release notes 2023-12-04 09:49:42 +00:00
Sebastián Ramírez
41495e30c7 📝 Update docs for Decimal, use proper types (#719) 2023-12-04 09:49:23 +00:00
github-actions
50b0198423 📝 Update release notes 2023-12-04 09:47:19 +00:00
Sebastián Ramírez
853d787923 ♻️ Refactor type generation of selects re-order to prioritize models to optimize editor support (#718) 2023-12-04 09:46:59 +00:00
github-actions
e5fddb97a7 📝 Update release notes 2023-11-30 15:23:25 +00:00
Sebastián Ramírez
4ac87146b1 🔇 Do not raise deprecation warnings for execute as it's automatically used internally (#716)
* 🔇 Do not raise deprecation warnings for execute as it's automatically used internally

*  Tweak tests to not use deprecated query
2023-11-30 15:23:06 +00:00
github-actions
2ecc86275f 📝 Update release notes 2023-11-30 15:20:09 +00:00
pre-commit-ci[bot]
f42314956f ⬆ [pre-commit.ci] pre-commit autoupdate (#697)
updates:
- [github.com/astral-sh/ruff-pre-commit: v0.1.4 → v0.1.6](https://github.com/astral-sh/ruff-pre-commit/compare/v0.1.4...v0.1.6)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-11-30 16:19:47 +01:00
github-actions
98739b071c 📝 Update release notes 2023-11-29 15:52:16 +00:00
Sebastián Ramírez
d8effcbc5c 📝 Add source examples for Python 3.9 and 3.10 (#715)
* 📝 Add source examples for Python 3.9 and 3.10

*  Add tests for new source examples for Python 3.9 and 3.10, still needs pytest markers

*  Add tests for fastapi examples

*  Update tests for FastAPI app testing, for Python 3.9 and 3.10, fixing multi-app testing conflicts

*  Require Python 3.9 and 3.10 for tests

*  Update tests with missing markers
2023-11-29 16:51:55 +01:00
github-actions
cce30d7546 📝 Update release notes 2023-11-28 22:41:22 +00:00
Sebastián Ramírez
33c5e5c98d 🔧 Show line numbers in docs during local development (#714)
🔧 Show line numbers during local development
2023-11-28 23:41:03 +01:00
github-actions
2b0dfb50c8 📝 Update release notes 2023-11-28 22:12:55 +00:00
Sebastián Ramírez
799d0aa7a6 📝 Update details syntax with new pymdown extensions format (#713) 2023-11-28 23:12:33 +01:00
github-actions
be464fba69 📝 Update release notes 2023-11-28 20:50:54 +00:00
Sebastián Ramírez
a95bd3873d 🔧 Update config with new pymdown extensions (#712)
* 🔧 Update config with new pymdown extensions

* 📝 Update admonition blocks syntax

* 📝 Update syntax for tabs with new pymdown extensions
2023-11-28 21:50:33 +01:00
github-actions
71baff6015 📝 Update release notes 2023-11-27 09:58:47 +00:00
Sebastián Ramírez
f18ea03b07 🙈 Update gitignore, include all coverage files (#711) 2023-11-27 09:58:25 +00:00
github-actions
65ee2610b6 📝 Update release notes 2023-11-26 14:20:17 +00:00
Sebastián Ramírez
47bcd9df8d ⬆️ Add support for Python 3.11 and Python 3.12 (#710) 2023-11-26 15:20:01 +01:00
github-actions
781a2d6b0a 📝 Update release notes 2023-11-26 13:57:29 +00:00
Sebastián Ramírez
a974d9104f Move OpenAPI tests inline to simplify updating them with Pydantic v2 (#709) 2023-11-26 13:57:12 +00:00
Sebastián Ramírez
b1c2f822c9 🔖 Release version 0.0.12 2023-11-18 12:32:59 +01:00
Sebastián Ramírez
382b1b0cbb 📝 Update release notes 2023-11-18 12:32:24 +01:00
github-actions
6d00f6fcbd 📝 Update release notes 2023-11-18 11:30:55 +00:00
Sebastián Ramírez
8ed856d322 Upgrade SQLAlchemy to 2.0, including initial work by farahats9 (#700)
Co-authored-by: Mohamed Farahat <farahats9@yahoo.com>
Co-authored-by: Stefan Borer <stefan.borer@gmail.com>
Co-authored-by: Peter Landry <peter.landry@gmail.com>
2023-11-18 12:30:37 +01:00
github-actions
77c6fed305 📝 Update release notes 2023-11-08 16:04:47 +00:00
pre-commit-ci[bot]
c0294423f4 ⬆ [pre-commit.ci] pre-commit autoupdate (#686)
updates:
- https://github.com/charliermarsh/ruff-pre-commithttps://github.com/astral-sh/ruff-pre-commit
- [github.com/astral-sh/ruff-pre-commit: v0.1.2 → v0.1.4](https://github.com/astral-sh/ruff-pre-commit/compare/v0.1.2...v0.1.4)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-11-08 17:04:24 +01:00
github-actions
e05eae6a49 📝 Update release notes 2023-11-04 01:43:16 +00:00
Sebastián Ramírez
ed22232dee 👷 Upgrade latest-changes GitHub Action (#693) 2023-11-04 01:42:52 +00:00
Sebastián Ramírez
dacc1fa9ca 🔖 Release version 0.0.11 2023-10-29 13:56:39 +04:00
Sebastián Ramírez
0b2d015fc4 📝 Update release notes 2023-10-29 13:56:00 +04:00
github-actions
d8a20d9c21 📝 Update release notes 2023-10-29 09:21:52 +00:00
dependabot[bot]
188f7cd172 ⬆ Update coverage requirement from ^6.2 to >=6.2,<8.0 (#663)
Updates the requirements on [coverage](https://github.com/nedbat/coveragepy) to permit the latest version.
- [Release notes](https://github.com/nedbat/coveragepy/releases)
- [Changelog](https://github.com/nedbat/coveragepy/blob/master/CHANGES.rst)
- [Commits](https://github.com/nedbat/coveragepy/compare/6.2...7.2.7)

---
updated-dependencies:
- dependency-name: coverage
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-29 09:18:26 +00:00
github-actions
12af94655b 📝 Update release notes 2023-10-29 09:09:02 +00:00
dependabot[bot]
4bb99763b1 ⬆ Update mkdocs-material requirement from 9.1.21 to 9.2.7 (#675)
Updates the requirements on [mkdocs-material](https://github.com/squidfunk/mkdocs-material) to permit the latest version.
- [Release notes](https://github.com/squidfunk/mkdocs-material/releases)
- [Changelog](https://github.com/squidfunk/mkdocs-material/blob/master/CHANGELOG)
- [Commits](https://github.com/squidfunk/mkdocs-material/compare/9.1.21...9.2.7)

---
updated-dependencies:
- dependency-name: mkdocs-material
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-29 13:08:22 +04:00
github-actions
9dd11ef74f 📝 Update release notes 2023-10-29 09:00:31 +00:00
Sebastián Ramírez
fa5d14e413 ⬆️ Upgrade mypy manually (#684) 2023-10-29 08:59:56 +00:00
github-actions
df1efcfa7f 📝 Update release notes 2023-10-29 08:55:43 +00:00
dependabot[bot]
fc1d7afae9 ⬆ Update black requirement from ^22.10.0 to >=22.10,<24.0 (#664)
Updates the requirements on [black](https://github.com/psf/black) to permit the latest version.
- [Release notes](https://github.com/psf/black/releases)
- [Changelog](https://github.com/psf/black/blob/main/CHANGES.md)
- [Commits](https://github.com/psf/black/compare/22.10.0...23.3.0)

---
updated-dependencies:
- dependency-name: black
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-29 08:55:04 +00:00
github-actions
a2d1b4eeaf 📝 Update release notes 2023-10-29 08:52:01 +00:00
Sebastián Ramírez
94f3765fcf 👷 Update CI to build MkDocs Insiders only when the secrets are available, for Dependabot (#683) 2023-10-29 12:51:26 +04:00
github-actions
31ed654dd0 📝 Update release notes 2023-10-29 08:11:21 +00:00
Maruo.S
cbaf172c63 Add support for passing a custom SQLAlchemy type to Field() with sa_type (#505)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-29 12:10:39 +04:00
github-actions
c557cf6d18 📝 Update release notes 2023-10-29 07:25:17 +00:00
Matthieu LAURENT
9632980664 🎨 Update inline source examples, hide # in annotations (from MkDocs Material) (#677)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-29 07:24:32 +00:00
github-actions
6457775a0f 📝 Update release notes 2023-10-28 13:55:56 +00:00
Sebastián Ramírez
717594ef13 Do not allow invalid combinations of field parameters for columns and relationships, sa_column excludes sa_column_args, primary_key, nullable, etc. (#681)
* ♻️ Make sa_column exclusive, do not allow incompatible arguments, sa_column_args, primary_key, etc

*  Add tests for new errors when incorrectly using sa_column

*  Add tests for sa_column_args and sa_column_kwargs

* ♻️ Do not allow sa_relationship with sa_relationship_args or sa_relationship_kwargs

*  Add tests for relationship errors

*  Fix test for sa_column_args
2023-10-28 17:55:23 +04:00
Sebastián Ramírez
e4e1385eed 🔖 Release version 0.0.10 2023-10-26 18:34:49 +04:00
github-actions
13cc722110 📝 Update release notes 2023-10-26 14:32:59 +00:00
Sebastián Ramírez
7fdfee10a5 🔧 Adopt Ruff for formatting (#679) 2023-10-26 18:32:26 +04:00
github-actions
8d14232538 📝 Update release notes 2023-10-26 10:18:41 +00:00
Daniil Fajnberg
99f8ce3894 Add support for all Field parameters from Pydantic 1.9.0 and above, make Pydantic 1.9.0 the minimum required version (#440)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-26 14:18:05 +04:00
Sebastián Ramírez
d05c3ee495 🔖 Release version 0.0.9 2023-10-24 01:01:18 +04:00
Sebastián Ramírez
596718d93b 📝 Update release notes 2023-10-24 00:59:49 +04:00
github-actions
a6ce817ca5 📝 Update release notes 2023-10-23 20:46:39 +00:00
github-actions
dcc4e4c36a 📝 Update release notes 2023-10-23 20:46:26 +00:00
Simon Weiß
80fd7e03cf 📝 Clarify description of in-memory SQLite database in docs/tutorial/create-db-and-table.md (#601)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 20:46:05 +00:00
pre-commit-ci[bot]
1acb683f80 ⬆ [pre-commit.ci] pre-commit autoupdate (#672)
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.4.0 → v4.5.0](https://github.com/pre-commit/pre-commit-hooks/compare/v4.4.0...v4.5.0)
- [github.com/asottile/pyupgrade: v3.7.0 → v3.15.0](https://github.com/asottile/pyupgrade/compare/v3.7.0...v3.15.0)
- https://github.com/charliermarsh/ruff-pre-commithttps://github.com/astral-sh/ruff-pre-commit
- [github.com/astral-sh/ruff-pre-commit: v0.0.275 → v0.1.1](https://github.com/astral-sh/ruff-pre-commit/compare/v0.0.275...v0.1.1)
- [github.com/psf/black: 23.3.0 → 23.10.0](https://github.com/psf/black/compare/23.3.0...23.10.0)

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-24 00:45:45 +04:00
github-actions
9fd7306648 📝 Update release notes 2023-10-23 20:37:48 +00:00
Sebastián Ramírez
9d3ca01dd0 📝 Tweak wording in docs/tutorial/fastapi/multiple-models.md (#674)
Co-authored-by: Luis Benitez <lbenitez000@gmail.com>
2023-10-23 20:37:07 +00:00
github-actions
6cd086f25f 📝 Update release notes 2023-10-23 19:22:23 +00:00
PookieBuns
376603efb2 ✏️ Fix contributing instructions to run tests, update script name (#634)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 19:21:38 +00:00
github-actions
30d2b30217 📝 Update release notes 2023-10-23 17:22:58 +00:00
Abenezer Belachew
9b186c89a8 📝 Update link to docs for intro to databases (#593)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 17:22:22 +00:00
github-actions
fc3120a877 📝 Update release notes 2023-10-23 17:06:30 +00:00
dependabot[bot]
6d361e3ffb ⬆ Bump dawidd6/action-download-artifact from 2.24.2 to 2.28.0 (#660)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.24.2 to 2.28.0.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.24.2...v2.28.0)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-23 21:05:55 +04:00
github-actions
03f295b397 📝 Update release notes 2023-10-23 16:56:29 +00:00
Jon Michaelchuck
403d44ea78 📝 Update docs, use offset in example with limit and where (#273)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 20:55:53 +04:00
github-actions
a1caaa08d7 📝 Update release notes 2023-10-23 16:29:36 +00:00
Jerry Wu
d192142eb9 📝 Fix docs for Pydantic's fields using le (lte is invalid, use le ) (#207)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 16:28:51 +00:00
github-actions
beb7a24275 📝 Update release notes 2023-10-23 15:33:44 +00:00
Sebastián Ramírez
dee70033b8 Refactor OpenAPI FastAPI tests to simplify updating them later, this moves things around without changes (#671) 2023-10-23 15:33:08 +00:00
github-actions
189059e07e 📝 Update release notes 2023-10-23 15:32:48 +00:00
dependabot[bot]
475b838c8b ⬆ Bump actions/checkout from 3 to 4 (#670)
Bumps [actions/checkout](https://github.com/actions/checkout) from 3 to 4.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v3...v4)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2023-10-23 19:32:09 +04:00
github-actions
d6e4f9b9e3 📝 Update release notes 2023-10-23 15:16:53 +00:00
Michael Oliver
1062e1b485 🔧 Update mypy config, use strict = true instead of manual configs (#428)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 19:16:17 +04:00
github-actions
8e55ea5125 📝 Update release notes 2023-10-23 14:58:52 +00:00
Arseny Boykov
9732c5ac60 🐛 Fix AsyncSession type annotations for exec() (#58)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 18:58:16 +04:00
github-actions
b8996f0e62 📝 Update release notes 2023-10-23 13:59:53 +00:00
Daniil Fajnberg
9809b5bc83 🐛 Fix allowing using a ForeignKey directly, remove repeated column construction from SQLModelMetaclass.__init__ and upgrade minimum SQLAlchemy to >=1.4.36 (#443)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 17:59:06 +04:00
github-actions
c213f5daf4 📝 Update release notes 2023-10-23 11:22:53 +00:00
Sandro Tosi
d1cf613461 ⬆️ Upgrade support for SQLAlchemy 1.4.49, update tests (#519)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2023-10-23 15:22:10 +04:00
github-actions
d281a0fa9f 📝 Update release notes 2023-10-23 09:40:31 +00:00
Daniil Fajnberg
9511c4677d ⬆ Raise SQLAlchemy version requirement to at least 1.4.29 (related to #434) (#439)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 13:39:55 +04:00
github-actions
c25a8cb89b 📝 Update release notes 2023-10-23 09:23:24 +00:00
Sebastián Ramírez
d3261cab59 🐛 Fix enum type checks ordering in get_sqlalchemy_type (#669)
Co-authored-by: Pierre Cheynier <p.cheynier@criteo.com>
2023-10-23 13:22:44 +04:00
github-actions
40c1af9202 📝 Update release notes 2023-10-23 08:15:40 +00:00
Sebastián Ramírez
b83e848699 ⬆️ Upgrade MkDocs Material (#668) 2023-10-23 08:15:05 +00:00
github-actions
2676cf2b06 📝 Update release notes 2023-10-23 08:12:08 +00:00
Sebastián Ramírez
56f43904c1 🎨 Update docs format and references with pre-commit and Ruff (#667) 2023-10-23 08:11:36 +00:00
github-actions
7c5894ee75 📝 Update release notes 2023-10-23 07:47:04 +00:00
Sebastián Ramírez
27a81b2112 🎨 Run pre-commit on all files and autoformat (#666) 2023-10-23 11:46:31 +04:00
github-actions
7f72c60ae4 📝 Update release notes 2023-10-23 07:35:25 +00:00
Sebastián Ramírez
065fcdc828 👷 Move to Ruff and add pre-commit (#661)
* 👷 Add pre-commit

* 🔧 Add pyproject.toml config for Ruff

*  Replace isort, flake8, autoflake with Ruff

* 🔨 Update lint and format scripts

* 🎨 Format with Ruff

* 🔧 Update Poetry config
2023-10-23 07:34:50 +00:00
github-actions
9ba3039106 📝 Update release notes 2023-10-23 06:43:04 +00:00
David Danier
840fd08ab2 Raise a more clear error when a type is not valid (#425)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-23 10:42:30 +04:00
github-actions
a8a792e3c0 📝 Update release notes 2023-10-22 12:55:08 +00:00
Matvey Fedoseev
8970833b14 📝 Update outdated link in docs/db-to-code.md (#649)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-22 12:54:36 +00:00
github-actions
5231c8b6bb 📝 Update release notes 2023-10-22 12:51:20 +00:00
Kian-Meng Ang
1568bad01e ✏️ Fix typos found with codespell (#520)
Found via `codespell -S *.svg,*.css,*.js,*.drawio -L pullrequest,sesion`
2023-10-22 16:50:44 +04:00
github-actions
357417e6d5 📝 Update release notes 2023-10-22 12:47:27 +00:00
Dipendra Raj Panta
893d64fd31 📝 Fix typos (duplication) in main page (#631)
* Update README.md

* Update index.md
2023-10-22 16:46:52 +04:00
github-actions
2799303f6c 📝 Update release notes 2023-10-22 12:27:13 +00:00
Ben Rapaport
a2e2942aad 📝 Update release notes, add second author to PR (#429)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-22 12:26:37 +00:00
github-actions
b7d6a0a3c3 📝 Update release notes 2023-10-22 12:04:24 +00:00
Jorge Alvarado
bdcf11bca6 📝 Update instructions about how to make a foreign key required in docs/tutorial/relationship-attributes/define-relationships-attributes.md (#474)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-22 16:03:51 +04:00
github-actions
d939b7c45c 📝 Update release notes 2023-10-22 12:02:24 +00:00
byrman
d5219aa3c5 🐛 Fix SQLAlchemy version 1.4.36 breaks SQLModel relationships (#315) (#461)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-22 16:01:51 +04:00
github-actions
aa7169b93b 📝 Update release notes 2023-10-22 10:03:26 +00:00
Sugato Ray
89c356cb77 🛠️ Add CITATION.cff file for academic citations (#13)
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2023-10-22 14:02:53 +04:00
github-actions
088164ef2a 📝 Update release notes 2023-08-01 09:19:41 +00:00
Sebastián Ramírez
1e2fd10047 👷 Update docs deployments to Cloudflare (#630) 2023-08-01 11:18:53 +02:00
github-actions
30a9c23a34 📝 Update release notes 2023-07-31 19:53:00 +00:00
github-actions
da29f7940d 📝 Update release notes 2023-07-31 19:52:51 +00:00
github-actions
40007c80da 📝 Update release notes 2023-07-31 19:48:54 +00:00
Sebastián Ramírez
e246ae8864 👷 Update CI debug mode with Tmate (#629) 2023-07-31 19:48:21 +00:00
github-actions
aaa54492c1 📝 Update release notes 2023-07-31 19:39:15 +00:00
Sebastián Ramírez
73fa81af74 👷 Update latest changes token (#616) 2023-07-31 19:38:43 +00:00
Sebastián Ramírez
a21d5c85a3 👷‍♂️ Upgrade CI for docs (#628) 2023-07-31 17:15:43 +02:00
Sebastián Ramírez
02bd7ebffd 🗑️ Deprecate Python 3.6 and upgrade Poetry and Poetry Version Plugin (#627) 2023-07-29 12:32:47 +02:00
github-actions
43a689d369 📝 Update release notes 2023-02-21 11:02:54 +00:00
Sebastián Ramírez
810236c26c ⬆️ Upgrade analytics (#558) 2023-02-21 11:02:18 +00:00
github-actions
33e00c3ab3 📝 Update release notes 2023-02-03 17:53:01 +00:00
Sebastián Ramírez
5c9a3b3b21 📝 Update help SQLModel docs (#548) 2023-02-03 18:52:25 +01:00
github-actions
dc44d2e2c4 📝 Update release notes 2023-01-31 14:14:55 +00:00
Sebastián Ramírez
1c294ddeb6 🔧 Update new issue chooser to point to GitHub Discussions (#546) 2023-01-31 15:14:16 +01:00
github-actions
c47a54df91 📝 Update release notes 2023-01-30 10:50:32 +00:00
Sebastián Ramírez
624a2142bf 🔧 Add template for GitHub Discussion questions and update issues template (#544) 2023-01-30 11:49:56 +01:00
github-actions
7b3148c0b4 📝 Update release notes 2022-12-16 18:46:26 +00:00
Sebastián Ramírez
cf36b2d9ba 👷 Refactor CI artifact upload/download for docs previews (#514) 2022-12-16 18:45:51 +00:00
github-actions
5fa9062ed9 📝 Update release notes 2022-11-12 06:44:52 +00:00
Colin Marquardt
267cd42fb6 ✏️ Fix typo in internal function name get_sqlachemy_type() (#496)
Corrected name is get_sqlalchemy_type().
2022-11-12 07:44:19 +01:00
github-actions
497270dc55 📝 Update release notes 2022-11-12 06:38:16 +00:00
dependabot[bot]
aa87ff37ea ⬆ Bump actions/cache from 2 to 3 (#497)
Bumps [actions/cache](https://github.com/actions/cache) from 2 to 3.
- [Release notes](https://github.com/actions/cache/releases)
- [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md)
- [Commits](https://github.com/actions/cache/compare/v2...v3)

---
updated-dependencies:
- dependency-name: actions/cache
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-12 07:37:34 +01:00
github-actions
0fe1e6d5a3 📝 Update release notes 2022-11-11 17:30:42 +00:00
David Brochart
54b5db9842 ✏️ Fix typo in docs (#446)
* Fix typo

* Again

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-11 17:30:09 +00:00
github-actions
c31bac638c 📝 Update release notes 2022-11-10 06:43:44 +00:00
dependabot[bot]
203db14e9b ⬆ Bump dawidd6/action-download-artifact from 2.24.0 to 2.24.2 (#493)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.24.0 to 2.24.2.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.24.0...v2.24.2)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-10 07:43:06 +01:00
github-actions
06bb369bcb 📝 Update release notes 2022-11-08 15:04:40 +00:00
Santhosh Solomon
209791734c ✏️ Fix typo in docs/tutorial/create-db-and-table.md (#477)
typo fixed in docs/tutorial/create-db-and-table.md

Co-authored-by: Santhosh Solomon <santhoshsolomon@Santhoshs-MacBook-Air.local>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-08 15:04:06 +00:00
github-actions
fbc6f3b536 📝 Update release notes 2022-11-07 14:21:59 +00:00
Michael Cuffaro
22faa192b9 ✏️ Fix small typos in docs (#481)
Fix small typos

Fixing small typos here and there while reading the document.

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-07 14:21:23 +00:00
github-actions
3a9244c69f 📝 Update release notes 2022-11-05 01:04:44 +00:00
Sebastián Ramírez
8070b142b8 🔧 Update Smokeshow coverage threshold (#487) 2022-11-05 02:04:13 +01:00
github-actions
f0aa199611 📝 Update release notes 2022-11-04 22:02:09 +00:00
Sebastián Ramírez
5956940908 👷 Move from Codecov to Smokeshow (#486) 2022-11-04 22:01:37 +00:00
github-actions
ea79c47c0e 📝 Update release notes 2022-11-04 21:44:25 +00:00
dependabot[bot]
7e26dac198 ⬆ Bump actions/setup-python from 2 to 4 (#411)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-04 22:43:45 +01:00
github-actions
bb32178bda 📝 Update release notes 2022-11-04 21:32:51 +00:00
dependabot[bot]
5ca9375f26 ⬆ Update black requirement from ^21.5-beta.1 to ^22.10.0 (#460)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-04 22:32:13 +01:00
github-actions
e7d8b69b53 📝 Update release notes 2022-11-04 21:18:47 +00:00
Sebastián Ramírez
c6ad5b8109 Add extra dev dependencies for MkDocs Material (#485) 2022-11-04 22:16:59 +01:00
github-actions
8003c73877 📝 Update release notes 2022-11-04 21:14:56 +00:00
github-actions
b532a4c304 📝 Update release notes 2022-11-04 21:14:34 +00:00
dependabot[bot]
29d9721d1a ⬆ Update mypy requirement from 0.930 to 0.971 (#380)
Update mypy requirement from 0.930 to 0.971

Updates the requirements on [mypy](https://github.com/python/mypy) to permit the latest version.
- [Release notes](https://github.com/python/mypy/releases)
- [Commits](https://github.com/python/mypy/compare/v0.930...v0.971)

---
updated-dependencies:
- dependency-name: mypy
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 22:14:11 +01:00
dependabot[bot]
f0f6f93e28 ⬆ Update coverage requirement from ^5.5 to ^6.2 (#171)
Update coverage requirement from ^5.5 to ^6.2

Updates the requirements on [coverage](https://github.com/nedbat/coveragepy) to permit the latest version.
- [Release notes](https://github.com/nedbat/coveragepy/releases)
- [Changelog](https://github.com/nedbat/coveragepy/blob/master/CHANGES.rst)
- [Commits](https://github.com/nedbat/coveragepy/compare/coverage-5.5...6.2)

---
updated-dependencies:
- dependency-name: coverage
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-04 22:13:58 +01:00
github-actions
91d8e38208 📝 Update release notes 2022-11-04 21:03:39 +00:00
github-actions
ccdab8fb24 📝 Update release notes 2022-11-04 21:02:59 +00:00
dependabot[bot]
592c877cfc ⬆ Bump codecov/codecov-action from 2 to 3 (#415)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 22:00:58 +01:00
dependabot[bot]
fee7ecf619 ⬆ Bump actions/upload-artifact from 2 to 3 (#412)
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 22:00:21 +01:00
github-actions
e8f61fb9d0 📝 Update release notes 2022-11-04 21:00:05 +00:00
dependabot[bot]
781174e6e9 ⬆ Update flake8 requirement from ^3.9.2 to ^5.0.4 (#396)
Updates the requirements on [flake8](https://github.com/pycqa/flake8) to permit the latest version.
- [Release notes](https://github.com/pycqa/flake8/releases)
- [Commits](https://github.com/pycqa/flake8/compare/3.9.2...5.0.4)

---
updated-dependencies:
- dependency-name: flake8
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-11-04 21:59:26 +01:00
github-actions
ba76745f43 📝 Update release notes 2022-11-04 20:45:07 +00:00
github-actions
5615a80fc5 📝 Update release notes 2022-11-04 20:44:06 +00:00
dependabot[bot]
375e83d068 ⬆ Update pytest requirement from ^6.2.4 to ^7.0.1 (#242)
Updates the requirements on [pytest](https://github.com/pytest-dev/pytest) to permit the latest version.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/6.2.4...7.0.1)

---
updated-dependencies:
- dependency-name: pytest
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 21:44:02 +01:00
github-actions
666a9a3557 📝 Update release notes 2022-11-04 20:43:32 +00:00
dependabot[bot]
1dde3e0044 ⬆ Bump actions/checkout from 2 to 3.1.0 (#458)
Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.1.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v2...v3.1.0)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 21:43:25 +01:00
dependabot[bot]
8b87bf8b40 ⬆ Bump dawidd6/action-download-artifact from 2.9.0 to 2.24.0 (#470)
Bumps [dawidd6/action-download-artifact](https://github.com/dawidd6/action-download-artifact) from 2.9.0 to 2.24.0.
- [Release notes](https://github.com/dawidd6/action-download-artifact/releases)
- [Commits](https://github.com/dawidd6/action-download-artifact/compare/v2.9.0...v2.24.0)

---
updated-dependencies:
- dependency-name: dawidd6/action-download-artifact
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2022-11-04 21:43:01 +01:00
github-actions
94715b6fa8 📝 Update release notes 2022-11-04 20:05:07 +00:00
Sebastián Ramírez
27a16744f2 👷 Update Dependabot config (#484) 2022-11-04 21:04:31 +01:00
Sebastián Ramírez
75ce45588b 🔖 Release version 0.0.8 2022-08-30 19:52:36 +02:00
Sebastián Ramírez
b3e1a66a21 🔖 Release version 0.0.8 2022-08-30 19:47:41 +02:00
Sebastián Ramírez
c94db7b8a0 📝 Update release notes 2022-08-30 19:46:58 +02:00
github-actions
a67326d358 📝 Update release notes 2022-08-30 16:36:07 +00:00
Sebastián Ramírez
e88b5d3691 📝 Adjust and clarify docs for docs/tutorial/create-db-and-table.md (#426) 2022-08-30 16:35:29 +00:00
github-actions
fdb049bee3 📝 Update release notes 2022-08-30 16:19:19 +00:00
Jonas Krüger Svensson
ae144e0a39 🐛 Fix auto detecting and setting nullable, allowing overrides in field (#423)
Co-authored-by: Benjamin Rapaport <br@getallstreet.com>
Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
2022-08-30 18:18:32 +02:00
github-actions
85f5e7fc45 📝 Update release notes 2022-08-29 09:44:50 +00:00
Sebastián Ramírez
b51ebaf658 ♻️ Update expresion.py, sync from Jinja2 template, implement inherit_cache to solve errors like: SAWarning: Class SelectOfScalar will not make use of SQL compilation caching (#422) 2022-08-29 11:44:08 +02:00
github-actions
f232166db5 📝 Update release notes 2022-08-29 08:34:17 +00:00
Theodore Williams
4143edd251 ✏ Fix typo in docs/tutorial/connect/remove-data-connections.md (#421) 2022-08-29 10:33:41 +02:00
477 changed files with 31216 additions and 5680 deletions

View File

@@ -1,5 +1,3 @@
name: Question or Problem
description: Ask a question or ask about a problem
labels: [question]
body:
- type: markdown
@@ -8,29 +6,29 @@ body:
Thanks for your interest in SQLModel! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
I'm asking this because answering questions and solving problems in GitHub is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling questions.
All that, on top of all the incredible help provided by a bunch of community members that give a lot of their time to come here and help others.
If more SQLModel users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
As there are too many questions, I'll have to discard and close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: I added a very descriptive title to this issue.
- label: I added a very descriptive title here.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
- label: I used the GitHub search to find a similar question and didn't find it.
required: true
- label: I searched the SQLModel documentation, with the integrated search.
required: true
@@ -48,10 +46,10 @@ body:
label: Commit to Help
description: |
After submitting this, I commit to one of:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
* Review one Pull Request by downloading the code and following all the review process](https://sqlmodel.tiangolo.com/help/#review-pull-requests).
options:
- label: I commit to help with one of those options 👆

View File

@@ -2,3 +2,12 @@ blank_issues_enabled: false
contact_links:
- name: Security Contact
about: Please report security vulnerabilities to security@tiangolo.com
- name: Question or Problem
about: Ask a question or ask about a problem in GitHub Discussions.
url: https://github.com/tiangolo/sqlmodel/discussions/categories/questions
- name: Feature Request
about: To suggest an idea or ask about a feature, please start with a question saying what you would like to achieve. There might be a way to do it already.
url: https://github.com/tiangolo/sqlmodel/discussions/categories/questions
- name: Show and tell
about: Show what you built with SQLModel or to be used with SQLModel.
url: https://github.com/tiangolo/sqlmodel/discussions/categories/show-and-tell

View File

@@ -1,214 +0,0 @@
name: Feature Request
description: Suggest an idea or ask for a feature that you would like to have in SQLModel
labels: [enhancement]
body:
- type: markdown
attributes:
value: |
Thanks for your interest in SQLModel! 🚀
Please follow these instructions, fill every question, and do every step. 🙏
I'm asking this because answering questions and solving problems in GitHub issues is what consumes most of the time.
I end up not being able to add new features, fix bugs, review pull requests, etc. as fast as I wish because I have to spend too much time handling issues.
All that, on top of all the incredible help provided by a bunch of community members that give a lot of their time to come here and help others.
If more SQLModel users came to help others like them just a little bit more, it would be much less effort for them (and you and me 😅).
By asking questions in a structured way (following this) it will be much easier to help you.
And there's a high chance that you will find the solution along the way and you won't even have to submit it and wait for an answer. 😎
As there are too many issues with questions, I'll have to close the incomplete ones. That will allow me (and others) to focus on helping people like you that follow the whole process and help us help you. 🤓
- type: checkboxes
id: checks
attributes:
label: First Check
description: Please confirm and check all the following options.
options:
- label: I added a very descriptive title to this issue.
required: true
- label: I used the GitHub search to find a similar issue and didn't find it.
required: true
- label: I searched the SQLModel documentation, with the integrated search.
required: true
- label: I already searched in Google "How to X in SQLModel" and didn't find any information.
required: true
- label: I already read and followed all the tutorial in the docs and didn't find an answer.
required: true
- label: I already checked if it is not related to SQLModel but to [Pydantic](https://github.com/samuelcolvin/pydantic).
required: true
- label: I already checked if it is not related to SQLModel but to [SQLAlchemy](https://github.com/sqlalchemy/sqlalchemy).
required: true
- type: checkboxes
id: help
attributes:
label: Commit to Help
description: |
After submitting this, I commit to one of:
* Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
* I already hit the "watch" button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
* Implement a Pull Request for a confirmed bug.
options:
- label: I commit to help with one of those options 👆
required: true
- type: textarea
id: example
attributes:
label: Example Code
description: |
Please add a self-contained, [minimal, reproducible, example](https://stackoverflow.com/help/minimal-reproducible-example) with your use case.
If I (or someone) can copy it, run it, and see it right away, there's a much higher chance I (or someone) will be able to help you.
placeholder: |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(hero_1)
session.commit()
session.refresh(hero_1)
print(hero_1)
render: python
validations:
required: true
- type: textarea
id: description
attributes:
label: Description
description: |
What is your feature request?
Write a short description telling me what you are trying to solve and what you are currently doing.
placeholder: |
* Create a Hero model.
* Create a Hero instance.
* Save it to a SQLite database.
* I would like it to also automatically send me an email with all the SQL code executed.
validations:
required: true
- type: textarea
id: wanted-solution
attributes:
label: Wanted Solution
description: |
Tell me what's the solution you would like.
placeholder: |
I would like it to have a `send_email` configuration that defaults to `False`, and can be set to `True` to send me an email.
validations:
required: true
- type: textarea
id: wanted-code
attributes:
label: Wanted Code
description: Show me an example of how you would want the code to look like.
placeholder: |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Hero(SQLModel, table=True, send_email=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
hero_1 = Hero(name="Deadpond", secret_name="Dive Wilson")
engine = create_engine("sqlite:///database.db")
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
session.add(hero_1)
session.commit()
session.refresh(hero_1)
print(hero_1)
render: python
validations:
required: true
- type: textarea
id: alternatives
attributes:
label: Alternatives
description: |
Tell me about alternatives you've considered.
placeholder: |
To hire someone to look at the logs, write the SQL in paper, and then send me a letter by post with it.
- type: dropdown
id: os
attributes:
label: Operating System
description: What operating system are you on?
multiple: true
options:
- Linux
- Windows
- macOS
- Other
validations:
required: true
- type: textarea
id: os-details
attributes:
label: Operating System Details
description: You can add more details about your operating system here, in particular if you chose "Other".
- type: input
id: sqlmodel-version
attributes:
label: SQLModel Version
description: |
What SQLModel version are you using?
You can find the SQLModel version with:
```bash
python -c "import sqlmodel; print(sqlmodel.__version__)"
```
validations:
required: true
- type: input
id: python-version
attributes:
label: Python Version
description: |
What Python version are you using?
You can find the Python version with:
```bash
python --version
```
validations:
required: true
- type: textarea
id: context
attributes:
label: Additional Context
description: Add any additional context information or screenshots you think are useful.

22
.github/ISSUE_TEMPLATE/privileged.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Privileged
description: You are @tiangolo or he asked you directly to create an issue here. If not, check the other options. 👇
body:
- type: markdown
attributes:
value: |
Thanks for your interest in SQLModel! 🚀
If you are not @tiangolo or he didn't ask you directly to create an issue here, please start the conversation in a [Question in GitHub Discussions](https://github.com/tiangolo/sqlmodel/discussions/categories/questions) instead.
- type: checkboxes
id: privileged
attributes:
label: Privileged issue
description: Confirm that you are allowed to create an issue here.
options:
- label: I'm @tiangolo or he asked me directly to create an issue here.
required: true
- type: textarea
id: content
attributes:
label: Issue Content
description: Add the content of the issue here.

View File

@@ -48,9 +48,7 @@ if __name__ == "__main__":
use_pr = pr
break
if not use_pr:
logging.error(
f"No PR found for hash: {event.workflow_run.head_commit.id}"
)
logging.error(f"No PR found for hash: {event.workflow_run.head_commit.id}")
sys.exit(0)
github_headers = {
"Authorization": f"token {settings.input_token.get_secret_value()}"

View File

@@ -1,7 +0,0 @@
FROM python:3.7
RUN pip install httpx PyGithub "pydantic==1.5.1"
COPY ./app /app
CMD ["python", "/app/main.py"]

View File

@@ -1,10 +0,0 @@
name: Watch docs previews in PRs
description: Check PRs and trigger new docs deploys
author: "Sebastián Ramírez <tiangolo@gmail.com>"
inputs:
token:
description: 'Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }}'
required: true
runs:
using: docker
image: Dockerfile

View File

@@ -1,102 +0,0 @@
import logging
from datetime import datetime
from pathlib import Path
from typing import List, Optional
import httpx
from github import Github
from github.NamedUser import NamedUser
from pydantic import BaseModel, BaseSettings, SecretStr
github_api = "https://api.github.com"
netlify_api = "https://api.netlify.com"
main_branch = "main"
class Settings(BaseSettings):
input_token: SecretStr
github_repository: str
github_event_path: Path
github_event_name: Optional[str] = None
class Artifact(BaseModel):
id: int
node_id: str
name: str
size_in_bytes: int
url: str
archive_download_url: str
expired: bool
created_at: datetime
updated_at: datetime
class ArtifactResponse(BaseModel):
total_count: int
artifacts: List[Artifact]
def get_message(commit: str) -> str:
return f"Docs preview for commit {commit} at"
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
settings = Settings()
logging.info(f"Using config: {settings.json()}")
g = Github(settings.input_token.get_secret_value())
repo = g.get_repo(settings.github_repository)
owner: NamedUser = repo.owner
headers = {"Authorization": f"token {settings.input_token.get_secret_value()}"}
prs = list(repo.get_pulls(state="open"))
response = httpx.get(
f"{github_api}/repos/{settings.github_repository}/actions/artifacts",
headers=headers,
)
data = response.json()
artifacts_response = ArtifactResponse.parse_obj(data)
for pr in prs:
logging.info("-----")
logging.info(f"Processing PR #{pr.number}: {pr.title}")
pr_comments = list(pr.get_issue_comments())
pr_commits = list(pr.get_commits())
last_commit = pr_commits[0]
for pr_commit in pr_commits:
if pr_commit.commit.author.date > last_commit.commit.author.date:
last_commit = pr_commit
commit = last_commit.commit.sha
logging.info(f"Last commit: {commit}")
message = get_message(commit)
notified = False
for pr_comment in pr_comments:
if message in pr_comment.body:
notified = True
logging.info(f"Docs preview was notified: {notified}")
if not notified:
artifact_name = f"docs-zip-{commit}"
use_artifact: Optional[Artifact] = None
for artifact in artifacts_response.artifacts:
if artifact.name == artifact_name:
use_artifact = artifact
break
if not use_artifact:
logging.info("Artifact not available")
else:
logging.info(f"Existing artifact: {use_artifact.name}")
response = httpx.post(
f"{github_api}/repos/{settings.github_repository}/actions/workflows/preview-docs.yml/dispatches",
headers=headers,
json={
"ref": main_branch,
"inputs": {
"pr": f"{pr.number}",
"name": artifact_name,
"commit": commit,
},
},
)
logging.info(
f"Trigger sent, response status: {response.status_code} - content: {response.content}"
)
logging.info("Finished")

View File

@@ -5,8 +5,12 @@ updates:
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:
# Python
- package-ecosystem: "pip"
directory: "/"
schedule:
interval: "daily"
commit-message:
prefix:

View File

@@ -4,78 +4,91 @@ on:
branches:
- main
pull_request:
types: [opened, synchronize]
workflow_dispatch:
inputs:
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
types:
- opened
- synchronize
jobs:
changes:
runs-on: ubuntu-latest
# Required permissions
permissions:
pull-requests: read
# Set job outputs to values from filter step
outputs:
docs: ${{ steps.filter.outputs.docs }}
steps:
- uses: actions/checkout@v4
# For pull requests it's not necessary to checkout the code but for the main branch it is
- uses: dorny/paths-filter@v2
id: filter
with:
filters: |
docs:
- README.md
- docs/**
- docs_src/**
- pyproject.toml
- mkdocs.yml
- mkdocs.insiders.yml
- .github/workflows/build-docs.yml
- .github/workflows/deploy-docs.yml
build-docs:
runs-on: ubuntu-20.04
needs:
- changes
if: ${{ needs.changes.outputs.docs == 'true' }}
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: "3.7"
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }}
with:
limit-access-to-actor: true
- uses: actions/cache@v2
python-version: "3.11"
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root-docs
- name: Install poetry
key: ${{ runner.os }}-python-docs-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-v01
- name: Install Poetry
if: steps.cache.outputs.cache-hit != 'true'
# TODO: remove python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
# once there's a release of Poetry 1.2.x including poetry-core > 1.1.0a6
# Ref: https://github.com/python-poetry/poetry-core/pull/188
run: |
python -m pip install --upgrade pip
python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
python -m pip install "poetry==1.2.0a2"
python -m poetry plugin add poetry-version-plugin
python -m pip install "poetry"
python -m poetry self add poetry-version-plugin
- name: Configure poetry
run: python -m poetry config virtualenvs.create false
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: python -m poetry install
- name: Install Material for MkDocs Insiders
if: github.event.pull_request.head.repo.fork == false && steps.cache.outputs.cache-hit != 'true'
run: python -m poetry run pip install git+https://${{ secrets.ACTIONS_TOKEN }}@github.com/squidfunk/mkdocs-material-insiders.git
- uses: actions/cache@v2
if: ( github.event_name != 'pull_request' || github.secret_source == 'Actions' ) && steps.cache.outputs.cache-hit != 'true'
run: python -m poetry run pip install git+https://${{ secrets.SQLMODEL_MKDOCS_MATERIAL_INSIDERS }}@github.com/squidfunk/mkdocs-material-insiders.git
- uses: actions/cache@v3
with:
key: mkdocs-cards-${{ github.ref }}
path: .cache
- name: Verify README
run: python ./scripts/docs.py verify-readme
- name: Build Docs
if: github.event.pull_request.head.repo.fork == true
run: python -m poetry run mkdocs build
- name: Build Docs with Insiders
if: github.event.pull_request.head.repo.fork == false
run: python -m poetry run mkdocs build --config-file mkdocs.insiders.yml
- name: Zip docs
run: python -m poetry run bash ./scripts/zip-docs.sh
- uses: actions/upload-artifact@v2
run: python ./scripts/docs.py build
- uses: actions/upload-artifact@v3
with:
name: docs-zip
path: ./docs.zip
- name: Deploy to Netlify
uses: nwtgck/actions-netlify@v1.1.5
name: docs-site
path: ./site/**
# https://github.com/marketplace/actions/alls-green#why
docs-all-green: # This job does nothing and is only used for the branch protection
if: always()
needs:
- build-docs
runs-on: ubuntu-latest
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
publish-dir: './site'
production-branch: main
github-token: ${{ secrets.GITHUB_TOKEN }}
enable-commit-comment: false
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
jobs: ${{ toJSON(needs) }}
allowed-skips: build-docs

48
.github/workflows/deploy-docs.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Deploy Docs
on:
workflow_run:
workflows:
- Build Docs
types:
- completed
jobs:
deploy-docs:
runs-on: ubuntu-latest
steps:
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: echo "$GITHUB_CONTEXT"
- uses: actions/checkout@v4
- name: Clean site
run: |
rm -rf ./site
mkdir ./site
- name: Download Artifact Docs
id: download
uses: dawidd6/action-download-artifact@v2.28.0
with:
if_no_artifact_found: ignore
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: build-docs.yml
run_id: ${{ github.event.workflow_run.id }}
name: docs-site
path: ./site/
- name: Deploy to Cloudflare Pages
if: steps.download.outputs.found_artifact == 'true'
id: deploy
uses: cloudflare/pages-action@v1
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
projectName: sqlmodel
directory: './site'
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
branch: ${{ ( github.event.workflow_run.head_repository.full_name == github.repository && github.event.workflow_run.head_branch == 'main' && 'main' ) || ( github.event.workflow_run.head_sha ) }}
- name: Comment Deploy
if: steps.deploy.outputs.url != ''
uses: ./.github/actions/comment-docs-preview-in-pr
with:
token: ${{ secrets.GITHUB_TOKEN }}
deploy_url: "${{ steps.deploy.outputs.url }}"

View File

@@ -18,7 +18,7 @@ jobs:
issue-manager:
runs-on: ubuntu-latest
steps:
- uses: tiangolo/issue-manager@0.4.0
- uses: tiangolo/issue-manager@0.4.1
with:
token: ${{ secrets.GITHUB_TOKEN }}
config: >

View File

@@ -12,27 +12,30 @@ on:
description: PR number
required: true
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
default: 'false'
jobs:
latest-changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
with:
# To allow latest-changes to commit to the main branch
token: ${{ secrets.ACTIONS_TOKEN }}
token: ${{ secrets.SQLMODEL_LATEST_CHANGES }}
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }}
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- uses: docker://tiangolo/latest-changes:0.0.3
- uses: docker://tiangolo/latest-changes:0.2.0
# - uses: tiangolo/latest-changes@main
with:
token: ${{ secrets.GITHUB_TOKEN }}
latest_changes_file: docs/release-notes.md
latest_changes_header: '## Latest Changes\n\n'
latest_changes_header: '## Latest Changes'
end_regex: '^## '
debug_logs: true
label_header_prefix: '### '

View File

@@ -1,41 +0,0 @@
name: Preview Docs
on:
workflow_run:
workflows:
- Build Docs
types:
- completed
jobs:
preview-docs:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@v2
- name: Download Artifact Docs
uses: dawidd6/action-download-artifact@v2.9.0
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
workflow: build-docs.yml
run_id: ${{ github.event.workflow_run.id }}
name: docs-zip
- name: Unzip docs
run: |
rm -rf ./site
unzip docs.zip
rm -f docs.zip
- name: Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@v1.1.5
with:
publish-dir: './site'
production-deploy: false
github-token: ${{ secrets.GITHUB_TOKEN }}
enable-commit-comment: false
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Comment Deploy
uses: ./.github/actions/comment-docs-preview-in-pr
with:
token: ${{ secrets.GITHUB_TOKEN }}
deploy_url: "${{ steps.netlify.outputs.deploy-url }}"

View File

@@ -7,40 +7,36 @@ on:
workflow_dispatch:
inputs:
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
default: 'false'
jobs:
publish:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: "3.7"
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }}
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- uses: actions/cache@v2
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root-v2
- name: Install poetry
if: steps.cache.outputs.cache-hit != 'true'
# TODO: remove python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
# once there's a release of Poetry 1.2.x including poetry-core > 1.1.0a6
# Ref: https://github.com/python-poetry/poetry-core/pull/188
run: |
python -m pip install --upgrade pip
python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
python -m pip install "poetry==1.2.0a2"
python -m poetry plugin add poetry-version-plugin
python -m pip install "poetry"
python -m poetry self add poetry-version-plugin
- name: Configure poetry
run: python -m poetry config virtualenvs.create false
- name: Install Dependencies

35
.github/workflows/smokeshow.yml vendored Normal file
View File

@@ -0,0 +1,35 @@
name: Smokeshow
on:
workflow_run:
workflows: [Test]
types: [completed]
permissions:
statuses: write
jobs:
smokeshow:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
runs-on: ubuntu-latest
steps:
- uses: actions/setup-python@v4
with:
python-version: '3.9'
- run: pip install smokeshow
- uses: dawidd6/action-download-artifact@v2.28.0
with:
workflow: test.yml
commit: ${{ github.event.workflow_run.head_sha }}
- run: smokeshow upload coverage-html
env:
SMOKESHOW_GITHUB_STATUS_DESCRIPTION: Coverage {coverage-percentage}
SMOKESHOW_GITHUB_COVERAGE_THRESHOLD: 95
SMOKESHOW_GITHUB_CONTEXT: coverage
SMOKESHOW_GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
SMOKESHOW_GITHUB_PR_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
SMOKESHOW_AUTH_KEY: ${{ secrets.SMOKESHOW_AUTH_KEY }}

View File

@@ -5,58 +5,121 @@ on:
branches:
- main
pull_request:
types: [opened, synchronize]
types:
- opened
- synchronize
workflow_dispatch:
inputs:
debug_enabled:
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)'
required: false
default: false
default: 'false'
jobs:
test:
runs-on: ubuntu-20.04
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.6.15", "3.7", "3.8", "3.9", "3.10"]
python-version:
- "3.7"
- "3.8"
- "3.9"
- "3.10"
- "3.11"
- "3.12"
pydantic-version:
- pydantic-v1
- pydantic-v2
fail-fast: false
steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v2
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
# Allow debugging with tmate
- name: Setup tmate session
uses: mxschmitt/action-tmate@v3
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled }}
if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }}
with:
limit-access-to-actor: true
- uses: actions/cache@v2
- uses: actions/cache@v3
id: cache
with:
path: ${{ env.pythonLocation }}
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root
key: ${{ runner.os }}-python-${{ env.pythonLocation }}-${{ hashFiles('pyproject.toml') }}-root-v2
- name: Install poetry
if: steps.cache.outputs.cache-hit != 'true'
# TODO: remove python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
# once there's a release of Poetry 1.2.x including poetry-core > 1.1.0a6
# Ref: https://github.com/python-poetry/poetry-core/pull/188
run: |
python -m pip install --upgrade pip
python -m pip install --force git+https://github.com/python-poetry/poetry-core.git@ad33bc2
python -m pip install "poetry==1.2.0a2"
python -m poetry plugin add poetry-version-plugin
python -m pip install "poetry"
python -m poetry self add poetry-version-plugin
- name: Configure poetry
run: python -m poetry config virtualenvs.create false
- name: Install Dependencies
if: steps.cache.outputs.cache-hit != 'true'
run: python -m poetry install
- name: Install Pydantic v1
if: matrix.pydantic-version == 'pydantic-v1'
run: pip install --upgrade "pydantic>=1.10.0,<2.0.0"
- name: Install Pydantic v2
if: matrix.pydantic-version == 'pydantic-v2'
run: pip install --upgrade "pydantic>=2.0.2,<3.0.0"
- name: Lint
if: ${{ matrix.python-version != '3.6.15' }}
# Do not run on Python 3.7 as mypy behaves differently
if: matrix.python-version != '3.7' && matrix.pydantic-version == 'pydantic-v2'
run: python -m poetry run bash scripts/lint.sh
- run: mkdir coverage
- name: Test
run: python -m poetry run bash scripts/test.sh
- name: Upload coverage
uses: codecov/codecov-action@v2
env:
COVERAGE_FILE: coverage/.coverage.${{ runner.os }}-py${{ matrix.python-version }}
CONTEXT: ${{ runner.os }}-py${{ matrix.python-version }}
- name: Store coverage files
uses: actions/upload-artifact@v3
with:
name: coverage
path: coverage
coverage-combine:
needs:
- test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v4
with:
python-version: '3.8'
- name: Get coverage files
uses: actions/download-artifact@v3
with:
name: coverage
path: coverage
- run: pip install coverage[toml]
- run: ls -la coverage
- run: coverage combine coverage
- run: coverage report
- run: coverage html --show-contexts --title "Coverage for ${{ github.sha }}"
- name: Store coverage HTML
uses: actions/upload-artifact@v3
with:
name: coverage-html
path: htmlcov
# https://github.com/marketplace/actions/alls-green#why
alls-green: # This job does nothing and is only used for the branch protection
if: always()
needs:
- coverage-combine
runs-on: ubuntu-latest
steps:
- name: Decide whether the needed jobs succeeded or failed
uses: re-actors/alls-green@release/v1
with:
jobs: ${{ toJSON(needs) }}

2
.gitignore vendored
View File

@@ -7,7 +7,7 @@ poetry.lock
dist
htmlcov
*.egg-info
.coverage
.coverage*
coverage.xml
site
*.db

25
.pre-commit-config.yaml Normal file
View File

@@ -0,0 +1,25 @@
# See https://pre-commit.com for more information
# See https://pre-commit.com/hooks.html for more hooks
default_language_version:
python: python3.10
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: check-added-large-files
- id: check-toml
- id: check-yaml
args:
- --unsafe
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
hooks:
- id: ruff
args:
- --fix
- id: ruff-format
ci:
autofix_commit_msg: 🎨 [pre-commit.ci] Auto format from pre-commit.com hooks
autoupdate_commit_msg: ⬆ [pre-commit.ci] pre-commit autoupdate

24
CITATION.cff Normal file
View File

@@ -0,0 +1,24 @@
# This CITATION.cff file was generated with cffinit.
# Visit https://bit.ly/cffinit to generate yours today!
cff-version: 1.2.0
title: SQLModel
message: >-
If you use this software, please cite it using the
metadata from this file.
type: software
authors:
- given-names: Sebastián
family-names: Ramírez
email: tiangolo@gmail.com
identifiers:
repository-code: 'https://github.com/tiangolo/sqlmodel'
url: 'https://sqlmodel.tiangolo.com'
abstract: >-
SQLModel, SQL databases in Python, designed for
simplicity, compatibility, and robustness.
keywords:
- fastapi
- pydantic
- sqlalchemy
license: MIT

View File

@@ -11,9 +11,8 @@
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3APublish" target="_blank">
<img src="https://github.com/tiangolo/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
</a>
<a href="https://codecov.io/gh/tiangolo/sqlmodel" target="_blank">
<img src="https://img.shields.io/codecov/c/github/tiangolo/sqlmodel?color=%2334D058" alt="Coverage">
</a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/sqlmodel" target="_blank">
<img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/sqlmodel.svg" alt="Coverage">
<a href="https://pypi.org/project/sqlmodel" target="_blank">
<img src="https://img.shields.io/pypi/v/sqlmodel?color=%2334D058&label=pypi%20package" alt="Package version">
</a>
@@ -39,6 +38,14 @@ The key features are:
* **Extensible**: You have all the power of SQLAlchemy and Pydantic underneath.
* **Short**: Minimize code duplication. A single type annotation does a lot of work. No need to duplicate models in SQLAlchemy and Pydantic.
## Sponsors
<!-- sponsors -->
<a href="https://www.govcert.lu" target="_blank" title="This project is being supported by GOVCERT.LU"><img src="https://sqlmodel.tiangolo.com/img/sponsors/govcert.png"></a>
<!-- /sponsors -->
## SQL Databases in FastAPI
<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>
@@ -51,7 +58,7 @@ It combines SQLAlchemy and Pydantic and tries to simplify the code you write as
## Requirements
A recent and currently supported version of Python (right now, <a href="https://www.python.org/downloads/" class="external-link" target="_blank">Python supports versions 3.6 and above</a>).
A recent and currently supported <a href="https://www.python.org/downloads/" class="external-link" target="_blank">version of Python</a>.
As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. They will be automatically installed when you install SQLModel.
@@ -69,7 +76,7 @@ Successfully installed sqlmodel
## Example
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com" target="_blank">SQLModel documentation</a>.
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com/databases/" target="_blank">SQLModel documentation</a>.
Here's a quick example. ✨

6
data/sponsors.yml Normal file
View File

@@ -0,0 +1,6 @@
gold: []
silver:
- url: https://www.govcert.lu
title: This project is being supported by GOVCERT.LU
img: https://sqlmodel.tiangolo.com/img/sponsors/govcert.png
bronze: []

View File

@@ -19,17 +19,15 @@ In most cases this would probably not be a problem, for example measuring views
## Decimal Types
Pydantic has special support for `Decimal` types using the <a href="https://pydantic-docs.helpmanual.io/usage/types/#arguments-to-condecimal" class="external-link" target="_blank">`condecimal()` special function</a>.
Pydantic has special support for <a href="https://docs.pydantic.dev/latest/api/standard_library_types/#decimaldecimal" class="external-link" target="_blank">`Decimal` types</a>.
!!! tip
Pydantic 1.9, that will be released soon, has improved support for `Decimal` types, without needing to use the `condecimal()` function.
When you use `Decimal` you can specify the number of digits and decimal places to support in the `Field()` function. They will be validated by Pydantic (for example when using FastAPI) and the same information will also be used for the database columns.
But meanwhile, you can already use this feature with `condecimal()` in **SQLModel** it as it's explained here.
/// info
When you use `condecimal()` you can specify the number of digits and decimal places to support. They will be validated by Pydantic (for example when using FastAPI) and the same information will also be used for the database columns.
For the database, **SQLModel** will use <a href="https://docs.sqlalchemy.org/en/20/core/type_basics.html#sqlalchemy.types.DECIMAL" class="external-link" target="_blank">SQLAlchemy's `DECIMAL` type</a>.
!!! info
For the database, **SQLModel** will use <a href="https://docs.sqlalchemy.org/en/14/core/type_basics.html#sqlalchemy.types.DECIMAL" class="external-link" target="_blank">SQLAlchemy's `DECIMAL` type</a>.
///
## Decimals in SQLModel
@@ -41,14 +39,13 @@ Let's say that each hero in the database will have an amount of money. We could
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/advanced/decimal/tutorial001.py!}
```
</details>
///
Here we are saying that `money` can have at most `5` digits with `max_digits`, **this includes the integers** (to the left of the decimal dot) **and the decimals** (to the right of the decimal dot).
@@ -72,8 +69,11 @@ We are also saying that the number of decimal places (to the right of the decima
* `123`
* Even though this number doesn't have any decimals, we still have 3 places saved for them, which means that we can **only use 2 places** for the **integer part**, and this number has 3 integer digits. So, the allowed number of integer digits is `max_digits` - `decimal_places` = 2.
!!! tip
Make sure you adjust the number of digits and decimal places for your own needs, in your own application. 🤓
/// tip
Make sure you adjust the number of digits and decimal places for your own needs, in your own application. 🤓
///
## Create models with Decimals
@@ -87,14 +87,13 @@ When creating new models you can actually pass normal (`float`) numbers, Pydanti
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/advanced/decimal/tutorial001.py!}
```
</details>
///
## Select Decimal data
@@ -108,14 +107,13 @@ Then, when working with Decimal types, you can confirm that they indeed avoid th
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/advanced/decimal/tutorial001.py!}
```
</details>
///
## Review the results
@@ -142,7 +140,10 @@ Total money: 3.300
</div>
!!! warning
Although Decimal types are supported and used in the Python side, not all databases support it. In particular, SQLite doesn't support decimals, so it will convert them to the same floating `NUMERIC` type it supports.
/// warning
But decimals are supported by most of the other SQL databases. 🎉
Although Decimal types are supported and used in the Python side, not all databases support it. In particular, SQLite doesn't support decimals, so it will convert them to the same floating `NUMERIC` type it supports.
But decimals are supported by most of the other SQL databases. 🎉
///

View File

@@ -6,10 +6,6 @@ First, you might want to see the basic ways to [help SQLModel and get help](help
If you already cloned the repository and you know that you need to deep dive in the code, here are some guidelines to set up your environment.
### Python
SQLModel supports Python 3.6 and above, but for development you should have at least **Python 3.7**.
### Poetry
**SQLModel** uses <a href="https://python-poetry.org/" class="external-link" target="_blank">Poetry</a> to build, package, and publish the project.
@@ -116,7 +112,7 @@ There is a script that you can run locally to test all the code and generate cov
<div class="termy">
```console
$ bash scripts/test-cov-html.sh
$ bash scripts/test.sh
```
</div>

View File

@@ -1,9 +1,12 @@
# Intro to Databases
!!! info
Are you a seasoned developer and already know everything about databases? 🤓
/// info
Then you can skip to the [Tutorial - User Guide: First Steps](tutorial/index.md){.internal-link target=_blank} right away.
Are you a seasoned developer and already know everything about databases? 🤓
Then you can skip to the [Tutorial - User Guide: First Steps](tutorial/index.md){.internal-link target=_blank} right away.
///
If you don't know everything about databases, here's a quick overview.
@@ -17,8 +20,11 @@ So, what is a database?
A **database** is a system to store and manage data in a structured and very efficient way.
!!! tip
It's very common to abbreviate the word "database" as **"DB"**.
/// tip
It's very common to abbreviate the word "database" as **"DB"**.
///
As there's a lot of information about databases, and it can get very technical and academic, I'll give you a quick overview about some of the main concepts here.
@@ -28,8 +34,11 @@ I'll even tell you a bit about different types of databases, including the ones
When starting to program, it might **not be obvious** why having a database apart from the code for your program is a **good idea**. Let's start with that.
!!! tip
If that's obvious to you, just continue in the next section below. 👇
/// tip
If that's obvious to you, just continue in the next section below. 👇
///
In your code you already have **variables**, **dictionaries**, **lists**, etc. They all store **data** in some way already. Why would you need to have a separate database?
@@ -128,7 +137,7 @@ If we worked with a single table to store our heroes, it could be like this:
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
</tr>
<tr>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Factor</td><td>Sister Margarets Bar</td>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Factor</td><td>Sister Margaret's Bar</td>
</tr>
<tr>
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Sharp Tower</td>
@@ -157,7 +166,7 @@ We could end up with inconsistent information, having one place saying "Prevente
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
</tr>
<tr>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
<tr>
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Preventers Tower ✅</td>
@@ -176,7 +185,7 @@ We could forget the name of the team and end up adding "Mahjong" with an invalid
<th>id</th><th>name</th><th>secret_name</th><th>age</th><th>team</th><th>headquarters</th>
</tr>
<tr>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>1</td><td>Deadpond</td><td>Dive Wilson</td><td>null</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
<tr>
<td>2</td><td>Spider-Boy</td><td>Pedro Parqueador</td><td>null</td><td>Preventers</td><td>Preventers Tower</td>
@@ -185,7 +194,7 @@ We could forget the name of the team and end up adding "Mahjong" with an invalid
<td>3</td><td>Rusty-Man</td><td>Tommy Sharp</td><td>48</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>4</td><td>Mahjong</td><td>Neena Thurgirl</td><td>31</td><td>Y-Force 🚨</td><td>Sister Margarets Bar</td>
<td>4</td><td>Mahjong</td><td>Neena Thurgirl</td><td>31</td><td>Y-Force 🚨</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -207,7 +216,7 @@ The table for the teams could look like this:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -308,8 +317,11 @@ Next, it receives the data and puts it in Python objects that you can continue t
I'll tell you more about SQL, SQLModel, how to use them, and how they are related in the next sections.
!!! info "Technical Details"
SQLModel is built on top of SQLAlchemy. It is, in fact, just <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> mixed together with some sugar on top.
/// info | Technical Details
SQLModel is built on top of SQLAlchemy. It is, in fact, just <a href="https://www.sqlalchemy.org/" class="external-link" target="_blank">SQLAlchemy</a> and <a href="https://pydantic-docs.helpmanual.io/" class="external-link" target="_blank">Pydantic</a> mixed together with some sugar on top.
///
## NoSQL Databases

View File

@@ -62,7 +62,7 @@ The user is probably, in some way, telling your application:
2
```
And the would be this table (with a single row):
And the result would be this table (with a single row):
<table>
<tr>
@@ -111,7 +111,7 @@ DROP TABLE hero;
That is how you tell the database in SQL to delete the entire table `hero`.
<a href="http://www.nooooooooooooooo.com/" class="external-link" target="_blank">Nooooo!</a> We lost all the data in the `hero` table! 💥😱
<a href="https://theuselessweb.site/nooooooooooooooo/" class="external-link" target="_blank">Nooooo!</a> We lost all the data in the `hero` table! 💥😱
### SQL Sanitization
@@ -172,8 +172,11 @@ The difference in the final SQL statement is subtle, but it changes the meaning
SELECT * FROM hero WHERE id = "2; DROP TABLE hero;";
```
!!! tip
Notice the double quotes (`"`) making it a string instead of more raw SQL.
/// tip
Notice the double quotes (`"`) making it a string instead of more raw SQL.
///
The database will not find any record with that ID:
@@ -187,8 +190,11 @@ Then your code will continue to execute and calmly tell the user that it couldn'
But we never deleted the `hero` table. 🎉
!!! info
Of course, there are also other ways to do SQL data sanitization without using a tool like **SQLModel**, but it's still a nice feature you get by default.
/// info
Of course, there are also other ways to do SQL data sanitization without using a tool like **SQLModel**, but it's still a nice feature you get by default.
///
### Editor Support
@@ -291,8 +297,11 @@ There are many ORMs available apart from **SQLModel**, you can read more about s
## SQL Table Names
!!! info "Technical Background"
This is a bit of boring background for SQL purists. Feel free to skip this section. 😉
/// info | Technical Background
This is a bit of boring background for SQL purists. Feel free to skip this section. 😉
///
When working with pure SQL, it's common to name the tables in plural. So, the table would be named `heroes` instead of `hero`, because it could contain multiple rows, each with one hero.
@@ -304,5 +313,8 @@ You will see **your own code** a lot more than the internal table names, so it's
So, to keep things consistent, I'll keep using the same table names that **SQLModel** would have generated.
!!! tip
You can also override the table name. You can read about it in the Advanced User Guide.
/// tip
You can also override the table name. You can read about it in the Advanced User Guide.
///

View File

@@ -12,7 +12,7 @@ Nevertheless, SQLModel is completely **independent** of FastAPI and can be used
## Just Modern Python
It's all based on standard <abbr title="Python currently supported versions, 3.6 and above.">modern **Python**</abbr> type annotations. No new syntax to learn. Just standard modern Python.
It's all based on standard <abbr title="Currently supported versions of Python">modern **Python**</abbr> type annotations. No new syntax to learn. Just standard modern Python.
If you need a 2 minute refresher of how to use Python types (even if you don't use SQLModel or FastAPI), check the FastAPI tutorial section: <a href="https://fastapi.tiangolo.com/python-types/" class="external-link" target="_blank">Python types intro</a>.
@@ -40,12 +40,15 @@ You won't need to keep guessing the types of different attributes in your models
<img class="shadow" src="/img/index/autocompletion01.png">
!!! info
Don't worry, adopting this in-development standard only affects/improves editor support.
/// info
It doesn't affect performance or correctness. And if the in-progress standard was deprecated your code won't be affected.
Don't worry, adopting this in-development standard only affects/improves editor support.
Meanwhile, you will get inline errors (like type checks) and autocompletion on places you wouldn't get with any other library. 🎉
It doesn't affect performance or correctness. And if the in-progress standard was deprecated your code won't be affected.
Meanwhile, you will get inline errors (like type checks) and autocompletion on places you wouldn't get with any other library. 🎉
///
## Short

View File

@@ -58,26 +58,128 @@ You can:
I love to hear about how **SQLModel** is being used, what you have liked in it, in which project/company are you using it, etc.
## Help others with issues in GitHub
## Help others with questions in GitHub
You can see <a href="https://github.com/tiangolo/sqlmodel/issues" class="external-link" target="_blank">existing issues</a> and try and help others, most of the times they are questions that you might already know the answer for. 🤓
You can try and help others with their questions in:
* <a href="https://github.com/tiangolo/sqlmodel/discussions/categories/questions?discussions_q=category%3AQuestions+is%3Aunanswered" class="external-link" target="_blank">GitHub Discussions</a>
* <a href="https://github.com/tiangolo/sqlmodel/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Aquestion+-label%3Aanswered+" class="external-link" target="_blank">GitHub Issues</a>
In many cases you might already know the answer for those questions. 🤓
Just remember, the most important point is: try to be kind. People come with their frustrations and in many cases don't ask in the best way, but try as best as you can to be kind. 🤗
The idea is for the **SQLModel** community to be kind and welcoming. At the same time, don't accept bullying or disrespectful behavior towards others. We have to take care of each other.
---
Here's how to help others with questions (in discussions or issues):
### Understand the question
* Check if you can understand what is the **purpose** and use case of the person asking.
* Then check if the question (the vast majority are questions) is **clear**.
* In many cases the question asked is about an imaginary solution from the user, but there might be a **better** one. If you can understand the problem and use case better, you might be able to suggest a better **alternative solution**.
* If you can't understand the question, ask for more **details**.
### Reproduce the problem
For most of the cases and most of the questions there's something related to the person's **original code**.
In many cases they will only copy a fragment of the code, but that's not enough to **reproduce the problem**.
* You can ask them to provide a <a href="https://stackoverflow.com/help/minimal-reproducible-example" class="external-link" target="_blank">minimal, reproducible, example</a>, that you can **copy-paste** and run locally to see the same error or behavior they are seeing, or to understand their use case better.
* If you are feeling too generous, you can try to **create an example** like that yourself, just based on the description of the problem. Just have in mind that this might take a lot of time and it might be better to ask them to clarify the problem first.
### Suggest solutions
* After being able to understand the question, you can give them a possible **answer**.
* In many cases, it's better to understand their **underlying problem or use case**, because there might be a better way to solve it than what they are trying to do.
### Ask to close
If they reply, there's a high chance you would have solved their problem, congrats, **you're a hero**! 🦸
* Now, if that solved their problem, you can ask them to:
* In GitHub Discussions: mark the comment as the **answer**.
* In GitHub Issues: **close** the issue**.
## Watch the GitHub repository
You can "watch" SQLModel in GitHub (clicking the "watch" button at the top right): <a href="https://github.com/tiangolo/sqlmodel" class="external-link" target="_blank">https://github.com/tiangolo/sqlmodel</a>. 👀
If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue.
If you select "Watching" instead of "Releases only" you will receive notifications when someone creates a new issue or question. You can also specify that you only want to be notified about new issues, or discussions, or PRs, etc.
Then you can try and help them solve those issues.
Then you can try and help them solve those questions.
## Create issues
## Ask Questions
You can <a href="https://github.com/tiangolo/sqlmodel/issues/new/choose" class="external-link" target="_blank">create a new issue</a> in the GitHub repository, for example to:
You can <a href="https://github.com/tiangolo/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">create a new question</a> in the GitHub repository, for example to:
* Ask a **question** or ask about a **problem**.
* Suggest a new **feature**.
**Note**: if you create an issue, then I'm going to ask you to also help others. 😉
**Note**: if you do it, then I'm going to ask you to also help others. 😉
## Review Pull Requests
You can help me review pull requests from others.
Again, please try your best to be kind. 🤗
---
Here's what to have in mind and how to review a pull request:
### Understand the problem
* First, make sure you **understand the problem** that the pull request is trying to solve. It might have a longer discussion in a GitHub Discussion or issue.
* There's also a good chance that the pull request is not actually needed because the problem can be solved in a **different way**. Then you can suggest or ask about that.
### Don't worry about style
* Don't worry too much about things like commit message styles, I will squash and merge customizing the commit manually.
* Also don't worry about style rules, there are already automatized tools checking that.
And if there's any other style or consistency need, I'll ask directly for that, or I'll add commits on top with the needed changes.
### Check the code
* Check and read the code, see if it makes sense, **run it locally** and see if it actually solves the problem.
* Then **comment** saying that you did that, that's how I will know you really checked it.
/// info
Unfortunately, I can't simply trust PRs that just have several approvals.
Several times it has happened that there are PRs with 3, 5 or more approvals, probably because the description is appealing, but when I check the PRs, they are actually broken, have a bug, or don't solve the problem they claim to solve. 😅
So, it's really important that you actually read and run the code, and let me know in the comments that you did. 🤓
///
* If the PR can be simplified in a way, you can ask for that, but there's no need to be too picky, there might be a lot of subjective points of view (and I will have my own as well 🙈), so it's better if you can focus on the fundamental things.
### Tests
* Help me check that the PR has **tests**.
* Check that the tests **fail** before the PR. 🚨
* Then check that the tests **pass** after the PR. ✅
* Many PRs don't have tests, you can **remind** them to add tests, or you can even **suggest** some tests yourself. That's one of the things that consume most time and you can help a lot with that.
* Then also comment what you tried, that way I'll know that you checked it. 🤓
## Create a Pull Request
@@ -86,7 +188,47 @@ You can [contribute](contributing.md){.internal-link target=_blank} to the sourc
* To fix a typo you found on the documentation.
* To propose new documentation sections.
* To fix an existing issue/bug.
* Make sure to add tests.
* To add a new feature.
* Make sure to add tests.
* Make sure to add documentation if it's relevant.
## Help Maintain SQLModel
Help me maintain **SQLModel**! 🤓
There's a lot of work to do, and for most of it, **YOU** can do it.
The main tasks that you can do right now are:
* [Help others with questions in GitHub](#help-others-with-questions-in-github){.internal-link target=_blank} (see the section above).
* [Review Pull Requests](#review-pull-requests){.internal-link target=_blank} (see the section above).
Those two tasks are what **consume time the most**. That's the main work of maintaining SQLModel.
If you can help me with that, **you are helping me maintain SQLModel** and making sure it keeps **advancing faster and better**. 🚀
## Join the chat
Join the 👥 <a href="https://discord.gg/VQjSZaeJmf" class="external-link" target="_blank">FastAPI and Friends Discord chat server</a> 👥 and hang out with others in the community. There's a `#sqlmodel` channel.
/// tip
For questions, ask them in <a href="https://github.com/tiangolo/sqlmodel/discussions/new?category=questions" class="external-link" target="_blank">GitHub Discussions</a>, there's a much better chance you will receive help there.
Use the chat only for other general conversations.
///
### Don't use the chat for questions
Have in mind that as chats allow more "free conversation", it's easy to ask questions that are too general and more difficult to answer, so, you might not receive answers.
In GitHub, the template will guide you to write the right question so that you can more easily get a good answer, or even solve the problem yourself even before asking. And in GitHub I can make sure I always answer everything, even if it takes some time. I can't personally do that with the chat. 😅
Conversations in the chat are also not as easily searchable as in GitHub, so questions and answers might get lost in the conversation.
On the other side, there are thousands of users in the chat, so there's a high chance you'll find someone to talk to there, almost all the time. 😄
## Sponsor the author

View File

@@ -90,4 +90,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 16 KiB

View File

@@ -202,4 +202,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -115,7 +115,7 @@
<mxCell id="56" value="&lt;span style=&quot;font-family: &amp;#34;roboto&amp;#34; ; font-size: 18px&quot;&gt;Z-Force&lt;/span&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
<mxGeometry x="50" width="110" height="50" as="geometry"/>
</mxCell>
<mxCell id="57" value="&lt;p style=&quot;background-color: rgb(255 , 255 , 255) ; line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margarets Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
<mxCell id="57" value="&lt;p style=&quot;background-color: rgb(255 , 255 , 255) ; line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margaret's Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;strokeColor=none;fillColor=none;" parent="54" vertex="1">
<mxGeometry x="160" width="200" height="50" as="geometry"/>
</mxCell>
<mxCell id="66" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;strokeWidth=2;" parent="1" source="18" target="54" edge="1">
@@ -148,4 +148,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 37 KiB

After

Width:  |  Height:  |  Size: 37 KiB

View File

@@ -81,4 +81,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -34,4 +34,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.5 KiB

After

Width:  |  Height:  |  Size: 8.5 KiB

View File

@@ -61,4 +61,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.7 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@@ -94,4 +94,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 30 KiB

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -94,4 +94,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -94,4 +94,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -97,4 +97,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -94,4 +94,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -97,4 +97,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -97,4 +97,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

@@ -100,4 +100,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 28 KiB

After

Width:  |  Height:  |  Size: 28 KiB

View File

@@ -89,4 +89,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -103,7 +103,7 @@
<mxCell id="56" value="&lt;span style=&quot;font-family: &amp;#34;roboto&amp;#34; ; font-size: 18px&quot;&gt;Z-Force&lt;/span&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
<mxGeometry x="50" width="110" height="50" as="geometry"/>
</mxCell>
<mxCell id="57" value="&lt;p style=&quot;line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margarets Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
<mxCell id="57" value="&lt;p style=&quot;line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margaret's Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;fillColor=#e1d5e7;strokeColor=#9673a6;" parent="54" vertex="1">
<mxGeometry x="160" width="200" height="50" as="geometry"/>
</mxCell>
<mxCell id="69" value="&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;heroteamlink&lt;/font&gt;" style="shape=table;html=1;whiteSpace=wrap;startSize=30;container=1;collapsible=0;childLayout=tableLayout;fontStyle=1;align=center;fillColor=#FFFFFF;swimlaneFillColor=#ffffff;" vertex="1" parent="1">
@@ -217,4 +217,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 53 KiB

View File

@@ -130,4 +130,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -130,4 +130,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -130,4 +130,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 44 KiB

After

Width:  |  Height:  |  Size: 44 KiB

View File

@@ -38,4 +38,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 126 KiB

After

Width:  |  Height:  |  Size: 126 KiB

View File

@@ -49,4 +49,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 130 KiB

View File

@@ -115,7 +115,7 @@
<mxCell id="56" value="&lt;span style=&quot;font-family: &amp;#34;roboto&amp;#34; ; font-size: 18px&quot;&gt;Z-Force&lt;/span&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
<mxGeometry x="50" width="110" height="50" as="geometry"/>
</mxCell>
<mxCell id="57" value="&lt;p style=&quot;background-color: rgb(255 , 255 , 255) ; line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margarets Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
<mxCell id="57" value="&lt;p style=&quot;background-color: rgb(255 , 255 , 255) ; line-height: 19px&quot;&gt;&lt;font face=&quot;Roboto&quot; data-font-src=&quot;https://fonts.googleapis.com/css?family=Roboto&quot; style=&quot;font-size: 18px&quot;&gt;Sister Margaret's Bar&lt;/font&gt;&lt;/p&gt;" style="shape=partialRectangle;html=1;whiteSpace=wrap;connectable=0;top=0;left=0;bottom=0;right=0;overflow=hidden;" parent="54" vertex="1">
<mxGeometry x="160" width="200" height="50" as="geometry"/>
</mxCell>
<mxCell id="66" style="edgeStyle=orthogonalEdgeStyle;rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;strokeWidth=2;" parent="1" source="18" target="54" edge="1">
@@ -139,4 +139,4 @@
</root>
</mxGraphModel>
</diagram>
</mxfile>
</mxfile>

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 43 KiB

View File

@@ -1,3 +1,7 @@
<style>
.md-content .md-typeset h1 { display: none; }
</style>
<p align="center">
<a href="https://sqlmodel.tiangolo.com"><img src="https://sqlmodel.tiangolo.com/img/logo-margin/logo-margin-vector.svg" alt="SQLModel"></a>
</p>
@@ -11,9 +15,8 @@
<a href="https://github.com/tiangolo/sqlmodel/actions?query=workflow%3APublish" target="_blank">
<img src="https://github.com/tiangolo/sqlmodel/workflows/Publish/badge.svg" alt="Publish">
</a>
<a href="https://codecov.io/gh/tiangolo/sqlmodel" target="_blank">
<img src="https://img.shields.io/codecov/c/github/tiangolo/sqlmodel?color=%2334D058" alt="Coverage">
</a>
<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/tiangolo/sqlmodel" target="_blank">
<img src="https://coverage-badge.samuelcolvin.workers.dev/tiangolo/sqlmodel.svg" alt="Coverage">
<a href="https://pypi.org/project/sqlmodel" target="_blank">
<img src="https://img.shields.io/pypi/v/sqlmodel?color=%2334D058&label=pypi%20package" alt="Package version">
</a>
@@ -39,6 +42,21 @@ The key features are:
* **Extensible**: You have all the power of SQLAlchemy and Pydantic underneath.
* **Short**: Minimize code duplication. A single type annotation does a lot of work. No need to duplicate models in SQLAlchemy and Pydantic.
## Sponsors
<!-- sponsors -->
{% if sponsors %}
{% for sponsor in sponsors.gold -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor -%}
{%- for sponsor in sponsors.silver -%}
<a href="{{ sponsor.url }}" target="_blank" title="{{ sponsor.title }}"><img src="{{ sponsor.img }}" style="border-radius:15px"></a>
{% endfor %}
{% endif %}
<!-- /sponsors -->
## SQL Databases in FastAPI
<a href="https://fastapi.tiangolo.com" target="_blank"><img src="https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png" style="width: 20%;"></a>
@@ -51,7 +69,7 @@ It combines SQLAlchemy and Pydantic and tries to simplify the code you write as
## Requirements
A recent and currently supported version of Python (right now, <a href="https://www.python.org/downloads/" class="external-link" target="_blank">Python supports versions 3.6 and above</a>).
A recent and currently supported <a href="https://www.python.org/downloads/" class="external-link" target="_blank">version of Python</a>.
As **SQLModel** is based on **Pydantic** and **SQLAlchemy**, it requires them. They will be automatically installed when you install SQLModel.
@@ -69,7 +87,7 @@ Successfully installed sqlmodel
## Example
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com" target="_blank">SQLModel documentation</a>.
For an introduction to databases, SQL, and everything else, see the <a href="https://sqlmodel.tiangolo.com/databases/" target="_blank">SQLModel documentation</a>.
Here's a quick example. ✨

View File

@@ -72,14 +72,14 @@ class Termynal {
* Initialise the widget, get lines, clear container and start animation.
*/
init() {
/**
/**
* Calculates width and height of Termynal container.
* If container is empty and lines are dynamically loaded, defaults to browser `auto` or CSS.
*/
*/
const containerStyle = getComputedStyle(this.container);
this.container.style.width = containerStyle.width !== '0px' ?
this.container.style.width = containerStyle.width !== '0px' ?
containerStyle.width : undefined;
this.container.style.minHeight = containerStyle.height !== '0px' ?
this.container.style.minHeight = containerStyle.height !== '0px' ?
containerStyle.height : undefined;
this.container.setAttribute('data-termynal', '');
@@ -138,7 +138,7 @@ class Termynal {
restart.innerHTML = "restart ↻"
return restart
}
generateFinish() {
const finish = document.createElement('a')
finish.onclick = (e) => {
@@ -215,7 +215,7 @@ class Termynal {
/**
* Converts line data objects into line elements.
*
*
* @param {Object[]} lineData - Dynamically loaded lines.
* @param {Object} line - Line data object.
* @returns {Element[]} - Array of line elements.
@@ -231,7 +231,7 @@ class Termynal {
/**
* Helper function for generating attributes string.
*
*
* @param {Object} line - Line data object.
* @returns {string} - String of attributes.
*/

View File

@@ -12,9 +12,9 @@
});
});
</script>
<qa-bot
server="https://tiangolo-sqlmodel.docsqa.jina.ai"
theme="infer"
<qa-bot
server="https://tiangolo-sqlmodel.docsqa.jina.ai"
theme="infer"
title="SQLModel Bot"
description="SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
style="font-size: 0.8rem"
@@ -28,4 +28,4 @@
</dl>
</template>
</qa-bot>
{%- endblock %}
{%- endblock %}

View File

@@ -2,6 +2,191 @@
## Latest Changes
## 0.0.16
### Features
* ✨ Add new method `.sqlmodel_update()` to update models in place, including an `update` parameter for extra data. And fix implementation for the (now documented) `update` parameter for `.model_validate()`. PR [#804](https://github.com/tiangolo/sqlmodel/pull/804) by [@tiangolo](https://github.com/tiangolo).
* Updated docs: [Update Data with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/update/).
* New docs: [Update with Extra Data (Hashed Passwords) with FastAPI](https://sqlmodel.tiangolo.com/tutorial/fastapi/update-extra-data/).
## 0.0.15
### Fixes
* 🐛 Fix class initialization compatibility with Pydantic and SQLModel, fixing errors revealed by the latest Pydantic. PR [#807](https://github.com/tiangolo/sqlmodel/pull/807) by [@tiangolo](https://github.com/tiangolo).
### Internal
* ⬆ Bump tiangolo/issue-manager from 0.4.0 to 0.4.1. PR [#775](https://github.com/tiangolo/sqlmodel/pull/775) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👷 Fix GitHub Actions build docs filter paths for GitHub workflows. PR [#738](https://github.com/tiangolo/sqlmodel/pull/738) by [@tiangolo](https://github.com/tiangolo).
## 0.0.14
### Features
* ✨ Add support for Pydantic v2 (while keeping support for v1 if v2 is not available). PR [#722](https://github.com/tiangolo/sqlmodel/pull/722) by [@tiangolo](https://github.com/tiangolo) including initial work in PR [#699](https://github.com/tiangolo/sqlmodel/pull/699) by [@AntonDeMeester](https://github.com/AntonDeMeester).
## 0.0.13
### Fixes
* ♻️ Refactor type generation of selects re-order to prioritize models to optimize editor support. PR [#718](https://github.com/tiangolo/sqlmodel/pull/718) by [@tiangolo](https://github.com/tiangolo).
### Refactors
* 🔇 Do not raise deprecation warnings for execute as it's automatically used internally. PR [#716](https://github.com/tiangolo/sqlmodel/pull/716) by [@tiangolo](https://github.com/tiangolo).
* ✅ Move OpenAPI tests inline to simplify updating them with Pydantic v2. PR [#709](https://github.com/tiangolo/sqlmodel/pull/709) by [@tiangolo](https://github.com/tiangolo).
### Upgrades
* ⬆️ Add support for Python 3.11 and Python 3.12. PR [#710](https://github.com/tiangolo/sqlmodel/pull/710) by [@tiangolo](https://github.com/tiangolo).
### Docs
* ✏️ Fix typo, simplify single quote/apostrophe character in "Sister Margaret's" everywhere in the docs. PR [#721](https://github.com/tiangolo/sqlmodel/pull/721) by [@tiangolo](https://github.com/tiangolo).
* 📝 Update docs for Decimal, use proper types. PR [#719](https://github.com/tiangolo/sqlmodel/pull/719) by [@tiangolo](https://github.com/tiangolo).
* 📝 Add source examples for Python 3.9 and 3.10. PR [#715](https://github.com/tiangolo/sqlmodel/pull/715) by [@tiangolo](https://github.com/tiangolo).
### Internal
* 🙈 Update gitignore, include all coverage files. PR [#711](https://github.com/tiangolo/sqlmodel/pull/711) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update config with new pymdown extensions. PR [#712](https://github.com/tiangolo/sqlmodel/pull/712) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update docs build setup, add support for sponsors, add sponsor GOVCERT.LU. PR [#720](https://github.com/tiangolo/sqlmodel/pull/720) by [@tiangolo](https://github.com/tiangolo).
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#697](https://github.com/tiangolo/sqlmodel/pull/697) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* 🔧 Show line numbers in docs during local development. PR [#714](https://github.com/tiangolo/sqlmodel/pull/714) by [@tiangolo](https://github.com/tiangolo).
* 📝 Update details syntax with new pymdown extensions format. PR [#713](https://github.com/tiangolo/sqlmodel/pull/713) by [@tiangolo](https://github.com/tiangolo).
## 0.0.12
### Features
* ✨ Upgrade SQLAlchemy to 2.0. PR [#700](https://github.com/tiangolo/sqlmodel/pull/700) by [@tiangolo](https://github.com/tiangolo) including initial work in PR [#563](https://github.com/tiangolo/sqlmodel/pull/563) by [@farahats9](https://github.com/farahats9).
### Internal
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#686](https://github.com/tiangolo/sqlmodel/pull/686) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* 👷 Upgrade latest-changes GitHub Action. PR [#693](https://github.com/tiangolo/sqlmodel/pull/693) by [@tiangolo](https://github.com/tiangolo).
## 0.0.11
### Features
* ✨ Add support for passing a custom SQLAlchemy type to `Field()` with `sa_type`. PR [#505](https://github.com/tiangolo/sqlmodel/pull/505) by [@maru0123-2004](https://github.com/maru0123-2004).
* You might consider this a breaking change if you were using an incompatible combination of arguments, those arguments were not taking effect and now you will have a type error and runtime error telling you that.
* ✨ Do not allow invalid combinations of field parameters for columns and relationships, `sa_column` excludes `sa_column_args`, `primary_key`, `nullable`, etc. PR [#681](https://github.com/tiangolo/sqlmodel/pull/681) by [@tiangolo](https://github.com/tiangolo).
### Docs
* 🎨 Update inline source examples, hide `#` in annotations (from MkDocs Material). PR [#677](https://github.com/tiangolo/sqlmodel/pull/677) by [@Matthieu-LAURENT39](https://github.com/Matthieu-LAURENT39).
### Internal
* ⬆ Update coverage requirement from ^6.2 to >=6.2,<8.0. PR [#663](https://github.com/tiangolo/sqlmodel/pull/663) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Update mkdocs-material requirement from 9.1.21 to 9.2.7. PR [#675](https://github.com/tiangolo/sqlmodel/pull/675) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆️ Upgrade mypy manually. PR [#684](https://github.com/tiangolo/sqlmodel/pull/684) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Update black requirement from ^22.10.0 to >=22.10,<24.0. PR [#664](https://github.com/tiangolo/sqlmodel/pull/664) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👷 Update CI to build MkDocs Insiders only when the secrets are available, for Dependabot. PR [#683](https://github.com/tiangolo/sqlmodel/pull/683) by [@tiangolo](https://github.com/tiangolo).
## 0.0.10
### Features
* ✨ Add support for all `Field` parameters from Pydantic `1.9.0` and above, make Pydantic `1.9.0` the minimum required version. PR [#440](https://github.com/tiangolo/sqlmodel/pull/440) by [@daniil-berg](https://github.com/daniil-berg).
### Internal
* 🔧 Adopt Ruff for formatting. PR [#679](https://github.com/tiangolo/sqlmodel/pull/679) by [@tiangolo](https://github.com/tiangolo).
## 0.0.9
### Breaking Changes
* 🗑️ Deprecate Python 3.6 and upgrade Poetry and Poetry Version Plugin. PR [#627](https://github.com/tiangolo/sqlmodel/pull/627) by [@tiangolo](https://github.com/tiangolo).
### Features
* ✨ Raise a more clear error when a type is not valid. PR [#425](https://github.com/tiangolo/sqlmodel/pull/425) by [@ddanier](https://github.com/ddanier).
### Fixes
* 🐛 Fix `AsyncSession` type annotations for `exec()`. PR [#58](https://github.com/tiangolo/sqlmodel/pull/58) by [@Bobronium](https://github.com/Bobronium).
* 🐛 Fix allowing using a `ForeignKey` directly, remove repeated column construction from `SQLModelMetaclass.__init__` and upgrade minimum SQLAlchemy to `>=1.4.36`. PR [#443](https://github.com/tiangolo/sqlmodel/pull/443) by [@daniil-berg](https://github.com/daniil-berg).
* 🐛 Fix enum type checks ordering in `get_sqlalchemy_type`. PR [#669](https://github.com/tiangolo/sqlmodel/pull/669) by [@tiangolo](https://github.com/tiangolo).
* 🐛 Fix SQLAlchemy version 1.4.36 breaks SQLModel relationships (#315). PR [#461](https://github.com/tiangolo/sqlmodel/pull/461) by [@byrman](https://github.com/byrman).
### Upgrades
* ⬆️ Upgrade support for SQLAlchemy 1.4.49, update tests. PR [#519](https://github.com/tiangolo/sqlmodel/pull/519) by [@sandrotosi](https://github.com/sandrotosi).
* ⬆ Raise SQLAlchemy version requirement to at least `1.4.29` (related to #434). PR [#439](https://github.com/tiangolo/sqlmodel/pull/439) by [@daniil-berg](https://github.com/daniil-berg).
### Docs
* 📝 Clarify description of in-memory SQLite database in `docs/tutorial/create-db-and-table.md`. PR [#601](https://github.com/tiangolo/sqlmodel/pull/601) by [@SimonCW](https://github.com/SimonCW).
* 📝 Tweak wording in `docs/tutorial/fastapi/multiple-models.md`. PR [#674](https://github.com/tiangolo/sqlmodel/pull/674) by [@tiangolo](https://github.com/tiangolo).
* ✏️ Fix contributing instructions to run tests, update script name. PR [#634](https://github.com/tiangolo/sqlmodel/pull/634) by [@PookieBuns](https://github.com/PookieBuns).
* 📝 Update link to docs for intro to databases. PR [#593](https://github.com/tiangolo/sqlmodel/pull/593) by [@abenezerBelachew](https://github.com/abenezerBelachew).
* 📝 Update docs, use `offset` in example with `limit` and `where`. PR [#273](https://github.com/tiangolo/sqlmodel/pull/273) by [@jbmchuck](https://github.com/jbmchuck).
* 📝 Fix docs for Pydantic's fields using `le` (`lte` is invalid, use `le` ). PR [#207](https://github.com/tiangolo/sqlmodel/pull/207) by [@jrycw](https://github.com/jrycw).
* 📝 Update outdated link in `docs/db-to-code.md`. PR [#649](https://github.com/tiangolo/sqlmodel/pull/649) by [@MatveyF](https://github.com/MatveyF).
* ✏️ Fix typos found with codespell. PR [#520](https://github.com/tiangolo/sqlmodel/pull/520) by [@kianmeng](https://github.com/kianmeng).
* 📝 Fix typos (duplication) in main page. PR [#631](https://github.com/tiangolo/sqlmodel/pull/631) by [@Mr-DRP](https://github.com/Mr-DRP).
* 📝 Update release notes, add second author to PR. PR [#429](https://github.com/tiangolo/sqlmodel/pull/429) by [@br-follow](https://github.com/br-follow).
* 📝 Update instructions about how to make a foreign key required in `docs/tutorial/relationship-attributes/define-relationships-attributes.md`. PR [#474](https://github.com/tiangolo/sqlmodel/pull/474) by [@jalvaradosegura](https://github.com/jalvaradosegura).
* 📝 Update help SQLModel docs. PR [#548](https://github.com/tiangolo/sqlmodel/pull/548) by [@tiangolo](https://github.com/tiangolo).
* ✏️ Fix typo in internal function name `get_sqlachemy_type()`. PR [#496](https://github.com/tiangolo/sqlmodel/pull/496) by [@cmarqu](https://github.com/cmarqu).
* ✏️ Fix typo in docs. PR [#446](https://github.com/tiangolo/sqlmodel/pull/446) by [@davidbrochart](https://github.com/davidbrochart).
* ✏️ Fix typo in `docs/tutorial/create-db-and-table.md`. PR [#477](https://github.com/tiangolo/sqlmodel/pull/477) by [@FluffyDietEngine](https://github.com/FluffyDietEngine).
* ✏️ Fix small typos in docs. PR [#481](https://github.com/tiangolo/sqlmodel/pull/481) by [@micuffaro](https://github.com/micuffaro).
### Internal
* ⬆ [pre-commit.ci] pre-commit autoupdate. PR [#672](https://github.com/tiangolo/sqlmodel/pull/672) by [@pre-commit-ci[bot]](https://github.com/apps/pre-commit-ci).
* ⬆ Bump dawidd6/action-download-artifact from 2.24.2 to 2.28.0. PR [#660](https://github.com/tiangolo/sqlmodel/pull/660) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ✅ Refactor OpenAPI FastAPI tests to simplify updating them later, this moves things around without changes. PR [#671](https://github.com/tiangolo/sqlmodel/pull/671) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump actions/checkout from 3 to 4. PR [#670](https://github.com/tiangolo/sqlmodel/pull/670) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Update mypy config, use `strict = true` instead of manual configs. PR [#428](https://github.com/tiangolo/sqlmodel/pull/428) by [@michaeloliverx](https://github.com/michaeloliverx).
* ⬆️ Upgrade MkDocs Material. PR [#668](https://github.com/tiangolo/sqlmodel/pull/668) by [@tiangolo](https://github.com/tiangolo).
* 🎨 Update docs format and references with pre-commit and Ruff. PR [#667](https://github.com/tiangolo/sqlmodel/pull/667) by [@tiangolo](https://github.com/tiangolo).
* 🎨 Run pre-commit on all files and autoformat. PR [#666](https://github.com/tiangolo/sqlmodel/pull/666) by [@tiangolo](https://github.com/tiangolo).
* 👷 Move to Ruff and add pre-commit. PR [#661](https://github.com/tiangolo/sqlmodel/pull/661) by [@tiangolo](https://github.com/tiangolo).
* 🛠️ Add `CITATION.cff` file for academic citations. PR [#13](https://github.com/tiangolo/sqlmodel/pull/13) by [@sugatoray](https://github.com/sugatoray).
* 👷 Update docs deployments to Cloudflare. PR [#630](https://github.com/tiangolo/sqlmodel/pull/630) by [@tiangolo](https://github.com/tiangolo).
* 👷‍♂️ Upgrade CI for docs. PR [#628](https://github.com/tiangolo/sqlmodel/pull/628) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update CI debug mode with Tmate. PR [#629](https://github.com/tiangolo/sqlmodel/pull/629) by [@tiangolo](https://github.com/tiangolo).
* 👷 Update latest changes token. PR [#616](https://github.com/tiangolo/sqlmodel/pull/616) by [@tiangolo](https://github.com/tiangolo).
* ⬆️ Upgrade analytics. PR [#558](https://github.com/tiangolo/sqlmodel/pull/558) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Update new issue chooser to point to GitHub Discussions. PR [#546](https://github.com/tiangolo/sqlmodel/pull/546) by [@tiangolo](https://github.com/tiangolo).
* 🔧 Add template for GitHub Discussion questions and update issues template. PR [#544](https://github.com/tiangolo/sqlmodel/pull/544) by [@tiangolo](https://github.com/tiangolo).
* 👷 Refactor CI artifact upload/download for docs previews. PR [#514](https://github.com/tiangolo/sqlmodel/pull/514) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump actions/cache from 2 to 3. PR [#497](https://github.com/tiangolo/sqlmodel/pull/497) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump dawidd6/action-download-artifact from 2.24.0 to 2.24.2. PR [#493](https://github.com/tiangolo/sqlmodel/pull/493) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 🔧 Update Smokeshow coverage threshold. PR [#487](https://github.com/tiangolo/sqlmodel/pull/487) by [@tiangolo](https://github.com/tiangolo).
* 👷 Move from Codecov to Smokeshow. PR [#486](https://github.com/tiangolo/sqlmodel/pull/486) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Bump actions/setup-python from 2 to 4. PR [#411](https://github.com/tiangolo/sqlmodel/pull/411) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Update black requirement from ^21.5-beta.1 to ^22.10.0. PR [#460](https://github.com/tiangolo/sqlmodel/pull/460) by [@dependabot[bot]](https://github.com/apps/dependabot).
* Add extra dev dependencies for MkDocs Material. PR [#485](https://github.com/tiangolo/sqlmodel/pull/485) by [@tiangolo](https://github.com/tiangolo).
* ⬆ Update mypy requirement from 0.930 to 0.971. PR [#380](https://github.com/tiangolo/sqlmodel/pull/380) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Update coverage requirement from ^5.5 to ^6.2. PR [#171](https://github.com/tiangolo/sqlmodel/pull/171) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump codecov/codecov-action from 2 to 3. PR [#415](https://github.com/tiangolo/sqlmodel/pull/415) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump actions/upload-artifact from 2 to 3. PR [#412](https://github.com/tiangolo/sqlmodel/pull/412) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Update flake8 requirement from ^3.9.2 to ^5.0.4. PR [#396](https://github.com/tiangolo/sqlmodel/pull/396) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Update pytest requirement from ^6.2.4 to ^7.0.1. PR [#242](https://github.com/tiangolo/sqlmodel/pull/242) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump actions/checkout from 2 to 3.1.0. PR [#458](https://github.com/tiangolo/sqlmodel/pull/458) by [@dependabot[bot]](https://github.com/apps/dependabot).
* ⬆ Bump dawidd6/action-download-artifact from 2.9.0 to 2.24.0. PR [#470](https://github.com/tiangolo/sqlmodel/pull/470) by [@dependabot[bot]](https://github.com/apps/dependabot).
* 👷 Update Dependabot config. PR [#484](https://github.com/tiangolo/sqlmodel/pull/484) by [@tiangolo](https://github.com/tiangolo).
## 0.0.8
### Fixes
* 🐛 Fix auto detecting and setting `nullable`, allowing overrides in field. PR [#423](https://github.com/tiangolo/sqlmodel/pull/423) by [@JonasKs](https://github.com/JonasKs) and [@br-follow](https://github.com/br-follow).
* ♻️ Update `expresion.py`, sync from Jinja2 template, implement `inherit_cache` to solve errors like: `SAWarning: Class SelectOfScalar will not make use of SQL compilation caching`. PR [#422](https://github.com/tiangolo/sqlmodel/pull/422) by [@tiangolo](https://github.com/tiangolo).
### Docs
* 📝 Adjust and clarify docs for `docs/tutorial/create-db-and-table.md`. PR [#426](https://github.com/tiangolo/sqlmodel/pull/426) by [@tiangolo](https://github.com/tiangolo).
* ✏ Fix typo in `docs/tutorial/connect/remove-data-connections.md`. PR [#421](https://github.com/tiangolo/sqlmodel/pull/421) by [@VerdantFox](https://github.com/VerdantFox).
## 0.0.7

View File

@@ -14,14 +14,13 @@ But the same `id` field actually **can be `None`** in the Python code, so we dec
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
Next, I'll show you a bit more about the synchronization of data between the database and the Python code.
@@ -36,17 +35,16 @@ When we create a new `Hero` instance, we don't set the `id`:
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:23-26]!}
# Code below ommitted 👇
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
### How `Optional` Helps
@@ -82,14 +80,13 @@ We can confirm that by printing our heroes before adding them to the database:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
That will output:
@@ -125,17 +122,16 @@ We can verify by creating a session using a `with` block and adding the objects.
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:23-41]!}
# Code below ommitted 👇
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
This will, again, output the `id`s of the objects as `None`:
@@ -168,14 +164,13 @@ Then we can `commit` the changes in the session, and print again:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
And now, something unexpected happens, look at the output, it seems as if the `Hero` instance objects had no data at all:
@@ -198,9 +193,9 @@ INFO Engine COMMIT
// And now our prints
After committing the session
Hero 1:
Hero 2:
Hero 3:
Hero 1:
Hero 2:
Hero 3:
// What is happening here? 😱
```
@@ -238,17 +233,16 @@ To confirm and understand how this **automatic expiration and refresh** of data
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:33-58]!}
# Code below ommitted 👇
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
Now we are actually accessing the attributes, because instead of printing the whole object `hero_1`:
@@ -271,21 +265,21 @@ Let's see how it works:
```console
$ python app.py
// Output above ommitted 👆
// Output above omitted 👆
// After committing, the objects are expired and have no values
After committing the session
Hero 1:
Hero 2:
Hero 3:
Hero 1:
Hero 2:
Hero 3:
// Now we will access an attribute like the ID, this is the first print
After committing the session, show IDs
// Notice that before printing the first ID, the Session makes the Engine go to the database to refresh the data 🤓
INFO Engine BEGIN (implicit)
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [generated in 0.00017s] (1,)
@@ -293,8 +287,8 @@ INFO Engine [generated in 0.00017s] (1,)
Hero 1 ID: 1
// Before the next print, refresh the data for the second object
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.001245s ago] (2,)
@@ -302,8 +296,8 @@ INFO Engine [cached since 0.001245s ago] (2,)
Hero 2 ID: 2
// Before the third print, refresh its data
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.002215s ago] (3,)
@@ -335,17 +329,16 @@ You can do that too with `session.refresh(object)`:
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py[ln:33-67]!}
# Code below ommitted 👇
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
When Python executes this code:
@@ -362,23 +355,23 @@ Here's how the output would look like:
```console
$ python app.py
// Output above ommitted 👆
// Output above omitted 👆
// The first refresh
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [generated in 0.00024s] (1,)
// The second refresh
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.001487s ago] (2,)
// The third refresh
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.002377s ago] (3,)
@@ -411,14 +404,13 @@ There are no surprises here, it still works:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial001.py!}
```
</details>
///
And the output shows again the same data:
@@ -427,7 +419,7 @@ And the output shows again the same data:
```console
$ python app.py
// Output above ommitted 👆
// Output above omitted 👆
// By finishing the with block, the Session is closed, including a rollback of any pending transaction that could have been there and was not committed
INFO Engine ROLLBACK
@@ -445,10 +437,13 @@ Hero 3: age=48 id=3 name='Rusty-Man' secret_name='Tommy Sharp'
Now let's review all this code once again.
!!! tip
Each one of the numbered bubbles shows what each line will print in the output.
/// tip
And as we created the **engine** with `echo=True`, we can see the SQL statements being executed at each step.
Each one of the numbered bubbles shows what each line will print in the output.
And as we created the **engine** with `echo=True`, we can see the SQL statements being executed at each step.
///
```{ .python .annotate }
{!./docs_src/tutorial/automatic_id_none_refresh/tutorial002.py!}
@@ -468,12 +463,12 @@ INFO Engine PRAGMA main.table_info("hero")
INFO Engine [raw sql] ()
INFO Engine PRAGMA temp.table_info("hero")
INFO Engine [raw sql] ()
INFO Engine
INFO Engine
CREATE TABLE hero (
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
PRIMARY KEY (id)
)
@@ -497,23 +492,23 @@ INFO Engine INSERT INTO hero (name, secret_name, age) VALUES (?, ?, ?)
INFO Engine [cached since 0.001483s ago] ('Rusty-Man', 'Tommy Sharp', 48)
INFO Engine COMMIT
After committing the session
Hero 1:
Hero 2:
Hero 3:
Hero 1:
Hero 2:
Hero 3:
After committing the session, show IDs
INFO Engine BEGIN (implicit)
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [generated in 0.00029s] (1,)
Hero 1 ID: 1
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.002132s ago] (2,)
Hero 2 ID: 2
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
INFO Engine SELECT hero.id AS hero_id, hero.name AS hero_name, hero.secret_name AS hero_secret_name, hero.age AS hero_age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.003367s ago] (3,)
Hero 3 ID: 3
@@ -521,16 +516,16 @@ After committing the session, show names
Hero 1 name: Deadpond
Hero 2 name: Spider-Boy
Hero 3 name: Rusty-Man
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [generated in 0.00025s] (1,)
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.001583s ago] (2,)
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.002722s ago] (3,)
After refreshing the heroes

View File

@@ -138,7 +138,7 @@ So, the output would be:
$ python -m project.app
Created hero: id=1 secret_name='Dive Wilson' team_id=1 name='Deadpond' age=None
Hero's team: name='Z-Force' headquarters='Sister Margarets Bar' id=1
Hero's team: name='Z-Force' headquarters='Sister Margaret's Bar' id=1
```
</div>
@@ -149,10 +149,13 @@ Let's say that for some reason you hate the idea of having all the database mode
You can also do it. 😎 There's a couple of things to keep in mind. 🤓
!!! warning
This is a bit more advanced.
/// warning
If the solution above already worked for you, that might be enough for you, and you can continue in the next chapter. 🤓
This is a bit more advanced.
If the solution above already worked for you, that might be enough for you, and you can continue in the next chapter. 🤓
///
Let's assume that now the file structure is:
@@ -168,7 +171,7 @@ Let's assume that now the file structure is:
### Circular Imports and Type Annotations
The problem with circular imports is that Python can't resolve them at <abbr title="While it is executing the program, as oposed to the code as just text in a file stored on disk.">*runtime*</abbr>.
The problem with circular imports is that Python can't resolve them at <abbr title="While it is executing the program, as opposed to the code as just text in a file stored on disk.">*runtime*</abbr>.
But when using Python **type annotations** it's very common to need to declare the type of some variables with classes imported from other files.
@@ -240,7 +243,7 @@ And running that achieves the same result as before:
$ python -m project.app
Created hero: id=1 age=None name='Deadpond' secret_name='Dive Wilson' team_id=1
Hero's team: id=1 name='Z-Force' headquarters='Sister Margarets Bar'
Hero's team: id=1 name='Z-Force' headquarters='Sister Margaret's Bar'
```
</div>

View File

@@ -12,7 +12,7 @@ The `team` table will look like this:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -37,19 +37,21 @@ Each row in the table `hero` will point to a row in the table `team`:
<img alt="table relationships" src="/img/tutorial/relationships/select/relationships2.svg">
!!! info
We will later update **Spider-Boy** to add him to the **Preventers** team too, but not yet.
/// info
We will later update **Spider-Boy** to add him to the **Preventers** team too, but not yet.
///
We will continue with the code in the previous example and we will add more things to it.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
```
</details>
///
Make sure you remove the `database.db` file before running the examples to get the same results.
@@ -69,14 +71,13 @@ Let's start by creating two teams:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
This would hopefully look already familiar.
@@ -100,14 +101,13 @@ Let's not forget to add this function `create_heroes()` to the `main()` function
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
## Run it
@@ -126,7 +126,7 @@ INFO Engine BEGIN (implicit)
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
INFO Engine [generated in 0.00050s] ('Preventers', 'Sharp Tower')
INFO Engine INSERT INTO team (name, headquarters) VALUES (?, ?)
INFO Engine [cached since 0.002324s ago] ('Z-Force', 'Sister Margarets Bar')
INFO Engine [cached since 0.002324s ago] ('Z-Force', 'Sister Margaret's Bar')
INFO Engine COMMIT
```
@@ -148,18 +148,17 @@ As the `Hero` class model now has a field (column, attribute) `team_id`, we can
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
We haven't committed this hero to the database yet, but there are already a couple of things to pay **attention** to.
If the database already had some teams, we wouldn't even know **what is the ID** that is going to be automatically assigned to each team by the database, for example, we couldn't just guess `1` or `2`.
If the database already had some teams, we wouldn't even know **what is the ID** that is going to be automatically assigned to each team by the database, for example, we couldn't just guess `1` or `2`.
But once the team is created and committed to the database, we can access the object's `id` field to get that ID.
@@ -171,8 +170,8 @@ That line alone would generate an output of:
```
INFO Engine BEGIN (implicit)
INFO Engine SELECT team.id AS team_id, team.name AS team_name, team.headquarters AS team_headquarters
FROM team
INFO Engine SELECT team.id AS team_id, team.name AS team_name, team.headquarters AS team_headquarters
FROM team
WHERE team.id = ?
INFO Engine [generated in 0.00025s] (2,)
```
@@ -187,20 +186,19 @@ Let's now create two more heroes:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
When creating `hero_rusty_man`, we are accessing `team_preventers.id`, so that will also trigger a refresh of its data, generating an output of:
```
INFO Engine SELECT team.id AS team_id, team.name AS team_name, team.headquarters AS team_headquarters
FROM team
INFO Engine SELECT team.id AS team_id, team.name AS team_name, team.headquarters AS team_headquarters
FROM team
WHERE team.id = ?
INFO Engine [cached since 0.001795s ago] (1,)
```
@@ -233,14 +231,13 @@ Now let's refresh and print those new heroes to see their new ID pointing to the
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
If we execute that in the command line, it will output:
@@ -256,18 +253,18 @@ $ python app.py
INFO Engine BEGIN (implicit)
// Refresh the first hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [generated in 0.00021s] (1,)
// Refresh the second hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.001575s ago] (2,)
// Refresh the third hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.002518s ago] (3,)

View File

@@ -16,7 +16,7 @@ The team table will look like this:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -63,14 +63,13 @@ Import the things we need from `sqlmodel` and create a new `Team` model:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
```
</details>
///
This is very similar to what we have been doing with the `Hero` model.
@@ -95,18 +94,17 @@ This is the same model we have been using up to now, we are just adding the new
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
```
</details>
///
Most of that should look familiar:
The column will be named `team_id`. It will be an integer, and it could be `NULL` in the database (or `None` in Python), becase there could be some heroes that don't belong to any team.
The column will be named `team_id`. It will be an integer, and it could be `NULL` in the database (or `None` in Python), because there could be some heroes that don't belong to any team.
We add a default of `None` to the `Field()` so we don't have to explicitly pass `team_id=None` when creating a hero.
@@ -126,8 +124,11 @@ This is the name of the **table** in the database, so it is `"team"`, not the na
If you had a custom table name, you would use that custom table name.
!!! info
You can learn about setting a custom table name for a model in the Advanced User Guide.
/// info
You can learn about setting a custom table name for a model in the Advanced User Guide.
///
### Create the Tables
@@ -139,14 +140,13 @@ Now we can add the same code as before to create the engine and the function to
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:21-28]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
```
</details>
///
And as before, we'll call this function from another function `main()`, and we'll add that function `main()` to the main block of the file:
@@ -156,19 +156,21 @@ And as before, we'll call this function from another function `main()`, and we'l
{!./docs_src/tutorial/connect/create_tables/tutorial001.py[ln:31-36]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/create_tables/tutorial001.py!}
```
</details>
///
## Run the Code
!!! tip
Before running the code, make sure you delete the file `database.db` to make sure you start from scratch.
/// tip
Before running the code, make sure you delete the file `database.db` to make sure you start from scratch.
///
If we run the code we have up to now, it will go and create the database file `database.db` and the tables in it we just defined, `team` and `hero`:
@@ -191,24 +193,24 @@ INFO Engine PRAGMA temp.table_info("hero")
INFO Engine [raw sql] ()
// Create the tables
INFO Engine
INFO Engine
CREATE TABLE team (
id INTEGER,
name VARCHAR NOT NULL,
headquarters VARCHAR NOT NULL,
id INTEGER,
name VARCHAR NOT NULL,
headquarters VARCHAR NOT NULL,
PRIMARY KEY (id)
)
INFO Engine [no key 0.00010s] ()
INFO Engine
INFO Engine
CREATE TABLE hero (
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
team_id INTEGER,
PRIMARY KEY (id),
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
team_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(team_id) REFERENCES team (id)
)
@@ -229,9 +231,9 @@ So, the first SQL could also be written as:
```SQL
CREATE TABLE team (
id INTEGER,
name TEXT NOT NULL,
headquarters TEXT NOT NULL,
id INTEGER,
name TEXT NOT NULL,
headquarters TEXT NOT NULL,
PRIMARY KEY (id)
)
```
@@ -240,12 +242,12 @@ And the second table could be written as:
```SQL hl_lines="8"
CREATE TABLE hero (
id INTEGER,
name TEXT NOT NULL,
secret_name TEXT NOT NULL,
age INTEGER,
team_id INTEGER,
PRIMARY KEY (id),
id INTEGER,
name TEXT NOT NULL,
secret_name TEXT NOT NULL,
age INTEGER,
team_id INTEGER,
PRIMARY KEY (id),
FOREIGN KEY(team_id) REFERENCES team (id)
)
```

View File

@@ -6,7 +6,10 @@ But the main advantage and feature of SQL databases is being able to handle rela
Let's see how to use **SQLModel** to manage connected data in the next chapters. 🤝
!!! tip
We will extend this further in the next group of chapters making it even more convenient to work with in Python code, using **relationship attributes**.
/// tip
But you should start in this group of chapters first. 🤓
We will extend this further in the next group of chapters making it even more convenient to work with in Python code, using **relationship attributes**.
But you should start in this group of chapters first. 🤓
///

View File

@@ -12,7 +12,7 @@ The `team` table has this data:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -35,14 +35,13 @@ And the `hero` table has this data:
We will continue with the code in the previous example and we will add more things to it.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
## `SELECT` Connected Data with SQL
@@ -62,8 +61,11 @@ FROM hero, team
WHERE hero.team_id = team.id
```
!!! info
Because we have two columns called `name`, one for `hero` and one for `team`, we can specify them with the prefix of the table name and the dot to make it explicit what we refer to.
/// info
Because we have two columns called `name`, one for `hero` and one for `team`, we can specify them with the prefix of the table name and the dot to make it explicit what we refer to.
///
Notice that now in the `WHERE` part we are not comparing one column with a literal value (like `hero.name = "Deadpond"`), but we are comparing two columns.
@@ -99,14 +101,17 @@ You can go ahead and try it in **DB Browser for SQLite**:
<img class="shadow" src="/img/tutorial/relationships/select/image01.png">
!!! note
Wait, what about Spider-Boy? 😱
/// note
He doesn't have a team, so his `team_id` is `NULL` in the database. And this SQL is comparing that `NULL` from the `team_id` with all the `id` fields in the rows in the `team` table.
Wait, what about Spider-Boy? 😱
As there's no team with an ID of `NULL`, it doesn't find a match.
He doesn't have a team, so his `team_id` is `NULL` in the database. And this SQL is comparing that `NULL` from the `team_id` with all the `id` fields in the rows in the `team` table.
But we'll see how to fix that later with a `LEFT JOIN`.
As there's no team with an ID of `NULL`, it doesn't find a match.
But we'll see how to fix that later with a `LEFT JOIN`.
///
## Select Related Data with **SQLModel**
@@ -126,14 +131,13 @@ So, we can pass the `Hero` and `Team` model classes. And we can also use both th
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial001.py!}
```
</details>
///
Notice that in the comparison with `==` we are using the class attributes for both `Hero.team_id` and `Team.id`.
@@ -151,23 +155,25 @@ And as we used `select` with two models, we will receive tuples of instances of
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial001.py!}
```
</details>
///
For each iteration in the `for` loop we get a a tuple with an instance of the class `Hero` and an instance of the class `Team`.
And in this `for` loop we assign them to the variable `hero` and the variable `team`.
!!! info
There was a lot of research, design, and work behind **SQLModel** to make this provide the best possible developer experience.
/// info
And you should get autocompletion and inline errors in your editor for both `hero` and `team`. 🎉
There was a lot of research, design, and work behind **SQLModel** to make this provide the best possible developer experience.
And you should get autocompletion and inline errors in your editor for both `hero` and `team`. 🎉
///
## Add It to Main
@@ -181,14 +187,13 @@ As always, we must remember to add this new `select_heroes()` function to the `m
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial001.py!}
```
</details>
///
## Run the Program
@@ -203,13 +208,13 @@ $ python app.py
// Previous output omitted 😉
// Get the heroes with their teams
2021-08-09 08:55:50,682 INFO sqlalchemy.engine.Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
FROM hero, team
2021-08-09 08:55:50,682 INFO sqlalchemy.engine.Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
FROM hero, team
WHERE hero.team_id = team.id
2021-08-09 08:55:50,682 INFO sqlalchemy.engine.Engine [no key 0.00015s] ()
// Print the first hero and team
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margarets Bar' id=2 name='Z-Force'
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
// Print the second hero and team
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
@@ -281,10 +286,13 @@ Also in **DB Browser for SQLite**:
<img class="shadow" src="/img/tutorial/relationships/select/image02.png">
!!! tip
Why bother with all this if the result is the same?
/// tip
This `JOIN` will be useful in a bit to be able to also get Spider-Boy, even if he doesn't have a team.
Why bother with all this if the result is the same?
This `JOIN` will be useful in a bit to be able to also get Spider-Boy, even if he doesn't have a team.
///
## Join Tables in **SQLModel**
@@ -300,14 +308,13 @@ And in SQLModel (actually SQLAlchemy), when using the `.join()`, because we alre
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial002.py!}
```
</details>
///
Also notice that we are still including `Team` in the `select(Hero, Team)`, because we still want to access that data.
@@ -323,12 +330,12 @@ $ python app.py
// Previous output omitted 😉
// Select using a JOIN with automatic ON
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
FROM hero JOIN team ON team.id = hero.team_id
INFO Engine [no key 0.00032s] ()
// Print the first hero and team
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margarets Bar' id=2 name='Z-Force'
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
// Print the second hero and team
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
@@ -420,8 +427,11 @@ And that would return the following result, including **Spider-Boy** 🎉:
</tr>
</table>
!!! tip
The only difference between this query and the previous is that extra `LEFT OUTER`.
/// tip
The only difference between this query and the previous is that extra `LEFT OUTER`.
///
And here's another of the SQL variations, you could write `LEFT OUTER JOIN` or just `LEFT JOIN`, it means the same.
@@ -439,14 +449,13 @@ Now let's replicate the same query in **SQLModel**.
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial003.py!}
```
</details>
///
And if we run it, it will output:
@@ -458,13 +467,13 @@ $ python app.py
// Previous output omitted 😉
// SELECT using LEFT OUTER JOIN
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
FROM hero LEFT OUTER JOIN team ON team.id = hero.team_id
INFO Engine [no key 0.00051s] ()
// Print the first hero and team
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margarets Bar' id=2 name='Z-Force'
Hero: id=1 secret_name='Dive Wilson' team_id=2 name='Deadpond' age=None Team: headquarters='Sister Margaret's Bar' id=2 name='Z-Force'
// Print the second hero and team
Hero: id=2 secret_name='Tommy Sharp' team_id=1 name='Rusty-Man' age=48 Team: headquarters='Sharp Tower' id=1 name='Preventers'
// Print the third hero and team, we included Spider-Boy 🎉
@@ -501,14 +510,13 @@ We could even add some additional `.where()` after `.join()` to filter the data
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial004.py!}
```
</details>
///
Here we are **filtering** with `.where()` to get only the heroes that belong to the **Preventers** team.
@@ -522,9 +530,9 @@ If we run that, it would output:
$ python app.py
// Select only the hero data
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
// But still join with the team table
FROM hero JOIN team ON team.id = hero.team_id
FROM hero JOIN team ON team.id = hero.team_id
// And filter with WHERE to get only the Preventers
WHERE team.name = ?
INFO Engine [no key 0.00066s] ('Preventers',)
@@ -547,14 +555,13 @@ By putting the `Team` in `select()` we tell **SQLModel** and the database that w
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/select/tutorial005.py!}
```
</details>
///
And if we run that, it will output:
@@ -564,9 +571,9 @@ And if we run that, it will output:
$ python app.py
// Select the hero and the team data
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id, team.id AS id_1, team.name AS name_1, team.headquarters
// Join the hero with the team table
FROM hero JOIN team ON team.id = hero.team_id
FROM hero JOIN team ON team.id = hero.team_id
// Filter with WHERE to get only Preventers
WHERE team.name = ?
INFO Engine [no key 0.00018s] ('Preventers',)

View File

@@ -10,7 +10,7 @@ We currently have a `team` table:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -35,18 +35,17 @@ Let's see how to **remove** connections between rows in tables.
We will continue with the code from the previous chapter.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/update/tutorial001.py!}
```
</details>
///
## Break a Connection
We don't really have to delete anyting to break a connection. We can just assign `None` to the foreign key, in this case, to the `team_id`.
We don't really have to delete anything to break a connection. We can just assign `None` to the foreign key, in this case, to the `team_id`.
Let's say **Spider-Boy** is tired of the lack of friendly neighbors and wants to get out of the **Preventers**.
@@ -56,7 +55,7 @@ We can simply set the `team_id` to `None`, and now it doesn't have a connection
# Code above omitted 👆
{!./docs_src/tutorial/connect/delete/tutorial001.py[ln:31-32]!}
# Previous code here omitted 👈
{!./docs_src/tutorial/connect/delete/tutorial001.py[ln:68-72]!}
@@ -64,14 +63,13 @@ We can simply set the `team_id` to `None`, and now it doesn't have a connection
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/delete/tutorial001.py!}
```
</details>
///
Again, we just **assign** a value to that field attribute `team_id`, now the value is `None`, which means `NULL` in the database. Then we `add()` the hero to the session, and then `commit()`.
@@ -94,8 +92,8 @@ INFO Engine COMMIT
// Automatically start a new transaction
INFO Engine BEGIN (implicit)
// Refresh the hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.1661s ago] (3,)

View File

@@ -10,7 +10,7 @@ At this point we have a `team` table:
<td>1</td><td>Preventers</td><td>Sharp Tower</td>
</tr>
<tr>
<td>2</td><td>Z-Force</td><td>Sister Margarets Bar</td>
<td>2</td><td>Z-Force</td><td>Sister Margaret's Bar</td>
</tr>
</table>
@@ -37,14 +37,13 @@ Now we'll see how to **update** those connections between rows tables.
We will continue with the code we used to create some heroes, and we'll update them.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/insert/tutorial001.py!}
```
</details>
///
## Assign a Team to a Hero
@@ -56,7 +55,7 @@ Doing it is just like updating any other field:
# Code above omitted 👆
{!./docs_src/tutorial/connect/update/tutorial001.py[ln:31-32]!}
# Previous code here omitted 👈
{!./docs_src/tutorial/connect/update/tutorial001.py[ln:62-66]!}
@@ -64,14 +63,13 @@ Doing it is just like updating any other field:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/connect/update/tutorial001.py!}
```
</details>
///
We can simply **assign** a value to that field attribute `team_id`, then `add()` the hero to the session, and then `commit()`.
@@ -94,8 +92,8 @@ INFO Engine COMMIT
// Automatically start a new transaction
INFO Engine BEGIN (implicit)
// Refresh the hero data
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age, hero.team_id
FROM hero
WHERE hero.id = ?
INFO Engine [cached since 0.08837s ago] (3,)

View File

@@ -42,8 +42,11 @@ Click the button <kbd>New Database</kbd>.
A dialog should show up. Go to the [project directory you created](./index.md#create-a-project){.internal-link target=_blank} and save the file with a name of `database.db`.
!!! tip
It's common to save SQLite database files with an extension of `.db`. Sometimes also `.sqlite`.
/// tip
It's common to save SQLite database files with an extension of `.db`. Sometimes also `.sqlite`.
///
## Create a Table
@@ -164,6 +167,6 @@ Of course, you can also go and take a full SQL course or read a book about SQL,
We saw how to interact with SQLite databases in files using **DB Browser for SQLite** in a visual user interface.
We also saw how to use it to write some SQL directly to the SQLite database. This will be useful to verify the data in the database is looking correclty, to debug, etc.
We also saw how to use it to write some SQL directly to the SQLite database. This will be useful to verify the data in the database is looking correctly, to debug, etc.
In the next chapters we will start using **SQLModel** to interact with the database, and we will continue to use **DB Browser for SQLite** at the same time to look at the database underneath. 🔍

View File

@@ -33,8 +33,11 @@ The first thing we need to do is create a class to represent the data in the tab
A class like this that represents some data is commonly called a **model**.
!!! tip
That's why this package is called `SQLModel`. Because it's mainly used to create **SQL Models**.
/// tip
That's why this package is called `SQLModel`. Because it's mainly used to create **SQL Models**.
///
For that, we will import `SQLModel` (plus other things we will also use) and create a class `Hero` that inherits from `SQLModel` and represents the **table model** for our heroes:
@@ -44,23 +47,25 @@ For that, we will import `SQLModel` (plus other things we will also use) and cre
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
This class `Hero` **represents the table** for our heroes. And each instance we create later will **represent a row** in the table.
We use the config `table=True` to tell **SQLModel** that this is a **table model**, it represents a table.
!!! info
It's also possible to have models without `table=True`, those would be only **data models**, without a table in the database, they would not be **table models**.
/// info
Those **data models** will be **very useful later**, but for now, we'll just keep adding the `table=True` configuration.
It's also possible to have models without `table=True`, those would be only **data models**, without a table in the database, they would not be **table models**.
Those **data models** will be **very useful later**, but for now, we'll just keep adding the `table=True` configuration.
///
## Define the Fields, Columns
@@ -76,14 +81,13 @@ And the type of each of them will also be the type of table column:
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
Let's now see with more detail these field/column declarations.
@@ -103,17 +107,19 @@ And we also set the default value of `age` to `None`.
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
!!! tip
We also define `id` with `Optional`. But we will talk about `id` below.
/// tip
We also define `id` with `Optional`. But we will talk about `id` below.
///
This way, we tell **SQLModel** that `age` is not required when validating data and that it has a default value of `None`.
@@ -121,10 +127,13 @@ And we also tell it that, in the SQL database, the default value of `age` is `NU
So, this column is "nullable" (can be set to `NULL`).
!!! info
In terms of **Pydantic**, `age` is an **optional field**.
/// info
In terms of **SQLAlchemy**, `age` is a **nullable column**.
In terms of **Pydantic**, `age` is an **optional field**.
In terms of **SQLAlchemy**, `age` is a **nullable column**.
///
### Primary Key `id`
@@ -140,14 +149,13 @@ To do that, we use the special `Field` function from `sqlmodel` and set the argu
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
That way, we tell **SQLModel** that this `id` field/column is the primary key of the table.
@@ -196,21 +204,23 @@ Creating the **engine** is very simple, just call `create_engine()` with a URL f
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
You should normally have a single **engine** object for your whole application and re-use it everywhere.
!!! tip
There's another related thing called a **Session** that normally should *not* be a single object per application.
/// tip
But we will talk about it later.
There's another related thing called a **Session** that normally should *not* be a single object per application.
But we will talk about it later.
///
### Engine Database URL
@@ -220,7 +230,7 @@ Each supported database has it's own URL type. For example, for **SQLite** it is
* `sqlite:///databases/local/application.db`
* `sqlite:///db.sqlite`
For SQLAlchemy, there's also a special one, which is a database all *in memory*, this means that it is deleted after the program terminates, and it's also very fast:
SQLite supports a special database that lives all *in memory*. Hence, it's very fast, but be careful, the database gets deleted after the program terminates. You can specify this in-memory database by using just two slash characters (`//`) and no file name:
* `sqlite://`
@@ -230,14 +240,13 @@ For SQLAlchemy, there's also a special one, which is a database all *in memory*,
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
You can read a lot more about all the databases supported by **SQLAlchemy** (and that way supported by **SQLModel**) in the <a href="https://docs.sqlalchemy.org/en/14/core/engines.html" class="external-link" target="_blank">SQLAlchemy documentation</a>.
@@ -255,14 +264,13 @@ It is particularly useful for **learning** and **debugging**:
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
But in production, you would probably want to remove `echo=True`:
@@ -272,8 +280,11 @@ engine = create_engine(sqlite_url)
### Engine Technical Details
!!! tip
If you didn't know about SQLAlchemy before and are just learning **SQLModel**, you can probably skip this section, scroll below.
/// tip
If you didn't know about SQLAlchemy before and are just learning **SQLModel**, you can probably skip this section, scroll below.
///
You can read a lot more about the engine in the <a href="https://docs.sqlalchemy.org/en/14/tutorial/engine.html" class="external-link" target="_blank">SQLAlchemy documentation</a>.
@@ -289,12 +300,15 @@ Now everything is in place to finally create the database and table:
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
!!! tip
Creating the engine doesn't create the `database.db` file.
/// tip
But once we run `SQLModel.metadata.create_all(engine)`, it creates the `database.db` file **and** creates the `hero` table in that database.
Creating the engine doesn't create the `database.db` file.
Both things are done in this single step.
But once we run `SQLModel.metadata.create_all(engine)`, it creates the `database.db` file **and** creates the `hero` table in that database.
Both things are done in this single step.
///
Let's unwrap that:
@@ -395,17 +409,19 @@ Let's run the program to see it all working.
Put the code it in a file `app.py` if you haven't already.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial001.py!}
```
</details>
///
!!! tip
Remember to [activate the virtual environment](./index.md#create-a-python-virtual-environment){.internal-link target=_blank} before running it.
/// tip
Remember to [activate the virtual environment](./index.md#create-a-python-virtual-environment){.internal-link target=_blank} before running it.
///
Now run the program with Python:
@@ -415,22 +431,22 @@ Now run the program with Python:
// We set echo=True, so this will show the SQL code
$ python app.py
// First, some boilerplate SQL that we are not that intereted in
// First, some boilerplate SQL that we are not that interested in
INFO Engine BEGIN (implicit)
INFO Engine PRAGMA main.table_info("hero")
INFO Engine [raw sql] ()
INFO Engine PRAGMA temp.table_info("hero")
INFO Engine [raw sql] ()
INFO Engine
INFO Engine
// Finally, the glorious SQL to create the table ✨
CREATE TABLE hero (
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
id INTEGER,
name VARCHAR NOT NULL,
secret_name VARCHAR NOT NULL,
age INTEGER,
PRIMARY KEY (id)
)
@@ -442,20 +458,23 @@ INFO Engine COMMIT
</div>
!!! info
I simplified the output above a bit to make it easier to read.
/// info
But in reality, instead of showing:
I simplified the output above a bit to make it easier to read.
```
INFO Engine BEGIN (implicit)
```
But in reality, instead of showing:
it would show something like:
```
INFO Engine BEGIN (implicit)
```
```
2021-07-25 21:37:39,175 INFO sqlalchemy.engine.Engine BEGIN (implicit)
```
it would show something like:
```
2021-07-25 21:37:39,175 INFO sqlalchemy.engine.Engine BEGIN (implicit)
```
///
### `TEXT` or `VARCHAR`
@@ -479,8 +498,11 @@ Additional to the difference between those two data types, some databases like M
To make it easier to start using **SQLModel** right away independent of the database you use (even with MySQL), and without any extra configurations, by default, `str` fields are interpreted as `VARCHAR` in most databases and `VARCHAR(255)` in MySQL, this way you know the same class will be compatible with the most popular databases without extra effort.
!!! tip
You will learn how to change the maximum length of string columns later in the Advanced Tutorial - User Guide.
/// tip
You will learn how to change the maximum length of string columns later in the Advanced Tutorial - User Guide.
///
### Verify the Database
@@ -498,29 +520,31 @@ In this example it's just the `SQLModel.metadata.create_all(engine)`.
Let's put it in a function `create_db_and_tables()`:
```Python hl_lines="22-23"
```Python hl_lines="19-20"
{!./docs_src/tutorial/create_db_and_table/tutorial002.py[ln:1-20]!}
# More code here later 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/create_db_and_table/tutorial002.py!}
```
</details>
///
If `SQLModel.metadata.create_all(engine)` was not in a function and we tried to import something from this module (from this file) in another, it would try to create the database and table **every time**.
If `SQLModel.metadata.create_all(engine)` was not in a function and we tried to import something from this module (from this file) in another, it would try to create the database and table **every time** we executed that other file that imported this module.
We don't want that to happen like that, only when we **intend** it to happen, that's why we put it in a function.
We don't want that to happen like that, only when we **intend** it to happen, that's why we put it in a function, because we can make sure that the tables are created only when we call that function, and not when this module is imported somewhere else.
Now we would be able to, for example, import the `Hero` class in some other file without having those **side effects**.
!!! tip
😅 **Spoiler alert**: The function is called `create_db_and_tables()` because we will have more **tables** in the future with other classes apart from `Hero`. 🚀
/// tip
😅 **Spoiler alert**: The function is called `create_db_and_tables()` because we will have more **tables** in the future with other classes apart from `Hero`. 🚀
///
### Create Data as a Script
@@ -528,10 +552,13 @@ We prevented the side effects when importing something from your `app.py` file.
But we still want it to **create the database and table** when we call it with Python directly as an independent script from the terminal, just as as above.
!!! tip
Think of the word **script** and **program** as interchangeable.
/// tip
The word **script** often implies that the code could be run independently and easily. Or in some cases it refers to a relatively simple program.
Think of the word **script** and **program** as interchangeable.
The word **script** often implies that the code could be run independently and easily. Or in some cases it refers to a relatively simple program.
///
For that we can use the special variable `__name__` in an `if` block:
@@ -559,10 +586,13 @@ $ python app.py
from app import Hero
```
!!! tip
That `if` block using `if __name__ == "__main__":` is sometimes called the "**main block**".
/// tip
The official name (in the <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python docs</a>) is "**Top-level script environment**".
That `if` block using `if __name__ == "__main__":` is sometimes called the "**main block**".
The official name (in the <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">Python docs</a>) is "**Top-level script environment**".
///
#### More details
@@ -614,8 +644,11 @@ if __name__ == "__main__":
...will **not** be executed.
!!! info
For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
/// info
For more information, check <a href="https://docs.python.org/3/library/__main__.html" class="external-link" target="_blank">the official Python docs</a>.
///
## Last Review
@@ -631,8 +664,11 @@ Now, let's give the code a final look:
{!./docs_src/tutorial/create_db_and_table/annotations/en/tutorial003.md!}
!!! tip
Review what each line does by clicking each number bubble in the code. 👆
/// tip
Review what each line does by clicking each number bubble in the code. 👆
///
## Recap

View File

@@ -6,14 +6,13 @@ Now let's delete some data using **SQLModel**.
As before, we'll continue from where we left off with the previous code.
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/update/tutorial003.py!}
```
</details>
///
Remember to remove the `database.db` file before running the examples to get the same results.
@@ -71,14 +70,13 @@ We'll start by selecting the hero `"Spider-Youngster"` that we updated in the pr
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
As this is a new function `delete_heroes()`, we'll also add it to the `main()` function so that we call it when executing the program from the command line:
@@ -88,14 +86,13 @@ As this is a new function `delete_heroes()`, we'll also add it to the `main()` f
{!./docs_src/tutorial/delete/tutorial001.py[ln:92-100]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
That will print the same existing hero **Spider-Youngster**:
@@ -108,8 +105,8 @@ $ python app.py
// The SELECT with WHERE
INFO Engine BEGIN (implicit)
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.name = ?
INFO Engine [no key 0.00011s] ('Spider-Youngster',)
@@ -131,14 +128,13 @@ Now, very similar to how we used `session.add()` to add or update new heroes, we
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
## Commit the Session
@@ -154,14 +150,13 @@ This will save all the changes stored in the **session**, like the deleted hero:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
The same as we have seen before, `.commit()` will also save anything else that was added to the session. Including updates, or created heroes.
@@ -204,14 +199,13 @@ Because of that, the object still contains its attributes with the data in it, s
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
This will output:
@@ -242,14 +236,13 @@ To confirm if it was deleted, now let's query the database again, with the same
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
Here we are using `results.first()` to get the first object found (in case it found multiple) or `None`, if it didn't find anything.
@@ -272,8 +265,8 @@ $ python app.py
INFO Engine BEGIN (implicit)
// SQL to search for the hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
INFO Engine SELECT hero.id, hero.name, hero.secret_name, hero.age
FROM hero
WHERE hero.name = ?
INFO Engine [no key 0.00013s] ('Spider-Youngster',)
```
@@ -294,14 +287,13 @@ We'll do it by checking that the "first" item in the `results` is `None`:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/delete/tutorial001.py!}
```
</details>
///
This will output:
@@ -333,8 +325,11 @@ Now let's review all that code:
{!./docs_src/tutorial/delete/annotations/en/tutorial002.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
## Recap

View File

@@ -20,14 +20,13 @@ And if we actually find a hero, we just delete it with the **session**.
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/delete/tutorial001.py!}
```
</details>
///
After deleting it successfully, we just return a response of:

View File

@@ -8,8 +8,11 @@ So, we probably want to limit it.
Let's use the same **offset** and **limit** we learned about in the previous tutorial chapters for the API.
!!! info
In many cases, this is also called **pagination**.
/// info
In many cases, this is also called **pagination**.
///
## Add a Limit and Offset to the Query Parameters
@@ -29,29 +32,31 @@ And by default, we will return a maximum of `100` heroes, so `limit` will have a
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/limit_and_offset/tutorial001.py!}
```
</details>
///
We want to allow clients to set different `offset` and `limit` values.
But we don't want them to be able to set a `limit` of something like `9999`, that's over `9000`! 😱
So, to prevent it, we add additional validation to the `limit` query parameter, declaring that it has to be **l**ess **t**han or **e**qual to `100` with `lte=100`.
So, to prevent it, we add additional validation to the `limit` query parameter, declaring that it has to be **l**ess than or **e**qual to `100` with `le=100`.
This way, a client can decide to take fewer heroes if they want, but not more.
!!! info
If you need to refresh how query parameters and their validation work, check out the docs in FastAPI:
/// info
* <a href="https://fastapi.tiangolo.com/tutorial/query-params/" class="external-link" target="_blank">Query Parameters</a>
* <a href="https://fastapi.tiangolo.com/tutorial/query-params-str-validations/" class="external-link" target="_blank">Query Parameters and String Validations</a>
* <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/" class="external-link" target="_blank">Path Parameters and Numeric Validations</a>
If you need to refresh how query parameters and their validation work, check out the docs in FastAPI:
* <a href="https://fastapi.tiangolo.com/tutorial/query-params/" class="external-link" target="_blank">Query Parameters</a>
* <a href="https://fastapi.tiangolo.com/tutorial/query-params-str-validations/" class="external-link" target="_blank">Query Parameters and String Validations</a>
* <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/" class="external-link" target="_blank">Path Parameters and Numeric Validations</a>
///
## Check the Docs UI

View File

@@ -53,11 +53,11 @@ Here's the weird thing, the `id` currently seems also "optional". 🤔
This is because in our **SQLModel** class we declare the `id` with `Optional[int]`, because it could be `None` in memory until we save it in the database and we finally get the actual ID.
But in the responses, we would always send a model from the database, and it would **always have an ID**. So the `id` in the responses could be declared as required too.
But in the responses, we always send a model from the database, so it **always has an ID**. So the `id` in the responses can be declared as required.
This would mean that our application is making the compromise with the clients that if it sends a hero, it would for sure have an `id` with a value, it would not be `None`.
This means that our application is making the promise to the clients that if it sends a hero, it will for sure have an `id` with a value, it will not be `None`.
### Why Is it Important to Compromise with the Responses
### Why Is it Important to Have a Contract for Responses
The ultimate goal of an API is for some **clients to use it**.
@@ -119,14 +119,13 @@ The simplest way to solve it could be to create **multiple models**, each one wi
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001.py!}
```
</details>
///
Here's the important detail, and probably the most important feature of **SQLModel**: only `Hero` is declared with `table = True`.
@@ -136,8 +135,11 @@ But `HeroCreate` and `HeroRead` don't have `table = True`. They are only **data
This also means that `SQLModel.metadata.create_all()` won't create tables in the database for `HeroCreate` and `HeroRead`, because they don't have `table = True`, which is exactly what we want. 🚀
!!! tip
We will improve this code to avoid duplicating the fields, but for now we can continue learning with these models.
/// tip
We will improve this code to avoid duplicating the fields, but for now we can continue learning with these models.
///
## Use Multiple Models to Create a Hero
@@ -153,14 +155,13 @@ Let's first check how is the process to create a hero now:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial001.py!}
```
</details>
///
Let's check that in detail.
@@ -174,15 +175,17 @@ Now we use the type annotation `HeroCreate` for the request JSON data in the `he
# Code below omitted 👇
```
Then we create a new `Hero` (this is the actual **table** model that saves things to the database) using `Hero.from_orm()`.
Then we create a new `Hero` (this is the actual **table** model that saves things to the database) using `Hero.model_validate()`.
The method `.from_orm()` reads data from another object with attributes and creates a new instance of this class, in this case `Hero`.
The method `.model_validate()` reads data from another object with attributes (or a dict) and creates a new instance of this class, in this case `Hero`.
The alternative is `Hero.parse_obj()` that reads data from a dictionary.
In this case, we have a `HeroCreate` instance in the `hero` variable. This is an object with attributes, so we use `.model_validate()` to read those attributes.
But as in this case, we have a `HeroCreate` instance in the `hero` variable. This is an object with attributes, so we use `.from_orm()` to read those attributes.
/// tip
In versions of **SQLModel** before `0.0.14` you would use the method `.from_orm()`, but it is now deprecated and you should use `.model_validate()` instead.
///
With this, we create a new `Hero` instance (the one for the database) and put it in the variable `db_hero` from the data in the `hero` variable that is the `HeroCreate` instance we received from the request.
We can now create a new `Hero` instance (the one for the database) and put it in the variable `db_hero` from the data in the `hero` variable that is the `HeroCreate` instance we received from the request.
```Python hl_lines="3"
# Code above omitted 👆
@@ -208,10 +211,13 @@ And now that we return it, FastAPI will validate the data with the `response_mod
This will validate that all the data that we promised is there and will remove any data we didn't declare.
!!! tip
This filtering could be very important and could be a very good security feature, for example, to make sure you filter private data, hashed passwords, etc.
/// tip
You can read more about it in the <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI docs about Response Model</a>.
This filtering could be very important and could be a very good security feature, for example, to make sure you filter private data, hashed passwords, etc.
You can read more about it in the <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI docs about Response Model</a>.
///
In particular, it will make sure that the `id` is there and that it is indeed an integer (and not `None`).
@@ -261,14 +267,13 @@ So let's create a **base** model `HeroBase` that the others can inherit from:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
```
</details>
///
As you can see, this is *not* a **table model**, it doesn't have the `table = True` config.
@@ -286,14 +291,13 @@ Let's start with the only **table model**, the `Hero`:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
```
</details>
///
Notice that `Hero` now doesn't inherit from `SQLModel`, but from `HeroBase`.
@@ -317,14 +321,13 @@ Notice that the parent model `HeroBase` is not a **table model**, but still, we
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
```
</details>
///
This won't affect this parent **data model** `HeroBase`.
@@ -344,14 +347,13 @@ This is a fun one:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
```
</details>
///
What's happening here?
@@ -379,14 +381,13 @@ This one just declares that the `id` field is required when reading a hero from
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/multiple_models/tutorial002.py!}
```
</details>
///
## Review the Updated Docs UI

View File

@@ -8,8 +8,11 @@ Let's add a new *path operation* to read one single hero.
We want to get the hero based on the `id`, so we will use a **path parameter** `hero_id`.
!!! info
If you need to refresh how *path parameters* work, including their data validation, check the <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">FastAPI docs about Path Parameters</a>.
/// info
If you need to refresh how *path parameters* work, including their data validation, check the <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">FastAPI docs about Path Parameters</a>.
///
```Python hl_lines="8"
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:1-4]!}
@@ -19,14 +22,13 @@ We want to get the hero based on the `id`, so we will use a **path parameter** `
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
```
</details>
///
For example, to get the hero with ID `2` we would send a `GET` request to:
@@ -54,14 +56,13 @@ This will let the client know that they probably made a mistake on their side an
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
```
</details>
///
## Return the Hero
@@ -77,14 +78,13 @@ And because we are using the `response_model` with `HeroRead`, it will be valida
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py[ln:61-67]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/read_one/tutorial001.py!}
```
</details>
///
## Check the Docs UI

View File

@@ -64,14 +64,13 @@ And the same way, we declared the `TeamRead` with only the same base fields of t
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
Now, remember that <a href="https://fastapi.tiangolo.com/tutorial/response-model/" class="external-link" target="_blank">FastAPI uses the `response_model` to validate and **filter** the response data</a>?
@@ -84,19 +83,18 @@ In this case, we used `response_model=TeamRead` and `response_model=HeroRead`, s
# Code here omitted 👈
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:159-164]!}
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:158-163]!}
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
## Don't Include All the Data
@@ -186,14 +184,13 @@ We'll add them **after** the other models so that we can easily reference the pr
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py!}
```
</details>
///
These two models are very **simple in code**, but there's a lot happening here. Let's check it out.
@@ -234,19 +231,18 @@ In the case of the hero, this tells FastAPI to extract the `team` too. And in th
# Code here omitted 👈
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py[ln:168-173]!}
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py[ln:167-172]!}
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/relationships/tutorial001.py!}
```
</details>
///
## Check It Out in the Docs UI
@@ -267,7 +263,7 @@ Now we get the **team** data included:
"id": 1,
"team": {
"name": "Z-Force",
"headquarters": "Sister Margarets Bar",
"headquarters": "Sister Margaret's Bar",
"id": 1
}
}

View File

@@ -40,14 +40,13 @@ For example, we can pass the same `Hero` **SQLModel** class (because it is also
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/response_model/tutorial001.py!}
```
</details>
///
## List of Heroes in `response_model`
@@ -65,14 +64,13 @@ First, we import `List` from `typing` and then we declare the `response_model` w
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/response_model/tutorial001.py!}
```
</details>
///
## FastAPI and Response Model
@@ -100,10 +98,13 @@ Additionally, because the schemas are defined in using a standard, there are man
For example, client generators, that can automatically create the code necessary to talk to your API in many languages.
!!! info
If you are curious about the standards, FastAPI generates OpenAPI, that internally uses JSON Schema.
/// info
You can read about all that in the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/#openapi" class="external-link" target="_blank">FastAPI docs - First Steps</a>.
If you are curious about the standards, FastAPI generates OpenAPI, that internally uses JSON Schema.
You can read about all that in the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/#openapi" class="external-link" target="_blank">FastAPI docs - First Steps</a>.
///
## Recap

View File

@@ -14,14 +14,13 @@ Up to now, we have been creating a session in each *path operation*, in a `with`
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/delete/tutorial001.py!}
```
</details>
///
That's perfectly fine, but in many use cases we would want to use <a href="https://fastapi.tiangolo.com/tutorial/dependencies/" class="external-link" target="_blank">FastAPI Dependencies</a>, for example to **verify** that the client is **logged in** and get the **current user** before executing any other code in the *path operation*.
@@ -43,14 +42,13 @@ It could use `yield` instead of `return`, and in that case **FastAPI** will make
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
```
</details>
///
## Use the Dependency
@@ -72,23 +70,25 @@ We import `Depends()` from `fastapi`. Then we use it in the *path operation func
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
```
</details>
///
!!! tip
Here's a tip about that `*,` thing in the parameters.
/// tip
Here we are passing the parameter `session` that has a "default value" of `Depends(get_session)` before the parameter `hero`, that doesn't have any default value.
Here's a tip about that `*,` thing in the parameters.
Python would normally complain about that, but we can use the initial "parameter" `*,` to mark all the rest of the parameters as "keyword only", which solves the problem.
Here we are passing the parameter `session` that has a "default value" of `Depends(get_session)` before the parameter `hero`, that doesn't have any default value.
You can read more about it in the FastAPI documentation <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks" class="external-link" target="_blank">Path Parameters and Numeric Validations - Order the parameters as you need, tricks</a>
Python would normally complain about that, but we can use the initial "parameter" `*,` to mark all the rest of the parameters as "keyword only", which solves the problem.
You can read more about it in the FastAPI documentation <a href="https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/#order-the-parameters-as-you-need-tricks" class="external-link" target="_blank">Path Parameters and Numeric Validations - Order the parameters as you need, tricks</a>
///
The value of a dependency will **only be used for one request**, FastAPI will call it right before calling your code and will give you the value from that dependency.
@@ -118,14 +118,13 @@ This means that in the main code of the *path operation function*, it will work
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
```
</details>
///
In fact, you could think that all that block of code inside of the `create_hero()` function is still inside a `with` block for the **session**, because this is more or less what's happening behind the scenes.
@@ -145,14 +144,13 @@ But now, the `with` block is not explicitly in the function, but in the dependen
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
```
</details>
///
We will see how this is very useful when testing the code later. ✅
@@ -177,17 +175,16 @@ And then we remove the previous `with` block with the old **session**.
# Code here omitted 👈
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:55-107]!}
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py[ln:55-106]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/session_with_dependency/tutorial001.py!}
```
</details>
///
## Recap

View File

@@ -43,14 +43,13 @@ This is almost the same code we have seen up to now in previous examples:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
```
</details>
///
There's only one change here from the code we have used before, the `check_same_thread` in the `connect_args`.
@@ -62,10 +61,13 @@ But here we will make sure we don't share the same **session** in more than one
And we also need to disable it because in **FastAPI** each request could be handled by multiple interacting threads.
!!! info
That's enough information for now, you can read more about it in the <a href="https://fastapi.tiangolo.com/async/" class="external-link" target="_blank">FastAPI docs for `async` and `await`</a>.
/// info
The main point is, by ensuring you **don't share** the same **session** with more than one request, the code is already safe.
That's enough information for now, you can read more about it in the <a href="https://fastapi.tiangolo.com/async/" class="external-link" target="_blank">FastAPI docs for `async` and `await`</a>.
The main point is, by ensuring you **don't share** the same **session** with more than one request, the code is already safe.
///
## **FastAPI** App
@@ -85,14 +87,13 @@ And then create an `app` object that is an instance of that `FastAPI` class:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
```
</details>
///
## Create Database and Tables on `startup`
@@ -108,19 +109,21 @@ This should be called only once at startup, not before every request, so we put
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
```
</details>
///
## Create Heroes *Path Operation*
!!! info
If you need a refresher on what a **Path Operation** is (an endpoint with a specific HTTP Operation) and how to work with it in FastAPI, check out the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">FastAPI First Steps docs</a>.
/// info
If you need a refresher on what a **Path Operation** is (an endpoint with a specific HTTP Operation) and how to work with it in FastAPI, check out the <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">FastAPI First Steps docs</a>.
///
Let's create the **path operation** code to create a new hero.
@@ -134,21 +137,23 @@ It will be called when a user sends a request with a `POST` **operation** to the
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
```
</details>
///
!!! info
If you need a refresher on some of those concepts, checkout the FastAPI documentation:
/// info
* <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">First Steps</a>
* <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">Path Parameters - Data Validation and Data Conversion</a>
* <a href="https://fastapi.tiangolo.com/tutorial/body/" class="external-link" target="_blank">Request Body</a>
If you need a refresher on some of those concepts, checkout the FastAPI documentation:
* <a href="https://fastapi.tiangolo.com/tutorial/first-steps/" class="external-link" target="_blank">First Steps</a>
* <a href="https://fastapi.tiangolo.com/tutorial/path-params/" class="external-link" target="_blank">Path Parameters - Data Validation and Data Conversion</a>
* <a href="https://fastapi.tiangolo.com/tutorial/body/" class="external-link" target="_blank">Request Body</a>
///
## The **SQLModel** Advantage
@@ -162,8 +167,11 @@ And then, because this same **SQLModel** object is not only a **Pydantic** model
So we can use intuitive standard Python **type annotations**, and we don't have to duplicate a lot of the code for the database models and the API data models. 🎉
!!! tip
We will improve this further later, but for now, it already shows the power of having **SQLModel** classes be both **SQLAlchemy** models and **Pydantic** models at the same time.
/// tip
We will improve this further later, but for now, it already shows the power of having **SQLModel** classes be both **SQLAlchemy** models and **Pydantic** models at the same time.
///
## Read Heroes *Path Operation*
@@ -175,14 +183,13 @@ Now let's add another **path operation** to read all the heroes:
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py[ln:25-46]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py!}
```
</details>
///
This is pretty straightforward.
@@ -226,11 +233,14 @@ $ uvicorn main:app
</div>
!!! info
The command `uvicorn main:app` refers to:
/// info
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
The command `uvicorn main:app` refers to:
* `main`: the file `main.py` (the Python "module").
* `app`: the object created inside of `main.py` with the line `app = FastAPI()`.
///
### Uvicorn `--reload`

View File

@@ -24,14 +24,13 @@ And we also create a `TeamUpdate` **data model**.
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
We now also have **relationship attributes**. 🎉
@@ -47,14 +46,13 @@ Let's now update the `Hero` models too.
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
We now have a `team_id` in the hero models.
@@ -74,14 +72,13 @@ Notice that the **relationship attributes**, the ones with `Relationship()`, are
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
## Path Operations for Teams
@@ -92,19 +89,18 @@ These are equivalent and very similar to the **path operations** for the **heroe
```Python hl_lines="3-9 12-20 23-28 31-47 50-57"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:139-193]!}
{!./docs_src/tutorial/fastapi/teams/tutorial001.py[ln:138-192]!}
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/teams/tutorial001.py!}
```
</details>
///
## Using Relationships Attributes

View File

@@ -14,14 +14,13 @@ We will use the application with the hero models, but without team models, and w
Now we will see how useful it is to have this session dependency. ✨
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/main.py!}
```
</details>
///
## File Structure
@@ -71,8 +70,11 @@ Let's start with a simple test, with just the basic test code we need the check
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_001.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
That's the **core** of the code we need for all the tests later.
@@ -82,7 +84,7 @@ But now, we need to deal with a bit of logistics and details we are not paying a
This test looks fine, but there's a problem.
If we run it, it will use the same **production database** that we are using to store our very important **heroes**, and we will end up adding unnecesary data to it, or even worse, in future tests we could end up removing production data.
If we run it, it will use the same **production database** that we are using to store our very important **heroes**, and we will end up adding unnecessary data to it, or even worse, in future tests we could end up removing production data.
So, we should use an independent **testing database**, just for the tests.
@@ -116,8 +118,11 @@ That way we protect the production database and we have better control of the da
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_002.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
## Create the Engine and Session for Testing
@@ -165,10 +170,8 @@ But **it works great for testing**, because it can be quickly created before eac
And also, because it never has to write anything to a file and it's all just in memory, it will be even faster than normally. 🏎
<details>
<summary>
Other alternatives and ideas 👀
</summary>
/// details | Other alternatives and ideas 👀
Before arriving at the idea of using an **in-memory database** we could have explored other alternatives and ideas.
The first is that we are not deleting the file after we finish the test, so the next test could have **leftover data**. So, the right thing would be to delete the file right after finishing the test. 🔥
@@ -181,7 +184,7 @@ So, if we tried to run the tests at the same time **in parallel** to try to spee
Of course, we could also fix that, using some **random name** for each testing database file... but in the case of SQLite, we have an even better alternative by just using an **in-memory database**. ✨
</details>
///
## Configure the In-Memory Database
@@ -197,8 +200,11 @@ We just have to change a couple of parameters in the **engine**.
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_004.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
That's it, now the test will run using the **in-memory database**, which will be faster and probably safer.
@@ -214,8 +220,11 @@ Do we really have to duplicate all that for **each test**? No, we can do better!
We are using **pytest** to run the tests. And pytest also has a very similar concept to the **dependencies in FastAPI**.
!!! info
In fact, pytest was one of the things that inspired the design of the dependencies in FastAPI.
/// info
In fact, pytest was one of the things that inspired the design of the dependencies in FastAPI.
///
It's a way for us to declare some **code that should be run before** each test and **provide a value** for the test function (that's pretty much the same as FastAPI dependencies).
@@ -237,8 +246,11 @@ Let's see the first code example with a fixture:
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_005.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
**pytest** fixtures work in a very similar way to FastAPI dependencies, but have some minor differences:
@@ -274,8 +286,11 @@ So, we can create a **client fixture** that will be used in all the tests, and i
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/annotations/en/test_main_006.md!}
!!! tip
Check out the number bubbles to see what is done by each line of code.
/// tip
Check out the number bubbles to see what is done by each line of code.
///
Now we have a **client fixture** that, in turn, uses the **session fixture**.
@@ -297,19 +312,21 @@ Let's add some more tests:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
```
</details>
///
!!! tip
It's always **good idea** to not only test the normal case, but also that **invalid data**, **errors**, and **corner cases** are handled correctly.
/// tip
That's why we add these two extra tests here.
It's always **good idea** to not only test the normal case, but also that **invalid data**, **errors**, and **corner cases** are handled correctly.
That's why we add these two extra tests here.
///
Now, any additional test functions can be as **simple** as the first one, they just have to **declare the `client` parameter** to get the `TestClient` **fixture** with all the database stuff setup. Nice! 😎
@@ -331,14 +348,13 @@ But for the next test function, we will require **both fixtures**, the **client*
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
```
</details>
///
In this test function, we want to check that the *path operation* to **read a list of heroes** actually sends us heroes.
@@ -370,14 +386,13 @@ Using the same ideas, requiring the fixtures, creating data that we need for the
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py[ln:84-125]!}
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/app_testing/tutorial001/test_main.py!}
```
</details>
///
## Run the Tests

View File

@@ -0,0 +1,217 @@
# Update with Extra Data (Hashed Passwords) with FastAPI
In the previous chapter I explained to you how to update data in the database from input data coming from a **FastAPI** *path operation*.
Now I'll explain to you how to add **extra data**, additional to the input data, when updating or creating a model object.
This is particularly useful when you need to **generate some data** in your code that is **not coming from the client**, but you need to store it in the database. For example, to store a **hashed password**.
## Password Hashing
Let's imagine that each hero in our system also has a **password**.
We should never store the password in plain text in the database, we should only stored a **hashed version** of it.
"**Hashing**" means converting some content (a password in this case) into a sequence of bytes (just a string) that looks like gibberish.
Whenever you pass exactly the same content (exactly the same password) you get exactly the same gibberish.
But you **cannot convert** from the gibberish **back to the password**.
### Why use Password Hashing
If your database is stolen, the thief won't have your users' **plaintext passwords**, only the hashes.
So, the thief won't be able to try to use that password in another system (as many users use the same password everywhere, this would be dangerous).
/// tip
You could use <a href="https://passlib.readthedocs.io/en/stable/" class="external-link" target="_blank">passlib</a> to hash passwords.
In this example we will use a fake hashing function to focus on the data changes. 🤡
///
## Update Models with Extra Data
The `Hero` table model will now store a new field `hashed_password`.
And the data models for `HeroCreate` and `HeroUpdate` will also have a new field `password` that will contain the plain text password sent by clients.
```Python hl_lines="11 15 26"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:7-30]!}
# Code below omitted 👇
```
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
```
///
When a client is creating a new hero, they will send the `password` in the request body.
And when they are updating a hero, they could also send the `password` in the request body to update it.
## Hash the Password
The app will receive the data from the client using the `HeroCreate` model.
This contains the `password` field with the plain text password, and we cannot use that one. So we need to generate a hash from it.
```Python hl_lines="11"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:44-46]!}
# Code here omitted 👈
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:57-59]!}
# Code below omitted 👇
```
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
```
///
## Create an Object with Extra Data
Now we need to create the database hero.
In previous examples, we have used something like:
```Python
db_hero = Hero.model_validate(hero)
```
This creates a `Hero` (which is a *table model*) object from the `HeroCreate` (which is a *data model*) object that we received in the request.
And this is all good... but as `Hero` doesn't have a field `password`, it won't be extracted from the object `HeroCreate` that has it.
`Hero` actually has a `hashed_password`, but we are not providing it. We need a way to provide it...
### Dictionary Update
Let's pause for a second to check this, when working with dictionaries, there's a way to `update` a dictionary with extra data from another dictionary, something like this:
```Python hl_lines="14"
db_user_dict = {
"name": "Deadpond",
"secret_name": "Dive Wilson",
"age": None,
}
hashed_password = "fakehashedpassword"
extra_data = {
"hashed_password": hashed_password,
"age": 32,
}
db_user_dict.update(extra_data)
print(db_user_dict)
# {
# "name": "Deadpond",
# "secret_name": "Dive Wilson",
# "age": 32,
# "hashed_password": "fakehashedpassword",
# }
```
This `update` method allows us to add and override things in the original dictionary with the data from another dictionary.
So now, `db_user_dict` has the updated `age` field with `32` instead of `None` and more importantly, **it has the new `hashed_password` field**.
### Create a Model Object with Extra Data
Similar to how dictionaries have an `update` method, **SQLModel** models have a parameter `update` in `Hero.model_validate()` that takes a dictionary with extra data, or data that should take precedence:
```Python hl_lines="8"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:57-66]!}
# Code below omitted 👇
```
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
```
///
Now, `db_hero` (which is a *table model* `Hero`) will extract its values from `hero` (which is a *data model* `HeroCreate`), and then it will **`update`** its values with the extra data from the dictionary `extra_data`.
It will only take the fields defined in `Hero`, so **it will not take the `password`** from `HeroCreate`. And it will also **take its values** from the **dictionary passed to the `update`** parameter, in this case, the `hashed_password`.
If there's a field in both `hero` and the `extra_data`, **the value from the `extra_data` passed to `update` will take precedence**.
## Update with Extra Data
Now let's say we want to **update a hero** that already exists in the database.
The same way as before, to avoid removing existing data, we will use `exclude_unset=True` when calling `hero.model_dump()`, to get a dictionary with only the data sent by the client.
```Python hl_lines="9"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:85-91]!}
# Code below omitted 👇
```
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
```
///
Now, this `hero_data` dictionary could contain a `password`. We need to check it, and if it's there, we need to generate the `hashed_password`.
Then we can put that `hashed_password` in a dictionary.
And then we can update the `db_hero` object using the method `db_hero.sqlmodel_update()`.
It takes a model object or dictionary with the data to update the object and also an **additional `update` argument** with extra data.
```Python hl_lines="15"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial002.py[ln:85-101]!}
# Code below omitted 👇
```
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial002.py!}
```
///
/// tip
The method `db_hero.sqlmodel_update()` was added in SQLModel 0.0.16. 😎
///
## Recap
You can use the `update` parameter in `Hero.model_validate()` to provide extra data when creating a new object and `Hero.sqlmodel_update()` to provide extra data when updating an existing object. 🤓

View File

@@ -12,10 +12,13 @@ So, we need to have all those fields **marked as optional**.
And because the `HeroBase` has some of them as *required* and not optional, we will need to **create a new model**.
!!! tip
Here is one of those cases where it probably makes sense to use an **independent model** instead of trying to come up with a complex tree of models inheriting from each other.
/// tip
Because each field is **actually different** (we just change it to `Optional`, but that's already making it different), it makes sense to have them in their own model.
Here is one of those cases where it probably makes sense to use an **independent model** instead of trying to come up with a complex tree of models inheriting from each other.
Because each field is **actually different** (we just change it to `Optional`, but that's already making it different), it makes sense to have them in their own model.
///
So, let's create this new `HeroUpdate` model:
@@ -27,14 +30,13 @@ So, let's create this new `HeroUpdate` model:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
```
</details>
///
This is almost the same as `HeroBase`, but all the fields are optional, so we can't simply inherit from `HeroBase`.
@@ -52,14 +54,13 @@ We will use a `PATCH` HTTP operation. This is used to **partially update data**,
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
```
</details>
///
We also read the `hero_id` from the *path parameter* and the request body, a `HeroUpdate`.
@@ -77,20 +78,19 @@ So, we need to read the hero from the database, with the **same logic** we used
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
```
</details>
///
### Get the New Data
The `HeroUpdate` model has all the fields with **default values**, because they all have defaults, they are all optional, which is what we want.
But that also means that if we just call `hero.dict()` we will get a dictionary that could potentially have several or all of those values with their defaults, for example:
But that also means that if we just call `hero.model_dump()` we will get a dictionary that could potentially have several or all of those values with their defaults, for example:
```Python
{
@@ -102,7 +102,7 @@ But that also means that if we just call `hero.dict()` we will get a dictionary
And then, if we update the hero in the database with this data, we would be removing any existing values, and that's probably **not what the client intended**.
But fortunately Pydantic models (and so SQLModel models) have a parameter we can pass to the `.dict()` method for that: `exclude_unset=True`.
But fortunately Pydantic models (and so SQLModel models) have a parameter we can pass to the `.model_dump()` method for that: `exclude_unset=True`.
This tells Pydantic to **not include** the values that were **not sent** by the client. Saying it another way, it would **only** include the values that were **sent by the client**.
@@ -112,7 +112,7 @@ So, if the client sent a JSON with no values:
{}
```
Then the dictionary we would get in Python using `hero.dict(exclude_unset=True)` would be:
Then the dictionary we would get in Python using `hero.model_dump(exclude_unset=True)` would be:
```Python
{}
@@ -126,7 +126,7 @@ But if the client sent a JSON with:
}
```
Then the dictionary we would get in Python using `hero.dict(exclude_unset=True)` would be:
Then the dictionary we would get in Python using `hero.model_dump(exclude_unset=True)` would be:
```Python
{
@@ -144,20 +144,23 @@ Then we use that to get the data that was actually sent by the client:
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
```
</details>
///
/// tip
Before SQLModel 0.0.14, the method was called `hero.dict(exclude_unset=True)`, but it was renamed to `hero.model_dump(exclude_unset=True)` to be consistent with Pydantic v2.
///
## Update the Hero in the Database
Now that we have a **dictionary with the data sent by the client**, we can iterate for each one of the keys and the values, and then we set them in the database hero model `db_hero` using `setattr()`.
Now that we have a **dictionary with the data sent by the client**, we can use the method `db_hero.sqlmodel_update()` to update the object `db_hero`.
```Python hl_lines="10-11"
```Python hl_lines="10"
# Code above omitted 👆
{!./docs_src/tutorial/fastapi/update/tutorial001.py[ln:76-91]!}
@@ -165,28 +168,25 @@ Now that we have a **dictionary with the data sent by the client**, we can itera
# Code below omitted 👇
```
<details>
<summary>👀 Full file preview</summary>
/// details | 👀 Full file preview
```Python
{!./docs_src/tutorial/fastapi/update/tutorial001.py!}
```
</details>
///
If you are not familiar with that `setattr()`, it takes an object, like the `db_hero`, then an attribute name (`key`), that in our case could be `"name"`, and a value (`value`). And then it **sets the attribute with that name to the value**.
/// tip
So, if `key` was `"name"` and `value` was `"Deadpuddle"`, then this code:
The method `db_hero.sqlmodel_update()` was added in SQLModel 0.0.16. 🤓
```Python
setattr(db_hero, key, value)
```
Before that, you would need to manually get the values and set them using `setattr()`.
...would be more or less equivalent to:
///
```Python
db_hero.name = "Deadpuddle"
```
The method `db_hero.sqlmodel_update()` takes an argument with another model object or a dictionary.
For each of the fields in the **original** model object (`db_hero` in this example), it checks if the field is available in the **argument** (`hero_data` in this example) and then updates it with the provided value.
## Remove Fields
@@ -210,7 +210,7 @@ So, if the client wanted to intentionally remove the `age` of a hero, they could
}
```
And when getting the data with `hero.dict(exclude_unset=True)`, we would get:
And when getting the data with `hero.model_dump(exclude_unset=True)`, we would get:
```Python
{
@@ -228,4 +228,4 @@ These are some of the advantages of Pydantic, that we can use with SQLModel.
## Recap
Using `.dict(exclude_unset=True)` in SQLModel models (and Pydantic models) we can easily update data **correctly**, even in the **edge cases**. 😎
Using `.model_dump(exclude_unset=True)` in SQLModel models (and Pydantic models) we can easily update data **correctly**, even in the **edge cases**. 😎

Some files were not shown because too many files have changed in this diff Show More