Skip to content

Commit b868aa1

Browse files
Execute SQL scripts from on_restart/on_reindex directories (#70)
1 parent c5a421a commit b868aa1

File tree

2 files changed

+31
-8
lines changed

2 files changed

+31
-8
lines changed

src/dipdup/codegen.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,17 @@ async def create_package(self) -> None:
8080
with open(join(handlers_path, '__init__.py'), 'w'):
8181
pass
8282

83+
self._logger.info('Creating `%s/sql` directory', self._config.package)
84+
sql_path = join(self._config.package_path, 'sql')
85+
with suppress(FileExistsError):
86+
mkdir(sql_path)
87+
sql_on_restart_path = join(sql_path, 'on_restart')
88+
with suppress(FileExistsError):
89+
mkdir(sql_on_restart_path)
90+
sql_on_reindex_path = join(sql_path, 'on_reindex')
91+
with suppress(FileExistsError):
92+
mkdir(sql_on_reindex_path)
93+
8394
async def fetch_schemas(self) -> None:
8495
"""Fetch JSONSchemas for all contracts used in config"""
8596
self._logger.info('Creating `schemas` package')

src/dipdup/dipdup.py

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from genericpath import exists
1010
from tortoise import Tortoise
1111
from tortoise.exceptions import OperationalError
12-
from tortoise.transactions import in_transaction
12+
from tortoise.transactions import get_connection
1313
from tortoise.utils import get_schema_sql
1414

1515
import dipdup.utils as utils
@@ -30,7 +30,7 @@
3030
from dipdup.datasources import DatasourceT
3131
from dipdup.datasources.bcd.datasource import BcdDatasource
3232
from dipdup.datasources.tzkt.datasource import TzktDatasource
33-
from dipdup.exceptions import HandlerImportError
33+
from dipdup.exceptions import ConfigurationError, HandlerImportError
3434
from dipdup.hasura import configure_hasura
3535
from dipdup.index import BigMapIndex, HandlerContext, Index, OperationIndex
3636
from dipdup.models import BigMapData, IndexType, OperationData, State
@@ -264,27 +264,39 @@ async def _initialize_database(self, reindex: bool = False) -> None:
264264

265265
if schema_state is None:
266266
await Tortoise.generate_schemas()
267+
await self._execute_sql_scripts(reindex=True)
268+
267269
schema_state = State(index_type=IndexType.schema, index_name=connection_name, hash=schema_hash)
268270
await schema_state.save()
269271
elif schema_state.hash != schema_hash:
270272
self._logger.warning('Schema hash mismatch, reindexing')
271273
await self._ctx.reindex()
272274

275+
await self._execute_sql_scripts(reindex=False)
276+
277+
async def _execute_sql_scripts(self, reindex: bool) -> None:
278+
"""Execute SQL included with project"""
273279
sql_path = join(self._config.package_path, 'sql')
274280
if not exists(sql_path):
275281
return
282+
if any(map(lambda p: p not in ('on_reindex', 'on_restart'), listdir(sql_path))):
283+
raise ConfigurationError(
284+
f'SQL scripts must be placed either to `{self._config.package}/sql/on_restart` or to `{self._config.package}/sql/on_reindex` directory'
285+
)
276286
if not isinstance(self._config.database, PostgresDatabaseConfig):
277-
self._logger.warning('Injecting raw SQL supported on PostgreSQL only')
287+
self._logger.warning('Execution of user SQL scripts is supported on PostgreSQL only, skipping')
278288
return
279289

280-
for filename in listdir(sql_path):
290+
sql_path = join(sql_path, 'on_reindex' if reindex else 'on_restart')
291+
if not exists(sql_path):
292+
return
293+
self._logger.info('Executing SQL scripts from `%s`', sql_path)
294+
for filename in sorted(listdir(sql_path)):
281295
if not filename.endswith('.sql'):
282296
continue
283297

284298
with open(join(sql_path, filename)) as file:
285299
sql = file.read()
286300

287-
self._logger.info('Applying raw SQL from `%s`', filename)
288-
289-
async with in_transaction() as conn:
290-
await conn.execute_query(sql)
301+
self._logger.info('Executing `%s`', filename)
302+
await get_connection(None).execute_script(sql)

0 commit comments

Comments
 (0)