Skip to content

Commit 2946e68

Browse files
committed
Commit after truncate to reduce lock contention
Truncate takes an `AccessExclusive` lock on the table, which blocks all other transactions from accessing the table, including select for datastore_info and any other access to the table contents. Since those operations are called from the web interface, the UI can hang for the timeout period or untill the copy finishes. This is poor user experience when dealing with large files. So, truncate in it's own transaction, so that the AccessExclusive lock is held for the least amount of time possible.
1 parent 7b8bc6f commit 2946e68

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

ckanext/datapusher_plus/jobs.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1053,22 +1053,23 @@ def _push_to_datastore(
10531053
else:
10541054
cur = raw_connection.cursor()
10551055

1056-
# truncate table to use copy freeze option and further increase
1057-
# performance as there is no need for WAL logs to be maintained
1058-
# https://www.postgresql.org/docs/current/populate.html#POPULATE-COPY-FROM
1056+
# truncate table in case we're loading over an existing resource
10591057
try:
10601058
cur.execute(
10611059
sql.SQL("TRUNCATE TABLE {}").format(sql.Identifier(resource_id))
10621060
)
1063-
1061+
# commit to ensure that the AccessExclusive lock is only held for the
1062+
# duration of the truncate, otherwise no other access to the table is
1063+
# allowed, blocking all selects.
1064+
raw_connection.commit()
10641065
except psycopg2.Error as e:
10651066
logger.warning(f"Could not TRUNCATE: {e}")
10661067

10671068
col_names_list = [h["id"] for h in headers_dicts]
10681069
column_names = sql.SQL(",").join(sql.Identifier(c) for c in col_names_list)
10691070
copy_sql = sql.SQL(
10701071
"COPY {} ({}) FROM STDIN "
1071-
"WITH (FORMAT CSV, FREEZE 1, "
1072+
"WITH (FORMAT CSV, "
10721073
"HEADER 1, ENCODING 'UTF8');"
10731074
).format(
10741075
sql.Identifier(resource_id),

0 commit comments

Comments
 (0)