prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
import os from typing import List from sqlmodel.sql.expression import select from utilities.filepath import get_home_dir from sqlmodel import create_engine, SQLModel, Session # these are imported so that the initialization of the database can be done from schemas.common.event import Event from schemas.common.extension import Extension class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DB(metaclass=Singleton): def __init__(self) -> None: self.engine = create_engine("sqlite:///{}".format(os.path.join(get_home_dir(), "extensions.db"))) def initialize(self) -> None:
SQLModel.metadata.create_all(self.engine)
sqlmodel.SQLModel.metadata.create_all
import os from typing import List from sqlmodel.sql.expression import select from utilities.filepath import get_home_dir from sqlmodel import create_engine, SQLModel, Session # these are imported so that the initialization of the database can be done from schemas.common.event import Event from schemas.common.extension import Extension class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DB(metaclass=Singleton): def __init__(self) -> None: self.engine = create_engine("sqlite:///{}".format(os.path.join(get_home_dir(), "extensions.db"))) def initialize(self) -> None: SQLModel.metadata.create_all(self.engine) def save(self, obj: SQLModel) -> None: session =
Session(self.engine)
sqlmodel.Session
import os from typing import List from sqlmodel.sql.expression import select from utilities.filepath import get_home_dir from sqlmodel import create_engine, SQLModel, Session # these are imported so that the initialization of the database can be done from schemas.common.event import Event from schemas.common.extension import Extension class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DB(metaclass=Singleton): def __init__(self) -> None: self.engine = create_engine("sqlite:///{}".format(os.path.join(get_home_dir(), "extensions.db"))) def initialize(self) -> None: SQLModel.metadata.create_all(self.engine) def save(self, obj: SQLModel) -> None: session = Session(self.engine) session.add(obj) session.commit() session.refresh(obj) return obj def fetch_extensions(self)-> List[Extension]: with
Session(self.engine)
sqlmodel.Session
import os from typing import List from sqlmodel.sql.expression import select from utilities.filepath import get_home_dir from sqlmodel import create_engine, SQLModel, Session # these are imported so that the initialization of the database can be done from schemas.common.event import Event from schemas.common.extension import Extension class Singleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DB(metaclass=Singleton): def __init__(self) -> None: self.engine = create_engine("sqlite:///{}".format(os.path.join(get_home_dir(), "extensions.db"))) def initialize(self) -> None: SQLModel.metadata.create_all(self.engine) def save(self, obj: SQLModel) -> None: session = Session(self.engine) session.add(obj) session.commit() session.refresh(obj) return obj def fetch_extensions(self)-> List[Extension]: with Session(self.engine) as session: results = session.exec(
select(Extension)
sqlmodel.sql.expression.select
from typing import AsyncGenerator, Generator from aiobotocore.client import AioBaseClient from aiobotocore.session import get_session from sqlmodel import Session from sqlmodel.ext.asyncio.session import AsyncSession from ..core.config import settings from ..db.db import engine, engine_async async def get_s3() -> AsyncGenerator[AioBaseClient, None]: session = get_session() async with session.create_client( "s3", region_name=settings.MINIO_REGION_NAME, endpoint_url=settings.MINIO_URL, use_ssl=False, aws_secret_access_key=settings.MINIO_SECRET_KEY, aws_access_key_id=settings.MINIO_ACCESS_KEY, ) as client: yield client async def get_db_async() -> AsyncGenerator[AsyncSession, None]: async with
AsyncSession(engine_async)
sqlmodel.ext.asyncio.session.AsyncSession
from typing import AsyncGenerator, Generator from aiobotocore.client import AioBaseClient from aiobotocore.session import get_session from sqlmodel import Session from sqlmodel.ext.asyncio.session import AsyncSession from ..core.config import settings from ..db.db import engine, engine_async async def get_s3() -> AsyncGenerator[AioBaseClient, None]: session = get_session() async with session.create_client( "s3", region_name=settings.MINIO_REGION_NAME, endpoint_url=settings.MINIO_URL, use_ssl=False, aws_secret_access_key=settings.MINIO_SECRET_KEY, aws_access_key_id=settings.MINIO_ACCESS_KEY, ) as client: yield client async def get_db_async() -> AsyncGenerator[AsyncSession, None]: async with AsyncSession(engine_async) as session: yield session def get_db() -> Generator[Session, None, None]: with
Session(engine)
sqlmodel.Session
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine =
create_engine(url="sqlite:///users.db", echo=True)
sqlmodel.create_engine
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=True) class User(SQLModel, table=True): id:Optional[int] =
Field(None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=True) class User(SQLModel, table=True): id:Optional[int] = Field(None, primary_key=True) username: str password:str def get_session(): with Session(engine) as session: yield session def init_db():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from sqlmodel import SQLModel, Field, create_engine, Session engine = create_engine(url="sqlite:///users.db", echo=True) class User(SQLModel, table=True): id:Optional[int] = Field(None, primary_key=True) username: str password:str def get_session(): with
Session(engine)
sqlmodel.Session
from typing import Optional from sqlalchemy import create_engine, select from sqlalchemy.orm import Session from sqlmodel import Field, SQLModel def test_allow_instantiation_without_arguments(clear_sqlmodel): class Item(SQLModel): id: Optional[int] = Field(default=None, primary_key=True) name: str description: Optional[str] = None class Config: table = True engine = create_engine("sqlite:///:memory:")
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional from sqlalchemy import create_engine, select from sqlalchemy.orm import Session from sqlmodel import Field, SQLModel def test_allow_instantiation_without_arguments(clear_sqlmodel): class Item(SQLModel): id: Optional[int] = Field(default=None, primary_key=True) name: str description: Optional[str] = None class Config: table = True engine = create_engine("sqlite:///:memory:") SQLModel.metadata.create_all(engine) with Session(engine) as db: item = Item() item.name = "Rick" db.add(item) db.commit() result = db.execute(select(Item)).scalars().all() assert len(result) == 1 assert isinstance(item.id, int)
SQLModel.metadata.clear()
sqlmodel.SQLModel.metadata.clear
from typing import Optional from sqlalchemy import create_engine, select from sqlalchemy.orm import Session from sqlmodel import Field, SQLModel def test_allow_instantiation_without_arguments(clear_sqlmodel): class Item(SQLModel): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
"""Initial Revision ID: ec941f1f8242 Revises: <PASSWORD> Create Date: 2021-10-10 18:34:18.294594 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '<KEY>' down_revision = 'd<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('plant', sa.Column('id', sa.Integer(), nullable=True), sa.Column('name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from datetime import datetime from typing import Optional from sqlmodel import Field, SQLModel, Relationship from sqlalchemy import Column from sqlalchemy.dialects.postgresql import JSON class ZeroShotInferenceBase(SQLModel): text: str =
Field(nullable=False, index=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from sqlmodel import Field, SQLModel, Relationship from sqlalchemy import Column from sqlalchemy.dialects.postgresql import JSON class ZeroShotInferenceBase(SQLModel): text: str = Field(nullable=False, index=True) candidate_labels: list[str] = Field( nullable=False, index=True, sa_column=Column(JSON) ) class ZeroShotInference(ZeroShotInferenceBase, table=True): id: Optional[int] =
Field(default=None, nullable=False, primary_key=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from sqlmodel import Field, SQLModel, Relationship from sqlalchemy import Column from sqlalchemy.dialects.postgresql import JSON class ZeroShotInferenceBase(SQLModel): text: str = Field(nullable=False, index=True) candidate_labels: list[str] = Field( nullable=False, index=True, sa_column=Column(JSON) ) class ZeroShotInference(ZeroShotInferenceBase, table=True): id: Optional[int] = Field(default=None, nullable=False, primary_key=True) result: dict[str, float] = Field(nullable=False, sa_column=Column(JSON)) created_at: Optional[datetime] updated_at: Optional[datetime] created_by_id: Optional[int] =
Field(default=None, foreign_key="user.id")
sqlmodel.Field
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine =
create_engine(dsn)
sqlmodel.create_engine
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine = create_engine(dsn) return engine @pytest.fixture(scope="function") def connection(sql_engine): """sql_engine connection""" metadata = MetaData() metadata.reflect(sql_engine) metadata.drop_all(sql_engine) connection = sql_engine.connect() yield connection connection.close() @pytest.fixture(scope="function") def session(connection): transaction = connection.begin() session =
Session(bind=connection, autocommit=False, autoflush=True)
sqlmodel.Session
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine = create_engine(dsn) return engine @pytest.fixture(scope="function") def connection(sql_engine): """sql_engine connection""" metadata = MetaData() metadata.reflect(sql_engine) metadata.drop_all(sql_engine) connection = sql_engine.connect() yield connection connection.close() @pytest.fixture(scope="function") def session(connection): transaction = connection.begin() session = Session(bind=connection, autocommit=False, autoflush=True) yield session transaction.rollback() transaction.close() session.close() @pytest.fixture(scope="function") def seed_db(connection): connection.execute(
text("CREATE table users (id serial primary key, name text);")
sqlmodel.text
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine = create_engine(dsn) return engine @pytest.fixture(scope="function") def connection(sql_engine): """sql_engine connection""" metadata = MetaData() metadata.reflect(sql_engine) metadata.drop_all(sql_engine) connection = sql_engine.connect() yield connection connection.close() @pytest.fixture(scope="function") def session(connection): transaction = connection.begin() session = Session(bind=connection, autocommit=False, autoflush=True) yield session transaction.rollback() transaction.close() session.close() @pytest.fixture(scope="function") def seed_db(connection): connection.execute(text("CREATE table users (id serial primary key, name text);")) for user in range(100): connection.execute(text(f"INSERT into users(name) values ('user_{user}');")) connection.commit() yield connection.execute(
text("drop table users;")
sqlmodel.text
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine = create_engine(dsn) return engine @pytest.fixture(scope="function") def connection(sql_engine): """sql_engine connection""" metadata = MetaData() metadata.reflect(sql_engine) metadata.drop_all(sql_engine) connection = sql_engine.connect() yield connection connection.close() @pytest.fixture(scope="function") def session(connection): transaction = connection.begin() session = Session(bind=connection, autocommit=False, autoflush=True) yield session transaction.rollback() transaction.close() session.close() @pytest.fixture(scope="function") def seed_db(connection): connection.execute(text("CREATE table users (id serial primary key, name text);")) for user in range(100): connection.execute(text(f"INSERT into users(name) values ('user_{user}');")) connection.commit() yield connection.execute(text("drop table users;")) connection.commit() @pytest.fixture(scope="function") def make_db(connection): pass metadata = MetaData() metadata.reflect(connection) metadata.drop_all(connection) BaseEntity.metadata.create_all(connection) connection.commit() yield BaseEntity.metadata.drop_all(connection) connection.commit() @pytest.fixture(scope="function") def raw_connection(make_db, sql_engine): raw = sql_engine.raw_connection() yield raw raw.close() @pytest.fixture(scope="function") def raw_pg3_connection(make_db, sql_engine): connection = pg3_connect(str(sql_engine.url)) yield connection connection.close() @pytest.fixture def debug_logger(): custom_logger = logging.getLogger("dbgen") custom_logger.propagate = True custom_logger.setLevel(logging.DEBUG) log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s Test" formatter = logging.Formatter(log_format) console_handler = logging.StreamHandler(stream=sys.stdout) console_handler.setFormatter(formatter) custom_logger.addHandler(console_handler) return custom_logger @pytest.fixture(scope='function') def recreate_meta(connection): connection.execute(
text(f'create schema if not exists {config.meta_schema}')
sqlmodel.text
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import os import sys import pytest from psycopg import connect as pg3_connect from sqlalchemy import MetaData from sqlmodel import Session, create_engine, text from dbgen.configuration import config from dbgen.core.entity import BaseEntity from dbgen.core.metadata import meta_registry @pytest.fixture() def clear_registry(): # Clear the tables in the metadata for the default base model BaseEntity.metadata.clear() # Clear the Models associated with the registry, to avoid warnings BaseEntity._sa_registry.dispose() yield BaseEntity.metadata.clear() BaseEntity._sa_registry.dispose() @pytest.fixture(scope="module") def sql_engine(): dsn = os.environ.get('TEST_DSN', config.main_dsn) engine = create_engine(dsn) return engine @pytest.fixture(scope="function") def connection(sql_engine): """sql_engine connection""" metadata = MetaData() metadata.reflect(sql_engine) metadata.drop_all(sql_engine) connection = sql_engine.connect() yield connection connection.close() @pytest.fixture(scope="function") def session(connection): transaction = connection.begin() session = Session(bind=connection, autocommit=False, autoflush=True) yield session transaction.rollback() transaction.close() session.close() @pytest.fixture(scope="function") def seed_db(connection): connection.execute(text("CREATE table users (id serial primary key, name text);")) for user in range(100): connection.execute(
text(f"INSERT into users(name) values ('user_{user}');")
sqlmodel.text
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID =
Field(foreign_key="tenant.id", index=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str =
Field(nullable=True, index=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool =
Field(nullable=False, default=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool =
Field(nullable=False, default=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str =
Field(nullable=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str =
Field(nullable=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID =
Field(foreign_key="tenant.id", nullable=False, index=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str =
Field(nullable=True, index=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str =
Field(nullable=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool =
Field(nullable=False, default=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger(ish) data --- transaction_id: str =
Field(nullable=True)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger(ish) data --- transaction_id: str = Field(nullable=True) tag: str =
Field(nullable=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger(ish) data --- transaction_id: str = Field(nullable=True) tag: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) revocation_enabled: bool =
Field(nullable=False, default=False)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger(ish) data --- transaction_id: str = Field(nullable=True) tag: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) revocation_enabled: bool = Field(nullable=False, default=False) revocation_registry_size: int =
Field(nullable=True, default=None)
sqlmodel.Field
"""Governance Database Tables/Models. Models of the Traction tables for Governance and related data. This includes ledger related tables for schemas and credential definitions. """ import uuid from datetime import datetime from typing import List from sqlmodel import Field, Relationship from sqlalchemy import ( Column, func, String, select, desc, text, UniqueConstraint, ) from sqlalchemy.dialects.postgresql import TIMESTAMP, ARRAY, UUID from sqlmodel.ext.asyncio.session import AsyncSession from api.db.models.base import BaseModel from api.endpoints.models.v1.errors import ( NotFoundError, ) class SchemaTemplate(BaseModel, table=True): """SchemaTemplate. This is the model for the Schema table (postgresql specific dialects in use). Schemas are registered on the ledger, so there can be only one... However, each Tenant can import the same schema for their own purposes. For now, there will be redundancy in the Schema data, we are going to wait on usage to determine if we need to normalize and have a singular table for Schemas for all and then join table for Schema/Tenant. There is already a table for v0 API named tenantschema and this is named differently to avoid confusion and interference. When v0 is retired/deleted, perhaps we change the name then... For a given tenant, the schema can be found by the schema_template_id (Traction id) or schema_id (ledger id). Attributes: schema_template_id: Traction ID tenant_id: Traction Tenant ID, owner of this Contact schema_id: This will be the ledger schema id - this is not a UUID name: a "pretty" name for the schema, this can be different than the name on the ledger (schema_name). status: Status of the schema as it is being endorsed and registered tags: Set by tenant for arbitrary grouping of their Schemas deleted: Schema/Tenant "soft" delete indicator. imported: When True, this tenant imported the schema, otherwise they created it version: version, on ledger attributes: list of attribute names, on ledger schema_name: name as is appears on the ledger transaction_id: id used when schema is being endorsed and registered state: The underlying AcaPy endorser state created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "schema_template" __table_args__ = (UniqueConstraint("tenant_id", "schema_id"),) schema_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", index=True) schema_id: str = Field(nullable=True, index=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) imported: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger data --- version: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) schema_name: str = Field(nullable=True) transaction_id: str = Field(nullable=True) # --- ledger data created_at: datetime = Field( sa_column=Column(TIMESTAMP, nullable=False, server_default=func.now()) ) updated_at: datetime = Field( sa_column=Column( TIMESTAMP, nullable=False, server_default=func.now(), onupdate=func.now() ) ) @classmethod async def get_by_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_template_id: uuid.UUID, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_template_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_template_id: Traction ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_template_id == schema_template_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for id<{schema_template_id}>", ) return db_rec @classmethod async def get_by_schema_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, schema_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by schema_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call schema_id: Ledger Schema ID of Schema Template Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.schema_id == schema_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.schema_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for schema_id<{schema_id}>", ) return db_rec @classmethod async def get_by_transaction_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, transaction_id: str, deleted: bool | None = False, ) -> "SchemaTemplate": """Get SchemaTemplate by transaction_id. Find and return the database SchemaTemplate record Args: db: database session tenant_id: Traction ID of tenant making the call transaction_id: Transaction ID from endorser Returns: The Traction SchemaTemplate (db) record Raises: NotFoundError: if the SchemaTemplate cannot be found by schema ID and deleted flag """ q = ( select(cls) .where(cls.tenant_id == tenant_id) .where(cls.transaction_id == transaction_id) .where(cls.deleted == deleted) ) q_result = await db.execute(q) db_rec = q_result.scalar_one_or_none() if not db_rec: raise NotFoundError( code="schema_template.transaction_id_not_found", title="Schema Template does not exist", detail=f"Schema Template does not exist for transaction_id<{transaction_id}>", # noqa: E501 ) return db_rec @classmethod async def list_by_tenant_id( cls: "SchemaTemplate", db: AsyncSession, tenant_id: uuid.UUID, ) -> List["SchemaTemplate"]: """List by Tenant ID. Find and return list of SchemaTemplate records for Tenant. Args: db: database session tenant_id: Traction ID of Tenant Returns: List of Traction SchemaTemplate (db) records in descending order """ q = select(cls).where(cls.tenant_id == tenant_id).order_by(desc(cls.updated_at)) q_result = await db.execute(q) db_recs = q_result.scalars() return db_recs class CredentialTemplate(BaseModel, table=True): """Credential Template. Model for the Credential Definition table (postgresql specific dialects in use). This will track Credential Definitions for the Tenants. For a given tenant, the Credential Tempalte can be found by the credential_template_id (Traction id) or cred_def_id (ledger id). Attributes: credential_template_id: Traction ID tenant_id: Traction Tenant ID schema_template_id: Traction ID for Schema Template cred_def_id: Credential Definition ID from the ledger schema_id: Ledger ID of Schema this credential definition is for name: based on SchemaTemplate.name, but allow override here... status: Status of the credential definition as it is being endorsed and registered deleted: Credential Definition "soft" delete indicator. transaction_id: id used when schema is being endorsed and registered tags: Set by tenant for arbitrary grouping of Credential Templates/Definitions tag: tag used to create the credential definition (on ledger) attributes: list of attribute names (on ledger) state: The underlying AcaPy endorser state revocation_enabled: when True, subsequent Credentials can be revoked. revocation_registry_size: how large the default revocation registry is revocation_registry_state: The underlying AcaPy endorser state for revocation created_at: Timestamp when record was created in Traction updated_at: Timestamp when record was last modified in Traction """ __tablename__ = "credential_template" credential_template_id: uuid.UUID = Field( sa_column=Column( UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"), ) ) tenant_id: uuid.UUID = Field(foreign_key="tenant.id", nullable=False, index=True) schema_template_id: uuid.UUID = Field( foreign_key="schema_template.schema_template_id", nullable=False, index=True ) cred_def_id: str = Field(nullable=True, index=True) schema_id: str = Field(nullable=True) name: str = Field(nullable=False) status: str = Field(nullable=False) tags: List[str] = Field(sa_column=Column(ARRAY(String))) deleted: bool = Field(nullable=False, default=False) state: str = Field(nullable=False) # ledger(ish) data --- transaction_id: str = Field(nullable=True) tag: str = Field(nullable=False) attributes: List[str] = Field(sa_column=Column(ARRAY(String))) revocation_enabled: bool = Field(nullable=False, default=False) revocation_registry_size: int = Field(nullable=True, default=None) revocation_registry_state: str =
Field(nullable=False)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str =
Field(max_length=100, sa_column_kwargs={"unique": True})
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str =
Field(max_length=150, sa_column_kwargs={"unique": True})
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool =
Field(default=False)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str =
Field(max_length=100)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] =
Field(max_length=100)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] =
Field(default=None)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] =
Field(default=None)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] =
Field(default=None)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] =
Field(default=None)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int =
Field(default=0)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int = Field(default=0) """The user's discussion count.""" comment_count: int =
Field(default=0)
sqlmodel.Field
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int = Field(default=0) """The user's discussion count.""" comment_count: int = Field(default=0) """The user's comment (post) count.""" access_tokens: t.List['DB_AccessToken'] =
Relationship(back_populates='user')
sqlmodel.Relationship
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int = Field(default=0) """The user's discussion count.""" comment_count: int = Field(default=0) """The user's comment (post) count.""" access_tokens: t.List['DB_AccessToken'] = Relationship(back_populates='user') """List of access tokens belonging to this user.""" api_keys: t.List['DB_APIKey'] =
Relationship(back_populates='user')
sqlmodel.Relationship
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int = Field(default=0) """The user's discussion count.""" comment_count: int = Field(default=0) """The user's comment (post) count.""" access_tokens: t.List['DB_AccessToken'] = Relationship(back_populates='user') """List of access tokens belonging to this user.""" api_keys: t.List['DB_APIKey'] = Relationship(back_populates='user') """List of API keys that perform actions on behalf of this user.""" discussions: t.List['DB_Discussion'] =
Relationship(back_populates='author')
sqlmodel.Relationship
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=Column(JSON), default={"notify_discussionRenamed_alert": True,"notify_postLiked_alert": True,"notify_discussionLocked_alert": True,"notify_postMentioned_alert": True,"notify_postMentioned_email": False,"notify_userMentioned_alert": True,"notify_userMentioned_email": False,"notify_newPost_alert": True, "notify_newPost_email": True, "notify_userSuspended_alert": True, "notify_userUnsuspended_alert": True, "followAfterReply": True, "discloseOnline": True, "indexProfile": True, "locale": None }) """The user's preferences (e. g.: for notifications).""" joined_at: t.Optional[datetime] = Field(default=None) """When did the user join the forum.""" last_seen_at: t.Optional[datetime] = Field(default=None) """When was the user last seen at.""" marked_all_as_read_at: t.Optional[datetime] = Field(default=None) """When did the user mark all discussions as read.""" read_notifications_at: t.Optional[datetime] = Field(default=None) """When did the user read their notifications.""" discussion_count: int = Field(default=0) """The user's discussion count.""" comment_count: int = Field(default=0) """The user's comment (post) count.""" access_tokens: t.List['DB_AccessToken'] = Relationship(back_populates='user') """List of access tokens belonging to this user.""" api_keys: t.List['DB_APIKey'] = Relationship(back_populates='user') """List of API keys that perform actions on behalf of this user.""" discussions: t.List['DB_Discussion'] = Relationship(back_populates='author') """List of discussions that this user made.""" tags: t.List['DB_Tag'] =
Relationship(back_populates='users', link_model=DB_TagUser)
sqlmodel.Relationship
import typing as t if t.TYPE_CHECKING: from .other import DB_AccessToken, DB_APIKey from .discussions import DB_Discussion from datetime import datetime from sqlmodel import SQLModel, Field, Relationship, Column, JSON from ..extensions.tags import DB_Tag, DB_TagUser class DB_User(SQLModel, table=True): __tablename__ = 'users' id: t.Optional[int] = Field(default=None, primary_key=True) """The ID of the user. This is handled by the database.""" username: str = Field(max_length=100, sa_column_kwargs={"unique": True}) """The user's username.""" email: str = Field(max_length=150, sa_column_kwargs={"unique": True}) """The user's E-mail address.""" is_email_confirmed: bool = Field(default=False) """Whether or not the user confirmed their E-mail address.""" password: str = Field(max_length=100) """The user's password (<PASSWORD>).""" avatar_url: t.Optional[str] = Field(max_length=100) """The file name of user's avatar. Avatars are located in the `public/assets/avatars` directory of your forum root.""" preferences: t.Dict[str, bool] = Field(sa_column=
Column(JSON)
sqlmodel.Column
# Creazione entità "base", editor support, creazione, id automatici # https://sqlmodel.tiangolo.com/tutorial/insert/ from typing import Optional from sqlmodel import Field, SQLModel, Session, create_engine class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
# Creazione entità "base", editor support, creazione, id automatici # https://sqlmodel.tiangolo.com/tutorial/insert/ from typing import Optional from sqlmodel import Field, SQLModel, Session, create_engine class Tag(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Creazione entità "base", editor support, creazione, id automatici # https://sqlmodel.tiangolo.com/tutorial/insert/ from typing import Optional from sqlmodel import Field, SQLModel, Session, create_engine class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProductType(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Creazione entità "base", editor support, creazione, id automatici # https://sqlmodel.tiangolo.com/tutorial/insert/ from typing import Optional from sqlmodel import Field, SQLModel, Session, create_engine class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str 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
# Creazione entità "base", editor support, creazione, id automatici # https://sqlmodel.tiangolo.com/tutorial/insert/ from typing import Optional from sqlmodel import Field, SQLModel, Session, create_engine class Tag(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProductType(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str 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_nomayo = Tag(name="No mayo") tipo_panino = ProductType(name="panino") tipo_bibita = ProductType(name="bibita") with
Session(engine)
sqlmodel.Session
from sqlmodel import create_engine engine =
create_engine("sqlite:///database.db")
sqlmodel.create_engine
from typing import Optional from sqlmodel import Field, SQLModel from fastapi_server.models.user import User class ChatMessage(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel from fastapi_server.models.user import User class ChatMessage(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) timestamp: int message: str user_id: int =
Field(foreign_key='user.id')
sqlmodel.Field
"""add school abbreviations and acronyms Revision ID: 41f361ac6a74 Revises: c<PASSWORD> Create Date: 2022-06-07 03:48:15.445488+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "41f361ac6a74" down_revision = "c1b1ed99e50d" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "schools", sa.Column( "abbreviations", postgresql.ARRAY(
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add school abbreviations and acronyms Revision ID: 41f361ac6a74 Revises: c<PASSWORD> Create Date: 2022-06-07 03:48:15.445488+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "41f361ac6a74" down_revision = "c1b1ed99e50d" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "schools", sa.Column( "abbreviations", postgresql.ARRAY(sqlmodel.sql.sqltypes.AutoString()), nullable=False, server_default=sa.text("array[]::varchar[]"), ), ) op.add_column( "schools", sa.Column( "alternatives", postgresql.ARRAY(
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""v1-tenant_token Revision ID: <KEY> Revises: <KEY> Create Date: 2022-05-18 14:55:32.794587 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): op.add_column( "tenant", sa.Column("wallet_token",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from typing import Any, Dict, List, Optional, Union from pydantic.networks import EmailStr from app.crud.base_sqlmodel import CRUDBase from sqlmodel.ext.asyncio.session import AsyncSession from sqlmodel import select from app.schemas.user import IUserCreate, IUserUpdate from app.models.user import User from app.core.security import verify_password, get_password_hash from datetime import datetime class CRUDUser(CRUDBase[User, IUserCreate, IUserUpdate]): async def get_by_email( self, db_session: AsyncSession, *, email: str ) -> Optional[User]: users = await db_session.exec(
select(User)
sqlmodel.select
"""v1-contact-invitation-key Revision ID: <KEY> Revises: e40469d1045a Create Date: 2022-05-11 15:23:29.495804 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "<KEY>" down_revision = "e40469d1045a" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "contact", sa.Column("invitation_key",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from typing import Optional from sqlalchemy import UniqueConstraint from sqlmodel import Field, Relationship, SQLModel from db.base import BaseDBModel from model.item import Item from model.warehouse import Warehouse class InventoryEditableFields(SQLModel): item_id: int =
Field(foreign_key="item.id")
sqlmodel.Field
from typing import Optional from sqlalchemy import UniqueConstraint from sqlmodel import Field, Relationship, SQLModel from db.base import BaseDBModel from model.item import Item from model.warehouse import Warehouse class InventoryEditableFields(SQLModel): item_id: int = Field(foreign_key="item.id") warehouse_id: int =
Field(foreign_key="warehouse.id")
sqlmodel.Field
from typing import Optional from sqlalchemy import UniqueConstraint from sqlmodel import Field, Relationship, SQLModel from db.base import BaseDBModel from model.item import Item from model.warehouse import Warehouse class InventoryEditableFields(SQLModel): item_id: int = Field(foreign_key="item.id") warehouse_id: int = Field(foreign_key="warehouse.id") quantity: float class Inventory(BaseDBModel, InventoryEditableFields, table=True): __table_args__ = (UniqueConstraint("id", "item_id", "warehouse_id"),) item: Optional[Item] =
Relationship(back_populates="item_inventories")
sqlmodel.Relationship
from typing import Optional from sqlalchemy import UniqueConstraint from sqlmodel import Field, Relationship, SQLModel from db.base import BaseDBModel from model.item import Item from model.warehouse import Warehouse class InventoryEditableFields(SQLModel): item_id: int = Field(foreign_key="item.id") warehouse_id: int = Field(foreign_key="warehouse.id") quantity: float class Inventory(BaseDBModel, InventoryEditableFields, table=True): __table_args__ = (UniqueConstraint("id", "item_id", "warehouse_id"),) item: Optional[Item] = Relationship(back_populates="item_inventories") warehouse: Optional[Warehouse] =
Relationship(back_populates="warehouse_inventories")
sqlmodel.Relationship
import logging from sqlmodel import SQLModel, create_engine import json from dataclasses import dataclass from etl.stores import run as etl_stores from etl.sales import run as etl_sales from etl.products import run as etl_products # config to define variables @dataclass class Config: stores_url: str stores_filepath: str db_conn_uri: str log_level: str # TODO convert this to a DAG or a pipeline if __name__ == '__main__': # load the config config_dict = {} with open('config.json', 'r') as f: config_dict = json.load(f) if config_dict['log_level'] == 'DEBUG': config_dict['log_level'] = logging.DEBUG else: config_dict['log_level'] = logging.INFO # create the config object config = Config(**config_dict) # setup logging logging.basicConfig() logging.getLogger().setLevel(config.log_level) # create the database engine engine =
create_engine(config.db_conn_uri)
sqlmodel.create_engine
import logging from sqlmodel import SQLModel, create_engine import json from dataclasses import dataclass from etl.stores import run as etl_stores from etl.sales import run as etl_sales from etl.products import run as etl_products # config to define variables @dataclass class Config: stores_url: str stores_filepath: str db_conn_uri: str log_level: str # TODO convert this to a DAG or a pipeline if __name__ == '__main__': # load the config config_dict = {} with open('config.json', 'r') as f: config_dict = json.load(f) if config_dict['log_level'] == 'DEBUG': config_dict['log_level'] = logging.DEBUG else: config_dict['log_level'] = logging.INFO # create the config object config = Config(**config_dict) # setup logging logging.basicConfig() logging.getLogger().setLevel(config.log_level) # create the database engine engine = create_engine(config.db_conn_uri) # create the sqlmodel metadata for the engine
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Any import sqlalchemy.exc from ariadne import convert_kwargs_to_snake_case from graphql.type.definition import GraphQLResolveInfo from graphql_relay.node.node import from_global_id from sqlmodel import select from ariadne_example.app.db.session import Session, engine from ariadne_example.app.core.struсtures import TaskStatusEnum, TASK_QUEUES from ariadne_example.app.models import Task from ariadne_example.app.core.exceptions import NotFoundError @convert_kwargs_to_snake_case def resolve_create_task( obj: Any, info: GraphQLResolveInfo, user_id: str, task_input: dict, ) -> int: with Session(engine) as session: local_user_id, _ = from_global_id(user_id) try: task = Task( title=task_input.get("title"), created_at=task_input.get("created_at"), status=task_input.get("status"), user_id=local_user_id ) session.add(task) session.commit() session.refresh(task) except sqlalchemy.exc.IntegrityError: raise NotFoundError(msg='Не найден пользователь с таким user_id') return task.id @convert_kwargs_to_snake_case async def resolve_change_task_status( obj: Any, info: GraphQLResolveInfo, new_status: TaskStatusEnum, task_id: str, ) -> None: with Session(engine) as session: local_task_id, _ = from_global_id(task_id) try: statement =
select(Task)
sqlmodel.select
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "steam_app", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("type",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "steam_app", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("type", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("is_free", sa.Boolean(), nullable=True), sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "steam_app", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("type", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("is_free", sa.Boolean(), nullable=True), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column( "controller_support",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "steam_app", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("type", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("is_free", sa.Boolean(), nullable=True), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column( "controller_support", sqlmodel.sql.sqltypes.AutoString(), nullable=True, ), sa.Column("metacritic_score", sa.Integer(), nullable=True), sa.Column( "metacritic_url",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init Revision ID: fb8ce6ce7c6b Revises: Create Date: 2021-11-27 16:52:18.035895 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "fb8ce6ce7c6b" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "appid_error", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("reason", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.PrimaryKeyConstraint("pk"), sa.UniqueConstraint("appid"), ) op.create_table( "category", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "genre", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("id", sa.Integer(), nullable=False), sa.Column( "description", sqlmodel.sql.sqltypes.AutoString(), nullable=False ), sa.PrimaryKeyConstraint("pk"), ) op.create_table( "steam_app", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("appid", sa.Integer(), nullable=False), sa.Column("type", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("is_free", sa.Boolean(), nullable=True), sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column( "controller_support", sqlmodel.sql.sqltypes.AutoString(), nullable=True, ), sa.Column("metacritic_score", sa.Integer(), nullable=True), sa.Column( "metacritic_url", sqlmodel.sql.sqltypes.AutoString(), nullable=True ), sa.Column("recommendations", sa.Integer(), nullable=True), sa.Column("achievements_total", sa.Integer(), nullable=True), sa.Column("release_date", sa.Date(), nullable=True), sa.Column("created", sa.DateTime(), nullable=False), sa.Column("updated", sa.DateTime(), nullable=False), sa.PrimaryKeyConstraint("pk"), ) op.create_index( op.f("ix_steam_app_appid"), "steam_app", ["appid"], unique=True ) op.create_index( op.f("ix_steam_app_name"), "steam_app", ["name"], unique=False ) op.create_table( "achievement", sa.Column("pk", sa.Integer(), nullable=True), sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str =
Field(description="Item code", min_length=1)
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str =
Field(description="Item Name", min_length=1)
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] =
Field(description="Production/Buy cost of the item", ge=0)
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat =
Field(description="Sugested sell value of item")
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat = Field(description="Sugested sell value of item") amount: int =
Field(default=0, description="Quantity of itens avaliable", ge=0)
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat = Field(description="Sugested sell value of item") amount: int = Field(default=0, description="Quantity of itens avaliable", ge=0) class CreateItem(BaseItem): @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): if "," in value and "." not in value: value = value.replace(",", ".") value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class UpdateItem(BaseItem): id: UUID =
Field(description="ID do item")
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat = Field(description="Sugested sell value of item") amount: int = Field(default=0, description="Quantity of itens avaliable", ge=0) class CreateItem(BaseItem): @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): if "," in value and "." not in value: value = value.replace(",", ".") value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class UpdateItem(BaseItem): id: UUID = Field(description="ID do item") @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class QueryItem(SQLModel): name: Optional[str] =
Field(description="Name of the item for query")
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat = Field(description="Sugested sell value of item") amount: int = Field(default=0, description="Quantity of itens avaliable", ge=0) class CreateItem(BaseItem): @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): if "," in value and "." not in value: value = value.replace(",", ".") value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class UpdateItem(BaseItem): id: UUID = Field(description="ID do item") @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class QueryItem(SQLModel): name: Optional[str] = Field(description="Name of the item for query") code: Optional[str] =
Field(description="Code of the item for query")
sqlmodel.Field
from typing import TYPE_CHECKING, Any, Dict, Optional, Union from uuid import UUID, uuid4 from pydantic import PositiveFloat, validator from sqlmodel import Column, Field, Relationship, SQLModel from sqlmodel.sql.sqltypes import GUID if TYPE_CHECKING: from .user import User class BaseItem(SQLModel): code: str = Field(description="Item code", min_length=1) name: str = Field(description="Item Name", min_length=1) cost: Optional[float] = Field(description="Production/Buy cost of the item", ge=0) value: PositiveFloat = Field(description="Sugested sell value of item") amount: int = Field(default=0, description="Quantity of itens avaliable", ge=0) class CreateItem(BaseItem): @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): if "," in value and "." not in value: value = value.replace(",", ".") value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class UpdateItem(BaseItem): id: UUID = Field(description="ID do item") @validator("value") def validate_value(cls, value: Union[str, float], values: Dict[str, Any]) -> float: if isinstance(value, str): value = float(value) if (values.get("cost") or 0) >= value: raise ValueError("The sugested sell value must be higher then buy value!") return value class QueryItem(SQLModel): name: Optional[str] = Field(description="Name of the item for query") code: Optional[str] = Field(description="Code of the item for query") avaliable: Optional[bool] =
Field(description="Flag to identify if the item is avaliable")
sqlmodel.Field