prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
from typing import Optional from sqlmodel import SQLModel, Field, func, DateTime, Column, Boolean from datetime import datetime class BaseModel(SQLModel): """ BaseModel class """ class Config: use_enum_values = True class BaseTableFields(SQLModel): """ BaseTableField class """ id: Optional[int] = Field(default=None, primary_key=True, nullable=False) created_at: Optional[datetime] = Field( default=None, sa_column=Column( DateTime(timezone=True), server_default=func.now(), nullable=False, ) ) updated_at: Optional[datetime] = Field( default=None, sa_column=Column( DateTime(timezone=True), server_default=func.now(), onupdate=
func.now()
sqlmodel.func.now
"""Initial Migration3 Revision ID: 849d12c13c8a Revises: Create Date: 2021-12-19 17:06:36.345137 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = '849d12<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('username',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial Migration3 Revision ID: 849d12c13c8a Revises: Create Date: 2021-12-19 17:06:36.345137 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = '849d12<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('email',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Initial Migration3 Revision ID: 849d12c13c8a Revises: Create Date: 2021-12-19 17:06:36.345137 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = '849d12<PASSWORD>' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( 'user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('password_hashed',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""participant id as string Revision ID: <KEY> Revises: 11<PASSWORD>3<PASSWORD> Create Date: 2022-04-04 04:34:56.202331+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "11505f38b<PASSWORD>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint( "applications_participant_id_fkey", "applications", type_="foreignkey" ) op.alter_column( "applications", "participant_id", type_=
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""participant id as string Revision ID: <KEY> Revises: 11<PASSWORD>3<PASSWORD> Create Date: 2022-04-04 04:34:56.202331+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "11505f38b<PASSWORD>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint( "applications_participant_id_fkey", "applications", type_="foreignkey" ) op.alter_column( "applications", "participant_id", type_=sqlmodel.sql.sqltypes.AutoString(), nullable=False, ) op.alter_column( "participants", "id", type_=
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str = Field(default=None, primary_key=True) sku: str =
Field(foreign_key="product.sku")
sqlmodel.Field
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str = Field(default=None, primary_key=True) sku: str = Field(foreign_key="product.sku") price: float quantity: int transaction_id: int =
Field(foreign_key="transaction.id")
sqlmodel.Field
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str = Field(default=None, primary_key=True) sku: str = Field(foreign_key="product.sku") price: float quantity: int transaction_id: int = Field(foreign_key="transaction.id") # Each transaction has an id, store_id, date, and total class Transaction(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str = Field(default=None, primary_key=True) sku: str = Field(foreign_key="product.sku") price: float quantity: int transaction_id: int = Field(foreign_key="transaction.id") # Each transaction has an id, store_id, date, and total class Transaction(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) store_id: str =
Field(foreign_key="store.id")
sqlmodel.Field
from datetime import datetime import logging from typing import List, Optional from pydantic import BaseConfig from sqlmodel import Field, SQLModel, Session import shortuuid import random from faker import Faker # Line items that would be on a receipt # Each line item has an id, sku, price, quantity, and transaction_id class LineItem(SQLModel, table=True): id: str = Field(default=None, primary_key=True) sku: str = Field(foreign_key="product.sku") price: float quantity: int transaction_id: int = Field(foreign_key="transaction.id") # Each transaction has an id, store_id, date, and total class Transaction(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) store_id: str = Field(foreign_key="store.id") date: datetime total: float # TODO extract real sales data, transform it, and load into db # for now random data in the correct format will do. def run(engine): # Allow arbitary types for Pydantic validation BaseConfig.arbitrary_types_allowed = True # Create a fake data generator fake = Faker() # Create a session to interact with the database with
Session(engine)
sqlmodel.Session
"""add messages Revision ID: d2388da5bbfd Revises: <PASSWORD> Create Date: 2022-05-04 21:49:29.234380+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from common.database.tables.types import TimeStamp # revision identifiers, used by Alembic. revision = "d2388da5bbfd" down_revision = "3<PASSWORD>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "messages", sa.Column( "created_at", TimeStamp(), server_default=sa.func.now(), nullable=False, ), sa.Column( "updated_at", TimeStamp(), server_default=sa.func.now(), nullable=False, ), sa.Column("sent", sa.Boolean(), nullable=False), sa.Column("subject",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add messages Revision ID: d2388da5bbfd Revises: <PASSWORD> Create Date: 2022-05-04 21:49:29.234380+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from common.database.tables.types import TimeStamp # revision identifiers, used by Alembic. revision = "d2388da5bbfd" down_revision = "3<PASSWORD>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "messages", sa.Column( "created_at", TimeStamp(), server_default=sa.func.now(), nullable=False, ), sa.Column( "updated_at", TimeStamp(), server_default=sa.func.now(), nullable=False, ), sa.Column("sent", sa.Boolean(), nullable=False), sa.Column("subject", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("content",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add events Revision ID: 02338256c6aa Revises: 108677b68119 Create Date: 2022-06-01 03:17:51.063172+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from common.database.tables.types import TimeStamp # revision identifiers, used by Alembic. revision = "02338256c6aa" down_revision = "108677b68119" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "events", sa.Column( "valid_from", TimeStamp(timezone=True), nullable=False, ), sa.Column( "valid_until", TimeStamp(timezone=True), nullable=False, ), sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add events Revision ID: 02338256c6aa Revises: 108677b68119 Create Date: 2022-06-01 03:17:51.063172+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from common.database.tables.types import TimeStamp # revision identifiers, used by Alembic. revision = "02338256c6aa" down_revision = "108677b68119" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "events", sa.Column( "valid_from", TimeStamp(timezone=True), nullable=False, ), sa.Column( "valid_until", TimeStamp(timezone=True), nullable=False, ), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("code",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str =
Field(description="Client name")
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] =
Field(description="Client email", nullable=True)
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] =
Field(description="Client cellphone", nullable=True)
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] =
Field(description="Postal code", nullable=True)
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] =
Field(description="Address of Client", nullable=True)
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID =
Field(description="Client ID")
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID = Field(description="Client ID") class QueryClient(SQLModel): name: Optional[str] =
Field(description="Name of client for query")
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID = Field(description="Client ID") class QueryClient(SQLModel): name: Optional[str] = Field(description="Name of client for query") class Client(BaseClient, table=True): __tablename__ = "clients" id: UUID = Field(default_factory=uuid4, description="Client ID", sa_column=Column("id", GUID(), primary_key=True)) owner_id: UUID =
Field(description="User ID that owns the client", foreign_key="users.id")
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID = Field(description="Client ID") class QueryClient(SQLModel): name: Optional[str] = Field(description="Name of client for query") class Client(BaseClient, table=True): __tablename__ = "clients" id: UUID = Field(default_factory=uuid4, description="Client ID", sa_column=Column("id", GUID(), primary_key=True)) owner_id: UUID = Field(description="User ID that owns the client", foreign_key="users.id") created_at: datetime =
Field(default_factory=now_datetime)
sqlmodel.Field
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID = Field(description="Client ID") class QueryClient(SQLModel): name: Optional[str] = Field(description="Name of client for query") class Client(BaseClient, table=True): __tablename__ = "clients" id: UUID = Field(default_factory=uuid4, description="Client ID", sa_column=Column("id", GUID(), primary_key=True)) owner_id: UUID = Field(description="User ID that owns the client", foreign_key="users.id") created_at: datetime = Field(default_factory=now_datetime) owner: "User" =
Relationship()
sqlmodel.Relationship
from datetime import datetime from typing import TYPE_CHECKING, List, Optional from uuid import UUID, uuid4 from pydantic import EmailStr, constr, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID from ...utils.date import now_datetime if TYPE_CHECKING: from .order import Order from .user import User class BaseClient(SQLModel): name: str = Field(description="Client name") email: Optional[EmailStr] = Field(description="Client email", nullable=True) phone: Optional[constr(regex=r"^\d{2}9\d{8}$")] = Field(description="Client cellphone", nullable=True) # noqa zip_code: Optional[str] = Field(description="Postal code", nullable=True) address: Optional[str] = Field(description="Address of Client", nullable=True) @validator("name") def validate_name(cls, value: str) -> str: return value.title() class CreateClient(BaseClient): pass class UpdateClient(BaseClient): id: UUID = Field(description="Client ID") class QueryClient(SQLModel): name: Optional[str] = Field(description="Name of client for query") class Client(BaseClient, table=True): __tablename__ = "clients" id: UUID = Field(default_factory=uuid4, description="Client ID", sa_column=Column("id",
GUID()
sqlmodel.sql.sqltypes.GUID
from typing import Optional, List from pydantic import BaseModel, validator, ValidationError from sqlmodel import SQLModel, Field class User(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional, List from pydantic import BaseModel, validator, ValidationError from sqlmodel import SQLModel, Field class User(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) username: str =
Field(nullable=False, sa_column_kwargs={"unique": True})
sqlmodel.Field
# from sqlmodel import select from app.src.db.engine import get_db from sqlmodel import Session, select from app.src.db.manager import create_table from app.src.models.db.product import Product from app.src.models.db.product_type import ProductType from app.src.models.db.tag import Tag def test_data(): # create the tables (come renderle dipendenti da una sessione) engine = get_db() create_table() with
Session(engine)
sqlmodel.Session
# from sqlmodel import select from app.src.db.engine import get_db from sqlmodel import Session, select from app.src.db.manager import create_table from app.src.models.db.product import Product from app.src.models.db.product_type import ProductType from app.src.models.db.tag import Tag def test_data(): # create the tables (come renderle dipendenti da una sessione) engine = get_db() create_table() with Session(engine) as session: # define data type_panini = ProductType(name="Panino", description="Tutto ciò che è panino") cibo_tag = Tag(name="cibo") panino = Product( name="panino", description="panino buono", price=3.30, available=True, product_type=type_panini, tags=[cibo_tag], ) kebab = Product( name="kebab", description="senza cipolla", price=4, available=True, product_type=type_panini, tags=[cibo_tag], ) session.add(type_panini) session.add(cibo_tag) session.add(panino) session.add(kebab) statement =
select(Product)
sqlmodel.select
# from sqlmodel import select from app.src.db.engine import get_db from sqlmodel import Session, select from app.src.db.manager import create_table from app.src.models.db.product import Product from app.src.models.db.product_type import ProductType from app.src.models.db.tag import Tag def test_data(): # create the tables (come renderle dipendenti da una sessione) engine = get_db() create_table() with Session(engine) as session: # define data type_panini = ProductType(name="Panino", description="Tutto ciò che è panino") cibo_tag = Tag(name="cibo") panino = Product( name="panino", description="panino buono", price=3.30, available=True, product_type=type_panini, tags=[cibo_tag], ) kebab = Product( name="kebab", description="senza cipolla", price=4, available=True, product_type=type_panini, tags=[cibo_tag], ) session.add(type_panini) session.add(cibo_tag) session.add(panino) session.add(kebab) statement = select(Product) results = session.exec(statement) products = results.all() assert len(products) >= 1 results =
select(Product)
sqlmodel.select
from pydantic.types import List, Optional from sqlmodel import Field, Relationship, SQLModel class TeamBase(SQLModel): name: str headquarters: str class Config: schema_extra = { "example": { "name": "wonderful league", "headquarters": "Fortress of Solitude", } } class Team(TeamBase, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from pydantic.types import List, Optional from sqlmodel import Field, Relationship, SQLModel class TeamBase(SQLModel): name: str headquarters: str class Config: schema_extra = { "example": { "name": "wonderful league", "headquarters": "Fortress of Solitude", } } class Team(TeamBase, table=True): id: Optional[int] = Field(default=None, primary_key=True) heroes: List["Hero"] =
Relationship(back_populates="team")
sqlmodel.Relationship
from urllib.parse import urlparse from datetime import datetime import dramatiq from dramatiq.brokers.redis import RedisBroker from sqlmodel import Session from app.db import engine from app.models import Document, DocumentInput from app.predict import CategoryPrediction from app.settings import settings redis_parameters = urlparse(settings.redis_url) redis_broker = RedisBroker( host=redis_parameters.hostname, port=redis_parameters.port, username=redis_parameters.username, password=redis_parameters.password, # Heroku Redis with TLS use self-signed certs, so we need to tinker a bit ssl=redis_parameters.scheme == "rediss", ssl_cert_reqs=None, ) dramatiq.set_broker(redis_broker) category_prediction = CategoryPrediction() @dramatiq.actor def ingest_document(document_json: str): document = DocumentInput.parse_raw(document_json) with
Session(engine)
sqlmodel.Session
import typing as t from sqlmodel import Field, SQLModel class Quotes(SQLModel, table=True): id: t.Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Type from sqlmodel import select, Session from ..db import engine from ..models.base import TSQLModelDB class BaseRepository: model: Type[TSQLModelDB] @classmethod def create(cls, **kwargs) -> TSQLModelDB: db_model = cls.model(**kwargs) db_model.save() return db_model @classmethod def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None: with
Session(engine)
sqlmodel.Session
from typing import Type from sqlmodel import select, Session from ..db import engine from ..models.base import TSQLModelDB class BaseRepository: model: Type[TSQLModelDB] @classmethod def create(cls, **kwargs) -> TSQLModelDB: db_model = cls.model(**kwargs) db_model.save() return db_model @classmethod def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None: with Session(engine) as session: return session.exec(select(cls.model) .offset(offset) .limit(limit) ).unique().all() @classmethod def get_model_by_id(cls, _id: int) -> TSQLModelDB | None: with
Session(engine)
sqlmodel.Session
from typing import Type from sqlmodel import select, Session from ..db import engine from ..models.base import TSQLModelDB class BaseRepository: model: Type[TSQLModelDB] @classmethod def create(cls, **kwargs) -> TSQLModelDB: db_model = cls.model(**kwargs) db_model.save() return db_model @classmethod def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None: with Session(engine) as session: return session.exec(select(cls.model) .offset(offset) .limit(limit) ).unique().all() @classmethod def get_model_by_id(cls, _id: int) -> TSQLModelDB | None: with Session(engine) as session: return session.get(cls.model, _id) @classmethod def get_model_by_attr(cls, **kwargs) -> TSQLModelDB | None: with
Session(engine)
sqlmodel.Session
from typing import Type from sqlmodel import select, Session from ..db import engine from ..models.base import TSQLModelDB class BaseRepository: model: Type[TSQLModelDB] @classmethod def create(cls, **kwargs) -> TSQLModelDB: db_model = cls.model(**kwargs) db_model.save() return db_model @classmethod def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None: with Session(engine) as session: return session.exec(select(cls.model) .offset(offset) .limit(limit) ).unique().all() @classmethod def get_model_by_id(cls, _id: int) -> TSQLModelDB | None: with Session(engine) as session: return session.get(cls.model, _id) @classmethod def get_model_by_attr(cls, **kwargs) -> TSQLModelDB | None: with Session(engine) as session: return session.exec(
select(cls.model)
sqlmodel.select
from typing import Type from sqlmodel import select, Session from ..db import engine from ..models.base import TSQLModelDB class BaseRepository: model: Type[TSQLModelDB] @classmethod def create(cls, **kwargs) -> TSQLModelDB: db_model = cls.model(**kwargs) db_model.save() return db_model @classmethod def get_all(cls, offset: int = 0, limit: int = 100) -> list[TSQLModelDB] | None: with Session(engine) as session: return session.exec(
select(cls.model)
sqlmodel.select
from unittest.mock import patch from sqlmodel import create_engine from ...conftest import get_testing_print_function def test_tutorial(clear_sqlmodel): from docs_src.tutorial.where import tutorial010 as mod mod.sqlite_url = "sqlite://" mod.engine =
create_engine(mod.sqlite_url)
sqlmodel.create_engine
from sqlmodel import Session, func, text, SQLModel, select from typing import Any, List, Literal, Optional, Type, TypeVar, Generic ReadType = TypeVar("ReadType", bound=SQLModel) CreateType = TypeVar("CreateType", bound=SQLModel) UpdateType = TypeVar("UpdateType", bound=SQLModel) class BaseRepository(Generic[ReadType, CreateType, UpdateType]): entity: Type[ReadType] def __init__(self, db: Session): self.db = db def get_entity(self, *args: Any, **kwargs: Any) -> Optional[ReadType]: result = self.db.exec( select(self.entity) .filter(*args) .filter_by(**kwargs) ) return result.first() def get_entities(self, *args: Any, offset: int = 0, limit: int = 100, order_by: str = 'id', order: Literal['desc', 'asc'] = 'asc', **kwargs: Any) -> List[ReadType]: result = self.db.exec( select(self.entity) .filter(*args) .filter_by(**kwargs) .offset(offset) .limit(limit) .order_by(
text(f"{order_by} {order}")
sqlmodel.text
from sqlmodel import Session, func, text, SQLModel, select from typing import Any, List, Literal, Optional, Type, TypeVar, Generic ReadType = TypeVar("ReadType", bound=SQLModel) CreateType = TypeVar("CreateType", bound=SQLModel) UpdateType = TypeVar("UpdateType", bound=SQLModel) class BaseRepository(Generic[ReadType, CreateType, UpdateType]): entity: Type[ReadType] def __init__(self, db: Session): self.db = db def get_entity(self, *args: Any, **kwargs: Any) -> Optional[ReadType]: result = self.db.exec( select(self.entity) .filter(*args) .filter_by(**kwargs) ) return result.first() def get_entities(self, *args: Any, offset: int = 0, limit: int = 100, order_by: str = 'id', order: Literal['desc', 'asc'] = 'asc', **kwargs: Any) -> List[ReadType]: result = self.db.exec( select(self.entity) .filter(*args) .filter_by(**kwargs) .offset(offset) .limit(limit) .order_by(text(f"{order_by} {order}")) ) return result.all() def count_entities(self) -> int: return self.db.query(
func.count(self.entity.id)
sqlmodel.func.count
from sqlmodel import Session, func, text, SQLModel, select from typing import Any, List, Literal, Optional, Type, TypeVar, Generic ReadType = TypeVar("ReadType", bound=SQLModel) CreateType = TypeVar("CreateType", bound=SQLModel) UpdateType = TypeVar("UpdateType", bound=SQLModel) class BaseRepository(Generic[ReadType, CreateType, UpdateType]): entity: Type[ReadType] def __init__(self, db: Session): self.db = db def get_entity(self, *args: Any, **kwargs: Any) -> Optional[ReadType]: result = self.db.exec(
select(self.entity)
sqlmodel.select
from sqlmodel import Session, func, text, SQLModel, select from typing import Any, List, Literal, Optional, Type, TypeVar, Generic ReadType = TypeVar("ReadType", bound=SQLModel) CreateType = TypeVar("CreateType", bound=SQLModel) UpdateType = TypeVar("UpdateType", bound=SQLModel) class BaseRepository(Generic[ReadType, CreateType, UpdateType]): entity: Type[ReadType] def __init__(self, db: Session): self.db = db def get_entity(self, *args: Any, **kwargs: Any) -> Optional[ReadType]: result = self.db.exec( select(self.entity) .filter(*args) .filter_by(**kwargs) ) return result.first() def get_entities(self, *args: Any, offset: int = 0, limit: int = 100, order_by: str = 'id', order: Literal['desc', 'asc'] = 'asc', **kwargs: Any) -> List[ReadType]: result = self.db.exec(
select(self.entity)
sqlmodel.select
from sqlmodel import SQLModel, create_engine sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url)
sqlmodel.create_engine
from sqlmodel import SQLModel, create_engine sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
"""add swag tiers Revision ID: <KEY> Revises: 02338256c6aa Create Date: 2022-06-01 05:58:25.373228+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "02338256c6aa" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "swag_tiers", sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add swag tiers Revision ID: <KEY> Revises: 02338256c6aa Create Date: 2022-06-01 05:58:25.373228+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "02338256c6aa" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "swag_tiers", sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("description",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
import hypothesis.strategies as st from hypothesis import given from hypothesis.strategies import DataObject from sqlmodel import Session, select from fastapi_server.models.user import User from fastapi_server.test.base_test import BaseTest class TestDatabase(BaseTest): def test_user_add_single(self, method_session_fixture: Session): session = method_session_fixture assert isinstance(session, Session) username = 'asd' email = '<EMAIL>' password = '<PASSWORD>' assert session.exec(
select(User)
sqlmodel.select
import hypothesis.strategies as st from hypothesis import given from hypothesis.strategies import DataObject from sqlmodel import Session, select from fastapi_server.models.user import User from fastapi_server.test.base_test import BaseTest class TestDatabase(BaseTest): def test_user_add_single(self, method_session_fixture: Session): session = method_session_fixture assert isinstance(session, Session) username = 'asd' email = '<EMAIL>' password = '<PASSWORD>' assert session.exec(select(User)).all() == [] session.add( User( username=username, email=email, password_hashed=password, is_admin=False, is_disabled=False, is_verified=False, ) ) session.commit() assert session.exec(
select(User)
sqlmodel.select
import hypothesis.strategies as st from hypothesis import given from hypothesis.strategies import DataObject from sqlmodel import Session, select from fastapi_server.models.user import User from fastapi_server.test.base_test import BaseTest class TestDatabase(BaseTest): def test_user_add_single(self, method_session_fixture: Session): session = method_session_fixture assert isinstance(session, Session) username = 'asd' email = '<EMAIL>' password = '<PASSWORD>' assert session.exec(select(User)).all() == [] session.add( User( username=username, email=email, password_hashed=password, is_admin=False, is_disabled=False, is_verified=False, ) ) session.commit() assert session.exec(select(User)).all() != [] @given(data=st.data()) def test_user_add_multiple(self, data: DataObject): username = data.draw(st.from_regex('[a-zA-Z0-9]{1,20}', fullmatch=True)) email = data.draw(st.from_regex('[a-zA-Z]{1,20}@gmailcom', fullmatch=True)) password = data.draw(st.from_regex('[a-zA-Z0-9]{1,20}', fullmatch=True)) with self.example_session_context() as session: assert session.exec(
select(User)
sqlmodel.select
import hypothesis.strategies as st from hypothesis import given from hypothesis.strategies import DataObject from sqlmodel import Session, select from fastapi_server.models.user import User from fastapi_server.test.base_test import BaseTest class TestDatabase(BaseTest): def test_user_add_single(self, method_session_fixture: Session): session = method_session_fixture assert isinstance(session, Session) username = 'asd' email = '<EMAIL>' password = '<PASSWORD>' assert session.exec(select(User)).all() == [] session.add( User( username=username, email=email, password_hashed=password, is_admin=False, is_disabled=False, is_verified=False, ) ) session.commit() assert session.exec(select(User)).all() != [] @given(data=st.data()) def test_user_add_multiple(self, data: DataObject): username = data.draw(st.from_regex('[a-zA-Z0-9]{1,20}', fullmatch=True)) email = data.draw(st.from_regex('[a-zA-Z]{1,20}@gmailcom', fullmatch=True)) password = data.draw(st.from_regex('[a-zA-Z0-9]{1,20}', fullmatch=True)) with self.example_session_context() as session: assert session.exec(select(User)).all() == [] session.add( User( username=username, email=email, password_hashed=password, is_admin=False, is_disabled=False, is_verified=False, ) ) session.commit() assert session.exec(
select(User)
sqlmodel.select
from select import select from app.schemas.common import ( IGetResponseBase, IPostResponseBase, IDeleteResponseBase, ) from app.utils.text_nlp import analyze_text from app.schemas.text_inference import ( TextInferenceCreate, TextInferenceRead, ) from fastapi_pagination import Page, Params from sqlmodel.ext.asyncio.session import AsyncSession from fastapi import APIRouter, Depends, HTTPException, Query from app.api import deps from app import crud from app.models import TextInference from app.models import TextInferenceBase from app.models.user import User from sqlmodel import select router = APIRouter() @router.get( "/text-classification-inferences/", response_model=IGetResponseBase[Page[TextInferenceRead]], ) async def get_text_classification_inferences( params: Params = Depends(), db_session: AsyncSession = Depends(deps.get_db), current_user: User = Depends(deps.get_current_active_user), ): inferences = await crud.text_inference.get_multi_paginated( db_session, params=params ) return IGetResponseBase[Page[TextInferenceRead]](data=inferences) @router.get( "/text-classification-inferences/order_by_created_at/", response_model=IGetResponseBase[Page[TextInferenceRead]], ) async def text_classification_inferences_order_by_created_at( params: Params = Depends(), db_session: AsyncSession = Depends(deps.get_db), current_user: User = Depends(deps.get_current_active_user), ): query =
select(TextInference)
sqlmodel.select
""" DAG related functions. """ import operator from collections import defaultdict from io import StringIO from typing import Any, DefaultDict, Dict, List, Optional, Set import asciidag.graph import asciidag.node from sqlmodel import Session, select from sqloxide import parse_sql from datajunction.constants import DJ_DATABASE_ID from datajunction.models.database import Database from datajunction.models.node import Node from datajunction.sql.parse import find_nodes_by_key from datajunction.typing import ParseTree def render_dag(dependencies: Dict[str, Set[str]], **kwargs: Any) -> str: """ Render the DAG of dependencies. """ out = StringIO() graph = asciidag.graph.Graph(out, **kwargs) asciidag_nodes: Dict[str, asciidag.node.Node] = {} tips = sorted( [build_asciidag(name, dependencies, asciidag_nodes) for name in dependencies], key=lambda n: n.item, ) graph.show_nodes(tips) out.seek(0) return out.getvalue() def build_asciidag( name: str, dependencies: Dict[str, Set[str]], asciidag_nodes: Dict[str, asciidag.node.Node], ) -> asciidag.node.Node: """ Build the nodes for ``asciidag``. """ if name in asciidag_nodes: asciidag_node = asciidag_nodes[name] else: asciidag_node = asciidag.node.Node(name) asciidag_nodes[name] = asciidag_node asciidag_node.parents = sorted( [ build_asciidag(child, dependencies, asciidag_nodes) for child in dependencies[name] ], key=lambda n: n.item, ) return asciidag_node def get_computable_databases( node: Node, columns: Optional[Set[str]] = None, ) -> Set[Database]: """ Return all the databases where a given node can be computed. This takes into consideration the node expression, since some of the columns might not be present in all databases. """ if columns is None: columns = {column.name for column in node.columns} # add all the databases where the node is explicitly materialized tables = [ table for table in node.tables if columns <= {column.name for column in table.columns} ] databases = {table.database for table in tables} # add all the databases that are common between the parents and match all the columns parent_columns = get_referenced_columns_from_sql(node.expression, node.parents) if node.parents: parent_databases = [ get_computable_databases(parent, parent_columns[parent.name]) for parent in node.parents ] databases |= set.intersection(*parent_databases) return databases def get_database_for_nodes( session: Session, nodes: List[Node], node_columns: Dict[str, Set[str]], database_id: Optional[int] = None, ) -> Database: """ Given a list of nodes, return the best database to compute metric. When no nodes are passed, the database with the lowest cost is returned. """ if nodes: databases = set.intersection( *[get_computable_databases(node, node_columns[node.name]) for node in nodes] ) else: databases = session.exec(
select(Database)
sqlmodel.select
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine =
create_engine(sqlite_url, echo=True, connect_args=connect_args)
sqlmodel.create_engine
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with Session(engine) as session: assignment = LabelAssignment(meter_id=meter_id, label_id=data.label_id, start_time=data.start_time, end_time=data.end_time) ass1 = LabelAssignment(meter_id=1, label_id=1, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(assignment) session.commit() return "Label assigned successfully!" @app.get("/meters/{meter_id}/labels") def get_assigned_labels(meter_id: int): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with Session(engine) as session: assignment = LabelAssignment(meter_id=meter_id, label_id=data.label_id, start_time=data.start_time, end_time=data.end_time) ass1 = LabelAssignment(meter_id=1, label_id=1, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(assignment) session.commit() return "Label assigned successfully!" @app.get("/meters/{meter_id}/labels") def get_assigned_labels(meter_id: int): with Session(engine) as session: labels = session.query(LabelAssignment.start_time, LabelAssignment.end_time, Label.name, Label.color, LabelAssignment.id).filter( LabelAssignment.meter_id == meter_id).join(Label).all() return labels @app.delete("/labels/assignments/{assignment_id}") def delete_assignment(assignment_id: int): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with Session(engine) as session: assignment = LabelAssignment(meter_id=meter_id, label_id=data.label_id, start_time=data.start_time, end_time=data.end_time) ass1 = LabelAssignment(meter_id=1, label_id=1, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(assignment) session.commit() return "Label assigned successfully!" @app.get("/meters/{meter_id}/labels") def get_assigned_labels(meter_id: int): with Session(engine) as session: labels = session.query(LabelAssignment.start_time, LabelAssignment.end_time, Label.name, Label.color, LabelAssignment.id).filter( LabelAssignment.meter_id == meter_id).join(Label).all() return labels @app.delete("/labels/assignments/{assignment_id}") def delete_assignment(assignment_id: int): with Session(engine) as session: session.query(LabelAssignment).filter( LabelAssignment.id == assignment_id).delete() session.commit() return "Label assignment deleted successfully!" @app.get("/labels") def get_labels(): with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with Session(engine) as session: assignment = LabelAssignment(meter_id=meter_id, label_id=data.label_id, start_time=data.start_time, end_time=data.end_time) ass1 = LabelAssignment(meter_id=1, label_id=1, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(assignment) session.commit() return "Label assigned successfully!" @app.get("/meters/{meter_id}/labels") def get_assigned_labels(meter_id: int): with Session(engine) as session: labels = session.query(LabelAssignment.start_time, LabelAssignment.end_time, Label.name, Label.color, LabelAssignment.id).filter( LabelAssignment.meter_id == meter_id).join(Label).all() return labels @app.delete("/labels/assignments/{assignment_id}") def delete_assignment(assignment_id: int): with Session(engine) as session: session.query(LabelAssignment).filter( LabelAssignment.id == assignment_id).delete() session.commit() return "Label assignment deleted successfully!" @app.get("/labels") def get_labels(): with Session(engine) as session: labels = session.query(Label).all() return labels @app.post("/db/setDefaults") def set_defaults(): clear_db() with
Session(engine)
sqlmodel.Session
from fastapi import FastAPI from sqlmodel import SQLModel, create_engine, Session, select from datetime import datetime from datastore.model import Label, LabelAssignment, Meter, Measurement from pydantic import BaseModel SQLITE_FILE_NAME = "database.db" sqlite_url = f"sqlite:///{SQLITE_FILE_NAME}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def create_db_and_tables(): SQLModel.metadata.create_all(engine) app = FastAPI() @app.on_event("startup") def on_startup(): create_db_and_tables() @app.get("/meters") def read_usage(): with Session(engine) as session: meters = session.query(Meter).all() return meters @app.get("/meters/{meter_id}/") def read_meter(meter_id: int): with Session(engine) as session: meter = session.query(Meter).filter(Meter.id == meter_id).first() return meter @app.get("/meters/{meter_id}/measurements") def read_measurements(meter_id: int, start_date: datetime = None, end_date: datetime = None): with Session(engine) as session: query = session.query(Measurement).filter( Measurement.meter_id == meter_id) if start_date: query = query.filter(Measurement.capture_time >= start_date) if end_date: query = query.filter(Measurement.capture_time <= end_date) measurements = query.all() return measurements class LabelAssignmentPostData(BaseModel): label_id: int start_time: datetime end_time: datetime @app.post("/meters/{meter_id}/labels") def assign_label(meter_id: int, data: LabelAssignmentPostData): with Session(engine) as session: assignment = LabelAssignment(meter_id=meter_id, label_id=data.label_id, start_time=data.start_time, end_time=data.end_time) ass1 = LabelAssignment(meter_id=1, label_id=1, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(assignment) session.commit() return "Label assigned successfully!" @app.get("/meters/{meter_id}/labels") def get_assigned_labels(meter_id: int): with Session(engine) as session: labels = session.query(LabelAssignment.start_time, LabelAssignment.end_time, Label.name, Label.color, LabelAssignment.id).filter( LabelAssignment.meter_id == meter_id).join(Label).all() return labels @app.delete("/labels/assignments/{assignment_id}") def delete_assignment(assignment_id: int): with Session(engine) as session: session.query(LabelAssignment).filter( LabelAssignment.id == assignment_id).delete() session.commit() return "Label assignment deleted successfully!" @app.get("/labels") def get_labels(): with Session(engine) as session: labels = session.query(Label).all() return labels @app.post("/db/setDefaults") def set_defaults(): clear_db() with Session(engine) as session: meter1 = Meter(serial_number="Meter one", id=1) meter2 = Meter(serial_number="Meter two", id=2) for i in range(0, 59): session.add(Measurement(meter_id=meter1.id, voltage_phase_1=10+i, voltage_phase_2=(i*i) % 230, voltage_phase_3=30, capture_time=datetime(2020, 1, 1, 0, 0, i))) session.add(meter1) session.add(meter2) label1 = Label(name="Label one", id=1, color="red") label2 = Label(name="Label two", id=2, color="blue") ass1 = LabelAssignment(meter_id=meter1.id, label_id=label1.id, start_time=datetime( 2020, 1, 1, 0, 0, 30), end_time=datetime(2020, 1, 1, 0, 0, 40)) session.add(label1) session.add(label2) session.add(ass1) session.commit() return "Default set successfully!" @app.post("/db/clear") def clear_db(): with
Session(engine)
sqlmodel.Session
"""node state add Revision ID: <KEY> Revises: ad46aa4e<PASSWORD> Create Date: 2021-11-15 21:08:52.990959 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "preps", sa.Column("node_state",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
import pytest from fastapi.testclient import TestClient from sqlmodel import Session, SQLModel, create_engine from sqlmodel.pool import StaticPool from .main import Hero, app, get_session @pytest.fixture(name="session") def session_fixture(): engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool )
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import pytest from fastapi.testclient import TestClient from sqlmodel import Session, SQLModel, create_engine from sqlmodel.pool import StaticPool from .main import Hero, app, get_session @pytest.fixture(name="session") def session_fixture(): engine = create_engine( "sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool ) SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('spotify',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('spotify', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('amazon',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('spotify', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('amazon', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('apple_music',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add playlist and item models Revision ID: 979da9b7aff0 Revises: <PASSWORD> Create Date: 2021-10-31 13:09:14.064217 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '979da9b7aff0' down_revision = 'a<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('item', sa.Column('title', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('artist', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('id', sa.Integer(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_item_artist'), 'item', ['artist'], unique=False) op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) op.create_table('playlist', sa.Column('entity_id', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('spotify', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('amazon', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('apple_music', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('image',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from datetime import datetime, date from decimal import Decimal from typing import Optional, List from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ...db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class HistoryProblem(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from datetime import datetime from sqlalchemy import DateTime, String from sqlalchemy.sql.schema import Column from sqlmodel import Field, SQLModel class Test(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from datetime import datetime from sqlalchemy import DateTime, String from sqlalchemy.sql.schema import Column from sqlmodel import Field, SQLModel class Test(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class DataStorage(SQLModel, table=True): test_id: int =
Field(foreign_key="test.id")
sqlmodel.Field
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\
Relationship(back_populates="tags", link_model=TagProductLink)
sqlmodel.Relationship
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\
Relationship(back_populates="products", link_model=TagProductLink)
sqlmodel.Relationship
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with
Session(engine)
sqlmodel.Session
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with
Session(engine)
sqlmodel.Session
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with Session(engine) as session: tag_no_maionese = session.exec( select(Tag).where(Tag.name == "Senza Maionese") ).one() tag_maionese = session.exec( select(Tag).where(Tag.name == "Con Maionese") ).one() hamburger = session.exec( select(Product).where(Product.name == "hamburger") ).one() hamburger.tags.append(tag_no_maionese) hamburger.tags.remove(tag_maionese) session.add(hamburger) session.commit() print("Updated hamburger:", hamburger.tags) print("Updated tags:", tag_maionese.products, tag_no_maionese.products) def select_products(): with
Session(engine)
sqlmodel.Session
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with Session(engine) as session: tag_no_maionese = session.exec( select(Tag).where(Tag.name == "Senza Maionese") ).one() tag_maionese = session.exec( select(Tag).where(Tag.name == "Con Maionese") ).one() hamburger = session.exec( select(Product).where(Product.name == "hamburger") ).one() hamburger.tags.append(tag_no_maionese) hamburger.tags.remove(tag_maionese) session.add(hamburger) session.commit() print("Updated hamburger:", hamburger.tags) print("Updated tags:", tag_maionese.products, tag_no_maionese.products) def select_products(): with Session(engine) as session: statement =
select(Product, ProductType)
sqlmodel.select
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with Session(engine) as session: tag_no_maionese = session.exec(
select(Tag)
sqlmodel.select
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with Session(engine) as session: tag_no_maionese = session.exec( select(Tag).where(Tag.name == "Senza Maionese") ).one() tag_maionese = session.exec(
select(Tag)
sqlmodel.select
# Creare connessioni tra tabelle M:N (many to many): Product e Tags # https://sqlmodel.tiangolo.com/tutorial/many-to-many/ # e seguito from typing import Optional, List from sqlmodel import Field, SQLModel, Session,\ Relationship, create_engine, select # Tabella di associazione tra Tag e Product class TagProductLink(SQLModel, table=True): tag_id: Optional[int] = Field( default=None, foreign_key="tag.id", primary_key=True ) product_id: Optional[int] = Field( default=None, foreign_key="product.id", primary_key=True ) class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str # Relazione many con Product products: List["Product"] =\ Relationship(back_populates="tags", link_model=TagProductLink) class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class Product(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str product_type: Optional[int] = Field(default=None, foreign_key="producttype.id") # Relazione many con Tag tags: List["Tag"] =\ Relationship(back_populates="products", link_model=TagProductLink) 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_entities(): tag_offerta = Tag(name="Offerta") tag_maionese = Tag(name="Con Maionese") tag_no_maionese = Tag(name="Senza Maionese") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with Session(engine) as session: session.add(tag_offerta) session.add(tag_maionese) session.add(tag_no_maionese) session.add(tipo_panino) session.add(tipo_bibita) session.commit() session.refresh(tag_offerta) session.refresh(tag_maionese) session.refresh(tag_no_maionese) session.refresh(tipo_panino) session.refresh(tipo_bibita) hamburger = Product( name="hamburger", product_type=tipo_panino.id, tags=[tag_offerta, tag_maionese] ) coke = Product( name="Coca Cola", product_type=tipo_bibita.id, tags=[tag_offerta] ) session.add(hamburger) session.add(coke) session.commit() session.refresh(hamburger) session.refresh(coke) print("Created :", hamburger) print("Created :", coke) def update_burger(): with Session(engine) as session: tag_no_maionese = session.exec( select(Tag).where(Tag.name == "Senza Maionese") ).one() tag_maionese = session.exec( select(Tag).where(Tag.name == "Con Maionese") ).one() hamburger = session.exec(
select(Product)
sqlmodel.select
"""Criação dos bancos de dados""" from sqlmodel import SQLModel from mitmirror.infra.entities import * from .database_config import engine def create_db(): """Criando bancos de dados""" base =
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typer.testing import CliRunner import os from timerdo.main import app, sqlite_file_name from timerdo.tables import ToDo, Timer from sqlmodel import create_engine, Session, select from datetime import datetime, timedelta try: os.rename('/home/cmts/.config/timerdo/timerdo_db.db', '/home/cmts/.config/timerdo/timerdo_db_moved.db') except FileNotFoundError: pass sqlite_url = f'sqlite:///{sqlite_file_name}' engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
from typer.testing import CliRunner import os from timerdo.main import app, sqlite_file_name from timerdo.tables import ToDo, Timer from sqlmodel import create_engine, Session, select from datetime import datetime, timedelta try: os.rename('/home/cmts/.config/timerdo/timerdo_db.db', '/home/cmts/.config/timerdo/timerdo_db_moved.db') except FileNotFoundError: pass sqlite_url = f'sqlite:///{sqlite_file_name}' engine = create_engine(sqlite_url, echo=True) runner = CliRunner() def test_add_none(): """Test add function with no argument""" result = runner.invoke(app, ['add']) assert result.exit_code == 2 def test_add_task(): """Test add function with task argument""" task = 'test add' result = runner.invoke(app, ['add', task]) with
Session(engine)
sqlmodel.Session
from typer.testing import CliRunner import os from timerdo.main import app, sqlite_file_name from timerdo.tables import ToDo, Timer from sqlmodel import create_engine, Session, select from datetime import datetime, timedelta try: os.rename('/home/cmts/.config/timerdo/timerdo_db.db', '/home/cmts/.config/timerdo/timerdo_db_moved.db') except FileNotFoundError: pass sqlite_url = f'sqlite:///{sqlite_file_name}' engine = create_engine(sqlite_url, echo=True) runner = CliRunner() def test_add_none(): """Test add function with no argument""" result = runner.invoke(app, ['add']) assert result.exit_code == 2 def test_add_task(): """Test add function with task argument""" task = 'test add' result = runner.invoke(app, ['add', task]) with Session(engine) as session: query = session.exec(select(ToDo).where(ToDo.task == task)).one() task = query.task status = query.status assert result.exit_code == 0 assert task == task assert status == 'to do' def test_add_status(): """Test status""" task = 'Test status' status = 'dif' result = runner.invoke(app, ['add', task, '--status', status]) assert result.exit_code == 1 assert 'status must be "to do" or "doing"\n' in result.stdout def test_add_due_date(): """Test due date""" task = 'Test due date' date = datetime.strftime(datetime.now(), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--due-date', date]) assert result.exit_code == 1 assert f'due date must be grater than {datetime.today().date()}\n' in \ result.stdout def test_add_reminder(): """Test reminder""" task = 'Test reminder' date = datetime.strftime(datetime.now(), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--reminder', date]) assert result.exit_code == 1 assert f'reminder must be grater than {datetime.today().date()}\n' in \ result.stdout def test_add_due_date_reminder(): """Test due-date and reminder""" task = 'Test due-date and reminder' due_date = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') reminder = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--reminder', reminder, '--due-date', due_date]) assert result.exit_code == 1 assert f'reminder must be smaller than {due_date}\n' in \ result.stdout def test_add_full_entry(): """Test add full task""" task = 'something' project = 'test project' due_date = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') reminder = datetime.strftime( datetime.now() + timedelta(days=1), '%Y-%m-%d') status = 'doing' tag = 'tag' result = runner.invoke(app, ['add', task, '--project', project, '--due-date', due_date, '--reminder', reminder, '--status', status, '--tag', tag]) assert result.exit_code == 0 with
Session(engine)
sqlmodel.Session
from typer.testing import CliRunner import os from timerdo.main import app, sqlite_file_name from timerdo.tables import ToDo, Timer from sqlmodel import create_engine, Session, select from datetime import datetime, timedelta try: os.rename('/home/cmts/.config/timerdo/timerdo_db.db', '/home/cmts/.config/timerdo/timerdo_db_moved.db') except FileNotFoundError: pass sqlite_url = f'sqlite:///{sqlite_file_name}' engine = create_engine(sqlite_url, echo=True) runner = CliRunner() def test_add_none(): """Test add function with no argument""" result = runner.invoke(app, ['add']) assert result.exit_code == 2 def test_add_task(): """Test add function with task argument""" task = 'test add' result = runner.invoke(app, ['add', task]) with Session(engine) as session: query = session.exec(select(ToDo).where(ToDo.task == task)).one() task = query.task status = query.status assert result.exit_code == 0 assert task == task assert status == 'to do' def test_add_status(): """Test status""" task = 'Test status' status = 'dif' result = runner.invoke(app, ['add', task, '--status', status]) assert result.exit_code == 1 assert 'status must be "to do" or "doing"\n' in result.stdout def test_add_due_date(): """Test due date""" task = 'Test due date' date = datetime.strftime(datetime.now(), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--due-date', date]) assert result.exit_code == 1 assert f'due date must be grater than {datetime.today().date()}\n' in \ result.stdout def test_add_reminder(): """Test reminder""" task = 'Test reminder' date = datetime.strftime(datetime.now(), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--reminder', date]) assert result.exit_code == 1 assert f'reminder must be grater than {datetime.today().date()}\n' in \ result.stdout def test_add_due_date_reminder(): """Test due-date and reminder""" task = 'Test due-date and reminder' due_date = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') reminder = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') result = runner.invoke(app, ['add', task, '--reminder', reminder, '--due-date', due_date]) assert result.exit_code == 1 assert f'reminder must be smaller than {due_date}\n' in \ result.stdout def test_add_full_entry(): """Test add full task""" task = 'something' project = 'test project' due_date = datetime.strftime( datetime.now() + timedelta(days=2), '%Y-%m-%d') reminder = datetime.strftime( datetime.now() + timedelta(days=1), '%Y-%m-%d') status = 'doing' tag = 'tag' result = runner.invoke(app, ['add', task, '--project', project, '--due-date', due_date, '--reminder', reminder, '--status', status, '--tag', tag]) assert result.exit_code == 0 with Session(engine) as session: query = session.exec(select(ToDo).where(ToDo.task == task, ToDo.project == project, ToDo.status == status, ToDo.tag == tag)).one() assert query is not None def test_start(): """Test start""" todo_id = '1' result = runner.invoke(app, ['start', todo_id]) assert result.exit_code == 0 with
Session(engine)
sqlmodel.Session