feat: new orm module

This commit is contained in:
EstrellaXD
2023-06-14 20:39:19 +08:00
parent 76112ad3e1
commit 6bd6306dc6
8 changed files with 248 additions and 218 deletions

View File

@@ -1,43 +1,31 @@
from .connector import Connector
class Insert:
def __init__(self, db: Connector, table_name: str, data: dict):
self.db = db
def __init__(self, connector, table_name: str, data: dict):
self._connector = connector
self._table_name = table_name
self._columns = data.items()
def __gen_id(self) -> int:
self.db.execute(f"SELECT MAX(id) FROM {self._table_name}")
max_id = self.db.fetchone()[0]
self._connector.execute(f"SELECT MAX(id) FROM {self._table_name}")
max_id = self._connector.fetchone()[0]
if max_id is None:
return 1
return max_id + 1
def one(self, data: dict) -> bool:
def one(self, data: dict):
if data["id"] is not None:
raise ValueError("id must be None")
_id = self.__gen_id()
data["id"] = _id
columns = ", ".join(data.keys())
placeholders = ", ".join([f":{key}" for key in data.keys()])
self.db.execute(
self._connector.execute(
f"""
INSERT INTO {self._table_name} ({columns})
VALUES ({placeholders})
""",
data,
)
return True
def list(self, data: list[dict]):
columns = ", ".join(data[0].keys())
placeholders = ", ".join([f":{key}" for key in data[0].keys()])
self.db.executemany(
f"""
INSERT INTO {self._table_name} ({columns})
VALUES ({placeholders})
""",
data,
)
return True
def many(self, data: list[dict]):
for item in data:
self.one(item)