Skip to content

Commit 5ab074b

Browse files
committed
Implemented pg_hook.get_cursor to make SR upload fast
1 parent e91a2c6 commit 5ab074b

1 file changed

Lines changed: 28 additions & 37 deletions

File tree

app/airflow/dags/libs/SR_processing/db_services.py

Lines changed: 28 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from collections import defaultdict
33
from typing import Any, Dict, List, Tuple
44

5+
from psycopg2.extras import execute_values
56
from airflow.providers.postgres.hooks.postgres import PostgresHook
67
from libs.enums import JobStageType, StageStatusType
78
from libs.queries import create_fields_query
@@ -105,27 +106,21 @@ def update_temp_data_dictionary_table(
105106
}
106107
)
107108

108-
# Insert records into the temporary table
109+
# Using execute_values with page_size=5000 instead of insert_rows() (fixed page_size=100) for better performance
109110
if dictionary_records:
110-
pg_hook.insert_rows(
111-
table=f"temp_data_dictionary_{scan_report_id}",
112-
rows=[
113-
(
114-
d["table_name"],
115-
d["field_name"],
116-
d["value"],
117-
d["value_description"],
118-
)
119-
for d in dictionary_records
120-
],
121-
target_fields=[
122-
"table_name",
123-
"field_name",
124-
"value",
125-
"value_description",
126-
],
127-
commit_every=10000, # commit every 50k
128-
)
111+
rows = [
112+
(
113+
d["table_name"],
114+
d["field_name"],
115+
d["value"],
116+
d["value_description"],
117+
)
118+
for d in dictionary_records
119+
]
120+
sql = f"INSERT INTO temp_data_dictionary_{scan_report_id} (table_name, field_name, value, value_description) VALUES %s"
121+
with pg_hook.get_cursor() as cur:
122+
execute_values(cur, sql, rows, page_size=5000)
123+
cur.connection.commit()
129124

130125
logging.info(
131126
f"Created temporary data dictionary table with {len(dictionary_records)} records"
@@ -197,23 +192,19 @@ def create_temp_field_values_table(
197192
)
198193

199194
if field_values_data:
200-
pg_hook.insert_rows(
201-
table=f"temp_field_values_{table_id}",
202-
rows=[
203-
(
204-
d["field_name"],
205-
d["value"],
206-
d["frequency"],
207-
)
208-
for d in field_values_data
209-
],
210-
target_fields=[
211-
"field_name",
212-
"value",
213-
"frequency",
214-
],
215-
commit_every=10000, # commit every 50k to reduce transaction overhead
216-
)
195+
# Using execute_values with page_size=5000 instead of insert_rows() (fixed page_size=100) for better performance
196+
rows = [
197+
(
198+
d["field_name"],
199+
d["value"],
200+
d["frequency"],
201+
)
202+
for d in field_values_data
203+
]
204+
sql = f"INSERT INTO temp_field_values_{table_id} (field_name, value, frequency) VALUES %s"
205+
with pg_hook.get_cursor() as cur:
206+
execute_values(cur, sql, rows, page_size=5000)
207+
cur.connection.commit()
217208

218209
except Exception as e:
219210
logging.error(f"Error creating data dictionary table: {str(e)}")

0 commit comments

Comments
 (0)