This commit is contained in:
Waylon Walker 2023-06-08 09:02:43 -05:00
parent a9ee4a2bd8
commit d68cda91cf
No known key found for this signature in database
GPG key ID: 66E2BF2B4190EFE4
22 changed files with 824 additions and 55 deletions

View file

@ -0,0 +1,99 @@
from typing import Optional
from fastapi import HTTPException
from pydantic import BaseModel
from sqlmodel import Field, Relationship, SQLModel, Session, select
from learn_sql_model.config import Config
from learn_sql_model.models.pet import Pet
class {{modelname}}Base(SQLModel, table=False):
class {{modelname}}({{modelname.lower()}}Base, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
class {{modelname}}Create({{modelname.lower()}}Base):
...
def post(self, config: Config) -> {{modelname}}:
config.init()
with Session(config.database.engine) as session:
db_{{modelname.lower()}} = {{modelname}}.from_orm(self)
session.add(db_{{modelname.lower()}})
session.commit()
session.refresh(db_{{modelname.lower()}})
return db_{{modelname.lower()}}
class {{modelname}}Read({{modelname.lower()}}Base):
id: int
@classmethod
def get(
cls,
config: Config,
id: int,
) -> {{modelname}}:
with config.database.session as session:
{{modelname.lower()}} = session.get({{modelname}}, id)
if not {{modelname.lower()}}:
raise HTTPException(status_code=404, detail="{{modelname}} not found")
return {{modelname.lower()}}
@classmethod
def list(
self,
config: Config,
where=None,
offset=0,
limit=None,
) -> {{modelname}}:
with config.database.session as session:
statement = select({{modelname}})
if where != "None":
from sqlmodel import text
statement = statement.where(text(where))
statement = statement.offset(offset).limit(limit)
{{modelname.lower()}}es = session.exec(statement).all()
return {{modelname.lower()}}es
class {{modelname}}Update(SQLModel):
# id is required to get the {{modelname.lower()}}
id: int
# all other fields, must match the model, but with Optional default None
def update(self, config: Config) -> {{modelname}}:
with Session(config.database.engine) as session:
db_{{modelname.lower()}} = session.get({{modelname}}, self.id)
if not db_{{modelname.lower()}}:
raise HTTPException(status_code=404, detail="{{modelname}} not found")
{{modelname.lower()}}_data = self.dict(exclude_unset=True)
for key, value in {{modelname.lower()}}_data.items():
if value is not None:
setattr(db_{{modelname.lower()}}, key, value)
session.add(db_{{modelname.lower()}})
session.commit()
session.refresh(db_{{modelname.lower()}})
return db_{{modelname.lower()}}
class {{modelname}}Delete(BaseModel):
id: int
def delete(self, config: Config) -> {{modelname}}:
config.init()
with Session(config.database.engine) as session:
{{modelname.lower()}} = session.get({{modelname}}, self.id)
if not {{modelname.lower()}}:
raise HTTPException(status_code=404, detail="{{modelname}} not found")
session.delete({{modelname.lower()}})
session.commit()
return {"ok": True}