from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, relationship


# _V 对象 ，_T 类 ，_W 判断条件，_J join表
class Dao():
    # session=sessionmaker()
    def __init__(self, str):
        engine = create_engine(str)
        DBSession = sessionmaker(bind=engine)
        # 创建 session 对象:
        self.session = DBSession()
    def close(self):
        self.session.close()
    def Add(self, _V):
        self.session.add(_V)
        self.session.commit()

    def Update(self, _T, _V, _W):
        p = _V.to_dict()
        for k, v in list(p.items()):
            if k in _V.getPK():  # 对象需要有 getPK 方法返回 []string
                del p[k]
            if v == None:
                del p[k]
        self.session.query(_T).filter(_W).update(p, synchronize_session=False)
        self.session.commit()

    def Del(self, _T, _W):
        self.session.query(_T).filter(_W).delete()
        self.session.commit()

    def select(self, _T, _W):
        rows = self.session.query(_T).filter(_W).all()
        return rows

    # 双表查询
    def multi_select(self, _T, _J, _W):
        rows = self.session.query(_T, _J).join(_J).filter(_W).all()
        return rows
    def other(self):
        self.session.expire()
