Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 7 additions & 7 deletions pdm_build.py
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
import os
from typing import Any, Dict, List
from typing import Any

from pdm.backend.hooks import Context

Expand All@@ -9,30 +9,30 @@
def pdm_build_initialize(context: Context) -> None:
metadata = context.config.metadata
# Get custom config for the current package, from the env var
config: Dict[str, Any] = context.config.data["tool"]["tiangolo"][
config: dict[str, Any] = context.config.data["tool"]["tiangolo"][
"_internal-slim-build"
]["packages"][TIANGOLO_BUILD_PACKAGE]
project_config: Dict[str, Any] = config["project"]
project_config: dict[str, Any] = config["project"]
# Get main optional dependencies, extras
optional_dependencies: Dict[str, List[str]] = metadata.get(
optional_dependencies: dict[str, list[str]] = metadata.get(
"optional-dependencies", {}
)
# Get custom optional dependencies name to always include in this (non-slim) package
include_optional_dependencies: List[str] = config.get(
include_optional_dependencies: list[str] = config.get(
"include-optional-dependencies", []
)
# Override main [project] configs with custom configs for this package
for key, value in project_config.items():
metadata[key] = value
# Get custom build config for the current package
build_config: Dict[str, Any] = (
build_config: dict[str, Any] = (
config.get("tool", {}).get("pdm", {}).get("build", {})
)
# Override PDM build config with custom build config for this package
for key, value in build_config.items():
context.config.build_config[key] = value
# Get main dependencies
dependencies: List[str] = metadata.get("dependencies", [])
dependencies: list[str] = metadata.get("dependencies", [])
# Add optional dependencies to the default dependencies for this (non-slim) package
for include_optional in include_optional_dependencies:
optional_dependencies_group = optional_dependencies.get(include_optional, [])
Expand Down
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,7 +7,7 @@ name = "sqlmodel"
dynamic = ["version"]
description = "SQLModel, SQL databases in Python, designed for simplicity, compatibility, and robustness."
readme = "README.md"
requires-python = ">=3.8"
requires-python = ">=3.9"
authors = [
{ name = "Sebastián Ramírez", email = "tiangolo@gmail.com" },
]
Expand All@@ -21,7 +21,6 @@ classifiers = [
"Intended Audience :: Science/Research",
"Intended Audience :: System Administrators",
"Programming Language :: Python :: 3 :: Only",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
Expand Down
9 changes: 4 additions & 5 deletions scripts/generate_select.py
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
import os
from itertools import product
from pathlib import Path
from typing import List, Tuple

import black
from jinja2 import Template
Expand All@@ -21,15 +20,15 @@ class Arg(BaseModel):
annotation: str


arg_groups: List[Arg] = []
arg_groups: list[Arg] = []

signatures: List[Tuple[List[Arg], List[str]]] = []
signatures: list[tuple[list[Arg], list[str]]] = []

for total_args in range(2, number_of_types + 1):
arg_types_tuples = product(["model", "scalar"], repeat=total_args)
for arg_type_tuple in arg_types_tuples:
args: List[Arg] = []
return_types: List[str] = []
args: list[Arg] = []
return_types: list[str] = []
for i, arg_type in enumerate(arg_type_tuple):
if arg_type == "scalar":
t_var = f"_TScalar_{i}"
Expand Down
8 changes: 4 additions & 4 deletions scripts/mkdocs_hooks.py
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
from typing import Any, List, Union
from typing import Any, Union

from mkdocs.config.defaults import MkDocsConfig
from mkdocs.structure.files import Files
Expand All@@ -7,9 +7,9 @@


def generate_renamed_section_items(
items: List[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> List[Union[Page, Section, Link]]:
new_items: List[Union[Page, Section, Link]] = []
items: list[Union[Page, Section, Link]], *, config: MkDocsConfig
) -> list[Union[Page, Section, Link]]:
new_items: list[Union[Page, Section, Link]] = []
for item in items:
if isinstance(item, Section):
new_title = item.title
Expand Down
68 changes: 32 additions & 36 deletions sqlmodel/_compat.py
Original file line numberDiff line numberDiff line change
@@ -1,28 +1,24 @@
import sys
import types
from collections.abc import Generator, Mapping, Set
from contextlib import contextmanager
from contextvars import ContextVar
from dataclasses import dataclass
from typing import (
TYPE_CHECKING,
AbstractSet,
Annotated,
Any,
Callable,
Dict,
ForwardRef,
Generator,
Mapping,
Optional,
Set,
Type,
TypeVar,
Union,
)

from pydantic import VERSION as P_VERSION
from pydantic import BaseModel
from pydantic.fields import FieldInfo
from typing_extensions import Annotated, get_args, get_origin
from typing_extensions import get_args, get_origin

# Reassign variable to make it reexported for mypy
PYDANTIC_VERSION = P_VERSION
Expand All@@ -36,7 +32,7 @@
UnionType = getattr(types, "UnionType", Union)
NoneType = type(None)
T = TypeVar("T")
InstanceOrType = Union[T, Type[T]]
InstanceOrType = Union[T, type[T]]
_TSQLModel = TypeVar("_TSQLModel", bound="SQLModel")


Expand All@@ -49,7 +45,7 @@ class FakeMetadata:
@dataclass
class ObjectWithUpdateWrapper:
obj: Any
update: Dict[str, Any]
update: dict[str, Any]

def __getattribute__(self, __name: str) -> Any:
update = super().__getattribute__("update")
Expand DownExpand Up@@ -103,7 +99,7 @@ def set_config_value(
) -> None:
model.model_config[parameter] = value # type: ignore[literal-required]

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
# TODO: refactor the usage of this function to always pass the class
# not the instance, and then remove this extra check
# this is for compatibility with Pydantic v3
Expand All@@ -115,16 +111,16 @@ def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.model_fields_set

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__pydantic_fields_set__", set())
object.__setattr__(new_object, "__pydantic_extra__", None)
object.__setattr__(new_object, "__pydantic_private__", None)

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
raw_annotations: Dict[str, Any] = class_dict.get("__annotations__", {})
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
raw_annotations: dict[str, Any] = class_dict.get("__annotations__", {})
if sys.version_info >= (3, 14) and "__annotations__" not in class_dict:
# See https://github.com/pydantic/pydantic/pull/11991
from annotationlib import (
Expand All@@ -139,7 +135,7 @@ def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
)
return raw_annotations

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "model_config", {})
if config:
return config.get("table", False) or False
Expand DownExpand Up@@ -243,15 +239,15 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]: # pragma: no cover
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]: # pragma: no cover
return None

def sqlmodel_table_construct(
*,
self_instance: _TSQLModel,
values: Dict[str, Any],
_fields_set: Union[Set[str], None] = None,
values: dict[str, Any],
_fields_set: Union[set[str], None] = None,
) -> _TSQLModel:
# Copy from Pydantic's BaseModel.construct()
# Ref: https://github.com/pydantic/pydantic/blob/v2.5.2/pydantic/main.py#L198
Expand All@@ -264,8 +260,8 @@ def sqlmodel_table_construct(
old_dict = self_instance.__dict__.copy()
# End SQLModel override

fields_values: Dict[str, Any] = {}
defaults: Dict[
fields_values: dict[str, Any] = {}
defaults: dict[
str, Any
] = {} # keeping this separate from `fields_values` helps us compute `_fields_set`
for name, field in cls.model_fields.items():
Expand All@@ -279,7 +275,7 @@ def sqlmodel_table_construct(
_fields_set = set(fields_values.keys())
fields_values.update(defaults)

_extra: Union[Dict[str, Any], None] = None
_extra: Union[dict[str, Any], None] = None
if cls.model_config.get("extra") == "allow":
_extra = {}
for k, v in values.items():
Expand DownExpand Up@@ -315,13 +311,13 @@ def sqlmodel_table_construct(
return self_instance

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
if not is_table_model_class(cls):
new_obj: _TSQLModel = cls.__new__(cls)
Expand DownExpand Up@@ -366,7 +362,7 @@ def sqlmodel_validate(
setattr(new_obj, key, value)
return new_obj

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
old_dict = self.__dict__.copy()
if not is_table_model_class(self.__class__):
self.__pydantic_validator__.validate_python(
Expand DownExpand Up@@ -424,24 +420,24 @@ def set_config_value(
) -> None:
setattr(model.__config__, parameter, value) # type: ignore

def get_model_fields(model: InstanceOrType[BaseModel]) -> Dict[str, "FieldInfo"]:
def get_model_fields(model: InstanceOrType[BaseModel]) -> dict[str, "FieldInfo"]:
return model.__fields__ # type: ignore

def get_fields_set(
object: InstanceOrType["SQLModel"],
) -> Union[Set[str], Callable[[BaseModel], Set[str]]]:
) -> Union[set[str], Callable[[BaseModel], set[str]]]:
return object.__fields_set__

def init_pydantic_private_attrs(new_object: InstanceOrType["SQLModel"]) -> None:
object.__setattr__(new_object, "__fields_set__", set())

def get_annotations(class_dict: Dict[str, Any]) -> Dict[str, Any]:
def get_annotations(class_dict: dict[str, Any]) -> dict[str, Any]:
return resolve_annotations( # type: ignore[no-any-return]
class_dict.get("__annotations__", {}),
class_dict.get("__module__", None),
)

def is_table_model_class(cls: Type[Any]) -> bool:
def is_table_model_class(cls: type[Any]) -> bool:
config = getattr(cls, "__config__", None)
if config:
return getattr(config, "table", False)
Expand DownExpand Up@@ -492,8 +488,8 @@ def _calculate_keys(
include: Optional[Mapping[Union[int, str], Any]],
exclude: Optional[Mapping[Union[int, str], Any]],
exclude_unset: bool,
update: Optional[Dict[str, Any]] = None,
) -> Optional[AbstractSet[str]]:
update: Optional[dict[str, Any]] = None,
) -> Optional[Set[str]]:
if include is None and exclude is None and not exclude_unset:
# Original in Pydantic:
# return None
Expand All@@ -504,7 +500,7 @@ def _calculate_keys(
self.__fields__.keys() # noqa
) # | self.__sqlmodel_relationships__.keys()

keys: AbstractSet[str]
keys: Set[str]
if exclude_unset:
keys = self.__fields_set__.copy() # noqa
else:
Expand All@@ -528,13 +524,13 @@ def _calculate_keys(
return keys

def sqlmodel_validate(
cls: Type[_TSQLModel],
cls: type[_TSQLModel],
obj: Any,
*,
strict: Union[bool, None] = None,
from_attributes: Union[bool, None] = None,
context: Union[Dict[str, Any], None] = None,
update: Union[Dict[str, Any], None] = None,
context: Union[dict[str, Any], None] = None,
update: Union[dict[str, Any], None] = None,
) -> _TSQLModel:
# This was SQLModel's original from_orm() for Pydantic v1
# Duplicated from Pydantic
Expand DownExpand Up@@ -573,7 +569,7 @@ def sqlmodel_validate(
m._init_private_attributes() # type: ignore[attr-defined] # noqa
return m

def sqlmodel_init(*, self: "SQLModel", data: Dict[str, Any]) -> None:
def sqlmodel_init(*, self: "SQLModel", data: dict[str, Any]) -> None:
values, fields_set, validation_error = validate_model(self.__class__, data)
# Only raise errors if not a SQLModel model
if (
Expand Down
Loading