prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str =
Field(index=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str =
Field(index=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) secret_name: str age: Optional[int] =
Field(default=None, index=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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 Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): with
Session(engine)
sqlmodel.Session
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): with Session(engine) as session: team_preventers = Team(name="Preventers", headquarters="Sharp Tower") team_z_force = Team(name="Z-Force", headquarters="Sister Margaret鈥檚 Bar") session.add(team_preventers) session.add(team_z_force) session.commit() hero_deadpond = Hero( name="Deadpond", secret_name="<NAME>", team_id=team_z_force.id ) hero_rusty_man = Hero( name="Rusty-Man", secret_name="<NAME>", age=48, team_id=team_preventers.id, ) hero_spider_boy = Hero(name="Spider-Boy", secret_name="<NAME>") session.add(hero_deadpond) session.add(hero_rusty_man) session.add(hero_spider_boy) session.commit() session.refresh(hero_deadpond) session.refresh(hero_rusty_man) session.refresh(hero_spider_boy) print("Created hero:", hero_deadpond) print("Created hero:", hero_rusty_man) print("Created hero:", hero_spider_boy) def select_heroes(): with
Session(engine)
sqlmodel.Session
from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, select class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str = Field(index=True) headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) 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") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables(): SQLModel.metadata.create_all(engine) def create_heroes(): with Session(engine) as session: team_preventers = Team(name="Preventers", headquarters="Sharp Tower") team_z_force = Team(name="Z-Force", headquarters="Sister Margaret鈥檚 Bar") session.add(team_preventers) session.add(team_z_force) session.commit() hero_deadpond = Hero( name="Deadpond", secret_name="<NAME>", team_id=team_z_force.id ) hero_rusty_man = Hero( name="Rusty-Man", secret_name="<NAME>", age=48, team_id=team_preventers.id, ) hero_spider_boy = Hero(name="Spider-Boy", secret_name="<NAME>") session.add(hero_deadpond) session.add(hero_rusty_man) session.add(hero_spider_boy) session.commit() session.refresh(hero_deadpond) session.refresh(hero_rusty_man) session.refresh(hero_spider_boy) print("Created hero:", hero_deadpond) print("Created hero:", hero_rusty_man) print("Created hero:", hero_spider_boy) def select_heroes(): with Session(engine) as session: statement =
select(Hero, Team)
sqlmodel.select
from typing import Optional from pydantic import EmailStr from sqlmodel import Field, SQLModel from sb_backend.app.models.base.base_model import TimeStampMixin # Shared properties class UserBase(SQLModel): email: Optional[EmailStr] = None is_active: Optional[bool] = True is_superuser: bool = False full_name: Optional[str] = None # Properties to receive via API on creation class UserCreate(UserBase): email: EmailStr password: str # Properties to receive via API on update class UserUpdate(UserBase): password: Optional[str] = None class UserInDBBase(UserBase): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from enum import Enum from typing import TYPE_CHECKING, Optional, Set from sqlalchemy import Column from sqlalchemy import Enum as SQLEnum from sqlalchemy import ForeignKey, Integer from sqlmodel import Field, Relationship, SQLModel from .application import Status if TYPE_CHECKING: from .message import Message class Group(Enum): EVERYONE = "Everyone" APPLICATION_COMPLETE = "Application - Complete" APPLICATION_INCOMPLETE = "Application - Incomplete" STATUS_ACCEPTED = "Status - Accepted" STATUS_DENIED = "Status - Denied" STATUS_PENDING = "Status - Pending" @staticmethod def completion_states() -> Set["Group"]: return {Group.APPLICATION_COMPLETE, Group.APPLICATION_INCOMPLETE} @staticmethod def statuses() -> Set["Group"]: return {Group.STATUS_ACCEPTED, Group.STATUS_DENIED, Group.STATUS_PENDING} def to_status(self) -> Optional[Status]: if self == Group.STATUS_ACCEPTED: return Status.ACCEPTED elif self == Group.STATUS_DENIED: return Status.REJECTED elif self == Group.STATUS_PENDING: return Status.PENDING else: return None class RecipientBase(SQLModel): group: Group = Field( sa_column=Column( SQLEnum(Group), nullable=False, primary_key=True, ) ) class Recipient(RecipientBase, table=True): __tablename__ = "recipients" message_id: int = Field( sa_column=Column( Integer(), ForeignKey("messages.id", ondelete="CASCADE"), primary_key=True, ) ) message: "Message" =
Relationship(back_populates="recipients")
sqlmodel.Relationship
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine =
create_engine("sqlite://")
sqlmodel.create_engine
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://")
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(item_1) session.add(item_2) session.add(item_3) session.commit() # This "statement" is where the issue presents itself in PyCharm statement = ( select( Item.category,
func.count(Item.id)
sqlmodel.func.count
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(item_1) session.add(item_2) session.add(item_3) session.commit() # This "statement" is where the issue presents itself in PyCharm statement = ( select( Item.category, func.count(Item.id).label("my_count"),
func.total(Item.deleted)
sqlmodel.func.total
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(item_1) session.add(item_2) session.add(item_3) session.commit() # This "statement" is where the issue presents itself in PyCharm statement = ( select( Item.category, func.count(Item.id).label("my_count"), func.total(Item.deleted).label("delete_count"),
func.min(Item.created)
sqlmodel.func.min
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(item_1) session.add(item_2) session.add(item_3) session.commit() # This "statement" is where the issue presents itself in PyCharm statement = ( select( Item.category, func.count(Item.id).label("my_count"), func.total(Item.deleted).label("delete_count"), func.min(Item.created).label("oldest_timestamp"),
func.max(Item.created)
sqlmodel.func.max
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from datetime import datetime from typing import Optional from sqlmodel import Field, Session, SQLModel, create_engine, func, select class Item(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) created: datetime deleted: bool = False category: str version: float = 1 data: str # Create and save records to show that the query itself is working. item_1 = Item(created=datetime.now(), category="category_1", data="鉂わ笍 I love SQLModel.") item_2 = Item( created=datetime.now(), category="category_1", data="鉂わ笍 I love FastAPI.", deleted=True, ) item_3 = Item( created=datetime.now(), category="category_2", data="馃グ I appreciate your work on all of it!", ) engine = create_engine("sqlite://") SQLModel.metadata.create_all(engine) with Session(engine) as session: session.add(item_1) session.add(item_2) session.add(item_3) session.commit() # This "statement" is where the issue presents itself in PyCharm statement = ( select( Item.category, func.count(Item.id).label("my_count"), func.total(Item.deleted).label("delete_count"), func.min(Item.created).label("oldest_timestamp"), func.max(Item.created).label("newest_timestamp"),
func.group_concat(Item.version)
sqlmodel.func.group_concat
from datetime import date from typing import List from sqlmodel import select from config.config_utils import get_managed_teams_config from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.entities import Championship, Team from src.utils.fixtures_utils import convert_fixture_response_to_db NOTIFIER_DB_MANAGER = NotifierDBManager() def insert_league(fixture_league: Championship) -> DBLeague: league_statement = select(DBLeague).where(DBLeague.id == fixture_league.league_id) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) if not len(retrieved_league): league = DBLeague( id=fixture_league.league_id, name=fixture_league.name, logo=fixture_league.logo, country=fixture_league.country, ) NOTIFIER_DB_MANAGER.insert_record(league) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) return retrieved_league def insert_team(fixture_team: Team) -> DBTeam: team_statement = select(DBTeam).where(DBTeam.id == fixture_team.id) retrieved_team = NOTIFIER_DB_MANAGER.select_records(team_statement) if not len(retrieved_team): team = DBTeam( id=fixture_team.id, name=fixture_team.name, picture=fixture_team.picture, aliases=fixture_team.aliases, ) NOTIFIER_DB_MANAGER.insert_record(team) retrieved_team = NOTIFIER_DB_MANAGER.select_records(team_statement) return retrieved_team def save_fixtures(team_fixtures: List[dict]) -> None: converted_fixtures = [] fix_nr = 1 for fixture in team_fixtures: print(f"Converting & populating fixture {fix_nr}/{len(team_fixtures)}") converted_fixtures.append(convert_fixture_response_to_db(fixture)) fix_nr += 1 db_fixtures = [] for conv_fix in converted_fixtures: retrieved_league = insert_league(conv_fix.championship) retrieved_home_team = insert_team(conv_fix.home_team) retrieved_away_team = insert_team(conv_fix.away_team) fixture_statement = select(DBFixture).where(DBFixture.id == conv_fix.id) retrieved_fixture = NOTIFIER_DB_MANAGER.select_records(fixture_statement) if not len(retrieved_fixture): db_fixture = DBFixture( id=conv_fix.id, utc_date=conv_fix.utc_date, league=retrieved_league.pop().id, round=conv_fix.round, home_team=retrieved_home_team.pop().id, away_team=retrieved_away_team.pop().id, home_score=conv_fix.match_score.home_score, away_score=conv_fix.match_score.away_score, ) else: db_fixture = retrieved_fixture.pop() db_fixture.id = conv_fix.id db_fixture.utc_date = conv_fix.utc_date db_fixture.league = retrieved_league.pop().id db_fixture.round = conv_fix.round db_fixture.home_team = retrieved_home_team.pop().id db_fixture.away_team = retrieved_away_team.pop().id db_fixture.home_score = conv_fix.match_score.home_score db_fixture.away_score = conv_fix.match_score.away_score db_fixtures.append(db_fixture) NOTIFIER_DB_MANAGER.insert_records(db_fixtures) def populate_data(is_initial: bool = False) -> None: managed_teams = get_managed_teams_config() fixtures_client = FixturesClient() current_year = date.today().year last_year = current_year - 1 for team in managed_teams: if is_initial: team_fixtures = fixtures_client.get_fixtures_by(str(last_year), team.id) if "response" in team_fixtures.as_dict: save_fixtures(team_fixtures.as_dict["response"]) team_fixtures = fixtures_client.get_fixtures_by(str(current_year), team.id) if "response" in team_fixtures.as_dict: save_fixtures(team_fixtures.as_dict["response"]) if __name__ == "__main__": fixtures = NOTIFIER_DB_MANAGER.select_records(
select(DBFixture)
sqlmodel.select
from datetime import date from typing import List from sqlmodel import select from config.config_utils import get_managed_teams_config from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.entities import Championship, Team from src.utils.fixtures_utils import convert_fixture_response_to_db NOTIFIER_DB_MANAGER = NotifierDBManager() def insert_league(fixture_league: Championship) -> DBLeague: league_statement =
select(DBLeague)
sqlmodel.select
from datetime import date from typing import List from sqlmodel import select from config.config_utils import get_managed_teams_config from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.entities import Championship, Team from src.utils.fixtures_utils import convert_fixture_response_to_db NOTIFIER_DB_MANAGER = NotifierDBManager() def insert_league(fixture_league: Championship) -> DBLeague: league_statement = select(DBLeague).where(DBLeague.id == fixture_league.league_id) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) if not len(retrieved_league): league = DBLeague( id=fixture_league.league_id, name=fixture_league.name, logo=fixture_league.logo, country=fixture_league.country, ) NOTIFIER_DB_MANAGER.insert_record(league) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) return retrieved_league def insert_team(fixture_team: Team) -> DBTeam: team_statement =
select(DBTeam)
sqlmodel.select
from datetime import date from typing import List from sqlmodel import select from config.config_utils import get_managed_teams_config from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.entities import Championship, Team from src.utils.fixtures_utils import convert_fixture_response_to_db NOTIFIER_DB_MANAGER = NotifierDBManager() def insert_league(fixture_league: Championship) -> DBLeague: league_statement = select(DBLeague).where(DBLeague.id == fixture_league.league_id) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) if not len(retrieved_league): league = DBLeague( id=fixture_league.league_id, name=fixture_league.name, logo=fixture_league.logo, country=fixture_league.country, ) NOTIFIER_DB_MANAGER.insert_record(league) retrieved_league = NOTIFIER_DB_MANAGER.select_records(league_statement) return retrieved_league def insert_team(fixture_team: Team) -> DBTeam: team_statement = select(DBTeam).where(DBTeam.id == fixture_team.id) retrieved_team = NOTIFIER_DB_MANAGER.select_records(team_statement) if not len(retrieved_team): team = DBTeam( id=fixture_team.id, name=fixture_team.name, picture=fixture_team.picture, aliases=fixture_team.aliases, ) NOTIFIER_DB_MANAGER.insert_record(team) retrieved_team = NOTIFIER_DB_MANAGER.select_records(team_statement) return retrieved_team def save_fixtures(team_fixtures: List[dict]) -> None: converted_fixtures = [] fix_nr = 1 for fixture in team_fixtures: print(f"Converting & populating fixture {fix_nr}/{len(team_fixtures)}") converted_fixtures.append(convert_fixture_response_to_db(fixture)) fix_nr += 1 db_fixtures = [] for conv_fix in converted_fixtures: retrieved_league = insert_league(conv_fix.championship) retrieved_home_team = insert_team(conv_fix.home_team) retrieved_away_team = insert_team(conv_fix.away_team) fixture_statement =
select(DBFixture)
sqlmodel.select
from typing import TYPE_CHECKING from pydantic import validator from sqlalchemy import Column, ForeignKey, Integer, String from sqlmodel import Field, Relationship, SQLModel if TYPE_CHECKING: from .event import Event, EventList from .participant import Participant, ParticipantList class FeedbackBase(SQLModel): presentation: int content: int interest: int comments: str =
Field(default="", nullable=False)
sqlmodel.Field
from typing import TYPE_CHECKING from pydantic import validator from sqlalchemy import Column, ForeignKey, Integer, String from sqlmodel import Field, Relationship, SQLModel if TYPE_CHECKING: from .event import Event, EventList from .participant import Participant, ParticipantList class FeedbackBase(SQLModel): presentation: int content: int interest: int comments: str = Field(default="", nullable=False) again: bool =
Field(default=True, nullable=False)
sqlmodel.Field
from typing import TYPE_CHECKING from pydantic import validator from sqlalchemy import Column, ForeignKey, Integer, String from sqlmodel import Field, Relationship, SQLModel if TYPE_CHECKING: from .event import Event, EventList from .participant import Participant, ParticipantList class FeedbackBase(SQLModel): presentation: int content: int interest: int comments: str = Field(default="", nullable=False) again: bool = Field(default=True, nullable=False) @validator("presentation", "content", "interest") def between_1_and_5(cls, value: int): if value < 1 or value > 5: raise ValueError("must be between 1 and 5 inclusive") return value class Feedback(FeedbackBase, table=True): __tablename__ = "feedback" participant_id: str = Field( sa_column=Column( String(), ForeignKey("participants.id", ondelete="CASCADE"), nullable=False, primary_key=True, ) ) participant: "Participant" =
Relationship()
sqlmodel.Relationship
from typing import TYPE_CHECKING from pydantic import validator from sqlalchemy import Column, ForeignKey, Integer, String from sqlmodel import Field, Relationship, SQLModel if TYPE_CHECKING: from .event import Event, EventList from .participant import Participant, ParticipantList class FeedbackBase(SQLModel): presentation: int content: int interest: int comments: str = Field(default="", nullable=False) again: bool = Field(default=True, nullable=False) @validator("presentation", "content", "interest") def between_1_and_5(cls, value: int): if value < 1 or value > 5: raise ValueError("must be between 1 and 5 inclusive") return value class Feedback(FeedbackBase, table=True): __tablename__ = "feedback" participant_id: str = Field( sa_column=Column( String(), ForeignKey("participants.id", ondelete="CASCADE"), nullable=False, primary_key=True, ) ) participant: "Participant" = Relationship() event_id: int = Field( sa_column=Column( Integer(), ForeignKey("events.id", ondelete="CASCADE"), nullable=False, primary_key=True, ) ) event: "Event" =
Relationship(back_populates="feedback")
sqlmodel.Relationship
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str =
Field(max_length=30)
sqlmodel.Field
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine =
create_engine('sqlite:///:memory:')
sqlmodel.create_engine
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:')
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with
Session(engine)
sqlmodel.Session
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement = select(Hero).where(Hero.name == 'Spider-Boy') hero = session.exec(statement).first() logger.info(hero) # Or statement statement = select(Hero).where((Hero.name == 'Spider-Boy') | (Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # Or statement, alternative way statement = select(Hero).where(
or_(Hero.name == 'Spider-Boy', Hero.name == 'Rusty-Man')
sqlmodel.or_
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement =
select(Hero)
sqlmodel.select
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement = select(Hero).where(Hero.name == 'Spider-Boy') hero = session.exec(statement).first() logger.info(hero) # Or statement statement =
select(Hero)
sqlmodel.select
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement = select(Hero).where(Hero.name == 'Spider-Boy') hero = session.exec(statement).first() logger.info(hero) # Or statement statement = select(Hero).where((Hero.name == 'Spider-Boy') | (Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # Or statement, alternative way statement =
select(Hero)
sqlmodel.select
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement = select(Hero).where(Hero.name == 'Spider-Boy') hero = session.exec(statement).first() logger.info(hero) # Or statement statement = select(Hero).where((Hero.name == 'Spider-Boy') | (Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # Or statement, alternative way statement = select(Hero).where(or_(Hero.name == 'Spider-Boy', Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # And statement statement =
select(Hero)
sqlmodel.select
from typing import Optional from loguru import logger from sqlmodel import Field, Session, SQLModel, create_engine, or_, select class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str = Field(max_length=30) age: Optional[int] = None def test_database_with_sqlmodel(): hero_1 = Hero(name='Deadpond', secret_name='<NAME>') hero_2 = Hero(name='Spider-Boy', secret_name='<NAME>') hero_3 = Hero(name='Rusty-Man', secret_name='<NAME>', age=48) # engine = create_engine('sqlite:///temp.db') engine = create_engine('sqlite:///:memory:') SQLModel.metadata.create_all(engine) with Session(engine) as session: for hero in [hero_1, hero_2, hero_3]: session.add(hero) session.commit() with Session(engine) as session: statement = select(Hero).where(Hero.name == 'Spider-Boy') hero = session.exec(statement).first() logger.info(hero) # Or statement statement = select(Hero).where((Hero.name == 'Spider-Boy') | (Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # Or statement, alternative way statement = select(Hero).where(or_(Hero.name == 'Spider-Boy', Hero.name == 'Rusty-Man')) heroes = session.exec(statement) for hero in heroes: logger.info(hero) # And statement statement = select(Hero).where(Hero.name == 'Spider-Boy', Hero.secret_name == '<NAME>') heroes = session.exec(statement) for hero in heroes: logger.info(hero) # And statement, alternative way statement =
select(Hero)
sqlmodel.select
from __future__ import annotations import inspect from functools import wraps from typing import Any, Callable, Dict, List, Literal, Type, TypeVar from fastapi.encoders import jsonable_encoder from sqlalchemy.orm import Query, noload, raiseload, selectinload, subqueryload from sqlalchemy.sql.elements import BinaryExpression from sqlmodel import SQLModel, select from sqlmodel.ext.asyncio.session import AsyncSession Self = TypeVar("Self", bound="Base") LoadStrategy = Literal["subquery", "selectin", "raise", "raise_on_sql", "noload"] load_strategy_map: Dict[LoadStrategy, Callable[..., Any]] = { "subquery": subqueryload, "selectin": selectinload, "raise": raiseload, "raise_on_sql": raiseload, "noload": noload, } class InvalidTable(RuntimeError): """Raised when calling a method coupled to SQLAlchemy operations. It should be called only by SQLModel objects that are tables. """ def is_table(cls: Type[Self]) -> bool: base_is_table = False for base in cls.__bases__: config = getattr(base, "__config__") if config and getattr(config, "table", False): base_is_table = True break return getattr(cls.__config__, "table", False) and not base_is_table def validate_table(func): @wraps(func) def wrapper(self, *args, **kwargs): cls = self if inspect.isclass(self) else self.__class__ if not is_table(cls): raise InvalidTable( f'"{cls.__name__}" is not a table. ' "Add the class parameter `table=True` or don't use with this object." ) return func(self, *args, **kwargs) return wrapper def _prepare_query( cls: Type[Self], load_strategy: Dict[str, LoadStrategy] | None ) -> Query: load_strategy = load_strategy or {} query =
select(cls)
sqlmodel.select
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine =
create_engine(url="sqlite:///users.db", echo=False)
sqlmodel.create_engine
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=False) class User(SQLModel, table=True): id: Optional[int] =
Field(None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=False) class User(SQLModel, table=True): id: Optional[int] = Field(None, primary_key=True) username: str password: str def get_session(): with Session(engine) as session: yield session def init_db():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=False) class User(SQLModel, table=True): id: Optional[int] = Field(None, primary_key=True) username: str password: str def get_session(): with
Session(engine)
sqlmodel.Session
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_places_nearby_address'), 'places_nearby', ['address'], unique=False) op.create_index(op.f('ix_places_nearby_chain_name'), 'places_nearby', ['chain_name'], unique=False) op.create_index(op.f('ix_places_nearby_created_at'), 'places_nearby', ['created_at'], unique=False) op.create_index(op.f('ix_places_nearby_distance'), 'places_nearby', ['distance'], unique=False) op.create_index(op.f('ix_places_nearby_id'), 'places_nearby', ['id'], unique=False) op.create_index(op.f('ix_places_nearby_latitude'), 'places_nearby', ['latitude'], unique=False) op.create_index(op.f('ix_places_nearby_listing_id'), 'places_nearby', ['listing_id'], unique=False) op.create_index(op.f('ix_places_nearby_longitude'), 'places_nearby', ['longitude'], unique=False) op.create_index(op.f('ix_places_nearby_name'), 'places_nearby', ['name'], unique=False) op.create_index(op.f('ix_places_nearby_updated_at'), 'places_nearby', ['updated_at'], unique=False) op.create_index(op.f('ix_places_nearby_website'), 'places_nearby', ['website'], unique=False) op.create_index(op.f('ix_places_nearby_website_domain'), 'places_nearby', ['website_domain'], unique=False) op.create_table('routes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_places_nearby_address'), 'places_nearby', ['address'], unique=False) op.create_index(op.f('ix_places_nearby_chain_name'), 'places_nearby', ['chain_name'], unique=False) op.create_index(op.f('ix_places_nearby_created_at'), 'places_nearby', ['created_at'], unique=False) op.create_index(op.f('ix_places_nearby_distance'), 'places_nearby', ['distance'], unique=False) op.create_index(op.f('ix_places_nearby_id'), 'places_nearby', ['id'], unique=False) op.create_index(op.f('ix_places_nearby_latitude'), 'places_nearby', ['latitude'], unique=False) op.create_index(op.f('ix_places_nearby_listing_id'), 'places_nearby', ['listing_id'], unique=False) op.create_index(op.f('ix_places_nearby_longitude'), 'places_nearby', ['longitude'], unique=False) op.create_index(op.f('ix_places_nearby_name'), 'places_nearby', ['name'], unique=False) op.create_index(op.f('ix_places_nearby_updated_at'), 'places_nearby', ['updated_at'], unique=False) op.create_index(op.f('ix_places_nearby_website'), 'places_nearby', ['website'], unique=False) op.create_index(op.f('ix_places_nearby_website_domain'), 'places_nearby', ['website_domain'], unique=False) op.create_table('routes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_places_nearby_address'), 'places_nearby', ['address'], unique=False) op.create_index(op.f('ix_places_nearby_chain_name'), 'places_nearby', ['chain_name'], unique=False) op.create_index(op.f('ix_places_nearby_created_at'), 'places_nearby', ['created_at'], unique=False) op.create_index(op.f('ix_places_nearby_distance'), 'places_nearby', ['distance'], unique=False) op.create_index(op.f('ix_places_nearby_id'), 'places_nearby', ['id'], unique=False) op.create_index(op.f('ix_places_nearby_latitude'), 'places_nearby', ['latitude'], unique=False) op.create_index(op.f('ix_places_nearby_listing_id'), 'places_nearby', ['listing_id'], unique=False) op.create_index(op.f('ix_places_nearby_longitude'), 'places_nearby', ['longitude'], unique=False) op.create_index(op.f('ix_places_nearby_name'), 'places_nearby', ['name'], unique=False) op.create_index(op.f('ix_places_nearby_updated_at'), 'places_nearby', ['updated_at'], unique=False) op.create_index(op.f('ix_places_nearby_website'), 'places_nearby', ['website'], unique=False) op.create_index(op.f('ix_places_nearby_website_domain'), 'places_nearby', ['website_domain'], unique=False) op.create_table('routes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_places_nearby_address'), 'places_nearby', ['address'], unique=False) op.create_index(op.f('ix_places_nearby_chain_name'), 'places_nearby', ['chain_name'], unique=False) op.create_index(op.f('ix_places_nearby_created_at'), 'places_nearby', ['created_at'], unique=False) op.create_index(op.f('ix_places_nearby_distance'), 'places_nearby', ['distance'], unique=False) op.create_index(op.f('ix_places_nearby_id'), 'places_nearby', ['id'], unique=False) op.create_index(op.f('ix_places_nearby_latitude'), 'places_nearby', ['latitude'], unique=False) op.create_index(op.f('ix_places_nearby_listing_id'), 'places_nearby', ['listing_id'], unique=False) op.create_index(op.f('ix_places_nearby_longitude'), 'places_nearby', ['longitude'], unique=False) op.create_index(op.f('ix_places_nearby_name'), 'places_nearby', ['name'], unique=False) op.create_index(op.f('ix_places_nearby_updated_at'), 'places_nearby', ['updated_at'], unique=False) op.create_index(op.f('ix_places_nearby_website'), 'places_nearby', ['website'], unique=False) op.create_index(op.f('ix_places_nearby_website_domain'), 'places_nearby', ['website_domain'], unique=False) op.create_table('routes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial 5 Revision ID: 0101e666f4e9 Revises: 6c98e82ae2b5 Create Date: 2021-11-14 01:40:19.792380 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '0101e666f4e9' down_revision = '6c98e82ae2b5' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('interest_points', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_interest_points_address'), 'interest_points', ['address'], unique=False) op.create_index(op.f('ix_interest_points_chain_name'), 'interest_points', ['chain_name'], unique=False) op.create_index(op.f('ix_interest_points_created_at'), 'interest_points', ['created_at'], unique=False) op.create_index(op.f('ix_interest_points_distance'), 'interest_points', ['distance'], unique=False) op.create_index(op.f('ix_interest_points_id'), 'interest_points', ['id'], unique=False) op.create_index(op.f('ix_interest_points_latitude'), 'interest_points', ['latitude'], unique=False) op.create_index(op.f('ix_interest_points_listing_id'), 'interest_points', ['listing_id'], unique=False) op.create_index(op.f('ix_interest_points_longitude'), 'interest_points', ['longitude'], unique=False) op.create_index(op.f('ix_interest_points_name'), 'interest_points', ['name'], unique=False) op.create_index(op.f('ix_interest_points_updated_at'), 'interest_points', ['updated_at'], unique=False) op.create_index(op.f('ix_interest_points_website'), 'interest_points', ['website'], unique=False) op.create_index(op.f('ix_interest_points_website_domain'), 'interest_points', ['website_domain'], unique=False) op.create_table('places_nearby', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('listing_id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('updated_at', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['listing_id'], ['listings.id'], ), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_places_nearby_address'), 'places_nearby', ['address'], unique=False) op.create_index(op.f('ix_places_nearby_chain_name'), 'places_nearby', ['chain_name'], unique=False) op.create_index(op.f('ix_places_nearby_created_at'), 'places_nearby', ['created_at'], unique=False) op.create_index(op.f('ix_places_nearby_distance'), 'places_nearby', ['distance'], unique=False) op.create_index(op.f('ix_places_nearby_id'), 'places_nearby', ['id'], unique=False) op.create_index(op.f('ix_places_nearby_latitude'), 'places_nearby', ['latitude'], unique=False) op.create_index(op.f('ix_places_nearby_listing_id'), 'places_nearby', ['listing_id'], unique=False) op.create_index(op.f('ix_places_nearby_longitude'), 'places_nearby', ['longitude'], unique=False) op.create_index(op.f('ix_places_nearby_name'), 'places_nearby', ['name'], unique=False) op.create_index(op.f('ix_places_nearby_updated_at'), 'places_nearby', ['updated_at'], unique=False) op.create_index(op.f('ix_places_nearby_website'), 'places_nearby', ['website'], unique=False) op.create_index(op.f('ix_places_nearby_website_domain'), 'places_nearby', ['website_domain'], unique=False) op.create_table('routes', sa.Column('id', sa.Integer(), nullable=False), sa.Column('latitude', sa.Float(), nullable=True), sa.Column('longitude', sa.Float(), nullable=True), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('distance', sa.Integer(), nullable=False), sa.Column('website', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('website_domain', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('chain_name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from __future__ import annotations from fastapi import Depends from fastapi.security import OAuth2PasswordBearer from sqlmodel import Session, select from src.database import engine from src.models import User from src.services.auth import decode_jwt from .http_exceptions import credentials_exception def get_db(): with
Session(engine)
sqlmodel.Session
from __future__ import annotations from fastapi import Depends from fastapi.security import OAuth2PasswordBearer from sqlmodel import Session, select from src.database import engine from src.models import User from src.services.auth import decode_jwt from .http_exceptions import credentials_exception def get_db(): with Session(engine) as session: yield session oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/sign-in") def get_current_user( db: Session = Depends(get_db), token: str = Depends(oauth2_scheme) ): token_data = decode_jwt(token) if token_data is None or token_data.email is None: raise credentials_exception stmt =
select(User)
sqlmodel.select
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str =
Field(index=True)
sqlmodel.Field
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] =
Field(default=None, index=True)
sqlmodel.Field
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[UUID] =
Field(default=None, foreign_key="team.id")
sqlmodel.Field
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[UUID] = Field(default=None, foreign_key="team.id") class Hero(BaseUUIDModel, HeroBase, table=True): team: Optional["Team"] =
Relationship(back_populates="heroes", sa_relationship_kwargs={"lazy": "selectin"})
sqlmodel.Relationship
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[UUID] = Field(default=None, foreign_key="team.id") class Hero(BaseUUIDModel, HeroBase, table=True): team: Optional["Team"] = Relationship(back_populates="heroes", sa_relationship_kwargs={"lazy": "selectin"}) created_by_id: Optional[UUID] =
Field(default=None, foreign_key="user.id")
sqlmodel.Field
from sqlmodel import Field, Relationship, SQLModel from typing import Optional from app.models.base_uuid_model import BaseUUIDModel from uuid import UUID class HeroBase(SQLModel): name: str = Field(index=True) secret_name: str age: Optional[int] = Field(default=None, index=True) team_id: Optional[UUID] = Field(default=None, foreign_key="team.id") class Hero(BaseUUIDModel, HeroBase, table=True): team: Optional["Team"] = Relationship(back_populates="heroes", sa_relationship_kwargs={"lazy": "selectin"}) created_by_id: Optional[UUID] = Field(default=None, foreign_key="user.id") created_by: "User" =
Relationship(sa_relationship_kwargs={"lazy":"selectin", "primaryjoin":"Hero.created_by_id==User.id"})
sqlmodel.Relationship
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine =
create_engine('sqlite:///database.db')
sqlmodel.create_engine
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query =
select(Pessoa)
sqlmodel.select
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query = select(Pessoa) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome') def get_pessoa(): query =
select(Pessoa.nome)
sqlmodel.select
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query = select(Pessoa) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome') def get_pessoa(): query = select(Pessoa.nome) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome-idade') def get_pessoa(): query =
select(Pessoa.nome, Pessoa.idade)
sqlmodel.select
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query = select(Pessoa) with
Session(engine)
sqlmodel.Session
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query = select(Pessoa) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome') def get_pessoa(): query = select(Pessoa.nome) with
Session(engine)
sqlmodel.Session
from typing import Optional from fastapi import FastAPI from sqlmodel import ( SQLModel, Field, create_engine, select, Session ) # Criar engine do banco engine = create_engine('sqlite:///database.db') class Pessoa(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int # Cria o banco de dados SQLModel.metadata.create_all(engine) app = FastAPI() @app.get('/') def home(): return {'message': 'Deu bom'} @app.get('/pessoa') def get_pessoa(): query = select(Pessoa) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome') def get_pessoa(): query = select(Pessoa.nome) with Session(engine) as session: result = session.execute(query).scalars().all() return result @app.get('/pessoa-nome-idade') def get_pessoa(): query = select(Pessoa.nome, Pessoa.idade) with
Session(engine)
sqlmodel.Session
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str =
Field(primary_key=True)
sqlmodel.Field
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str =
Field(primary_key=True)
sqlmodel.Field
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] =
Relationship(back_populates="project_rel")
sqlmodel.Relationship
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] = Relationship(back_populates="project_rel") class Task(SQLModel, table=True): # type: ignore """The Task model. It is used to model a task. """ # setup the primary key of the table uuid: str =
Field(primary_key=True)
sqlmodel.Field
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] = Relationship(back_populates="project_rel") class Task(SQLModel, table=True): # type: ignore """The Task model. It is used to model a task. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties active_task_state: Optional[str] app_version_num: Optional[float] bytes_received: Optional[float] bytes_sent: Optional[float] checkpoint_cpu_time: Optional[float] completed_at: Optional[datetime] current_cpu_time: Optional[float] elapsed_time: Optional[float] estimated_cpu_time_remaining: Optional[float] exit_code: Optional[float] exit_statement: Optional[str] fraction_done: Optional[float] name: Optional[str] page_fault_rate: Optional[float] pid: Optional[float] plan_class: Optional[str] platform: Optional[str] progress_rate: Optional[float] received_at: Optional[datetime] report_deadline_at: Optional[datetime] scheduler_state: Optional[str] set_size: Optional[float] slot: Optional[float] slot_path: Optional[str] state: Optional[str] swap_size: Optional[float] version_num: Optional[float] wu_name: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship project_url: Optional[str] =
Field(foreign_key="project.url")
sqlmodel.Field
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] = Relationship(back_populates="project_rel") class Task(SQLModel, table=True): # type: ignore """The Task model. It is used to model a task. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties active_task_state: Optional[str] app_version_num: Optional[float] bytes_received: Optional[float] bytes_sent: Optional[float] checkpoint_cpu_time: Optional[float] completed_at: Optional[datetime] current_cpu_time: Optional[float] elapsed_time: Optional[float] estimated_cpu_time_remaining: Optional[float] exit_code: Optional[float] exit_statement: Optional[str] fraction_done: Optional[float] name: Optional[str] page_fault_rate: Optional[float] pid: Optional[float] plan_class: Optional[str] platform: Optional[str] progress_rate: Optional[float] received_at: Optional[datetime] report_deadline_at: Optional[datetime] scheduler_state: Optional[str] set_size: Optional[float] slot: Optional[float] slot_path: Optional[str] state: Optional[str] swap_size: Optional[float] version_num: Optional[float] wu_name: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship project_url: Optional[str] = Field(foreign_key="project.url") project_rel: Optional[Project] =
Relationship(back_populates="task")
sqlmodel.Relationship
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] = Relationship(back_populates="project_rel") class Task(SQLModel, table=True): # type: ignore """The Task model. It is used to model a task. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties active_task_state: Optional[str] app_version_num: Optional[float] bytes_received: Optional[float] bytes_sent: Optional[float] checkpoint_cpu_time: Optional[float] completed_at: Optional[datetime] current_cpu_time: Optional[float] elapsed_time: Optional[float] estimated_cpu_time_remaining: Optional[float] exit_code: Optional[float] exit_statement: Optional[str] fraction_done: Optional[float] name: Optional[str] page_fault_rate: Optional[float] pid: Optional[float] plan_class: Optional[str] platform: Optional[str] progress_rate: Optional[float] received_at: Optional[datetime] report_deadline_at: Optional[datetime] scheduler_state: Optional[str] set_size: Optional[float] slot: Optional[float] slot_path: Optional[str] state: Optional[str] swap_size: Optional[float] version_num: Optional[float] wu_name: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
# -*- coding: utf-8 -*- from datetime import datetime from typing import Optional from sqlmodel import Column, DateTime, Field, Relationship, SQLModel class Device(SQLModel, table=True): # type: ignore """The Device model. It is used to model a device. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] type: Optional[str] arch: Optional[str] cpid: Optional[str] cpu_type: Optional[str] cpu_architecture: Optional[str] cpu_features: Optional[str] processor_count: Optional[int] coprocessor_count: Optional[int] product_name: Optional[str] floating_point_speed: Optional[float] integer_speed: Optional[float] total_disk_space: Optional[float] free_disk_space: Optional[float] swap_space: Optional[float] domain_name: Optional[str] operating_system_version: Optional[str] boinc_version: Optional[str] scitizen_version: Optional[str] platform: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) class Project(SQLModel, table=True): # type: ignore """The Project model. It is used to model a project. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties name: Optional[str] avatar: Optional[str] description: Optional[str] general_area: Optional[str] home: Optional[str] image: Optional[str] is_active: Optional[bool] = True keywords: Optional[str] name: Optional[str] # type: ignore platforms: Optional[str] specific_area: Optional[str] summary: Optional[str] url: Optional[str] web_url: Optional[str] weak_authenticator: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(DateTime(), onupdate=datetime.utcnow, name="_updated_at") ) # setup the relationship task: Optional["Task"] = Relationship(back_populates="project_rel") class Task(SQLModel, table=True): # type: ignore """The Task model. It is used to model a task. """ # setup the primary key of the table uuid: str = Field(primary_key=True) # setup the columns / properties active_task_state: Optional[str] app_version_num: Optional[float] bytes_received: Optional[float] bytes_sent: Optional[float] checkpoint_cpu_time: Optional[float] completed_at: Optional[datetime] current_cpu_time: Optional[float] elapsed_time: Optional[float] estimated_cpu_time_remaining: Optional[float] exit_code: Optional[float] exit_statement: Optional[str] fraction_done: Optional[float] name: Optional[str] page_fault_rate: Optional[float] pid: Optional[float] plan_class: Optional[str] platform: Optional[str] progress_rate: Optional[float] received_at: Optional[datetime] report_deadline_at: Optional[datetime] scheduler_state: Optional[str] set_size: Optional[float] slot: Optional[float] slot_path: Optional[str] state: Optional[str] swap_size: Optional[float] version_num: Optional[float] wu_name: Optional[str] # setup the pseudo-columns (metadata related to the record) created_at: Optional[datetime] = Field( sa_column=Column(DateTime(), default=datetime.utcnow, name="_created_at") ) updated_at: Optional[datetime] = Field( sa_column=Column(
DateTime()
sqlmodel.DateTime
from datetime import datetime from typing import Optional from pydantic import BaseSettings, HttpUrl from sqlmodel import Field, SQLModel # pyright: ignore[reportUnknownVariableType] class Post(SQLModel): id: int text: Optional[str] photos: list[HttpUrl] date: datetime class PostDB(SQLModel, table=True): id: int =
Field(default=None, primary_key=True)
sqlmodel.Field
import os import pytest import time from fastapi.testclient import TestClient from sqlmodel import Session, create_engine from main import app from database import get_db from settings import Settings from alembic.command import upgrade, downgrade from alembic.config import Config @pytest.fixture(autouse=True) def slow_down_tests(): yield time.sleep(1) @pytest.fixture(scope="session") def apply_migrations(): config = Config("alembic.ini") upgrade(config, "head") yield downgrade(config, "base") @pytest.fixture(name="session") def session_fixture(apply_migrations: None): settings = Settings() engine = create_engine( settings.db_uri_test, connect_args={"check_same_thread": False} ) with
Session(engine)
sqlmodel.Session
import random from datetime import datetime from typing import List, Optional from sqlmodel import or_, select from config.notif_config import NotifConfig from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.emojis import Emojis from src.entities import Fixture, TeamStanding from src.senders.email_sender import send_email_html from src.senders.telegram_sender import send_telegram_message from src.utils.date_utils import get_date_spanish_text_format from src.utils.fixtures_utils import ( get_image_search, get_last_fixture, get_last_fixture_db, get_next_fixture, get_next_fixture_db, get_youtube_highlights_videos, ) from src.utils.message_utils import ( get_first_phrase_msg, get_team_intro_message, is_subscripted_for_team, ) class TeamFixturesManager: def __init__(self, season: str, team_id: str) -> None: self._season = season self._team_id = team_id self._fixtures_client = FixturesClient() self._notifier_db_manager = NotifierDBManager() def get_next_team_fixture_text(self, user: str = "") -> tuple: next_team_fixture = self.get_next_team_fixture() return ( self._telegram_next_fixture_notification(next_team_fixture, True, user) if next_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_last_team_fixture_text(self, user: str = "") -> tuple: last_team_fixture = self.get_last_team_fixture() return ( self._telegram_last_fixture_notification(last_team_fixture, user) if last_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_next_team_fixture(self) -> Optional[Fixture]: fixtures_statement =
select(DBFixture)
sqlmodel.select
import random from datetime import datetime from typing import List, Optional from sqlmodel import or_, select from config.notif_config import NotifConfig from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.emojis import Emojis from src.entities import Fixture, TeamStanding from src.senders.email_sender import send_email_html from src.senders.telegram_sender import send_telegram_message from src.utils.date_utils import get_date_spanish_text_format from src.utils.fixtures_utils import ( get_image_search, get_last_fixture, get_last_fixture_db, get_next_fixture, get_next_fixture_db, get_youtube_highlights_videos, ) from src.utils.message_utils import ( get_first_phrase_msg, get_team_intro_message, is_subscripted_for_team, ) class TeamFixturesManager: def __init__(self, season: str, team_id: str) -> None: self._season = season self._team_id = team_id self._fixtures_client = FixturesClient() self._notifier_db_manager = NotifierDBManager() def get_next_team_fixture_text(self, user: str = "") -> tuple: next_team_fixture = self.get_next_team_fixture() return ( self._telegram_next_fixture_notification(next_team_fixture, True, user) if next_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_last_team_fixture_text(self, user: str = "") -> tuple: last_team_fixture = self.get_last_team_fixture() return ( self._telegram_last_fixture_notification(last_team_fixture, user) if last_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_next_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) next_team_fixture = None if len(team_fixtures): next_team_fixture = get_next_fixture_db(team_fixtures) return next_team_fixture def notify_next_fixture_db(self) -> None: next_team_fixture = self.get_next_team_fixture() if next_team_fixture: if next_team_fixture.remaining_time().days < NotifConfig.NEXT_MATCH_THRESHOLD: self._perform_fixture_notification(next_team_fixture) def notify_next_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if next_team_fixture.remaining_time().days < 500: self._perform_fixture_notification(next_team_fixture) def notify_fixture_line_up_update(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if ( next_team_fixture.remaining_time().days < 1 and next_team_fixture.remaining_time().hours < 6 and next_team_fixture.line_up ): self._perform_line_up_confirmed_notification(next_team_fixture) else: print( f"There is still no line up for the match of {next_team_fixture.home_team} vs {next_team_fixture.away_team}" ) print(str(next_team_fixture.remaining_time())) def get_last_team_fixture(self) -> Optional[Fixture]: fixtures_statement =
select(DBFixture)
sqlmodel.select
import random from datetime import datetime from typing import List, Optional from sqlmodel import or_, select from config.notif_config import NotifConfig from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.emojis import Emojis from src.entities import Fixture, TeamStanding from src.senders.email_sender import send_email_html from src.senders.telegram_sender import send_telegram_message from src.utils.date_utils import get_date_spanish_text_format from src.utils.fixtures_utils import ( get_image_search, get_last_fixture, get_last_fixture_db, get_next_fixture, get_next_fixture_db, get_youtube_highlights_videos, ) from src.utils.message_utils import ( get_first_phrase_msg, get_team_intro_message, is_subscripted_for_team, ) class TeamFixturesManager: def __init__(self, season: str, team_id: str) -> None: self._season = season self._team_id = team_id self._fixtures_client = FixturesClient() self._notifier_db_manager = NotifierDBManager() def get_next_team_fixture_text(self, user: str = "") -> tuple: next_team_fixture = self.get_next_team_fixture() return ( self._telegram_next_fixture_notification(next_team_fixture, True, user) if next_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_last_team_fixture_text(self, user: str = "") -> tuple: last_team_fixture = self.get_last_team_fixture() return ( self._telegram_last_fixture_notification(last_team_fixture, user) if last_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_next_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) next_team_fixture = None if len(team_fixtures): next_team_fixture = get_next_fixture_db(team_fixtures) return next_team_fixture def notify_next_fixture_db(self) -> None: next_team_fixture = self.get_next_team_fixture() if next_team_fixture: if next_team_fixture.remaining_time().days < NotifConfig.NEXT_MATCH_THRESHOLD: self._perform_fixture_notification(next_team_fixture) def notify_next_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if next_team_fixture.remaining_time().days < 500: self._perform_fixture_notification(next_team_fixture) def notify_fixture_line_up_update(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if ( next_team_fixture.remaining_time().days < 1 and next_team_fixture.remaining_time().hours < 6 and next_team_fixture.line_up ): self._perform_line_up_confirmed_notification(next_team_fixture) else: print( f"There is still no line up for the match of {next_team_fixture.home_team} vs {next_team_fixture.away_team}" ) print(str(next_team_fixture.remaining_time())) def get_last_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) last_team_fixture = None if team_fixtures: last_team_fixture = get_last_fixture_db(team_fixtures) return last_team_fixture def notify_last_fixture_db(self) -> None: fixtures_statement =
select(DBFixture)
sqlmodel.select
import random from datetime import datetime from typing import List, Optional from sqlmodel import or_, select from config.notif_config import NotifConfig from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.emojis import Emojis from src.entities import Fixture, TeamStanding from src.senders.email_sender import send_email_html from src.senders.telegram_sender import send_telegram_message from src.utils.date_utils import get_date_spanish_text_format from src.utils.fixtures_utils import ( get_image_search, get_last_fixture, get_last_fixture_db, get_next_fixture, get_next_fixture_db, get_youtube_highlights_videos, ) from src.utils.message_utils import ( get_first_phrase_msg, get_team_intro_message, is_subscripted_for_team, ) class TeamFixturesManager: def __init__(self, season: str, team_id: str) -> None: self._season = season self._team_id = team_id self._fixtures_client = FixturesClient() self._notifier_db_manager = NotifierDBManager() def get_next_team_fixture_text(self, user: str = "") -> tuple: next_team_fixture = self.get_next_team_fixture() return ( self._telegram_next_fixture_notification(next_team_fixture, True, user) if next_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_last_team_fixture_text(self, user: str = "") -> tuple: last_team_fixture = self.get_last_team_fixture() return ( self._telegram_last_fixture_notification(last_team_fixture, user) if last_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_next_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) next_team_fixture = None if len(team_fixtures): next_team_fixture = get_next_fixture_db(team_fixtures) return next_team_fixture def notify_next_fixture_db(self) -> None: next_team_fixture = self.get_next_team_fixture() if next_team_fixture: if next_team_fixture.remaining_time().days < NotifConfig.NEXT_MATCH_THRESHOLD: self._perform_fixture_notification(next_team_fixture) def notify_next_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if next_team_fixture.remaining_time().days < 500: self._perform_fixture_notification(next_team_fixture) def notify_fixture_line_up_update(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if ( next_team_fixture.remaining_time().days < 1 and next_team_fixture.remaining_time().hours < 6 and next_team_fixture.line_up ): self._perform_line_up_confirmed_notification(next_team_fixture) else: print( f"There is still no line up for the match of {next_team_fixture.home_team} vs {next_team_fixture.away_team}" ) print(str(next_team_fixture.remaining_time())) def get_last_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) last_team_fixture = None if team_fixtures: last_team_fixture = get_last_fixture_db(team_fixtures) return last_team_fixture def notify_last_fixture_db(self) -> None: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) last_team_fixture = None if team_fixtures: last_team_fixture = get_last_fixture_db(team_fixtures) if last_team_fixture: if ( NotifConfig.LAST_MATCH_THRESHOLD_DAYS <= last_team_fixture.remaining_time().days <= 0 ): self._perform_last_fixture_notification(last_team_fixture) def notify_last_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) last_team_fixture = get_last_fixture( team_fixtures.as_dict["response"], self._team_id ) if last_team_fixture: if ( -1 <= last_team_fixture.remaining_time().days <= NotifConfig.LAST_MATCH_THRESHOLD_DAYS ): last_team_fixture.highlights = get_youtube_highlights_videos( last_team_fixture.home_team, last_team_fixture.away_team ) self._perform_last_fixture_notification(last_team_fixture) def _telegram_last_fixture_notification( self, team_fixture: Fixture, user: str = "" ) -> tuple: match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["last_match"] highlights_yt_url = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" highlights_text = f"{Emojis.FILM_PROJECTOR.value} <a href='{highlights_yt_url}'>HIGHLIGHTS</a>" telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {user}!\n\n" f"{team_intro_message} " f"jug贸 el {spanish_format_date}! \nEste fue el resultado: \n\n" f"{team_fixture.matched_played_telegram_like_repr()}" f"{highlights_text}" ) return (telegram_message, match_image_url) def _telegram_next_fixture_notification( self, team_fixture: Fixture, is_on_demand: False, user: str = "" ) -> tuple: spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) date_text = ( "es HOY!" if team_fixture.bsas_date.day == datetime.today().day else f"es el {Emojis.SPIRAL_CALENDAR.value} {spanish_format_date}." ) first_phrase = get_first_phrase_msg(True, is_on_demand) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["next_match"] intro_message = f"{first_phrase} {team_intro_message}" telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {user}! " f"\n\n{intro_message} {date_text}\n\n{team_fixture.telegram_like_repr()}" ) return (telegram_message, match_image_url) def _perform_last_fixture_notification( self, team_fixture: Fixture, team_standing: TeamStanding = None ) -> None: match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) # telegram team_standing_msg = ( f"{Emojis.RED_EXCLAMATION_MARK.value} Situaci贸n actual en el campeonato: \n\n{team_standing.telegram_like_repr()}\n" if team_standing else "" ) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["last_match"] highlights_yt_url = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" highlights_text = f"{Emojis.FILM_PROJECTOR.value} <a href='{highlights_yt_url}'>HIGHLIGHTS</a>" FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: if is_subscripted_for_team(recipient, self._team_id): telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n" f"{team_intro_message} " f"jug贸 ayer! \nEste fue el resultado: \n\n" f"{team_fixture.matched_played_telegram_like_repr()}" f"\n{highlights_text}" ) send_telegram_message( recipient.telegram_id, telegram_message, match_image_url, ) # email team_standing_email_msg = ( f"Situaci贸n actual en el campeonato: \n\n{team_standing.email_like_repr()}" if team_standing else "" ) match_image_text = f"<img src='{match_image_url}'>" email_standing_message = ( f"{Emojis.RED_EXCLAMATION_MARK.value}{team_standing_email_msg}\n" ) highlights_text = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = ( f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{team_intro_message} " f"jug贸 ayer!<br /><br />{match_image_text}<br /><br />Este fue el resultado: \n\n{team_fixture.matched_played_email_like_repr()}" f"<br /><br />{email_standing_message}<br /><br />{highlights_text}" ) send_email_html( f"{team_fixture.home_team.name} ({team_fixture.match_score.home_score}) - " f"({team_fixture.match_score.away_score}) {team_fixture.away_team.name}", message, recipient.email, ) def _perform_fixture_notification(self, team_fixture: Fixture) -> None: spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) match_image_text = f"<img width='100%' height='100%' src='{match_image_url}'>" date_text = ( "es HOY!" if team_fixture.bsas_date.day == datetime.today().day else f"es el {Emojis.SPIRAL_CALENDAR.value} {spanish_format_date}." ) first_phrase = get_first_phrase_msg(True) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["next_match"] intro_message = f"{first_phrase} {team_intro_message}" # telegram FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: if is_subscripted_for_team(recipient, self._team_id): telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola " f"{recipient.name}!\n\n{intro_message} {date_text}\n\n{team_fixture.telegram_like_repr()}" ) send_telegram_message( recipient.telegram_id, telegram_message, photo=match_image_url, ) # email EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message} {date_text}\n\n<br /><br />{match_image_text}<br /><br />{team_fixture.email_like_repr()}" send_email_html( f"{team_fixture.home_team.name} vs. {team_fixture.away_team.name}", message, recipient.email, ) def _perform_line_up_confirmed_notification(self, team_fixture: Fixture) -> None: match_teams = f"{team_fixture.home_team.name} vs {team_fixture.away_team.name}" match_image_url = get_image_search(match_teams) match_image_text = f"<img src='{match_image_url}'>" # telegram FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: intro_message = f"Se actualiz贸 la alineaci贸n para {match_teams}:" telegram_message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message}\n\n{team_fixture.telegram_like_repr()}" send_telegram_message( recipient.telegram_id, telegram_message, photo=match_image_url, ) # email EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message}\n\n<br /><br />{match_image_text}<br /><br />{team_fixture.email_like_repr()}" send_email_html( f"{team_fixture.home_team.name} vs. {team_fixture.away_team.name}", message, recipient.email, ) def _get_match_images(self, league_id: int) -> List[str]: match_image_url_team_statement =
select(DBTeam)
sqlmodel.select
import random from datetime import datetime from typing import List, Optional from sqlmodel import or_, select from config.notif_config import NotifConfig from src.api.fixtures_client import FixturesClient from src.db.db_manager import NotifierDBManager from src.db.notif_sql_models import Fixture as DBFixture from src.db.notif_sql_models import League as DBLeague from src.db.notif_sql_models import Team as DBTeam from src.emojis import Emojis from src.entities import Fixture, TeamStanding from src.senders.email_sender import send_email_html from src.senders.telegram_sender import send_telegram_message from src.utils.date_utils import get_date_spanish_text_format from src.utils.fixtures_utils import ( get_image_search, get_last_fixture, get_last_fixture_db, get_next_fixture, get_next_fixture_db, get_youtube_highlights_videos, ) from src.utils.message_utils import ( get_first_phrase_msg, get_team_intro_message, is_subscripted_for_team, ) class TeamFixturesManager: def __init__(self, season: str, team_id: str) -> None: self._season = season self._team_id = team_id self._fixtures_client = FixturesClient() self._notifier_db_manager = NotifierDBManager() def get_next_team_fixture_text(self, user: str = "") -> tuple: next_team_fixture = self.get_next_team_fixture() return ( self._telegram_next_fixture_notification(next_team_fixture, True, user) if next_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_last_team_fixture_text(self, user: str = "") -> tuple: last_team_fixture = self.get_last_team_fixture() return ( self._telegram_last_fixture_notification(last_team_fixture, user) if last_team_fixture else ("Fixture para el equipo no encontrado", "") ) def get_next_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) next_team_fixture = None if len(team_fixtures): next_team_fixture = get_next_fixture_db(team_fixtures) return next_team_fixture def notify_next_fixture_db(self) -> None: next_team_fixture = self.get_next_team_fixture() if next_team_fixture: if next_team_fixture.remaining_time().days < NotifConfig.NEXT_MATCH_THRESHOLD: self._perform_fixture_notification(next_team_fixture) def notify_next_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if next_team_fixture.remaining_time().days < 500: self._perform_fixture_notification(next_team_fixture) def notify_fixture_line_up_update(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) next_team_fixture = None if "response" in team_fixtures.as_dict: next_team_fixture = get_next_fixture( team_fixtures.as_dict["response"], self._team_id ) if next_team_fixture: if ( next_team_fixture.remaining_time().days < 1 and next_team_fixture.remaining_time().hours < 6 and next_team_fixture.line_up ): self._perform_line_up_confirmed_notification(next_team_fixture) else: print( f"There is still no line up for the match of {next_team_fixture.home_team} vs {next_team_fixture.away_team}" ) print(str(next_team_fixture.remaining_time())) def get_last_team_fixture(self) -> Optional[Fixture]: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) last_team_fixture = None if team_fixtures: last_team_fixture = get_last_fixture_db(team_fixtures) return last_team_fixture def notify_last_fixture_db(self) -> None: fixtures_statement = select(DBFixture).where( or_( DBFixture.home_team == self._team_id, DBFixture.away_team == self._team_id, ) ) team_fixtures = self._notifier_db_manager.select_records(fixtures_statement) last_team_fixture = None if team_fixtures: last_team_fixture = get_last_fixture_db(team_fixtures) if last_team_fixture: if ( NotifConfig.LAST_MATCH_THRESHOLD_DAYS <= last_team_fixture.remaining_time().days <= 0 ): self._perform_last_fixture_notification(last_team_fixture) def notify_last_fixture(self) -> None: team_fixtures = self._fixtures_client.get_fixtures_by( self._season, self._team_id ) last_team_fixture = get_last_fixture( team_fixtures.as_dict["response"], self._team_id ) if last_team_fixture: if ( -1 <= last_team_fixture.remaining_time().days <= NotifConfig.LAST_MATCH_THRESHOLD_DAYS ): last_team_fixture.highlights = get_youtube_highlights_videos( last_team_fixture.home_team, last_team_fixture.away_team ) self._perform_last_fixture_notification(last_team_fixture) def _telegram_last_fixture_notification( self, team_fixture: Fixture, user: str = "" ) -> tuple: match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["last_match"] highlights_yt_url = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" highlights_text = f"{Emojis.FILM_PROJECTOR.value} <a href='{highlights_yt_url}'>HIGHLIGHTS</a>" telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {user}!\n\n" f"{team_intro_message} " f"jug贸 el {spanish_format_date}! \nEste fue el resultado: \n\n" f"{team_fixture.matched_played_telegram_like_repr()}" f"{highlights_text}" ) return (telegram_message, match_image_url) def _telegram_next_fixture_notification( self, team_fixture: Fixture, is_on_demand: False, user: str = "" ) -> tuple: spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) date_text = ( "es HOY!" if team_fixture.bsas_date.day == datetime.today().day else f"es el {Emojis.SPIRAL_CALENDAR.value} {spanish_format_date}." ) first_phrase = get_first_phrase_msg(True, is_on_demand) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["next_match"] intro_message = f"{first_phrase} {team_intro_message}" telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {user}! " f"\n\n{intro_message} {date_text}\n\n{team_fixture.telegram_like_repr()}" ) return (telegram_message, match_image_url) def _perform_last_fixture_notification( self, team_fixture: Fixture, team_standing: TeamStanding = None ) -> None: match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) # telegram team_standing_msg = ( f"{Emojis.RED_EXCLAMATION_MARK.value} Situaci贸n actual en el campeonato: \n\n{team_standing.telegram_like_repr()}\n" if team_standing else "" ) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["last_match"] highlights_yt_url = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" highlights_text = f"{Emojis.FILM_PROJECTOR.value} <a href='{highlights_yt_url}'>HIGHLIGHTS</a>" FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: if is_subscripted_for_team(recipient, self._team_id): telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n" f"{team_intro_message} " f"jug贸 ayer! \nEste fue el resultado: \n\n" f"{team_fixture.matched_played_telegram_like_repr()}" f"\n{highlights_text}" ) send_telegram_message( recipient.telegram_id, telegram_message, match_image_url, ) # email team_standing_email_msg = ( f"Situaci贸n actual en el campeonato: \n\n{team_standing.email_like_repr()}" if team_standing else "" ) match_image_text = f"<img src='{match_image_url}'>" email_standing_message = ( f"{Emojis.RED_EXCLAMATION_MARK.value}{team_standing_email_msg}\n" ) highlights_text = f"https://www.youtube.com/results?search_query={team_fixture.home_team.name}+vs+{team_fixture.away_team.name}+jugadas+resumen" EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = ( f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{team_intro_message} " f"jug贸 ayer!<br /><br />{match_image_text}<br /><br />Este fue el resultado: \n\n{team_fixture.matched_played_email_like_repr()}" f"<br /><br />{email_standing_message}<br /><br />{highlights_text}" ) send_email_html( f"{team_fixture.home_team.name} ({team_fixture.match_score.home_score}) - " f"({team_fixture.match_score.away_score}) {team_fixture.away_team.name}", message, recipient.email, ) def _perform_fixture_notification(self, team_fixture: Fixture) -> None: spanish_format_date = get_date_spanish_text_format(team_fixture.bsas_date) match_images = self._get_match_images(team_fixture.championship.league_id) match_image_url = random.choice(match_images) match_image_text = f"<img width='100%' height='100%' src='{match_image_url}'>" date_text = ( "es HOY!" if team_fixture.bsas_date.day == datetime.today().day else f"es el {Emojis.SPIRAL_CALENDAR.value} {spanish_format_date}." ) first_phrase = get_first_phrase_msg(True) team_intro_message = get_team_intro_message( team_fixture.home_team if str(team_fixture.home_team.id) == str(self._team_id) else team_fixture.away_team )["next_match"] intro_message = f"{first_phrase} {team_intro_message}" # telegram FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: if is_subscripted_for_team(recipient, self._team_id): telegram_message = ( f"{Emojis.WAVING_HAND.value}Hola " f"{recipient.name}!\n\n{intro_message} {date_text}\n\n{team_fixture.telegram_like_repr()}" ) send_telegram_message( recipient.telegram_id, telegram_message, photo=match_image_url, ) # email EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message} {date_text}\n\n<br /><br />{match_image_text}<br /><br />{team_fixture.email_like_repr()}" send_email_html( f"{team_fixture.home_team.name} vs. {team_fixture.away_team.name}", message, recipient.email, ) def _perform_line_up_confirmed_notification(self, team_fixture: Fixture) -> None: match_teams = f"{team_fixture.home_team.name} vs {team_fixture.away_team.name}" match_image_url = get_image_search(match_teams) match_image_text = f"<img src='{match_image_url}'>" # telegram FOOTBALL_TELEGRAM_RECIPIENTS = NotifConfig.TELEGRAM_RECIPIENTS for recipient in FOOTBALL_TELEGRAM_RECIPIENTS: intro_message = f"Se actualiz贸 la alineaci贸n para {match_teams}:" telegram_message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message}\n\n{team_fixture.telegram_like_repr()}" send_telegram_message( recipient.telegram_id, telegram_message, photo=match_image_url, ) # email EMAIL_RECIPIENTS = NotifConfig.EMAIL_RECIPIENTS for recipient in EMAIL_RECIPIENTS: message = f"{Emojis.WAVING_HAND.value}Hola {recipient.name}!\n\n{intro_message}\n\n<br /><br />{match_image_text}<br /><br />{team_fixture.email_like_repr()}" send_email_html( f"{team_fixture.home_team.name} vs. {team_fixture.away_team.name}", message, recipient.email, ) def _get_match_images(self, league_id: int) -> List[str]: match_image_url_team_statement = select(DBTeam).where( DBTeam.id == self._team_id ) match_image_url_league_statement =
select(DBLeague)
sqlmodel.select
from datetime import datetime from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union from uuid import UUID from fastapi_pagination.ext.async_sqlmodel import paginate from fastapi_pagination import Params, Page from fastapi.encoders import jsonable_encoder from pydantic import BaseModel from sqlmodel import SQLModel, select, func from sqlalchemy.orm import selectinload from sqlmodel.ext.asyncio.session import AsyncSession from sqlmodel.sql.expression import Select, SelectOfScalar ModelType = TypeVar("ModelType", bound=SQLModel) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) SchemaType = TypeVar("SchemaType", bound=BaseModel) T = TypeVar("T", bound=SQLModel) class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model: Type[ModelType]): """ CRUD object with default methods to Create, Read, Update, Delete (CRUD). **Parameters** * `model`: A SQLAlchemy model class * `schema`: A Pydantic model (schema) class """ self.model = model async def get( self, db_session: AsyncSession, *, id: Union[UUID, str] ) -> Optional[ModelType]: response = await db_session.exec(select(self.model).where(self.model.id == id).options(selectinload('*'))) return response.first() async def get_by_ids(self, db_session: AsyncSession, list_ids: List[Union[UUID, str]],) -> Optional[List[ModelType]]: response = await db_session.exec(
select(self.model)
sqlmodel.select
from datetime import datetime from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union from uuid import UUID from fastapi_pagination.ext.async_sqlmodel import paginate from fastapi_pagination import Params, Page from fastapi.encoders import jsonable_encoder from pydantic import BaseModel from sqlmodel import SQLModel, select, func from sqlalchemy.orm import selectinload from sqlmodel.ext.asyncio.session import AsyncSession from sqlmodel.sql.expression import Select, SelectOfScalar ModelType = TypeVar("ModelType", bound=SQLModel) CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) SchemaType = TypeVar("SchemaType", bound=BaseModel) T = TypeVar("T", bound=SQLModel) class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): def __init__(self, model: Type[ModelType]): """ CRUD object with default methods to Create, Read, Update, Delete (CRUD). **Parameters** * `model`: A SQLAlchemy model class * `schema`: A Pydantic model (schema) class """ self.model = model async def get( self, db_session: AsyncSession, *, id: Union[UUID, str] ) -> Optional[ModelType]: response = await db_session.exec(select(self.model).where(self.model.id == id).options(selectinload('*'))) return response.first() async def get_by_ids(self, db_session: AsyncSession, list_ids: List[Union[UUID, str]],) -> Optional[List[ModelType]]: response = await db_session.exec(select(self.model).where(self.model.id.in_(list_ids))) return response.all() async def get_count( self, db_session: AsyncSession ) -> Optional[ModelType]: response = await db_session.exec(select(func.count()).select_from(select(self.model).subquery())) return response.one() async def get_multi( self, db_session: AsyncSession, *, skip: int = 0, limit: int = 100 ) -> List[ModelType]: response = await db_session.exec( select(self.model).offset(skip).limit(limit).order_by(self.model.id) ) return response.all() async def get_multi_paginated( self, db_session: AsyncSession, *, params: Optional[Params] = Params(), query: Optional[Union[T, Select[T], SelectOfScalar[T]]] = None ) -> Page[ModelType]: if query == None: query = self.model return await paginate(db_session, query, params) async def create( self, db_session: AsyncSession, *, obj_in: Union[CreateSchemaType, ModelType], created_by_id: Optional[Union[UUID, str]] = None ) -> ModelType: db_obj = self.model.from_orm(obj_in) # type: ignore db_obj.created_at = datetime.utcnow() db_obj.updated_at = datetime.utcnow() if(created_by_id): db_obj.created_by_id = created_by_id db_session.add(db_obj) await db_session.commit() await db_session.refresh(db_obj) return db_obj async def update( self, db_session: AsyncSession, *, obj_current: ModelType, obj_new: Union[UpdateSchemaType, Dict[str, Any], ModelType] ) -> ModelType: obj_data = jsonable_encoder(obj_current) if isinstance(obj_new, dict): update_data = obj_new else: update_data = obj_new.dict(exclude_unset=True) #This tells Pydantic to not include the values that were not sent for field in obj_data: if field in update_data: setattr(obj_current, field, update_data[field]) if field == "updated_at": setattr(obj_current, field, datetime.utcnow()) db_session.add(obj_current) await db_session.commit() await db_session.refresh(obj_current) return obj_current async def remove( self, db_session: AsyncSession, *, id: Union[UUID, str] ) -> ModelType: response = await db_session.exec(
select(self.model)
sqlmodel.select