DbServ和Mapper

DbServ原理

from lessweb import Context
class DatabaseKey(Enum):
    session = 1

class DbServ:
    ctx: Context

    @property
    def db(self) -> Session:
        session = self.ctx.box.get(DatabaseKey.session)
        if session is None:
            raise ValueError('database session not available')
        return session

    def mapper(self, cls: Type[T]) -> 'Mapper[T]':
        return Mapper(self.db, cls)

Mapper API

class Mapper(Generic[T]):
    tablename: str
    primary_key: str
    def __init__(self, session: Session, cls: Type[T]) -> None: ...
    def _where_clause(self) -> str: ...
    def _full_select_sql(self) -> str: ...
    def bridge(self, row) -> T: ...
    def select_count(self) -> int: ...
    def select_first(self) -> Optional[T]: ...
    def select(self) -> List[T]: ...
    def insert(self, obj: T, commit: bool=True) -> None: ...
    def insert_if_not_exist(self, obj: T, commit: bool=True) -> None: ...
    def update(self, obj: T, commit: bool=True) -> None: ...
    def increment(self, obj: T, commit: bool=True) -> None: ...
    def delete(self, commit: bool=True) -> None: ...
    def by_id(self, primary_key: Union[int, str]) -> 'Mapper[T]': ...
    def and_equal(self, obj: Union[T, Dict[str, Any]]) -> 'Mapper[T]': ...
    def and_(self, clause: str, data: Storage) -> 'Mapper[T]': ...
    def order_desc(self) -> 'Mapper[T]': ...
    def order_by(self, clause: str) -> 'Mapper[T]': ...

示例

可参考lessdoc源码:https://github.com/qorzj/lessdoc