prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] = Field(default=None, primary_key=True) ig_pk: int ig_hint_username: Optional[str] = None webhook_id: int min_time: datetime =
Field(default_factory=datetime.utcnow)
sqlmodel.Field
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] = Field(default=None, primary_key=True) ig_pk: int ig_hint_username: Optional[str] = None webhook_id: int min_time: datetime = Field(default_factory=datetime.utcnow) @property def aware_min_time(self) -> datetime: return self.min_time.replace(tzinfo=timezone.utc) @aware_min_time.setter def aware_min_time(self, value: datetime) -> None: assert value.tzinfo is not None delta = value.tzinfo.utcoffset(value) assert delta is not None self.min_time = value - delta ig_posts: List["Post"] =
Relationship(back_populates="ig_account")
sqlmodel.Relationship
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] = Field(default=None, primary_key=True) ig_pk: int ig_hint_username: Optional[str] = None webhook_id: int min_time: datetime = Field(default_factory=datetime.utcnow) @property def aware_min_time(self) -> datetime: return self.min_time.replace(tzinfo=timezone.utc) @aware_min_time.setter def aware_min_time(self, value: datetime) -> None: assert value.tzinfo is not None delta = value.tzinfo.utcoffset(value) assert delta is not None self.min_time = value - delta ig_posts: List["Post"] = Relationship(back_populates="ig_account") @classmethod def get(cls, session: Session, pk: int | str, webhook_id: int): pk_i = int(pk) query = select(cls).where(cls.ig_pk == pk_i, cls.webhook_id == webhook_id) acc = session.exec(query).one_or_none() if acc is None: acc = cls(ig_pk=pk_i, webhook_id=webhook_id) session.add(acc) return acc def make_post(self, session: Session, pk: int | str) -> Post: pk_i = int(pk) # use ig_account_id=-1 to remove type errors (overwritten by ig_account=self) post = Post(ig_account_id=-1, ig_account=self, ig_pk=pk_i) session.add(post) return post class DB: engine: Engine def __init__(self, engine: Engine) -> None: self.engine = engine
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] = Field(default=None, primary_key=True) ig_pk: int ig_hint_username: Optional[str] = None webhook_id: int min_time: datetime = Field(default_factory=datetime.utcnow) @property def aware_min_time(self) -> datetime: return self.min_time.replace(tzinfo=timezone.utc) @aware_min_time.setter def aware_min_time(self, value: datetime) -> None: assert value.tzinfo is not None delta = value.tzinfo.utcoffset(value) assert delta is not None self.min_time = value - delta ig_posts: List["Post"] = Relationship(back_populates="ig_account") @classmethod def get(cls, session: Session, pk: int | str, webhook_id: int): pk_i = int(pk) query = select(cls).where(cls.ig_pk == pk_i, cls.webhook_id == webhook_id) acc = session.exec(query).one_or_none() if acc is None: acc = cls(ig_pk=pk_i, webhook_id=webhook_id) session.add(acc) return acc def make_post(self, session: Session, pk: int | str) -> Post: pk_i = int(pk) # use ig_account_id=-1 to remove type errors (overwritten by ig_account=self) post = Post(ig_account_id=-1, ig_account=self, ig_pk=pk_i) session.add(post) return post class DB: engine: Engine def __init__(self, engine: Engine) -> None: self.engine = engine SQLModel.metadata.create_all(engine) def session(self) -> Session: return
Session(self.engine)
sqlmodel.Session
from datetime import datetime, timezone from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, Session, select from sqlalchemy.engine import Engine class Post(SQLModel, table=True): __tablename__ = "ig_posts" id: Optional[int] = Field(default=None, primary_key=True) ig_account_id: int = Field(foreign_key="ig_accounts.id") ig_pk: int webhook_message_id: Optional[int] = None ig_account: "IGAccount" = Relationship(back_populates="ig_posts") class IGAccount(SQLModel, table=True): __tablename__ = "ig_accounts" id: Optional[int] = Field(default=None, primary_key=True) ig_pk: int ig_hint_username: Optional[str] = None webhook_id: int min_time: datetime = Field(default_factory=datetime.utcnow) @property def aware_min_time(self) -> datetime: return self.min_time.replace(tzinfo=timezone.utc) @aware_min_time.setter def aware_min_time(self, value: datetime) -> None: assert value.tzinfo is not None delta = value.tzinfo.utcoffset(value) assert delta is not None self.min_time = value - delta ig_posts: List["Post"] = Relationship(back_populates="ig_account") @classmethod def get(cls, session: Session, pk: int | str, webhook_id: int): pk_i = int(pk) query =
select(cls)
sqlmodel.select
from unittest.mock import patch from sqlmodel import create_engine from ....conftest import get_testing_print_function expected_calls = [ [ "Created hero:", { "age": None, "id": 1, "secret_name": "<NAME>", "team_id": 1, "name": "Deadpond", }, ], [ "Created hero:", { "age": 48, "id": 2, "secret_name": "<NAME>", "team_id": 2, "name": "Rusty-Man", }, ], [ "Created hero:", { "age": None, "id": 3, "secret_name": "<NAME>", "team_id": None, "name": "Spider-Boy", }, ], [ "Updated hero:", { "age": None, "id": 3, "secret_name": "<NAME>", "team_id": 2, "name": "Spider-Boy", }, ], [ "Team Wakaland:", {"id": 3, "headquarters": "Wakaland Capital City", "name": "Wakaland"}, ], [ "Preventers new hero:", { "age": 32, "id": 6, "secret_name": "<NAME>", "team_id": 2, "name": "Tarantula", }, ], [ "Preventers new hero:", { "age": 36, "id": 7, "secret_name": "<NAME>", "team_id": 2, "name": "Dr. Weird", }, ], [ "Preventers new hero:", { "age": 93, "id": 8, "secret_name": "<NAME>", "team_id": 2, "name": "Captain North America", }, ], ] def test_tutorial(clear_sqlmodel): from docs_src.tutorial.relationship_attributes.create_and_update_relationships import ( tutorial001 as mod, ) mod.sqlite_url = "sqlite://" mod.engine =
create_engine(mod.sqlite_url)
sqlmodel.create_engine
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=False ) ) starting_no: SeriesCode ending_no: SeriesCode # starting_no: str = Field(max_length=20, nullable=False) # ending_no: str = Field(max_length=20, nullable=True, default='') last_date_used: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=True ) ) warning_no: str =
Field(max_length=20, nullable=True, default='')
sqlmodel.Field
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=False ) ) starting_no: SeriesCode ending_no: SeriesCode # starting_no: str = Field(max_length=20, nullable=False) # ending_no: str = Field(max_length=20, nullable=True, default='') last_date_used: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=True ) ) warning_no: str = Field(max_length=20, nullable=True, default='') last_no_used: str =
Field(max_length=20, nullable=True, default='')
sqlmodel.Field
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=False ) ) starting_no: SeriesCode ending_no: SeriesCode # starting_no: str = Field(max_length=20, nullable=False) # ending_no: str = Field(max_length=20, nullable=True, default='') last_date_used: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=True ) ) warning_no: str = Field(max_length=20, nullable=True, default='') last_no_used: str = Field(max_length=20, nullable=True, default='') increment_by: PositiveInt =
Field(default=1)
sqlmodel.Field
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=False ) ) starting_no: SeriesCode ending_no: SeriesCode # starting_no: str = Field(max_length=20, nullable=False) # ending_no: str = Field(max_length=20, nullable=True, default='') last_date_used: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=True ) ) warning_no: str = Field(max_length=20, nullable=True, default='') last_no_used: str = Field(max_length=20, nullable=True, default='') increment_by: PositiveInt = Field(default=1) blocked: bool = False # series_no_id: int = Field( # sa_column=Column( # Integer, # ForeignKey(NoSeries.id, ondelete="CASCADE"), # ), # nullable = False # ) # ForeignKey(NoSeries.id, ondelete="RESTRICT"), # series_no_id: int = Field(default=None, foreign_key="no_series.id") series_no_id: int series_no: Optional[NoSeries] = Relationship(back_populates = "noserieslines") class NoSeriesLine(NoSeriesLineBase, TimeStampMixin, table=True): """«No. Series Line» («Серия Номеров Строка»)""" __tablename__ = "no_series_line" __table_args__ = (UniqueConstraint("series_no_id", "starting_date"),) id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column(
DateTime(timezone=True)
sqlmodel.DateTime
import datetime from typing import Optional from pydantic import PositiveInt from sqlalchemy import Integer, ForeignKey from sqlmodel import Field, Column, DateTime, Relationship, SQLModel from sqlalchemy import UniqueConstraint from sb_backend.app.models.base.base_model import TimeStampMixin from sb_backend.app.models.fields import SeriesCode from .noseries import NoSeries class NoSeriesLineBase(SQLModel): """«No. Series Line» («Серия Номеров Строка»)""" starting_date: datetime.datetime = Field( sa_column=Column( DateTime(timezone=True), nullable=False ) ) starting_no: SeriesCode ending_no: SeriesCode # starting_no: str = Field(max_length=20, nullable=False) # ending_no: str = Field(max_length=20, nullable=True, default='') last_date_used: datetime.datetime = Field( sa_column=Column(
DateTime(timezone=True)
sqlmodel.DateTime
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] = Relationship(back_populates="heroes") class HeroRead(HeroBase): id: int class HeroCreate(HeroBase): pass class HeroUpdate(SQLModel): name: Optional[str] = None secret_name: Optional[str] = None age: Optional[int] = None team_id: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine =
create_engine(sqlite_url, echo=True, connect_args=connect_args)
sqlmodel.create_engine
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str =
Field(index=True)
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] =
Relationship(back_populates="team")
sqlmodel.Relationship
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str =
Field(index=True)
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] =
Field(default=None, index=True)
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] =
Field(default=None, foreign_key="team.id")
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] =
Relationship(back_populates="heroes")
sqlmodel.Relationship
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] = Relationship(back_populates="heroes") class HeroRead(HeroBase): id: int class HeroCreate(HeroBase): pass class HeroUpdate(SQLModel): name: Optional[str] = None secret_name: Optional[str] = None age: Optional[int] = None team_id: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] = Relationship(back_populates="heroes") class HeroRead(HeroBase): id: int class HeroCreate(HeroBase): pass class HeroUpdate(SQLModel): name: Optional[str] = None secret_name: Optional[str] = None age: Optional[int] = None team_id: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with
Session(engine)
sqlmodel.Session
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] = Relationship(back_populates="heroes") class HeroRead(HeroBase): id: int class HeroCreate(HeroBase): pass class HeroUpdate(SQLModel): name: Optional[str] = None secret_name: Optional[str] = None age: Optional[int] = None team_id: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroRead) def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate): db_hero = Hero.from_orm(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=List[HeroRead]) def read_heroes( *, session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, lte=100), ): heroes = session.exec(
select(Hero)
sqlmodel.select
from typing import List, Optional from fastapi import Depends, FastAPI, HTTPException, Query from sqlmodel import Field, Relationship, Session, SQLModel, create_engine, select class TeamBase(SQLModel): name: str = Field(index=True) headquarters: str class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] = Relationship(back_populates="team") class TeamCreate(TeamBase): pass class TeamRead(TeamBase): id: int class TeamUpdate(SQLModel): id: Optional[int] = None name: Optional[str] = None headquarters: Optional[str] = None class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] = Relationship(back_populates="heroes") class HeroRead(HeroBase): id: int class HeroCreate(HeroBase): pass class HeroUpdate(SQLModel): name: Optional[str] = None secret_name: Optional[str] = None age: Optional[int] = None team_id: Optional[int] = None sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def get_session(): with Session(engine) as session: yield session app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.post("/heroes/", response_model=HeroRead) def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate): db_hero = Hero.from_orm(hero) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.get("/heroes/", response_model=List[HeroRead]) def read_heroes( *, session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, lte=100), ): heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() return heroes @app.get("/heroes/{hero_id}", response_model=HeroRead) def read_hero(*, session: Session = Depends(get_session), hero_id: int): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") return hero @app.patch("/heroes/{hero_id}", response_model=HeroRead) def update_hero( *, session: Session = Depends(get_session), hero_id: int, hero: HeroUpdate ): db_hero = session.get(Hero, hero_id) if not db_hero: raise HTTPException(status_code=404, detail="Hero not found") hero_data = hero.dict(exclude_unset=True) for key, value in hero_data.items(): setattr(db_hero, key, value) session.add(db_hero) session.commit() session.refresh(db_hero) return db_hero @app.delete("/heroes/{hero_id}") def delete_hero(*, session: Session = Depends(get_session), hero_id: int): hero = session.get(Hero, hero_id) if not hero: raise HTTPException(status_code=404, detail="Hero not found") session.delete(hero) session.commit() return {"ok": True} @app.post("/teams/", response_model=TeamRead) def create_team(*, session: Session = Depends(get_session), team: TeamCreate): db_team = Team.from_orm(team) session.add(db_team) session.commit() session.refresh(db_team) return db_team @app.get("/teams/", response_model=List[TeamRead]) def read_teams( *, session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, lte=100), ): teams = session.exec(
select(Team)
sqlmodel.select
"""All database connection information is defined here""" from sqlmodel import SQLModel, create_engine from sqlalchemy.engine import Engine from sqlalchemy import event DB_FILE = "devices.db" sqlite_url = f"sqlite:///{DB_FILE}" connect_args = {"check_same_thread": False} engine = create_engine( sqlite_url, connect_args=connect_args, echo=True ) # set echo=True to view output # From SQLAlchemy docs to allow foreign Key support # https://docs.sqlalchemy.org/en/14/dialects/sqlite.html#foreign-key-support @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): """Used to enable foreign keys in sqlite""" cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() def create_db_and_tables(): """Used to create and initialize DB"""
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str =
Field(nullable=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str =
Field(nullable=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) # acapy data --- connection_id: uuid.UUID =
Field(nullable=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) # acapy data --- connection_id: uuid.UUID = Field(nullable=False) connection_protocol: str =
Field(nullable=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) # acapy data --- connection_id: uuid.UUID = Field(nullable=False) connection_protocol: str = Field(nullable=False) connection_alias: str =
Field(nullable=True, default=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) # acapy data --- connection_id: uuid.UUID = Field(nullable=False) connection_protocol: str = Field(nullable=False) connection_alias: str = Field(nullable=True, default=False) public_did: str =
Field(nullable=True, default=False)
sqlmodel.Field
"""Contact Database Tables/Models. Models of the Endorser tables for Contacts (Authors) and related data. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field from sqlalchemy import Column, func, text, String from sqlalchemy.dialects.postgresql import UUID, TIMESTAMP, ARRAY from api.db.models.base import BaseModel class Contact(BaseModel, table=True): """Contact. This is the model for the Contact table (postgresql specific dialects in use). Attributes: contact_id: Endorser's Contact ID author_status: Whether they are an approved author or not endorse_status: Whether endorsements are auto-approved or not tags: Set by endorser for arbitrary grouping of Contacts connection_id: Underlying AcaPy connection id connection_alias: Underlying AcaPy connection alias public_did: Represents the Contact's agent's Public DID (if any) state: The underlying AcaPy connection state created_at: Timestamp when record was created updated_at: Timestamp when record was last modified """ contact_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) author_status: str = Field(nullable=False) endorse_status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) # acapy data --- connection_id: uuid.UUID = Field(nullable=False) connection_protocol: str = Field(nullable=False) connection_alias: str = Field(nullable=True, default=False) public_did: str = Field(nullable=True, default=False) state: str =
Field(nullable=False)
sqlmodel.Field
from pydantic.types import Optional from sqlmodel import Field, Relationship, SQLModel from api.public.team.models import Team class HeroBase(SQLModel): name: str secret_name: str age: Optional[int] = None team_id: Optional[int] =
Field(default=None, foreign_key="team.id")
sqlmodel.Field
from pydantic.types import Optional from sqlmodel import Field, Relationship, SQLModel from api.public.team.models import Team class HeroBase(SQLModel): name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Config: schema_extra = { "example": { "id": 1, "name": "<NAME>", "secret_name": "<NAME>", "age": 27, "team_id": 1, } } class Hero(HeroBase, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from pydantic.types import Optional from sqlmodel import Field, Relationship, SQLModel from api.public.team.models import Team class HeroBase(SQLModel): name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") class Config: schema_extra = { "example": { "id": 1, "name": "<NAME>", "secret_name": "<NAME>", "age": 27, "team_id": 1, } } class Hero(HeroBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) team: Optional[Team] =
Relationship(back_populates="heroes")
sqlmodel.Relationship
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine =
create_engine("sqlite://")
sqlmodel.create_engine
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine =
create_engine("sqlite://")
sqlmodel.create_engine
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=True) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine =
create_engine("sqlite://")
sqlmodel.create_engine
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=True) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str =
Field(unique=False)
sqlmodel.Field
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str =
Field(unique=True)
sqlmodel.Field
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=True) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
import pytest from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine from sqlalchemy.exc import IntegrityError def test_should_allow_duplicate_row_if_unique_constraint_is_not_passed(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_allow_duplicate_row_if_unique_constraint_is_false(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=False) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with Session(engine) as session: session.add(hero_2) session.commit() session.refresh(hero_2) with Session(engine) as session: heroes = session.query(Hero).all() assert len(heroes) == 2 assert heroes[0].name == heroes[1].name def test_should_raise_exception_when_try_to_duplicate_row_if_unique_constraint_is_true(clear_sqlmodel): class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(unique=True) age: Optional[int] = None hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Deadpond", secret_name="<NAME>") engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(hero_1) session.commit() session.refresh(hero_1) with pytest.raises(IntegrityError): with
Session(engine)
sqlmodel.Session
from decouple import config from sqlmodel import Session, SQLModel, create_engine DATABASE_URL = config("DATABASE_URL") DEBUG = config("DEBUG", default=False, cast=bool) engine =
create_engine(DATABASE_URL, echo=DEBUG)
sqlmodel.create_engine
from decouple import config from sqlmodel import Session, SQLModel, create_engine DATABASE_URL = config("DATABASE_URL") DEBUG = config("DEBUG", default=False, cast=bool) engine = create_engine(DATABASE_URL, echo=DEBUG) def get_session(): with Session(engine) as session: yield session def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from decouple import config from sqlmodel import Session, SQLModel, create_engine DATABASE_URL = config("DATABASE_URL") DEBUG = config("DEBUG", default=False, cast=bool) engine = create_engine(DATABASE_URL, echo=DEBUG) def get_session(): with
Session(engine)
sqlmodel.Session
import uuid from datetime import datetime from typing import Optional, List import pydantic from sqlalchemy import Column, JSON from sqlmodel import Field, Relationship from api.db.models.base import BaseModel, BaseTable class SchemaDef(pydantic.BaseModel): id: Optional[str] = None name: Optional[str] = None version: Optional[str] = None attributes: Optional[List[str]] = [] class Governance(pydantic.BaseModel): schema_def: Optional[SchemaDef] = None cred_def_id: Optional[str] = None cred_def_tag: Optional[str] = None class SandboxBase(BaseModel): tag: Optional[str] =
Field(nullable=True)
sqlmodel.Field
import uuid from datetime import datetime from typing import Optional, List import pydantic from sqlalchemy import Column, JSON from sqlmodel import Field, Relationship from api.db.models.base import BaseModel, BaseTable class SchemaDef(pydantic.BaseModel): id: Optional[str] = None name: Optional[str] = None version: Optional[str] = None attributes: Optional[List[str]] = [] class Governance(pydantic.BaseModel): schema_def: Optional[SchemaDef] = None cred_def_id: Optional[str] = None cred_def_tag: Optional[str] = None class SandboxBase(BaseModel): tag: Optional[str] = Field(nullable=True) governance: dict = Field(default={}, sa_column=Column(JSON)) governance_cas: dict = Field(default={}, sa_column=Column(JSON)) class Sandbox(SandboxBase, BaseTable, table=True): lobs: List["Lob"] =
Relationship(back_populates="sandbox")
sqlmodel.Relationship
import uuid from datetime import datetime from typing import Optional, List import pydantic from sqlalchemy import Column, JSON from sqlmodel import Field, Relationship from api.db.models.base import BaseModel, BaseTable class SchemaDef(pydantic.BaseModel): id: Optional[str] = None name: Optional[str] = None version: Optional[str] = None attributes: Optional[List[str]] = [] class Governance(pydantic.BaseModel): schema_def: Optional[SchemaDef] = None cred_def_id: Optional[str] = None cred_def_tag: Optional[str] = None class SandboxBase(BaseModel): tag: Optional[str] = Field(nullable=True) governance: dict = Field(default={}, sa_column=Column(JSON)) governance_cas: dict = Field(default={}, sa_column=Column(JSON)) class Sandbox(SandboxBase, BaseTable, table=True): lobs: List["Lob"] = Relationship(back_populates="sandbox") # noqa: F821 students: List["Student"] =
Relationship(back_populates="sandbox")
sqlmodel.Relationship
import uuid from datetime import datetime from typing import Optional, List import pydantic from sqlalchemy import Column, JSON from sqlmodel import Field, Relationship from api.db.models.base import BaseModel, BaseTable class SchemaDef(pydantic.BaseModel): id: Optional[str] = None name: Optional[str] = None version: Optional[str] = None attributes: Optional[List[str]] = [] class Governance(pydantic.BaseModel): schema_def: Optional[SchemaDef] = None cred_def_id: Optional[str] = None cred_def_tag: Optional[str] = None class SandboxBase(BaseModel): tag: Optional[str] = Field(nullable=True) governance: dict = Field(default={}, sa_column=Column(JSON)) governance_cas: dict = Field(default={}, sa_column=Column(JSON)) class Sandbox(SandboxBase, BaseTable, table=True): lobs: List["Lob"] = Relationship(back_populates="sandbox") # noqa: F821 students: List["Student"] = Relationship(back_populates="sandbox") # noqa: F821 applicants: List["Applicant"] =
Relationship(back_populates="sandbox")
sqlmodel.Relationship