Skip to content

Commit fac07e3

Browse files
authored
Speedup queries with composite PK
1 parent cc0fd55 commit fac07e3

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

mysql_ch_replicator/mysql_api.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -95,12 +95,30 @@ def get_table_create_statement(self, table_name) -> str:
9595

9696
def get_records(self, table_name, order_by, limit, start_value=None):
9797
self.reconnect_if_required()
98-
order_by = ','.join(order_by)
98+
order_by_str = ','.join(order_by)
9999
where = ''
100+
100101
if start_value is not None:
101-
start_value = ','.join(map(str, start_value))
102-
where = f'WHERE ({order_by}) > ({start_value}) '
103-
query = f'SELECT * FROM `{table_name}` {where}ORDER BY {order_by} LIMIT {limit}'
102+
or_clauses = []
103+
104+
for i in range(len(order_by)):
105+
eq_parts = []
106+
107+
for j in range(i):
108+
eq_parts.append(f"{order_by[j]} = {start_value[j]}")
109+
110+
gt_part = f"{order_by[i]} > {start_value[i]}"
111+
112+
if eq_parts:
113+
clause = f"({' AND '.join(eq_parts)} AND {gt_part})"
114+
else:
115+
clause = f"({gt_part})"
116+
117+
or_clauses.append(clause)
118+
where = f"WHERE {' OR '.join(or_clauses)} "
119+
120+
query = f'SELECT * FROM `{table_name}` {where}ORDER BY {order_by_str} LIMIT {limit}'
121+
104122
self.cursor.execute(query)
105123
res = self.cursor.fetchall()
106124
records = [x for x in res]

0 commit comments

Comments
 (0)