Skip to content

Commit

Permalink
✨ expose some properties of Database
Browse files Browse the repository at this point in the history
  • Loading branch information
CMHopeSunshine committed Sep 19, 2023
1 parent a599882 commit 2f9aded
Showing 1 changed file with 16 additions and 15 deletions.
31 changes: 16 additions & 15 deletions cherry/database/engine.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ def __init__(self, url: Union[str, URL], echo: bool = False) -> None:
self._metadata = MetaData()
self._url = url

@property
def metadata(self):
return self._metadata

@property
def engine(self):
return self._engine

async def create_all(self):
async with self._engine.begin() as conn:
await conn.run_sync(self._metadata.create_all)
Expand All @@ -40,36 +48,29 @@ async def drop_all(self):
await conn.run_sync(self._metadata.drop_all)

async def init(self):
for model in self._models.values():
model._generate_sqlalchemy_column()
model._generate_sqlalchemy_table(self._metadata)
self.init_all_model()

if self._url.drivername.startswith("sqlite"):
self._set_sqlite()

await self.create_all()

def init_all_model(self):
for model in self._models.values():
model._generate_sqlalchemy_column()
model._generate_sqlalchemy_table(self._metadata)

async def dispose(self):
await self._engine.dispose()

def add_model(self, model: Type["Model"]):
self._models[model.__meta__.tablename] = model
model.__meta__.database = self

async def execute(
self,
*arg,
**kwargs,
):
async with self._engine.connect() as conn:
result = await conn.execute(*arg, **kwargs)
await conn.commit()
return result

async def __aenter__(self) -> AsyncConnection:
if self._connect is None:
self._connect = self._engine.connect()
async with self._lock:
if self._connect is None:
self._connect = self._engine.connect()
self._counter += 1
if self._counter == 1:
await self._connect.start()
Expand Down

0 comments on commit 2f9aded

Please sign in to comment.