prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
from sqlmodel import create_engine, SQLModel, Session sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" connect_args = {"check_same_thread": False} engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) def init_db(): SQLModel.metadata.create_all(engine) def get_session(): with
Session(engine)
sqlmodel.Session
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional[Weapon] = Relationship(back_populates="owner") powers: List[Power] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" =
Relationship(back_populates="weapon")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int =
Field(foreign_key="hero.id")
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" =
Relationship(back_populates="powers")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] =
Relationship(back_populates="team")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] =
Field(default=None, foreign_key="team.id")
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] =
Relationship(back_populates="heroes")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] =
Field(default=None, foreign_key="weapon.id")
sqlmodel.Field
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional[Weapon] =
Relationship(back_populates="owner")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional[Weapon] = Relationship(back_populates="owner") powers: List[Power] =
Relationship(back_populates="hero")
sqlmodel.Relationship
from typing import List, Optional from sqlmodel import Field, Relationship, SQLModel, create_engine class Weapon(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero: "Hero" = Relationship(back_populates="weapon") class Power(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str hero_id: int = Field(foreign_key="hero.id") hero: "Hero" = Relationship(back_populates="powers") class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str heroes: List["Hero"] = Relationship(back_populates="team") class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") team: Optional[Team] = Relationship(back_populates="heroes") weapon_id: Optional[int] = Field(default=None, foreign_key="weapon.id") weapon: Optional[Weapon] = Relationship(back_populates="owner") powers: List[Power] = Relationship(back_populates="hero") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from sqlmodel import SQLModel, Field import datetime from typing import Optional class Orders(SQLModel, table=True): invoice_no: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Imports from standard library import os from typing import Optional, Union import asyncio import time import sqlite3 import hashlib # Import these utilities from utils.merkletree import MerkleTree, MerkleError # Import the HTTP app server from fastapi import FastAPI, BackgroundTasks ################################## from sqlmodel import Field, SQLModel, create_engine class MerkleTable(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
# Imports from standard library import os from typing import Optional, Union import asyncio import time import sqlite3 import hashlib # Import these utilities from utils.merkletree import MerkleTree, MerkleError # Import the HTTP app server from fastapi import FastAPI, BackgroundTasks ################################## from sqlmodel import Field, SQLModel, create_engine class MerkleTable(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) timestamp: int ngsi_id_hash: str ngsi_value_hash: str ngsi_receipt: Optional[str] = None # The table scripts drop_table_script = """ DROP TABLE IF EXISTS testing; """ create_table_script = """ CREATE TABLE IF NOT EXISTS testing ( id INTEGER PRIMARY KEY, timestamp INTEGER NOT NULL, ngsi_id_hash TEXT NOT NULL, ngsi_value_hash TEXT NOT NULL, ngsi_receipt TEXT ); """ set_journal_wal = 'PRAGMA journal_mode=WAL' query_journal_mode = """PRAGMA journal_mode""" class MerkleBuffer: def __init__(self, db_name: str = 'mkbuffer.db', # Name of the database db_max_elements: int = 10000, # Maximum size of database, in number of records maxLeaves: int = 1024, # Maximum number of leaves of the Merkle Tree to notarize maxInterval: int = 60, # Notarize every maxInterval (seconds) even if not enough leaves received yet durability: int = 10 # Commit database every durability seconds, to make data permanent ) -> None: self.db_name = db_name self.maxLeaves = maxLeaves self.db_max_elements = db_max_elements self.maxInterval = maxInterval self.durability = durability self.next_record = 1 self.leaves = 0 self.last_notarization = time.time() print(f'MaxLeaves: {maxLeaves}') self.open() # Create a background task which commits the db every durability secs (or 2 sec as a minimum), # and registers the Merkle Tree even if not enough entries have been received if durability > 0 or maxInterval > 0: self.commit_task = asyncio.create_task(self.commit_background_task(min(durability, maxInterval))) def db_name(self): self.db_name def open(self): sqlite_file_name = "sqlmodel.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
from enum import Enum from typing import Optional from sqlmodel import Field, SQLModel class ExtensionType(str, Enum): DOCKER = 'DOCKER' WEBHOOK = 'WEBHOOK' BINARY = 'BINARY' class Extension(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import TYPE_CHECKING, List, Optional from uuid import UUID from sqlalchemy import event from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlmodel import Field, Relationship from sqlmodel.sql.sqltypes import GUID from joj.horse.models.base import DomainURLORMModel, url_pre_save from joj.horse.models.link_tables import ProblemProblemSetLink from joj.horse.schemas.base import Operation from joj.horse.schemas.problem_set import ProblemSetDetail from joj.horse.utils.errors import BizError, ErrorCode if TYPE_CHECKING: from joj.horse.models import Domain, Problem, Record, User class ProblemSet(DomainURLORMModel, ProblemSetDetail, table=True): # type: ignore[call-arg] __tablename__ = "problem_sets" __table_args__ = (UniqueConstraint("domain_id", "url"),) domain_id: UUID = Field( sa_column=Column( GUID, ForeignKey("domains.id", ondelete="CASCADE"), nullable=False ) ) domain: "Domain" =
Relationship(back_populates="problem_sets")
sqlmodel.Relationship
from typing import TYPE_CHECKING, List, Optional from uuid import UUID from sqlalchemy import event from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlmodel import Field, Relationship from sqlmodel.sql.sqltypes import GUID from joj.horse.models.base import DomainURLORMModel, url_pre_save from joj.horse.models.link_tables import ProblemProblemSetLink from joj.horse.schemas.base import Operation from joj.horse.schemas.problem_set import ProblemSetDetail from joj.horse.utils.errors import BizError, ErrorCode if TYPE_CHECKING: from joj.horse.models import Domain, Problem, Record, User class ProblemSet(DomainURLORMModel, ProblemSetDetail, table=True): # type: ignore[call-arg] __tablename__ = "problem_sets" __table_args__ = (UniqueConstraint("domain_id", "url"),) domain_id: UUID = Field( sa_column=Column( GUID, ForeignKey("domains.id", ondelete="CASCADE"), nullable=False ) ) domain: "Domain" = Relationship(back_populates="problem_sets") owner_id: Optional[UUID] = Field( sa_column=Column( GUID, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, ) ) owner: Optional["User"] =
Relationship(back_populates="owned_problem_sets")
sqlmodel.Relationship
from typing import TYPE_CHECKING, List, Optional from uuid import UUID from sqlalchemy import event from sqlalchemy.ext.orderinglist import ordering_list from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlmodel import Field, Relationship from sqlmodel.sql.sqltypes import GUID from joj.horse.models.base import DomainURLORMModel, url_pre_save from joj.horse.models.link_tables import ProblemProblemSetLink from joj.horse.schemas.base import Operation from joj.horse.schemas.problem_set import ProblemSetDetail from joj.horse.utils.errors import BizError, ErrorCode if TYPE_CHECKING: from joj.horse.models import Domain, Problem, Record, User class ProblemSet(DomainURLORMModel, ProblemSetDetail, table=True): # type: ignore[call-arg] __tablename__ = "problem_sets" __table_args__ = (UniqueConstraint("domain_id", "url"),) domain_id: UUID = Field( sa_column=Column( GUID, ForeignKey("domains.id", ondelete="CASCADE"), nullable=False ) ) domain: "Domain" = Relationship(back_populates="problem_sets") owner_id: Optional[UUID] = Field( sa_column=Column( GUID, ForeignKey("users.id", ondelete="SET NULL"), nullable=True, ) ) owner: Optional["User"] = Relationship(back_populates="owned_problem_sets") # problems_link: List["Problem"] = Relationship( # back_populates="problem_problem_set_links", # # link_model=ProblemProblemSetLink, # sa_relationship_kwargs={ # "secondary": ProblemProblemSetLink, # "order_by": "ProblemProblemSetLink.position", # "collection_class": ordering_list("position"), # }, # ) # maintain the order of many to many relationship problem_problem_set_links: List[ProblemProblemSetLink] = Relationship( back_populates="problem_set", sa_relationship_kwargs={ "order_by": "ProblemProblemSetLink.position", "collection_class": ordering_list("position"), }, ) problems: List["Problem"] = Relationship( back_populates="problem_sets", link_model=ProblemProblemSetLink, sa_relationship_kwargs={ "order_by": "ProblemProblemSetLink.position", }, ) records: List["Record"] =
Relationship(back_populates="problem_set")
sqlmodel.Relationship
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import Optional from uuid import UUID import sqlalchemy.types as types from sqlalchemy import Column from sqlalchemy.orm import registry from sqlmodel import Field, select from dbgen.core.decorators import transform from dbgen.core.entity import Entity from dbgen.core.generator import Generator from dbgen.core.model import Model from dbgen.core.node.extract import Extract from dbgen.core.node.query import Query my_registry = registry() class Parent(Entity, registry=my_registry, table=True): __identifying__ = {"label"} label: str myColumn: Optional[dict] = Field(None, sa_column=Column(types.JSON())) class Child(Entity, registry=my_registry, table=True): __identifying__ = {"label", "parent_id"} label: str new_col: str = "test" parent_id: Optional[UUID] =
Field(None, foreign_key="public.parent.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. from typing import Optional from uuid import UUID import sqlalchemy.types as types from sqlalchemy import Column from sqlalchemy.orm import registry from sqlmodel import Field, select from dbgen.core.decorators import transform from dbgen.core.entity import Entity from dbgen.core.generator import Generator from dbgen.core.model import Model from dbgen.core.node.extract import Extract from dbgen.core.node.query import Query my_registry = registry() class Parent(Entity, registry=my_registry, table=True): __identifying__ = {"label"} label: str myColumn: Optional[dict] = Field(None, sa_column=Column(types.JSON())) class Child(Entity, registry=my_registry, table=True): __identifying__ = {"label", "parent_id"} label: str new_col: str = "test" parent_id: Optional[UUID] = Field(None, foreign_key="public.parent.id") class CustomExtractor(Extract): n: int = 1000 def extract(self): for i in range(self.n): yield {'out': str(i)} def length(self, **_): return self.n @transform def failing_func(): raise ValueError("Failed") @transform def inputs_skipped(): from dbgen.exceptions import DBgenSkipException raise DBgenSkipException(msg="Skip!") def make_model(): with Model(name='new_api', registry=my_registry) as model: with Generator('add_parent'): new_extract = CustomExtractor(n=1000) Parent.load(insert=True, label=new_extract["out"], validation='strict', myColumn={'a': 1}) with Generator('add_parents_v2'): Parent.load(insert=True, label="parentier") with Generator('add_parents_v3'): Parent.load(insert=True, label="parent") @transform def concise_func(label: str) -> str: return f"{label}-test" with Generator('add_child'): query = Query(
select(Parent.id, Parent.label)
sqlmodel.select
from time import sleep from sqlmodel import select from icon_governance.config import settings from icon_governance.log import logger from icon_governance.models.preps import Prep from icon_governance.utils.rpc import ( convert_hex_int, get_preps_cps, get_sponsors_record, post_rpc_json, ) def get_cps(session): sponsors = post_rpc_json(get_sponsors_record()) if sponsors is None: logger.info("No sponsors found from rpc.") sleep(1) return for k, v in sponsors.items(): prep = session.get(Prep, k) if prep is None: logger.info("No preps found in db? Should not ever happen cuz of db_init.") continue prep.sponsored_cps_grants = convert_hex_int(v) session.merge(prep) session.commit() result = session.execute(
select(Prep)
sqlmodel.select
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine =
create_engine('sqlite:///database.db')
sqlmodel.create_engine
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int livros: List['Livro'] = Relationship(back_populates='person') class Livro(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) titulo: str pessoa_id: Optional[int] = Field(default=None, foreign_key='person.id') pessoa: Optional[Person] = Relationship(back_populates='livros')
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int livros: List['Livro'] =
Relationship(back_populates='person')
sqlmodel.Relationship
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int livros: List['Livro'] = Relationship(back_populates='person') class Livro(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int livros: List['Livro'] = Relationship(back_populates='person') class Livro(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) titulo: str pessoa_id: Optional[int] =
Field(default=None, foreign_key='person.id')
sqlmodel.Field
from typing import Optional, List from sqlmodel import ( SQLModel, Field, create_engine, Relationship ) engine = create_engine('sqlite:///database.db') class Person(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) nome: str idade: int livros: List['Livro'] = Relationship(back_populates='person') class Livro(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) titulo: str pessoa_id: Optional[int] = Field(default=None, foreign_key='person.id') pessoa: Optional[Person] =
Relationship(back_populates='livros')
sqlmodel.Relationship
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with
SQLSession(current_app.engine)
sqlmodel.Session
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with SQLSession(current_app.engine) as s: orgs =
select(Organization)
sqlmodel.select
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with SQLSession(current_app.engine) as s: orgs = select(Organization) results = s.exec(orgs).all() return render_template( "admin/organizations.html", session=session, organizations=results ) @bp.route("/server/organization", methods=["POST", "DELETE"]) def post_server(): if request.method == "POST": data = request.form org_id = data.get("id").strip() title = data.get("title").strip() return jsonify({}), 200 @bp.route("/catagory", methods=["POST"]) @admin_required def get_catagory(): data = request.form cat_id = data.get("id") title = data.get("title") color = data.get("color") with
SQLSession(current_app.engine)
sqlmodel.Session
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with SQLSession(current_app.engine) as s: orgs = select(Organization) results = s.exec(orgs).all() return render_template( "admin/organizations.html", session=session, organizations=results ) @bp.route("/server/organization", methods=["POST", "DELETE"]) def post_server(): if request.method == "POST": data = request.form org_id = data.get("id").strip() title = data.get("title").strip() return jsonify({}), 200 @bp.route("/catagory", methods=["POST"]) @admin_required def get_catagory(): data = request.form cat_id = data.get("id") title = data.get("title") color = data.get("color") with SQLSession(current_app.engine) as s: if cat_id: _catagory = s.exec(select(Catagory).where(Catagory.id == cat_id)).one() _catagory.title = data.get("title") _catagory.meta_ref = data.get("title").lower().replace(" ", "-") _catagory.color = data.get("color") s.add(_catagory) s.commit() else: _catagory = Catagory( title=data.get("title"), meta_ref=data.get("title").lower().replace(" ", "-"), color=data.get("color"), ) s.add(_catagory) s.commit() return jsonify({"result": "Operate successfully"}) @bp.route("/catagories", methods=["GET", "POST"]) def get_post_catagories(): if request.method == "GET": with
SQLSession(current_app.engine)
sqlmodel.Session
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with SQLSession(current_app.engine) as s: orgs = select(Organization) results = s.exec(orgs).all() return render_template( "admin/organizations.html", session=session, organizations=results ) @bp.route("/server/organization", methods=["POST", "DELETE"]) def post_server(): if request.method == "POST": data = request.form org_id = data.get("id").strip() title = data.get("title").strip() return jsonify({}), 200 @bp.route("/catagory", methods=["POST"]) @admin_required def get_catagory(): data = request.form cat_id = data.get("id") title = data.get("title") color = data.get("color") with SQLSession(current_app.engine) as s: if cat_id: _catagory = s.exec(select(Catagory).where(Catagory.id == cat_id)).one() _catagory.title = data.get("title") _catagory.meta_ref = data.get("title").lower().replace(" ", "-") _catagory.color = data.get("color") s.add(_catagory) s.commit() else: _catagory = Catagory( title=data.get("title"), meta_ref=data.get("title").lower().replace(" ", "-"), color=data.get("color"), ) s.add(_catagory) s.commit() return jsonify({"result": "Operate successfully"}) @bp.route("/catagories", methods=["GET", "POST"]) def get_post_catagories(): if request.method == "GET": with SQLSession(current_app.engine) as s: results = s.exec(
select(Catagory)
sqlmodel.select
from flask import Blueprint from flask import request from flask import jsonify from flask import session from flask import current_app from flask import render_template from flask import request from app.utils import render_markdown from sqlmodel import Session as SQLSession from sqlmodel import select from app.models.server import Catagory, Organization from app.utils.decorators import admin_required bp = Blueprint("admin", __name__) @bp.route("/") @admin_required def index(): return render_markdown( "page.html", file="admin.md", session=session, ) @bp.route("/organizations", methods=["GET"]) def get_organizations(): with SQLSession(current_app.engine) as s: orgs = select(Organization) results = s.exec(orgs).all() return render_template( "admin/organizations.html", session=session, organizations=results ) @bp.route("/server/organization", methods=["POST", "DELETE"]) def post_server(): if request.method == "POST": data = request.form org_id = data.get("id").strip() title = data.get("title").strip() return jsonify({}), 200 @bp.route("/catagory", methods=["POST"]) @admin_required def get_catagory(): data = request.form cat_id = data.get("id") title = data.get("title") color = data.get("color") with SQLSession(current_app.engine) as s: if cat_id: _catagory = s.exec(
select(Catagory)
sqlmodel.select
from typing import Optional import pytest from sqlmodel import Field, SQLModel, create_engine def test_missing_sql_type(): class CustomType: @classmethod def __get_validators__(cls): yield cls.validate @classmethod def validate(cls, v): return v with pytest.raises(ValueError): class Item(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID =
Field(nullable=False)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID =
Field(nullable=False)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
import uuid from datetime import datetime from sqlmodel import Field from api.db.models.base import BaseModel, BaseTable class TenantSchemaBase(BaseModel): tenant_id: uuid.UUID = Field(nullable=False) wallet_id: uuid.UUID = Field(nullable=False) # workflow_id will be null until the tenant kcks it off workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_name: str = Field(nullable=True, default=None) schema_version: str = Field(nullable=True, default=None) schema_attrs: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_tag: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) cred_revocation: bool = Field(nullable=True, default=None) cred_revoc_reg_size: int = Field(nullable=True, default=None) revoc_reg_state: str = Field(nullable=True, default=None) class TenantSchema(TenantSchemaBase, BaseTable, table=True): # This is the class that represents the table pass class TenantSchemaCreate(TenantSchemaBase): # This is the class that represents interface for creating a tenant # we must set all the required fields, # but do not need to set optional (and shouldn't) pass class TenantSchemaRead(TenantSchemaBase): # This is the class that represents interface for reading a tenant # here we indicate id, created_at and updated_at must be included id: uuid.UUID created_at: datetime updated_at: datetime class TenantSchemaUpdate(BaseModel): # This is our update interface # This does NOT inherit from TenantSchemaBase, # so no need to worry about accidentally updating id or other fields id: uuid.UUID workflow_id: uuid.UUID = Field(nullable=True, default=None) schema_id: str = Field(nullable=True, default=None) schema_txn_id: uuid.UUID = Field(nullable=True, default=None) schema_state: str = Field(nullable=True, default=None) cred_def_txn_id: uuid.UUID = Field(nullable=True, default=None) cred_def_id: str = Field(nullable=True, default=None) cred_def_state: str = Field(nullable=True, default=None) revoc_reg_state: str =
Field(nullable=True, default=None)
sqlmodel.Field
"""add remoteuser Revision ID: 5c6d07e2a9c1 Revises: <KEY> Create Date: 2022-02-13 01:54:01.310088 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '5c6d07e2a9c1' down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('remoteuser', sa.Column('username', sa.VARCHAR(), nullable=True), sa.Column('id', sa.Integer(), nullable=True), sa.Column('inbox',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""add remoteuser Revision ID: 5c6d07e2a9c1 Revises: <KEY> Create Date: 2022-02-13 01:54:01.310088 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '5c6d07e2a9c1' down_revision = '<KEY>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('remoteuser', sa.Column('username', sa.VARCHAR(), nullable=True), sa.Column('id', sa.Integer(), nullable=True), sa.Column('inbox', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('public_key',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add schools Revision ID: 423e059e8b64 Revises: 58d2280520b8 Create Date: 2022-02-12 07:44:42.189067+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "423e059e8b64" down_revision = "58d2280520b8" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "schools", sa.Column("id", sa.Integer(), nullable=False), sa.Column("name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
import os from flask import Flask import os import requests from app import config from app.routes import default from app.routes import debug from app.routes import auth from app.routes import admin from app.routes import profile from app.routes import server from app.pages import create_pages from sqlmodel import SQLModel from sqlmodel import create_engine from app.models.user import Log, User APP_SETTINGS = os.getenv("APP_SETTINGS", "Testing") def drop_database(config): import sqlalchemy from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy import inspect from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine(config["DATABASE_URI"]) meta = MetaData() meta.reflect(bind=engine) meta.drop_all(engine, checkfirst=False) def create_app(): app = Flask(__name__, template_folder="app/templates/", static_folder="app/static/") app.count_requests = 0 app.config.from_object(f"app.config.{APP_SETTINGS}") app.secret_key = os.urandom(256) app.url_map.strict_slashes = False app.register_blueprint(default.bp) app.register_blueprint(debug.bp, url_prefix="/debug") app.register_blueprint(auth.bp, url_prefix="/auth") app.register_blueprint(admin.bp, url_prefix="/admin") app.register_blueprint(profile.bp, url_prefix="/user") app.register_blueprint(server.bp, url_prefix="/server") app.register_error_handler(Exception, default.handle_exception) return app app = create_app() app.pages = create_pages() with app.app_context(): from app.database import engine app.engine = engine if os.getenv("DROP_DATABASE", False): drop_database(app.config)
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from string import ascii_lowercase from typing import Any, Dict, Tuple, Type, TypeVar from uuid import UUID from hypothesis import strategies as st from hypothesis.strategies._internal.strategies import SearchStrategy from sqlalchemy.orm import registry from sqlmodel import Field from dbgen.core.entity import BaseEntity, EntityMetaclass protected_words = {"mro"} uni_text = lambda x: st.text(ascii_lowercase, min_size=x) non_private_attr = uni_text(1).filter(lambda x: x[0] != "_").filter(lambda x: x not in protected_words) pydantic_type_strat = st.sampled_from((str, float, bool, int)) id_field = Field( default=None, primary_key=True, sa_column_kwargs={"autoincrement": False, "unique": True}, ) fk_field = lambda x:
Field(default=None, foreign_key=x)
sqlmodel.Field
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, SQLModel, or_ from sqlalchemy.exc import NoResultFound from ..models.user import User from typing import Optional from datetime import datetime router = APIRouter(prefix="/api/users", tags=["user"]) session =
Session(engine)
sqlmodel.Session
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, SQLModel, or_ from sqlalchemy.exc import NoResultFound from ..models.user import User from typing import Optional from datetime import datetime router = APIRouter(prefix="/api/users", tags=["user"]) session = Session(engine) @router.post("/") async def post_user( user: User, session: Session = Depends(get_session), ): """ Post a new user. Parameters ---------- user : User User that is to be added to the database. session : Session SQL session that is to be used to add the user. Defaults to creating a dependency on the running SQL model session. """ statement = select(User).where(User.short_name == user.short_name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(user) session.commit() session.refresh(user) return user @router.get("/") async def get_users( session: Session = Depends(get_session), is_active: bool = None, short_name: str = None, ): """ Get list of user(s). Parameters ---------- session : Session SQL session that is to be used to get the users. Defaults to creating a dependency on the running SQL model session. is_active : bool Status of users to be pulled. short_name : str Short name of user to be pulled. """ statement =
select(User)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, SQLModel, or_ from sqlalchemy.exc import NoResultFound from ..models.user import User from typing import Optional from datetime import datetime router = APIRouter(prefix="/api/users", tags=["user"]) session = Session(engine) @router.post("/") async def post_user( user: User, session: Session = Depends(get_session), ): """ Post a new user. Parameters ---------- user : User User that is to be added to the database. session : Session SQL session that is to be used to add the user. Defaults to creating a dependency on the running SQL model session. """ statement =
select(User)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, SQLModel, or_ from sqlalchemy.exc import NoResultFound from ..models.user import User from typing import Optional from datetime import datetime router = APIRouter(prefix="/api/users", tags=["user"]) session = Session(engine) @router.post("/") async def post_user( user: User, session: Session = Depends(get_session), ): """ Post a new user. Parameters ---------- user : User User that is to be added to the database. session : Session SQL session that is to be used to add the user. Defaults to creating a dependency on the running SQL model session. """ statement = select(User).where(User.short_name == user.short_name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(user) session.commit() session.refresh(user) return user @router.get("/") async def get_users( session: Session = Depends(get_session), is_active: bool = None, short_name: str = None, ): """ Get list of user(s). Parameters ---------- session : Session SQL session that is to be used to get the users. Defaults to creating a dependency on the running SQL model session. is_active : bool Status of users to be pulled. short_name : str Short name of user to be pulled. """ statement = select(User) if is_active != None: statement = ( select(User) .where(User.is_active == is_active) .order_by(User.start_date.desc()) ) result = session.exec(statement).all() return result @router.put("/{user_id}/") async def update_user( user_id: int, is_active: Optional[bool] = None, new_short_name: Optional[str] = None, new_first_name: Optional[str] = None, new_last_name: Optional[str] = None, new_email: Optional[str] = None, new_team_id: Optional[str] = None, session: Session = Depends(get_session), ): """ Update a user. Parameters ---------- user_id : int ID of user to be updated. is_active : Optional[bool] Updated status of user. new_short_name : Optional[bool] Updated short name of user. new_first_name : Optional[bool] Updated first name of user. new_last_name : Optional[bool] Updated last name of user. new_email : Optional[bool] Updated email of user new_team_id : Optional[bool] Updated team id. session : Session SQL session that is to be used to update the user. Defaults to creating a dependency on the running SQL model session. """ statement =
select(User)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, SQLModel, or_ from sqlalchemy.exc import NoResultFound from ..models.user import User from typing import Optional from datetime import datetime router = APIRouter(prefix="/api/users", tags=["user"]) session = Session(engine) @router.post("/") async def post_user( user: User, session: Session = Depends(get_session), ): """ Post a new user. Parameters ---------- user : User User that is to be added to the database. session : Session SQL session that is to be used to add the user. Defaults to creating a dependency on the running SQL model session. """ statement = select(User).where(User.short_name == user.short_name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(user) session.commit() session.refresh(user) return user @router.get("/") async def get_users( session: Session = Depends(get_session), is_active: bool = None, short_name: str = None, ): """ Get list of user(s). Parameters ---------- session : Session SQL session that is to be used to get the users. Defaults to creating a dependency on the running SQL model session. is_active : bool Status of users to be pulled. short_name : str Short name of user to be pulled. """ statement = select(User) if is_active != None: statement = (
select(User)
sqlmodel.select
from fastapi import Path, Depends, HTTPException from sqlmodel import Session, select from db import get_db_session from model.warehouse import Warehouse from service.base_crud import BaseCRUD async def validate_warehouse_id( warehouse_id: int = Path(...), db_session: Session = Depends(get_db_session) ) -> Warehouse: """Validates the if a warehouse is present with the given id. Args: warehouse_id: int. The id of the warehouse. db_session: Session. The database session used to interact with the DB. Returns: Warehouse. The warehouse corresponding to the warehouse_id. Raises: HTTPException. Warehouse does not exist in the DB. """ warehouse: Warehouse = warehouse_crud.get(db_session, warehouse_id) if not warehouse or not warehouse.active: raise HTTPException(status_code=404, detail='Warehouse does not exist') return warehouse class WarehouseCRUD(BaseCRUD): model = Warehouse def get_by_name(self, db_session: Session, name: str) -> Warehouse: """Fetches warehouse by name. Args: db_session: Session. The database session used to interact with the DB. name: str. The name of the warehouse. Returns: Warehouse. The warehouse having the given name. """ statement =
select(self.model)
sqlmodel.select
import pytest from typing import Generator, Dict from sqlmodel import Session, SQLModel, create_engine from sqlmodel.pool import StaticPool from fastapi.testclient import TestClient from app.models import * from app.main import app from app.api.deps import get_db @pytest.fixture(name="session") def session_fixture() -> Generator: engine = create_engine( "sqlite://", echo=False, connect_args={"check_same_thread": False}, poolclass=StaticPool, )
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import pytest from typing import Generator, Dict from sqlmodel import Session, SQLModel, create_engine from sqlmodel.pool import StaticPool from fastapi.testclient import TestClient from app.models import * from app.main import app from app.api.deps import get_db @pytest.fixture(name="session") def session_fixture() -> Generator: engine = create_engine( "sqlite://", echo=False, connect_args={"check_same_thread": False}, poolclass=StaticPool, ) SQLModel.metadata.create_all(engine) with
Session(engine)
sqlmodel.Session
import typing as t from sqlalchemy.orm import RelationshipProperty, selectinload from sqlmodel import select def get_schema_context(info): schema_context = info.context["auto_schema"] return schema_context def get_model_for_type(info, type_): schema_context = get_schema_context(info) model = schema_context["type_to_model"][type_] return model def get_strawberry_fields_for_type(info, type_): schema_context = get_schema_context(info) strawberry_fields = schema_context["type_to_type_definition"][type_].fields return strawberry_fields def get_mapper_for_column(info, column): return column.property.mapper def get_type_for_column(info, column): schema_context = get_schema_context(info) return schema_context["mapper_to_type"][get_mapper_for_column(info, column)] def get_graphql_python_name_map_for_type(info, type_): """Create a mapping from graphql field names to python attribute names""" strawberry_fields = get_strawberry_fields_for_type(info, type_) name_map = { f.get_graphql_name(info.schema.config.auto_camel_case): f.python_name for f in strawberry_fields } return name_map def get_selected_field_columns(info, type_, selected_fields, model=None): model = get_model_for_type(info, type_) if model is None else model name_map = get_graphql_python_name_map_for_type(info, type_) selected_field_columns = [ (s, getattr(model, name_map[s.name])) for s in selected_fields ] return selected_field_columns def get_selected_scalar_non_scalar_field_columns( info, type_, selected_fields, model=None ): selected_field_columns = get_selected_field_columns( info, type_, selected_fields, model ) scalar_field_columns = [ fc for fc in selected_field_columns if not isinstance(fc[1].property, RelationshipProperty) ] non_scalar_field_columns = [ c for c in selected_field_columns if isinstance(c[1].property, RelationshipProperty) ] return scalar_field_columns, non_scalar_field_columns def do_nested_select(info, type_, query, selected_field, column, parent_model): selected_fields = [s for s in selected_field.selections] model = get_model_for_type(info, type_) ( scalar_field_columns, non_scalar_field_columns, ) = get_selected_scalar_non_scalar_field_columns( info, type_, selected_fields, model ) # TODO: selectinload is good for one to many relationships because it does # not create cartesian product issues. # https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#what-kind-of-loading-to-use # however we probably want joined loading for many to one relationships # and we can set innerjoin to true if the relationship is nonnullable # https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#joined-eager-loading # one issue with selectinload is it will not work with nested relationships # that have compositie primary keys. this shows up on sql server # https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#select-in-loading subquery = selectinload(column) query = query.options(subquery) # TODO: this nested select is untested and probably doesn't work we want to # use chained loading to specify futher levels # https://docs.sqlalchemy.org/en/14/orm/loading_relationships.html#relationship-loading-with-loader-options if non_scalar_field_columns: for field_column in non_scalar_field_columns: field, column = field_column column_type = get_type_for_column(info, column) do_nested_select(info, column_type, subquery, field, column, model) return query def eq_filter(column, value): return column == value def neq_filter(column, value): return column != value def lt_filter(column, value): return column < value def lte_filter(column, value): return column <= value def gt_filter(column, value): return column > value def gte_filter(column, value): return column >= value def contains_filter(column, value): return column.contains(value) # TODO: write more filters filter_map = { "eq": eq_filter, "neq": neq_filter, "lt": lt_filter, "lte": lte_filter, "gt": gt_filter, "gte": gte_filter, "contains": contains_filter, } def do_filter(info, type_, query, column, filter): from api.strawberry_sqlalchemy.schema_generation import ( NonScalarComparison, ScalarComparison, ) scalar = isinstance(filter, ScalarComparison) non_scalar = isinstance(filter, NonScalarComparison) if scalar: for filter_key in filter.__dict__.keys(): value = getattr(filter, filter_key) if value is not None: filter_func = filter_map[filter_key] query = query.where(filter_func(column, value)) elif non_scalar: # TODO: implement non scalar filter processing raise NotImplementedError("Non scalar filters are not yet implemented.") return query def do_where(info, type_, query, where_clause): from api.strawberry_sqlalchemy.schema_generation import ( NonScalarComparison, ScalarComparison, ) if where_clause is None: return query isinstance(where_clause, ScalarComparison) non_scalar = isinstance(where_clause, NonScalarComparison) model = get_model_for_type(info, type_) name_map = get_graphql_python_name_map_for_type(info, type_) if non_scalar: for name in where_clause.__dict__.keys(): filter_ = getattr(where_clause, name) if filter_ is not None: column = ( None if name not in name_map else getattr(model, name_map[name]) ) query = do_filter(info, type_, query, column, filter_) return query def create_all_type_resolver(type_: type): """create a resolver for all instances of a type. Supports various filters""" from api.strawberry_sqlalchemy.schema_generation import ( create_non_scalar_comparison_expression, create_non_scalar_order_by_expression, create_non_scalar_select_columns_enum, ) def all_type_resolver( self, info, where: t.Optional[create_non_scalar_comparison_expression(type_)] = None, limit: t.Optional[int] = None, offset: t.Optional[int] = None, orderBy: t.Optional[create_non_scalar_order_by_expression(type_)] = None, distinctOn: t.Optional[ t.List[create_non_scalar_select_columns_enum(type_)] ] = None, ) -> t.List[type_]: # handle the case where we are querying a many attribute # in a one to many relationship # the many attribute uses an all_type_query resolver so that the user # can supply filters. but strawberry.field.get_result tries to # load the nested attribute using the resolver. # because we are using eager loading we actually just want to access # the attribute on the parent using get_attr(model, python_name) # we don't want to generate a nested query # TODO: to check that we are not at the root we check that the prev # path is not None. Not sure if this is always true! if info.path.prev is not None: return getattr(self, info.python_name) model = get_model_for_type(info, type_) db = info.context["db"] selected_fields = [s for s in info.selected_fields[0].selections] ( scalar_field_columns, non_scalar_field_columns, ) = get_selected_scalar_non_scalar_field_columns(info, type_, selected_fields) query =
select(model)
sqlmodel.select
from datetime import datetime, date from typing import Optional from fastapi import APIRouter from sqlmodel import Field, SQLModel router = APIRouter() class History(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime, date from typing import Optional from fastapi import APIRouter from sqlmodel import Field, SQLModel router = APIRouter() class History(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) patient_id: int hospital_id: Optional[int] hospital_node_id: Optional[int] hospital_room: str discipline_group_id: int discipline_id: int date: date source: str created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryDoctor(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime, date from typing import Optional from fastapi import APIRouter from sqlmodel import Field, SQLModel router = APIRouter() class History(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) patient_id: int hospital_id: Optional[int] hospital_node_id: Optional[int] hospital_room: str discipline_group_id: int discipline_id: int date: date source: str created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryDoctor(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) history_id: int doctor_id: int created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryModuleMap(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime, date from typing import Optional from fastapi import APIRouter from sqlmodel import Field, SQLModel router = APIRouter() class History(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) patient_id: int hospital_id: Optional[int] hospital_node_id: Optional[int] hospital_room: str discipline_group_id: int discipline_id: int date: date source: str created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryDoctor(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) history_id: int doctor_id: int created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryModuleMap(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) history_id: int module_id: int created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryTag(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
"""initial3 Revision ID: 01b6c8ce3965 Revises: <PASSWORD> Create Date: 2021-11-01 04:29:57.210756 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '01b6c8ce3965' down_revision = '<PASSWORD>' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('images', sa.Column('size_x', sa.Float(), nullable=False)) op.add_column('images', sa.Column('size_y', sa.Float(), nullable=False)) op.create_index(op.f('ix_images_size_x'), 'images', ['size_x'], unique=False) op.create_index(op.f('ix_images_size_y'), 'images', ['size_y'], unique=False) op.add_column('listings', sa.Column('url',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session =
Session(engine)
sqlmodel.Session
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(
or_(Team.name == team.name, Team.id == team.id)
sqlmodel.or_
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement = select(Team).where(Team.name == team_name) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no team named {team_name}""" return msg @router.get("/{team_id}/user-name") async def get_user_name_by_team_id( team_id: int, session: Session = Depends(get_session) ): """Get user name by team id""" statement = ( select(Team.id, User.id, User.name) .join(User) .where(Team.id == team_id) .where(User.active == True) ) result = session.exec(statement).one() return result @router.put("/{team_name}/activate") async def activate_team( team_name: str = None, session: Session = Depends(get_session), ): """Activate team""" statement = select(Team).where(Team.name == team_name) team_to_activate = session.exec(statement).one() team_to_activate.is_active = True team_to_activate.updated_at = datetime.now() session.add(team_to_activate) session.commit() session.refresh(team_to_activate) return team_to_activate @router.put("/{team_name}/deactivate") async def deactivate_team( team_name: str = None, session: Session = Depends(get_session), ): """Deactivate team""" statement = select(Team).where(Team.name == team_name) team_to_deactivate = session.exec(statement).one() team_to_deactivate.is_active = False team_to_deactivate.updated_at = datetime.now() session.add(team_to_deactivate) session.commit() session.refresh(team_to_deactivate) return team_to_deactivate @router.put("/") async def update_team( id: str = None, lead_user_id: str = None, name: str = None, is_active: bool = None, session: Session = Depends(get_session), ): """Update team""" statement = select(Team).where(
or_(Team.name == name, Team.id == id)
sqlmodel.or_
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement = select(Team).where(Team.name == team_name) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no team named {team_name}""" return msg @router.get("/{team_id}/user-name") async def get_user_name_by_team_id( team_id: int, session: Session = Depends(get_session) ): """Get user name by team id""" statement = ( select(Team.id, User.id, User.name) .join(User) .where(Team.id == team_id) .where(User.active == True) ) result = session.exec(statement).one() return result @router.put("/{team_name}/activate") async def activate_team( team_name: str = None, session: Session = Depends(get_session), ): """Activate team""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement = select(Team).where(Team.name == team_name) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no team named {team_name}""" return msg @router.get("/{team_id}/user-name") async def get_user_name_by_team_id( team_id: int, session: Session = Depends(get_session) ): """Get user name by team id""" statement = ( select(Team.id, User.id, User.name) .join(User) .where(Team.id == team_id) .where(User.active == True) ) result = session.exec(statement).one() return result @router.put("/{team_name}/activate") async def activate_team( team_name: str = None, session: Session = Depends(get_session), ): """Activate team""" statement = select(Team).where(Team.name == team_name) team_to_activate = session.exec(statement).one() team_to_activate.is_active = True team_to_activate.updated_at = datetime.now() session.add(team_to_activate) session.commit() session.refresh(team_to_activate) return team_to_activate @router.put("/{team_name}/deactivate") async def deactivate_team( team_name: str = None, session: Session = Depends(get_session), ): """Deactivate team""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement = select(Team).where(Team.name == team_name) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no team named {team_name}""" return msg @router.get("/{team_id}/user-name") async def get_user_name_by_team_id( team_id: int, session: Session = Depends(get_session) ): """Get user name by team id""" statement = ( select(Team.id, User.id, User.name) .join(User) .where(Team.id == team_id) .where(User.active == True) ) result = session.exec(statement).one() return result @router.put("/{team_name}/activate") async def activate_team( team_name: str = None, session: Session = Depends(get_session), ): """Activate team""" statement = select(Team).where(Team.name == team_name) team_to_activate = session.exec(statement).one() team_to_activate.is_active = True team_to_activate.updated_at = datetime.now() session.add(team_to_activate) session.commit() session.refresh(team_to_activate) return team_to_activate @router.put("/{team_name}/deactivate") async def deactivate_team( team_name: str = None, session: Session = Depends(get_session), ): """Deactivate team""" statement = select(Team).where(Team.name == team_name) team_to_deactivate = session.exec(statement).one() team_to_deactivate.is_active = False team_to_deactivate.updated_at = datetime.now() session.add(team_to_deactivate) session.commit() session.refresh(team_to_deactivate) return team_to_deactivate @router.put("/") async def update_team( id: str = None, lead_user_id: str = None, name: str = None, is_active: bool = None, session: Session = Depends(get_session), ): """Update team""" statement =
select(Team)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select, or_ from ..models.team import Team from ..models.user import User from sqlalchemy.exc import NoResultFound from datetime import datetime router = APIRouter(prefix="/api/teams", tags=["team"]) session = Session(engine) @router.post("/") async def post_team( *, team: Team, session: Session = Depends(get_session), ): """Post new team""" statement = select(Team).where(or_(Team.name == team.name, Team.id == team.id)) try: result = session.exec(statement).one() return False except NoResultFound: session.add(team) session.commit() session.refresh(team) return team @router.get("/") async def get_team_list(session: Session = Depends(get_session)): """Get team list""" statement = select(Team) results = session.exec(statement).all() return results @router.get("/active") async def get_active_team_list(session: Session = Depends(get_session)): """Get list of active teams""" statement = ( select( Team.id, Team.lead_user_id, Team.name.label("team_name"), Team.short_name.label("team_short_name"), User.id, User.short_name.label("user_name"), ) .join(User) .where(Team.is_active == True) ) results = session.exec(statement).all() return results @router.get("/{team_name}") async def read_teams(team_name: str = None, session: Session = Depends(get_session)): """Read the contents of a given team""" statement = select(Team).where(Team.name == team_name) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no team named {team_name}""" return msg @router.get("/{team_id}/user-name") async def get_user_name_by_team_id( team_id: int, session: Session = Depends(get_session) ): """Get user name by team id""" statement = (
select(Team.id, User.id, User.name)
sqlmodel.select
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional from uuid import UUID, uuid4 import requests from pydantic import HttpUrl from pydantic.tools import parse_obj_as from sqlalchemy.sql.expression import text from sqlmodel import Session, select from dbgen import Const, Entity, Extract, Generator, Model, Query from dbgen.configuration import config, get_engines from dbgen.core.node.transforms import PyBlock class CustomJsonExtract(Extract): url: HttpUrl = parse_obj_as(HttpUrl, 'https://jsonplaceholder.typicode.com/posts') outputs: List[str] = ['out', 'uuid'] def setup(self, **_): self._response = requests.get(self.url).json() self._response += [{}] def extract(self): for row in self._response: row['uuid'] = uuid4() yield {'out': row, 'uuid': row['uuid']} def length(self, **_): return len(self._response) class JSONEntityBase(Entity): __tablename__ = 'json_entity' tags: Optional[List[dict]] my_uuid: Optional[UUID] class JSONEntity(JSONEntityBase, table=True): __tablename__ = 'json_entity' __identifying__ = { 'json_val', } json_val: Optional[dict] model = Model(name='test_json') load_json = Generator(name='load_json', loads=[JSONEntity.load(insert=True, json_val=Const({}))]) model.add_gen(load_json) extract = CustomJsonExtract() load = JSONEntity.load(insert=True, json_val=extract['out'], my_uuid=extract['uuid']) load_http_json = Generator(name='load_http_json', extract=extract, loads=[load]) model.add_gen(load_http_json) query = Query(select(JSONEntity.id, JSONEntity.json_val.op('->')(text("'title'")).label('title'))) def get_title_words(text: str): if text: return [{'word': word} for word in text.split(' ')] pb = PyBlock(function=get_title_words, inputs=[query['title']]) load = JSONEntity.load(json_entity=query['id'], tags=pb['out']) add_tags = Generator(name='add_tags', extract=query, transforms=[pb], loads=[load]) model.add_gen(add_tags) if __name__ == '__main__': main_engine, _ = get_engines(config) with
Session(main_engine)
sqlmodel.Session
# Copyright 2021 Modelyst LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional from uuid import UUID, uuid4 import requests from pydantic import HttpUrl from pydantic.tools import parse_obj_as from sqlalchemy.sql.expression import text from sqlmodel import Session, select from dbgen import Const, Entity, Extract, Generator, Model, Query from dbgen.configuration import config, get_engines from dbgen.core.node.transforms import PyBlock class CustomJsonExtract(Extract): url: HttpUrl = parse_obj_as(HttpUrl, 'https://jsonplaceholder.typicode.com/posts') outputs: List[str] = ['out', 'uuid'] def setup(self, **_): self._response = requests.get(self.url).json() self._response += [{}] def extract(self): for row in self._response: row['uuid'] = uuid4() yield {'out': row, 'uuid': row['uuid']} def length(self, **_): return len(self._response) class JSONEntityBase(Entity): __tablename__ = 'json_entity' tags: Optional[List[dict]] my_uuid: Optional[UUID] class JSONEntity(JSONEntityBase, table=True): __tablename__ = 'json_entity' __identifying__ = { 'json_val', } json_val: Optional[dict] model = Model(name='test_json') load_json = Generator(name='load_json', loads=[JSONEntity.load(insert=True, json_val=Const({}))]) model.add_gen(load_json) extract = CustomJsonExtract() load = JSONEntity.load(insert=True, json_val=extract['out'], my_uuid=extract['uuid']) load_http_json = Generator(name='load_http_json', extract=extract, loads=[load]) model.add_gen(load_http_json) query = Query(select(JSONEntity.id, JSONEntity.json_val.op('->')(text("'title'")).label('title'))) def get_title_words(text: str): if text: return [{'word': word} for word in text.split(' ')] pb = PyBlock(function=get_title_words, inputs=[query['title']]) load = JSONEntity.load(json_entity=query['id'], tags=pb['out']) add_tags = Generator(name='add_tags', extract=query, transforms=[pb], loads=[load]) model.add_gen(add_tags) if __name__ == '__main__': main_engine, _ = get_engines(config) with Session(main_engine) as session: json_entity = session.exec(
select(JSONEntity)
sqlmodel.select
from datetime import date from typing import Optional from sqlmodel import SQLModel, Field # if TYPE_CHECKING: # from app.src.models.db.order import Order class AppUserBase(SQLModel): username: str name: Optional[str] surname: Optional[str] birth_date: Optional[date] email: str password: str isAdmin: bool = False class AppUser(AppUserBase, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
"""Implementing balance and fiscal_note_items tables Revision ID: 6099ed2a58e0 Revises: <KEY> Create Date: 2021-10-11 14:52:44.126077 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "6099ed2a58e0" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "balance", sa.Column("id",
sqlmodel.sql.sqltypes.GUID()
sqlmodel.sql.sqltypes.GUID
"""Implementing balance and fiscal_note_items tables Revision ID: 6099ed2a58e0 Revises: <KEY> Create Date: 2021-10-11 14:52:44.126077 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "6099ed2a58e0" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "balance", sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False), sa.Column("value", sa.Float(), nullable=False), sa.Column("type", sa.Enum("DEBT", "CREDIT", name="balancetype"), nullable=False), sa.Column( "operation", sa.Enum( "PAYMENT_OF_EMPLOYEES", "PAYMENT_OF_SUPPLIERS", "ANOTHER_PAYMENTS", "SALE_IN_PIX", "SALE_IN_DEBT", "SALE_IN_CREDIT", "SALE_IN_MONEY", name="operationtype", ), nullable=False, ), sa.Column("description",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Implementing balance and fiscal_note_items tables Revision ID: 6099ed2a58e0 Revises: <KEY> Create Date: 2021-10-11 14:52:44.126077 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "6099ed2a58e0" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "balance", sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False), sa.Column("value", sa.Float(), nullable=False), sa.Column("type", sa.Enum("DEBT", "CREDIT", name="balancetype"), nullable=False), sa.Column( "operation", sa.Enum( "PAYMENT_OF_EMPLOYEES", "PAYMENT_OF_SUPPLIERS", "ANOTHER_PAYMENTS", "SALE_IN_PIX", "SALE_IN_DEBT", "SALE_IN_CREDIT", "SALE_IN_MONEY", name="operationtype", ), nullable=False, ), sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=True), sa.Column("owner_id",
sqlmodel.sql.sqltypes.GUID()
sqlmodel.sql.sqltypes.GUID
"""Implementing balance and fiscal_note_items tables Revision ID: 6099ed2a58e0 Revises: <KEY> Create Date: 2021-10-11 14:52:44.126077 """ import sqlalchemy as sa import sqlmodel from alembic import op from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "6099ed2a58e0" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "balance", sa.Column("id", sqlmodel.sql.sqltypes.GUID(), nullable=False), sa.Column("value", sa.Float(), nullable=False), sa.Column("type", sa.Enum("DEBT", "CREDIT", name="balancetype"), nullable=False), sa.Column( "operation", sa.Enum( "PAYMENT_OF_EMPLOYEES", "PAYMENT_OF_SUPPLIERS", "ANOTHER_PAYMENTS", "SALE_IN_PIX", "SALE_IN_DEBT", "SALE_IN_CREDIT", "SALE_IN_MONEY", name="operationtype", ), nullable=False, ), sa.Column("description", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("created_at", sa.DateTime(), nullable=True), sa.Column("owner_id", sqlmodel.sql.sqltypes.GUID(), nullable=False), sa.ForeignKeyConstraint( ["owner_id"], ["users.id"], ), sa.PrimaryKeyConstraint("id"), ) op.create_index(op.f("ix_balance_created_at"), "balance", ["created_at"], unique=False) op.create_index(op.f("ix_balance_operation"), "balance", ["operation"], unique=False) op.create_index(op.f("ix_balance_owner_id"), "balance", ["owner_id"], unique=False) op.create_index(op.f("ix_balance_type"), "balance", ["type"], unique=False) op.create_table( "fiscal_note_items", sa.Column("id",
sqlmodel.sql.sqltypes.GUID()
sqlmodel.sql.sqltypes.GUID