prompt
stringlengths 45
17.8k
| completion
stringlengths 6
107
| api
stringlengths 12
42
|
---|---|---|
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Capacity(SQLModel, table=True):
"""Create an SQLModel for capcities"""
id: Optional[int] = Field(default=None, primary_key=True)
user_id: int = | Field(foreign_key="app_db.appuser.id") | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Capacity(SQLModel, table=True):
"""Create an SQLModel for capcities"""
id: Optional[int] = Field(default=None, primary_key=True)
user_id: int = Field(foreign_key="app_db.appuser.id")
team_id: int = | Field(foreign_key="app_db.team.id") | sqlmodel.Field |
import pickle
from typing import Optional, Dict, Any, List, cast
from enum import Enum
import orjson
from fastapi import APIRouter, Depends, Query
from pydantic import validator
from sqlmodel import Session, Field, select # type: ignore[import]
from sqlalchemy import distinct # type: ignore[import]
from app.db import get_db, FeedModel, FeedBase
router = APIRouter()
class FeedRead(FeedBase):
# parse from the backend to data structures
tags: List[str] = | Field(default_factory=list) | sqlmodel.Field |
import pickle
from typing import Optional, Dict, Any, List, cast
from enum import Enum
import orjson
from fastapi import APIRouter, Depends, Query
from pydantic import validator
from sqlmodel import Session, Field, select # type: ignore[import]
from sqlalchemy import distinct # type: ignore[import]
from app.db import get_db, FeedModel, FeedBase
router = APIRouter()
class FeedRead(FeedBase):
# parse from the backend to data structures
tags: List[str] = Field(default_factory=list)
data: Dict[str, Any] = | Field(default_factory={}) | sqlmodel.Field |
import pickle
from typing import Optional, Dict, Any, List, cast
from enum import Enum
import orjson
from fastapi import APIRouter, Depends, Query
from pydantic import validator
from sqlmodel import Session, Field, select # type: ignore[import]
from sqlalchemy import distinct # type: ignore[import]
from app.db import get_db, FeedModel, FeedBase
router = APIRouter()
class FeedRead(FeedBase):
# parse from the backend to data structures
tags: List[str] = Field(default_factory=list)
data: Dict[str, Any] = Field(default_factory={})
@validator("tags", pre=True)
def parse_tags(cls, v: Any) -> List[str]:
return cast(List[str], orjson.loads(v))
@validator("data", pre=True)
def parse_data(cls, v: Any) -> Dict[str, Any]:
if v is None:
return {}
else:
return cast(Dict[str, Any], pickle.loads(v))
class OrderBy(Enum):
score = "score"
when = "when"
class Sort(Enum):
asc = "asc"
ascending = "ascending"
desc = "desc"
descending = "descending"
# items which shouldn't be shown when sorted by 'score'
# since it'd make the feed too busy
INDIVIDUAL_FEED_TYPES = [
"anime_episode",
"manga_chapter",
"listen",
"trakt_history_episode",
"trakt_history_movie",
]
@router.get("/types", response_model=List[str])
async def data_types(
session: Session = Depends(get_db),
) -> List[str]:
stmt = select(distinct(FeedModel.ftype))
with session:
items: List[str] = list(session.exec(stmt))
return items
@router.get("/", response_model=List[FeedRead])
async def data(
offset: int = 0,
limit: int = Query(default=100, lte=100),
order_by: OrderBy = Query(default=OrderBy.when),
sort: Sort = Query(default=Sort.desc),
ftype: Optional[str] = Query(default=None, min_length=2),
query: Optional[str] = Query(default=None, min_length=2),
title: Optional[str] = Query(default=None, min_length=2),
creator: Optional[str] = Query(default=None, min_length=2),
subtitle: Optional[str] = Query(default=None, min_length=2),
session: Session = Depends(get_db),
) -> List[FeedRead]:
stmt = | select(FeedModel) | sqlmodel.select |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = Field(default=None, primary_key=True)
customers: List['Customer'] = | Relationship(back_populates='address') | sqlmodel.Relationship |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = Field(default=None, primary_key=True)
customers: List['Customer'] = Relationship(back_populates='address')
class AddressOut(AddressBase):
pass
class AddressIn(AddressBase):
pass
class CustomerBase(SQLModel):
first_name: str
last_name: str
birth_date: str
gender: str
mobile_number: str
email: str
class Customer(CustomerBase, table=True):
id: int = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = Field(default=None, primary_key=True)
customers: List['Customer'] = Relationship(back_populates='address')
class AddressOut(AddressBase):
pass
class AddressIn(AddressBase):
pass
class CustomerBase(SQLModel):
first_name: str
last_name: str
birth_date: str
gender: str
mobile_number: str
email: str
class Customer(CustomerBase, table=True):
id: int = Field(default=None, primary_key=True)
address_id: Optional[int] = | Field(default=None, foreign_key='address.id') | sqlmodel.Field |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = Field(default=None, primary_key=True)
customers: List['Customer'] = Relationship(back_populates='address')
class AddressOut(AddressBase):
pass
class AddressIn(AddressBase):
pass
class CustomerBase(SQLModel):
first_name: str
last_name: str
birth_date: str
gender: str
mobile_number: str
email: str
class Customer(CustomerBase, table=True):
id: int = Field(default=None, primary_key=True)
address_id: Optional[int] = Field(default=None, foreign_key='address.id')
address: Optional[Address] = Relationship(back_populates='customers',
sa_relationship_kwargs={'lazy': 'selectin'})
mobile_number: str = Field(sa_column=Column('mobile_number', String, unique=True))
email: str = Field(sa_column=Column('email', String, unique=True))
products: List['Product'] = Relationship(back_populates='customers', link_model=CustomerProductLink,
sa_relationship_kwargs={'lazy': 'selectin'})
class CustomerOut(CustomerBase):
id: int
address: Optional[AddressOut]
class CustomerIn(CustomerBase):
address: Optional[AddressIn]
class ProductBase(SQLModel):
name: Optional[str] = None
class Product(ProductBase, table=True):
id: int = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional, List
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from sqlmodel import SQLModel, Field, Relationship
class CustomerProductLink(SQLModel, table=True):
customer_id: Optional[int] = Field(
default=None, foreign_key='customer.id', primary_key=True
)
product_id: Optional[int] = Field(
default=None, foreign_key='product.id', primary_key=True
)
class AddressBase(SQLModel):
street_name: str
house_number: str
city: str
zip_code: str
class Address(AddressBase, table=True):
id: int = Field(default=None, primary_key=True)
customers: List['Customer'] = Relationship(back_populates='address')
class AddressOut(AddressBase):
pass
class AddressIn(AddressBase):
pass
class CustomerBase(SQLModel):
first_name: str
last_name: str
birth_date: str
gender: str
mobile_number: str
email: str
class Customer(CustomerBase, table=True):
id: int = Field(default=None, primary_key=True)
address_id: Optional[int] = Field(default=None, foreign_key='address.id')
address: Optional[Address] = Relationship(back_populates='customers',
sa_relationship_kwargs={'lazy': 'selectin'})
mobile_number: str = Field(sa_column=Column('mobile_number', String, unique=True))
email: str = Field(sa_column=Column('email', String, unique=True))
products: List['Product'] = Relationship(back_populates='customers', link_model=CustomerProductLink,
sa_relationship_kwargs={'lazy': 'selectin'})
class CustomerOut(CustomerBase):
id: int
address: Optional[AddressOut]
class CustomerIn(CustomerBase):
address: Optional[AddressIn]
class ProductBase(SQLModel):
name: Optional[str] = None
class Product(ProductBase, table=True):
id: int = Field(default=None, primary_key=True)
name: str = Field(sa_column=Column('name', String, unique=True))
customers: List[Customer] = | Relationship(back_populates='products', link_model=CustomerProductLink) | sqlmodel.Relationship |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = | Relationship(link_model=ListingFacilityLink) | sqlmodel.Relationship |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = | Field(default=None, foreign_key="listings.id") | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = | Field(default=None, foreign_key="listings.id") | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class PlaceNearby(PlaceNearbyBase, table=True):
__tablename__ = 'places_nearby'
id: Optional[int] = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class PlaceNearby(PlaceNearbyBase, table=True):
__tablename__ = 'places_nearby'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="places_nearby",)
class PlaceNearbyRead(PlaceNearbyBase):
id: int
created_at: datetime
updated_at: datetime
class PlaceNearbyCreate(PlaceNearbyBase):
pass
# #############################################################################
class InterestPointBase(SQLModel):
id: Optional[int]
name: str
is_active: bool
latitude: Optional[float] = None
longitude: Optional[float] = None
class InterestPoint(InterestPointBase, table=True):
__tablename__ = 'interest_points'
id: Optional[int] = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class PlaceNearby(PlaceNearbyBase, table=True):
__tablename__ = 'places_nearby'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="places_nearby",)
class PlaceNearbyRead(PlaceNearbyBase):
id: int
created_at: datetime
updated_at: datetime
class PlaceNearbyCreate(PlaceNearbyBase):
pass
# #############################################################################
class InterestPointBase(SQLModel):
id: Optional[int]
name: str
is_active: bool
latitude: Optional[float] = None
longitude: Optional[float] = None
class InterestPoint(InterestPointBase, table=True):
__tablename__ = 'interest_points'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class InterestPointRead(InterestPointBase):
id: int
created_at: datetime
updated_at: datetime
class InterestPointCreate(InterestPointBase):
pass
# #############################################################################
class RouteBase(SQLModel):
id: Optional[int]
waking_distance: Optional[int] = 0
total_distance: Optional[int] = 0
total_time: Optional[int] = 0
public_transport_count: Optional[int] = 0
listing_id: Optional[int] = | Field(default=None, foreign_key="listings.id") | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class PlaceNearby(PlaceNearbyBase, table=True):
__tablename__ = 'places_nearby'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="places_nearby",)
class PlaceNearbyRead(PlaceNearbyBase):
id: int
created_at: datetime
updated_at: datetime
class PlaceNearbyCreate(PlaceNearbyBase):
pass
# #############################################################################
class InterestPointBase(SQLModel):
id: Optional[int]
name: str
is_active: bool
latitude: Optional[float] = None
longitude: Optional[float] = None
class InterestPoint(InterestPointBase, table=True):
__tablename__ = 'interest_points'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class InterestPointRead(InterestPointBase):
id: int
created_at: datetime
updated_at: datetime
class InterestPointCreate(InterestPointBase):
pass
# #############################################################################
class RouteBase(SQLModel):
id: Optional[int]
waking_distance: Optional[int] = 0
total_distance: Optional[int] = 0
total_time: Optional[int] = 0
public_transport_count: Optional[int] = 0
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
interest_point_id: Optional[int] = Field(
default=None, foreign_key="interest_points.id")
class Route(RouteBase, table=True):
__tablename__ = 'routes'
id: int = | Field(primary_key=True) | sqlmodel.Field |
from typing import Optional, List
import sqlalchemy
from sqlmodel import SQLModel, Field, Relationship
from datetime import date, datetime
# #############################################################################
# Links
class ListingFacilityLink(SQLModel, table=True):
listing_id: int = Field(
foreign_key="listings.id", primary_key=True
)
facility_id: int = Field(
foreign_key="facilities.id", primary_key=True
)
# #############################################################################
class SongBase(SQLModel):
id: Optional[int]
name: str
artist: str
year: Optional[int] = None
class Song(SongBase, table=True):
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class SongRead(SongBase):
id: int
created_at: datetime
updated_at: datetime
class SongUpdate(SQLModel):
name: Optional[str] = None
artist: Optional[str] = None
year: Optional[int] = None
class SongCreate(SongBase):
pass
class Increment(SQLModel, table=True):
id: int = Field(primary_key=True)
# #############################################################################
class ListingBase(SQLModel):
id: int = Field(primary_key=True)
is_active: bool
title: Optional[str] = None
description: Optional[str] = None
url: str
source: str
source_id: str
source_code: Optional[str] = None
address: str
short_postal_code: Optional[str] = None
property_type: Optional[str] = None
postal_code: Optional[str] = None
ber_code: Optional[str] = None
views: Optional[int] = None
bedrooms: Optional[int] = None
bathrooms: Optional[int] = None
price: Optional[int] = None
rating_auto: Optional[int] = None
rating_user: Optional[int] = None
telegram_sent_at: Optional[datetime] = None
images_count: Optional[int] = 0
latitude: Optional[float] = None
longitude: Optional[float] = None
notes: Optional[str] = None
publish_date: Optional[datetime] = None
last_updated: Optional[datetime] = None
class Listing(ListingBase, table=True):
__tablename__ = 'listings'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
images: List["Image"] = Relationship(back_populates="listing",
# sa_relationship_kwargs={'lazy': 'joined'}
)
facilities: List["Facility"] = Relationship(link_model=ListingFacilityLink)
places_nearby: List["PlaceNearby"] = Relationship(
back_populates="listing",)
routes: List["Route"] = Relationship(back_populates="listing",)
class ListingRead(ListingBase):
id: str
created_at: datetime
updated_at: datetime
class ListingCreate(ListingBase):
pass
class ListingUpdate(ListingBase):
id: Optional[str]
is_active: Optional[bool]
url: Optional[str]
source: Optional[str]
source_id: Optional[str]
address: Optional[str]
# #############################################################################
class FacilityBase(SQLModel):
id: Optional[int]
name: str
category: Optional[str] = None
notes: Optional[str] = None
class Facility(FacilityBase, table=True):
__tablename__ = 'facilities'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class FacilityRead(FacilityBase):
id: int
created_at: datetime
updated_at: datetime
class FacilityCreate(FacilityBase):
pass
# #############################################################################
class ImageBase(SQLModel):
id: Optional[int]
url: str
url_600: Optional[str]
size_x: Optional[float]
size_y: Optional[float]
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class Image(ImageBase, table=True):
__tablename__ = 'images'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="images",
# sa_relationship_kwargs={'lazy': 'selectin'}
)
class ImageRead(ImageBase):
id: int
created_at: datetime
updated_at: datetime
class ImageCreate(ImageBase):
pass
# #############################################################################
class PlaceNearbyBase(SQLModel):
id: Optional[int]
latitude: Optional[float] = None
longitude: Optional[float] = None
query: Optional[str] = None
name: str
address: str
distance: int
website: Optional[str] = None
website_domain: Optional[str] = None
chain_name: Optional[str] = None
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
class PlaceNearby(PlaceNearbyBase, table=True):
__tablename__ = 'places_nearby'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="places_nearby",)
class PlaceNearbyRead(PlaceNearbyBase):
id: int
created_at: datetime
updated_at: datetime
class PlaceNearbyCreate(PlaceNearbyBase):
pass
# #############################################################################
class InterestPointBase(SQLModel):
id: Optional[int]
name: str
is_active: bool
latitude: Optional[float] = None
longitude: Optional[float] = None
class InterestPoint(InterestPointBase, table=True):
__tablename__ = 'interest_points'
id: Optional[int] = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
class InterestPointRead(InterestPointBase):
id: int
created_at: datetime
updated_at: datetime
class InterestPointCreate(InterestPointBase):
pass
# #############################################################################
class RouteBase(SQLModel):
id: Optional[int]
waking_distance: Optional[int] = 0
total_distance: Optional[int] = 0
total_time: Optional[int] = 0
public_transport_count: Optional[int] = 0
listing_id: Optional[int] = Field(default=None, foreign_key="listings.id")
interest_point_id: Optional[int] = Field(
default=None, foreign_key="interest_points.id")
class Route(RouteBase, table=True):
__tablename__ = 'routes'
id: int = Field(primary_key=True)
created_at: datetime = Field(default=datetime.now())
updated_at: datetime = Field(
default=datetime.now(),
sa_column_kwargs={'onupdate': datetime.now()})
listing: Optional[Listing] = Relationship(back_populates="routes",)
interest_point: Optional[InterestPoint] = | Relationship() | sqlmodel.Relationship |
"""add application resume
Revision ID: 07061a7c250f
Revises: 378a9b9a491b
Create Date: 2022-04-26 08:00:47.428979+00:00
"""
import sqlalchemy as sa
import sqlmodel
from alembic import op
# revision identifiers, used by Alembic.
revision = "07061a7c250f"
down_revision = "378a9b9a491b"
branch_labels = None
depends_on = None
def upgrade():
op.add_column(
"applications",
sa.Column("resume", | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSON
from sqlmodel import Field, Relationship
from api.db.models.base import BaseModel, BaseTable
class OutOfBandBase(BaseModel):
msg_type: str = | Field(nullable=False) | sqlmodel.Field |
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSON
from sqlmodel import Field, Relationship
from api.db.models.base import BaseModel, BaseTable
class OutOfBandBase(BaseModel):
msg_type: str = Field(nullable=False)
msg: dict = Field(default={}, sa_column=Column(JSON))
sender_id: uuid.UUID = None
recipient_id: uuid.UUID = None
sandbox_id: uuid.UUID = None
action: Optional[str] = | Field(nullable=True) | sqlmodel.Field |
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSON
from sqlmodel import Field, Relationship
from api.db.models.base import BaseModel, BaseTable
class OutOfBandBase(BaseModel):
msg_type: str = Field(nullable=False)
msg: dict = Field(default={}, sa_column=Column(JSON))
sender_id: uuid.UUID = None
recipient_id: uuid.UUID = None
sandbox_id: uuid.UUID = None
action: Optional[str] = Field(nullable=True)
class OutOfBand(OutOfBandBase, BaseTable, table=True):
__tablename__ = "out_of_band"
# optional else, required on save
sender_id: uuid.UUID = | Field(foreign_key="line_of_business.id") | sqlmodel.Field |
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSON
from sqlmodel import Field, Relationship
from api.db.models.base import BaseModel, BaseTable
class OutOfBandBase(BaseModel):
msg_type: str = Field(nullable=False)
msg: dict = Field(default={}, sa_column=Column(JSON))
sender_id: uuid.UUID = None
recipient_id: uuid.UUID = None
sandbox_id: uuid.UUID = None
action: Optional[str] = Field(nullable=True)
class OutOfBand(OutOfBandBase, BaseTable, table=True):
__tablename__ = "out_of_band"
# optional else, required on save
sender_id: uuid.UUID = Field(foreign_key="line_of_business.id")
recipient_id: uuid.UUID = | Field(foreign_key="line_of_business.id") | sqlmodel.Field |
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import Column
from sqlalchemy.dialects.postgresql import JSON
from sqlmodel import Field, Relationship
from api.db.models.base import BaseModel, BaseTable
class OutOfBandBase(BaseModel):
msg_type: str = Field(nullable=False)
msg: dict = Field(default={}, sa_column=Column(JSON))
sender_id: uuid.UUID = None
recipient_id: uuid.UUID = None
sandbox_id: uuid.UUID = None
action: Optional[str] = Field(nullable=True)
class OutOfBand(OutOfBandBase, BaseTable, table=True):
__tablename__ = "out_of_band"
# optional else, required on save
sender_id: uuid.UUID = Field(foreign_key="line_of_business.id")
recipient_id: uuid.UUID = Field(foreign_key="line_of_business.id")
sandbox_id: uuid.UUID = | Field(foreign_key="sandbox.id") | sqlmodel.Field |
"""Example code"""
from sqlmodel import Field, SQLModel
class CarBase(SQLModel):
"""
CarBase is the base model. This is a data-only model(Pydantic), since it lacks `table=True`.
"""
name: str
manufacturer: str
class Car(CarBase, table=True): # type: ignore
"""
Add `id` property to the base model. Since `table=True` it is a pydantic AND SQLAlchemy model
and represents a database table.
"""
id: int = | Field(default=None, primary_key=True) | sqlmodel.Field |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('country', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('country', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('address', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('country', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('hashed_password', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('country', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('hashed_password', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
op.create_index(op.f('ix_user_hashed_password'), 'user', ['hashed_password'], unique=False)
op.create_table('textinference',
sa.Column('result', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('text', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""empty message
Revision ID: 2d614148ea4b
Revises:
Create Date: 2022-03-17 22:29:00.613962
"""
from alembic import op
import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel # added
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '2d614148ea4b'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('role',
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('description', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('user',
sa.Column('first_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('last_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('is_active', sa.Boolean(), nullable=True),
sa.Column('is_superuser', sa.Boolean(), nullable=True),
sa.Column('birthdate', sa.DateTime(), nullable=True),
sa.Column('phone', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('state', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('country', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('address', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('hashed_password', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('role_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
op.create_index(op.f('ix_user_hashed_password'), 'user', ['hashed_password'], unique=False)
op.create_table('textinference',
sa.Column('result', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('text', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('created_at', sa.DateTime(), nullable=True),
sa.Column('updated_at', sa.DateTime(), nullable=True),
sa.Column('created_by_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['created_by_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_textinference_text'), 'textinference', ['text'], unique=False)
op.create_table('zeroshotinference',
sa.Column('candidate_labels', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('result', postgresql.JSON(astext_type=sa.Text()), nullable=True),
sa.Column('text', | sqlmodel.sql.sqltypes.AutoString() | sqlmodel.sql.sqltypes.AutoString |
"""Arquivo para fixtures"""
from unittest.mock import patch
from pytest import fixture
from sqlmodel import create_engine, SQLModel
from tests.mocks import mock_user
from mitmirror.infra.entities import * # pylint: disable=W0614, W0401
user = mock_user()
@fixture(scope="module")
def fake_user():
"""Mock de usuario"""
return user
@fixture(autouse=True, scope="function")
def separate_database(request):
"""
Cria um mock do banco de dados para que cada teste use um banco separado.
"""
tmpdir = request.getfixturevalue("tmpdir")
test_db = tmpdir.join("mitmirror.test.db")
engine = | create_engine(f"sqlite:///{test_db}") | sqlmodel.create_engine |
"""Arquivo para fixtures"""
from unittest.mock import patch
from pytest import fixture
from sqlmodel import create_engine, SQLModel
from tests.mocks import mock_user
from mitmirror.infra.entities import * # pylint: disable=W0614, W0401
user = mock_user()
@fixture(scope="module")
def fake_user():
"""Mock de usuario"""
return user
@fixture(autouse=True, scope="function")
def separate_database(request):
"""
Cria um mock do banco de dados para que cada teste use um banco separado.
"""
tmpdir = request.getfixturevalue("tmpdir")
test_db = tmpdir.join("mitmirror.test.db")
engine = create_engine(f"sqlite:///{test_db}")
| SQLModel.metadata.create_all(engine) | sqlmodel.SQLModel.metadata.create_all |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = | create_engine('sqlite:///database.db') | sqlmodel.create_engine |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = Field(default=None, primary_key=True)
nome: str
idade: str
| SQLModel.metadata.create_all(engine) | sqlmodel.SQLModel.metadata.create_all |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = Field(default=None, primary_key=True)
nome: str
idade: str
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.get('/')
def home():
return {'message' : 'Deu bom!!!'}
@app.get('/pessoa')
def pessoa():
query = | select(Pessoa) | sqlmodel.select |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = Field(default=None, primary_key=True)
nome: str
idade: str
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.get('/')
def home():
return {'message' : 'Deu bom!!!'}
@app.get('/pessoa')
def pessoa():
query = select(Pessoa)
with Session(engine) as session:
result = session.execute(query).scalars().all()
return result
@app.get('/pessoas-nome')
def pessoa():
query = | select(Pessoa.nome) | sqlmodel.select |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = Field(default=None, primary_key=True)
nome: str
idade: str
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.get('/')
def home():
return {'message' : 'Deu bom!!!'}
@app.get('/pessoa')
def pessoa():
query = select(Pessoa)
with | Session(engine) | sqlmodel.Session |
from typing import Optional
from fastapi import FastAPI
from sqlalchemy.sql.expression import table
from sqlmodel import (
SQLModel,
Field,
create_engine,
select,
Session
)
engine = create_engine('sqlite:///database.db')
class Pessoa(SQLModel, table=True):
id : Optional[int] = Field(default=None, primary_key=True)
nome: str
idade: str
SQLModel.metadata.create_all(engine)
app = FastAPI()
@app.get('/')
def home():
return {'message' : 'Deu bom!!!'}
@app.get('/pessoa')
def pessoa():
query = select(Pessoa)
with Session(engine) as session:
result = session.execute(query).scalars().all()
return result
@app.get('/pessoas-nome')
def pessoa():
query = select(Pessoa.nome)
with | Session(engine) | sqlmodel.Session |
from glob import glob
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Image(SQLModel, table=True):
key: Optional[int] = Field(default=None, primary_key=True)
image_name: str
label: str
image_url: str
engine = | create_engine("sqlite:///image.db") | sqlmodel.create_engine |
from glob import glob
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Image(SQLModel, table=True):
key: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from glob import glob
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Image(SQLModel, table=True):
key: Optional[int] = Field(default=None, primary_key=True)
image_name: str
label: str
image_url: str
engine = create_engine("sqlite:///image.db")
def read_images():
with | Session(engine) | sqlmodel.Session |
from glob import glob
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Image(SQLModel, table=True):
key: Optional[int] = Field(default=None, primary_key=True)
image_name: str
label: str
image_url: str
engine = create_engine("sqlite:///image.db")
def read_images():
with Session(engine) as session:
statement = | select(Image) | sqlmodel.select |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class IdType(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class IdType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class FeedbackType(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class IdType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class FeedbackType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class VisibilityLevel(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class IdType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class FeedbackType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class VisibilityLevel(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Module(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from datetime import datetime
from typing import Optional
from fastapi import APIRouter
from sqlmodel import Field, SQLModel
router = APIRouter()
class Right(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Province(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Amphoe(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
province_id: int
name: str
class Tambon(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
amphoe_id: int
name: str
class Religion(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class National(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Occupation(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class MaritalStatus(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class AcademicDegree(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Allergy(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Vehicle(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Language(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Relationship(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class IdType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class FeedbackType(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class VisibilityLevel(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
class Module(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
detail: str
created_at: datetime
updated_at: datetime
created_by: int
updated_by: Optional[int] = None
class ModuleFunction(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from sqlmodel import Session, select
from db import BaseDBModel
from service.base_crud import BaseCRUD
class TestTable(BaseDBModel, table=True):
test_str: str
test_int: int
TEST_ROW_DATA1 = {'test_str': 'str1', 'test_int': 1}
TEST_ROW_DATA2 = {'test_str': 'str2', 'test_int': 2}
class TestCRUD(BaseCRUD):
model = TestTable
test_crud = TestCRUD()
def test_get_returns_none_for_not_existing_rows(session: Session):
row = TestTable(**TEST_ROW_DATA1)
result_row = test_crud.get(session, row.id)
assert result_row is None
def test_get_returns_existing_row(session: Session):
row = TestTable(**TEST_ROW_DATA1)
session.add(row)
session.commit()
result_row: TestTable = test_crud.get(session, row.id)
assert row == result_row
def test_get_multiple_values_returns_empty_array_for_not_existing_rows(session: Session):
result_arr = test_crud.get_multiple_values(session)
assert len(result_arr) == 0
def create_and_return_multiple_rows(db_session: Session):
row1 = TestTable(**TEST_ROW_DATA1)
row2 = TestTable(**TEST_ROW_DATA2)
db_session.add(row1)
db_session.add(row2)
db_session.commit()
return [row1, row2]
def test_get_multiple_values_returns_existing_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session)
assert result_arr == rows
def test_get_multiple_values_returns_limited_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session, limit=1)
assert result_arr == [rows[0]]
def test_get_multiple_values_returns_offset_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session, offset=1)
assert result_arr == [rows[1]]
def test_create_row_returns_inserted_row(session: Session):
row = TestTable(**TEST_ROW_DATA1)
inserted_row: TestTable = test_crud.create(session, row)
assert inserted_row == row
def test_create_all_does_not_throw_errors(session: Session):
rows = [TestTable(**TEST_ROW_DATA1), TestTable(**TEST_ROW_DATA2)]
test_crud.create_all(session, rows)
inserted_rows = session.exec( | select(TestTable) | sqlmodel.select |
from sqlmodel import Session, select
from db import BaseDBModel
from service.base_crud import BaseCRUD
class TestTable(BaseDBModel, table=True):
test_str: str
test_int: int
TEST_ROW_DATA1 = {'test_str': 'str1', 'test_int': 1}
TEST_ROW_DATA2 = {'test_str': 'str2', 'test_int': 2}
class TestCRUD(BaseCRUD):
model = TestTable
test_crud = TestCRUD()
def test_get_returns_none_for_not_existing_rows(session: Session):
row = TestTable(**TEST_ROW_DATA1)
result_row = test_crud.get(session, row.id)
assert result_row is None
def test_get_returns_existing_row(session: Session):
row = TestTable(**TEST_ROW_DATA1)
session.add(row)
session.commit()
result_row: TestTable = test_crud.get(session, row.id)
assert row == result_row
def test_get_multiple_values_returns_empty_array_for_not_existing_rows(session: Session):
result_arr = test_crud.get_multiple_values(session)
assert len(result_arr) == 0
def create_and_return_multiple_rows(db_session: Session):
row1 = TestTable(**TEST_ROW_DATA1)
row2 = TestTable(**TEST_ROW_DATA2)
db_session.add(row1)
db_session.add(row2)
db_session.commit()
return [row1, row2]
def test_get_multiple_values_returns_existing_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session)
assert result_arr == rows
def test_get_multiple_values_returns_limited_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session, limit=1)
assert result_arr == [rows[0]]
def test_get_multiple_values_returns_offset_rows(session: Session):
rows = create_and_return_multiple_rows(session)
result_arr = test_crud.get_multiple_values(session, offset=1)
assert result_arr == [rows[1]]
def test_create_row_returns_inserted_row(session: Session):
row = TestTable(**TEST_ROW_DATA1)
inserted_row: TestTable = test_crud.create(session, row)
assert inserted_row == row
def test_create_all_does_not_throw_errors(session: Session):
rows = [TestTable(**TEST_ROW_DATA1), TestTable(**TEST_ROW_DATA2)]
test_crud.create_all(session, rows)
inserted_rows = session.exec(select(TestTable)).all()
assert inserted_rows == rows
def test_update_returns_updated_row(session: Session):
row = TestTable(**TEST_ROW_DATA1)
session.add(row)
session.commit()
new_item = TestTable.from_orm(row)
new_item.test_int = 10
updated_row: TestTable = test_crud.update(session, row, new_item)
assert new_item.test_int == updated_row.test_int
def test_delete_row_does_not_throw_error(session: Session):
row = TestTable(**TEST_ROW_DATA1)
session.add(row)
session.commit()
test_crud.delete(session, row.id)
inserted_row = session.exec(
| select(TestTable) | sqlmodel.select |
from typing import List, Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Zi(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(...)
stroke_count: int = Field(...)
strokes: str = Field(...)
heng_count: int = Field(...)
shu_count: int = Field(...)
pie_count: int = Field(...)
dian_count: int = Field(...)
zhe_count: int = Field(...)
engine = | create_engine('sqlite:///Data/strokes.db', connect_args={'check_same_thread': False}) | sqlmodel.create_engine |
from typing import List, Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Zi(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(...)
stroke_count: int = Field(...)
strokes: str = Field(...)
heng_count: int = Field(...)
shu_count: int = Field(...)
pie_count: int = Field(...)
dian_count: int = Field(...)
zhe_count: int = Field(...)
engine = create_engine('sqlite:///Data/strokes.db', connect_args={'check_same_thread': False})
| SQLModel.metadata.create_all(engine) | sqlmodel.SQLModel.metadata.create_all |
from typing import List, Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Zi(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(...)
stroke_count: int = Field(...)
strokes: str = Field(...)
heng_count: int = Field(...)
shu_count: int = Field(...)
pie_count: int = Field(...)
dian_count: int = Field(...)
zhe_count: int = Field(...)
engine = create_engine('sqlite:///Data/strokes.db', connect_args={'check_same_thread': False})
SQLModel.metadata.create_all(engine)
session = | Session(engine) | sqlmodel.Session |
from typing import List, Optional
from sqlmodel import Field, Session, SQLModel, create_engine
class Zi(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role)
results = session.exec(statement).all()
return results
@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of active roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role)
results = session.exec(statement).all()
return results
@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of active roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.is_active == True)
results = session.exec(statement).all()
return results
@router.put("/{role_id}/activate")
async def activate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Activate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be activated.
session : Session
SQL session that is to be used to activate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role)
results = session.exec(statement).all()
return results
@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of active roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.is_active == True)
results = session.exec(statement).all()
return results
@router.put("/{role_id}/activate")
async def activate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Activate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be activated.
session : Session
SQL session that is to be used to activate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role_id)
role_to_activate = session.exec(statement).one()
role_to_activate.is_active = True
role_to_activate.updated_at = datetime.now()
session.add(role_to_activate)
session.commit()
session.refresh(role_to_activate)
return role_to_activate
@router.put("/{role_id}/deactivate")
async def deactivate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Deactivate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be deactivated.
session : Session
SQL session that is to be used to deactivate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role)
results = session.exec(statement).all()
return results
@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of active roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.is_active == True)
results = session.exec(statement).all()
return results
@router.put("/{role_id}/activate")
async def activate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Activate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be activated.
session : Session
SQL session that is to be used to activate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role_id)
role_to_activate = session.exec(statement).one()
role_to_activate.is_active = True
role_to_activate.updated_at = datetime.now()
session.add(role_to_activate)
session.commit()
session.refresh(role_to_activate)
return role_to_activate
@router.put("/{role_id}/deactivate")
async def deactivate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Deactivate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be deactivated.
session : Session
SQL session that is to be used to deactivate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role_id)
role_to_deactivate = session.exec(statement).one()
role_to_deactivate.is_active = False
role_to_deactivate.updated_at = datetime.now()
session.add(role_to_deactivate)
session.commit()
session.refresh(role_to_deactivate)
return role_to_deactivate
@router.put("/")
async def update_role(
id: str = None,
new_name: str = None,
new_short_name: str = None,
is_active: bool = None,
session: Session = Depends(get_session),
):
"""
Update a role.
Parameters
----------
id : str
ID of role to be updated.
new_name : str
New name of the role.
new_short_name : str
New short name of the role.
is_active : bool
New status of the role.
session : Session
SQL session that is to be used to update the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = | select(Role.is_active) | 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.role import Role
from datetime import datetime
router = APIRouter(prefix="/api/roles", tags=["role"])
session = Session(engine)
@router.post("/")
async def post_role(*, role: Role, session: Session = Depends(get_session)):
"""
Post a new role.
Parameters
----------
role : Role
Role that is to be added to the database.
session : Session
SQL session that is to be used to add the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role.id)
try:
result = session.exec(statement).one()
return False
except NoResultFound:
session.add(role)
session.commit()
session.refresh(role)
return role
@router.get("/")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of all roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role)
results = session.exec(statement).all()
return results
@router.get("/active")
async def read_roles(session: Session = Depends(get_session)):
"""
Get list of active roles.
Parameters
----------
session : Session
SQL session that is to be used to get the roles.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.is_active == True)
results = session.exec(statement).all()
return results
@router.put("/{role_id}/activate")
async def activate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Activate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be activated.
session : Session
SQL session that is to be used to activate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role_id)
role_to_activate = session.exec(statement).one()
role_to_activate.is_active = True
role_to_activate.updated_at = datetime.now()
session.add(role_to_activate)
session.commit()
session.refresh(role_to_activate)
return role_to_activate
@router.put("/{role_id}/deactivate")
async def deactivate_role(
role_id: str = None,
session: Session = Depends(get_session),
):
"""
Deactivate a role using the role ID as a key.
Parameters
----------
role_id : str
ID of role to be deactivated.
session : Session
SQL session that is to be used to deactivate the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role).where(Role.id == role_id)
role_to_deactivate = session.exec(statement).one()
role_to_deactivate.is_active = False
role_to_deactivate.updated_at = datetime.now()
session.add(role_to_deactivate)
session.commit()
session.refresh(role_to_deactivate)
return role_to_deactivate
@router.put("/")
async def update_role(
id: str = None,
new_name: str = None,
new_short_name: str = None,
is_active: bool = None,
session: Session = Depends(get_session),
):
"""
Update a role.
Parameters
----------
id : str
ID of role to be updated.
new_name : str
New name of the role.
new_short_name : str
New short name of the role.
is_active : bool
New status of the role.
session : Session
SQL session that is to be used to update the role.
Defaults to creating a dependency on the running SQL model session.
"""
statement = select(Role.is_active).where(Role.id == id)
result = session.exec(statement).first()
if result == True:
statement = | select(Role) | sqlmodel.select |
from datetime import datetime
from typing import Optional
from sqlmodel import Field, SQLModel
class YouTube(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from time import sleep
from sqlmodel import select
from icon_governance.config import settings
from icon_governance.log import logger
from icon_governance.metrics import prom_metrics
from icon_governance.models.preps import Prep
from icon_governance.utils.rpc import convert_hex_int, getStake, post_rpc_json
def get_prep_stake(session):
result = session.execute( | select(Prep) | sqlmodel.select |
"""
dayong.impls
~~~~~~~~~~~~
Implementaion of interfaces and the logic for injecting them.
"""
import asyncio
from typing import Any
import tanjun
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlmodel import SQLModel, select
from sqlmodel.engine.result import ScalarResult
from sqlmodel.ext.asyncio.session import AsyncSession
from dayong.configs import DayongConfig, DayongConfigLoader
from dayong.models import Message
class MessageDBImpl:
"""Implementaion of a database connection for transacting and interacting with
message tables, those of which derive from message table models.
The data to be selected, retrieved, and modified is determined by the table model
object and its type. The type, in this case, is `dayong.models.Message`.
"""
def __init__(self) -> None:
self._conn: AsyncEngine
async def connect(self, config: DayongConfig = tanjun.injected(type=DayongConfig)):
"""Create a database connection.
If the `database_uri` is Falsy, the function will reattempt to get the url from
the environment variables.
Args:
config (DayongConfig, optional): [description]. Defaults to
tanjun.injected(type=DayongConfig).
"""
loop = asyncio.get_running_loop()
self._conn = await loop.run_in_executor(
None,
create_async_engine,
config.database_uri if config.database_uri else DayongConfigLoader().load(),
)
async def create_table(self) -> None:
"""Create physical message tables for all the message table models stored in
`SQLModel.metadata`.
"""
async with self._conn.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def add_row(self, tabe_model_object: Message) -> None:
"""Insert a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
async with | AsyncSession(self._conn) | sqlmodel.ext.asyncio.session.AsyncSession |
"""
dayong.impls
~~~~~~~~~~~~
Implementaion of interfaces and the logic for injecting them.
"""
import asyncio
from typing import Any
import tanjun
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlmodel import SQLModel, select
from sqlmodel.engine.result import ScalarResult
from sqlmodel.ext.asyncio.session import AsyncSession
from dayong.configs import DayongConfig, DayongConfigLoader
from dayong.models import Message
class MessageDBImpl:
"""Implementaion of a database connection for transacting and interacting with
message tables, those of which derive from message table models.
The data to be selected, retrieved, and modified is determined by the table model
object and its type. The type, in this case, is `dayong.models.Message`.
"""
def __init__(self) -> None:
self._conn: AsyncEngine
async def connect(self, config: DayongConfig = tanjun.injected(type=DayongConfig)):
"""Create a database connection.
If the `database_uri` is Falsy, the function will reattempt to get the url from
the environment variables.
Args:
config (DayongConfig, optional): [description]. Defaults to
tanjun.injected(type=DayongConfig).
"""
loop = asyncio.get_running_loop()
self._conn = await loop.run_in_executor(
None,
create_async_engine,
config.database_uri if config.database_uri else DayongConfigLoader().load(),
)
async def create_table(self) -> None:
"""Create physical message tables for all the message table models stored in
`SQLModel.metadata`.
"""
async with self._conn.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def add_row(self, tabe_model_object: Message) -> None:
"""Insert a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
async with AsyncSession(self._conn) as session:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, session.add, tabe_model_object)
await session.commit()
async def remove_row(self, tabe_model_object: Message) -> None:
"""Delete a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
table_model = type(tabe_model_object)
async with | AsyncSession(self._conn) | sqlmodel.ext.asyncio.session.AsyncSession |
"""
dayong.impls
~~~~~~~~~~~~
Implementaion of interfaces and the logic for injecting them.
"""
import asyncio
from typing import Any
import tanjun
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlmodel import SQLModel, select
from sqlmodel.engine.result import ScalarResult
from sqlmodel.ext.asyncio.session import AsyncSession
from dayong.configs import DayongConfig, DayongConfigLoader
from dayong.models import Message
class MessageDBImpl:
"""Implementaion of a database connection for transacting and interacting with
message tables, those of which derive from message table models.
The data to be selected, retrieved, and modified is determined by the table model
object and its type. The type, in this case, is `dayong.models.Message`.
"""
def __init__(self) -> None:
self._conn: AsyncEngine
async def connect(self, config: DayongConfig = tanjun.injected(type=DayongConfig)):
"""Create a database connection.
If the `database_uri` is Falsy, the function will reattempt to get the url from
the environment variables.
Args:
config (DayongConfig, optional): [description]. Defaults to
tanjun.injected(type=DayongConfig).
"""
loop = asyncio.get_running_loop()
self._conn = await loop.run_in_executor(
None,
create_async_engine,
config.database_uri if config.database_uri else DayongConfigLoader().load(),
)
async def create_table(self) -> None:
"""Create physical message tables for all the message table models stored in
`SQLModel.metadata`.
"""
async with self._conn.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def add_row(self, tabe_model_object: Message) -> None:
"""Insert a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
async with AsyncSession(self._conn) as session:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, session.add, tabe_model_object)
await session.commit()
async def remove_row(self, tabe_model_object: Message) -> None:
"""Delete a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
table_model = type(tabe_model_object)
async with AsyncSession(self._conn) as session:
# Temp ignore incompatible type passed to `exec()`. See:
# https://github.com/tiangolo/sqlmodel/issues/54
# https://github.com/tiangolo/sqlmodel/pull/58
row: ScalarResult[Any] = await session.exec(
select(table_model).where( # type: ignore
table_model.message_id == tabe_model_object.message_id
)
)
await session.delete(row)
await session.commit()
async def get_row(self, tabe_model_object: Message) -> ScalarResult[Any]:
"""Fetch a row from the message table.
Args:
tabe_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
Returns:
ScalarResult: An `ScalarResult` object which contains a scalar value or
sequence of scalar values.
"""
table_model = type(tabe_model_object)
async with | AsyncSession(self._conn) | sqlmodel.ext.asyncio.session.AsyncSession |
"""
dayong.impls
~~~~~~~~~~~~
Implementaion of interfaces and the logic for injecting them.
"""
import asyncio
from typing import Any
import tanjun
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlmodel import SQLModel, select
from sqlmodel.engine.result import ScalarResult
from sqlmodel.ext.asyncio.session import AsyncSession
from dayong.configs import DayongConfig, DayongConfigLoader
from dayong.models import Message
class MessageDBImpl:
"""Implementaion of a database connection for transacting and interacting with
message tables, those of which derive from message table models.
The data to be selected, retrieved, and modified is determined by the table model
object and its type. The type, in this case, is `dayong.models.Message`.
"""
def __init__(self) -> None:
self._conn: AsyncEngine
async def connect(self, config: DayongConfig = tanjun.injected(type=DayongConfig)):
"""Create a database connection.
If the `database_uri` is Falsy, the function will reattempt to get the url from
the environment variables.
Args:
config (DayongConfig, optional): [description]. Defaults to
tanjun.injected(type=DayongConfig).
"""
loop = asyncio.get_running_loop()
self._conn = await loop.run_in_executor(
None,
create_async_engine,
config.database_uri if config.database_uri else DayongConfigLoader().load(),
)
async def create_table(self) -> None:
"""Create physical message tables for all the message table models stored in
`SQLModel.metadata`.
"""
async with self._conn.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def add_row(self, tabe_model_object: Message) -> None:
"""Insert a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
async with AsyncSession(self._conn) as session:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, session.add, tabe_model_object)
await session.commit()
async def remove_row(self, tabe_model_object: Message) -> None:
"""Delete a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
table_model = type(tabe_model_object)
async with AsyncSession(self._conn) as session:
# Temp ignore incompatible type passed to `exec()`. See:
# https://github.com/tiangolo/sqlmodel/issues/54
# https://github.com/tiangolo/sqlmodel/pull/58
row: ScalarResult[Any] = await session.exec(
| select(table_model) | sqlmodel.select |
"""
dayong.impls
~~~~~~~~~~~~
Implementaion of interfaces and the logic for injecting them.
"""
import asyncio
from typing import Any
import tanjun
from sqlalchemy.ext.asyncio import AsyncEngine, create_async_engine
from sqlmodel import SQLModel, select
from sqlmodel.engine.result import ScalarResult
from sqlmodel.ext.asyncio.session import AsyncSession
from dayong.configs import DayongConfig, DayongConfigLoader
from dayong.models import Message
class MessageDBImpl:
"""Implementaion of a database connection for transacting and interacting with
message tables, those of which derive from message table models.
The data to be selected, retrieved, and modified is determined by the table model
object and its type. The type, in this case, is `dayong.models.Message`.
"""
def __init__(self) -> None:
self._conn: AsyncEngine
async def connect(self, config: DayongConfig = tanjun.injected(type=DayongConfig)):
"""Create a database connection.
If the `database_uri` is Falsy, the function will reattempt to get the url from
the environment variables.
Args:
config (DayongConfig, optional): [description]. Defaults to
tanjun.injected(type=DayongConfig).
"""
loop = asyncio.get_running_loop()
self._conn = await loop.run_in_executor(
None,
create_async_engine,
config.database_uri if config.database_uri else DayongConfigLoader().load(),
)
async def create_table(self) -> None:
"""Create physical message tables for all the message table models stored in
`SQLModel.metadata`.
"""
async with self._conn.begin() as conn:
await conn.run_sync(SQLModel.metadata.create_all)
async def add_row(self, tabe_model_object: Message) -> None:
"""Insert a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
async with AsyncSession(self._conn) as session:
loop = asyncio.get_running_loop()
await loop.run_in_executor(None, session.add, tabe_model_object)
await session.commit()
async def remove_row(self, tabe_model_object: Message) -> None:
"""Delete a row in the message table.
Args:
table_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
"""
table_model = type(tabe_model_object)
async with AsyncSession(self._conn) as session:
# Temp ignore incompatible type passed to `exec()`. See:
# https://github.com/tiangolo/sqlmodel/issues/54
# https://github.com/tiangolo/sqlmodel/pull/58
row: ScalarResult[Any] = await session.exec(
select(table_model).where( # type: ignore
table_model.message_id == tabe_model_object.message_id
)
)
await session.delete(row)
await session.commit()
async def get_row(self, tabe_model_object: Message) -> ScalarResult[Any]:
"""Fetch a row from the message table.
Args:
tabe_model_object (Message): An instance of `dayong.models.Message` or one
of its subclasses.
Returns:
ScalarResult: An `ScalarResult` object which contains a scalar value or
sequence of scalar values.
"""
table_model = type(tabe_model_object)
async with AsyncSession(self._conn) as session:
# Temp ignore incompatible type passed to `exec()`. See:
# https://github.com/tiangolo/sqlmodel/issues/54
# https://github.com/tiangolo/sqlmodel/pull/58
row: ScalarResult[Any] = await session.exec(
| select(table_model) | sqlmodel.select |
from sqlmodel import Field
from typing import Optional
from app.models.base_uuid_model import BaseUUIDModel
from uuid import UUID
class LinkGroupUser(BaseUUIDModel, table=True):
group_id: Optional[UUID] = | Field(default=None, nullable=False, foreign_key="group.id", primary_key=True) | sqlmodel.Field |
from sqlmodel import Field
from typing import Optional
from app.models.base_uuid_model import BaseUUIDModel
from uuid import UUID
class LinkGroupUser(BaseUUIDModel, table=True):
group_id: Optional[UUID] = Field(default=None, nullable=False, foreign_key="group.id", primary_key=True)
user_id: Optional[UUID] = | Field(default=None, nullable=False, foreign_key="user.id", primary_key=True) | sqlmodel.Field |
from typing import List, Optional
from functools import wraps
from uuid import UUID
from sqlalchemy.sql.schema import UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
# monkeypath from https://github.com/tiangolo/sqlmodel/issues/9
# without this all database fields are indexed be default
def set_default_index(func):
"""Decorator to set default index for SQLModel
Can be removed when https://github.com/tiangolo/sqlmodel/pull/11 is merged
"""
@wraps(func)
def inner(*args, index=False, **kwargs):
return func(*args, index=index, **kwargs)
return inner
# monkey patch field with default index=False
# this works as long as we always call Field()
Field = set_default_index(Field)
class TopicModelBase(SQLModel):
model_id: UUID = | Field() | sqlmodel.Field |
from typing import List, Optional
from functools import wraps
from uuid import UUID
from sqlalchemy.sql.schema import UniqueConstraint
from sqlmodel import Field, Relationship, SQLModel
# monkeypath from https://github.com/tiangolo/sqlmodel/issues/9
# without this all database fields are indexed be default
def set_default_index(func):
"""Decorator to set default index for SQLModel
Can be removed when https://github.com/tiangolo/sqlmodel/pull/11 is merged
"""
@wraps(func)
def inner(*args, index=False, **kwargs):
return func(*args, index=index, **kwargs)
return inner
# monkey patch field with default index=False
# this works as long as we always call Field()
Field = set_default_index(Field)
class TopicModelBase(SQLModel):
model_id: UUID = Field()
version: int = | Field(default=1) | sqlmodel.Field |