Skip to content

Commit a303702

Browse files
authored
Merge pull request #352 from django-daiquiri/fix-max-records-trim
Improve performance of the table trim to max_records
2 parents 4db8b27 + 0cdaa66 commit a303702

File tree

3 files changed

+14
-10
lines changed

3 files changed

+14
-10
lines changed

daiquiri/core/adapter/database/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,8 @@ def __init__(self, database_key, database_config):
1414
def connection(self):
1515
return connections[self.database_key]
1616

17-
def execute(self, sql):
18-
return self.connection().cursor().execute(sql)
17+
def execute(self, sql, args=None):
18+
return self.connection().cursor().execute(sql, args)
1919

2020
def fetchone(self, sql, args=None, as_dict=False):
2121
cursor = self.connection().cursor()

daiquiri/core/adapter/database/postgres.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -369,14 +369,17 @@ def trim_table_rows(self, schema_name, table_name, max_records):
369369
if not self.table_exists(schema_name, table_name):
370370
return
371371

372-
query = (
373-
'DELETE FROM '
374-
+ f'{self.escape_identifier(schema_name)}.{self.escape_identifier(table_name)} '
375-
+ 'WHERE ctid NOT IN (SELECT ctid FROM '
376-
+ f'{self.escape_identifier(schema_name)}.{self.escape_identifier(table_name)} '
377-
+ f'LIMIT {max_records} );'
378-
)
379-
self.execute(query)
372+
user_table = f'{self.escape_identifier(schema_name)}.{self.escape_identifier(table_name)}'
373+
query = f"""DELETE FROM {user_table} as t
374+
USING (
375+
SELECT ctid
376+
FROM {user_table}
377+
ORDER BY ctid
378+
OFFSET %s
379+
) as d
380+
WHERE t.ctid = d.ctid;
381+
"""
382+
self.execute(query, args=[max_records,])
380383

381384
def table_exists(self, schema_name, table_name):
382385
check_query = (

daiquiri/query/tasks.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def on_failure(self, exc, task_id, args, kwargs, einfo):
2828

2929
# log raised exception
3030
logger.error('run_query %s raised an exception (%s)', job_id, exc)
31+
logger.debug('run_query %s failed with an error: %s', job_id, einfo)
3132

3233
# set phase and error_summary of the crashed job
3334
job = QueryJob.objects.get(pk=job_id)

0 commit comments

Comments
 (0)