22import json
33import sqlparse
44import re
5- from pyparsing import Word , alphas , alphanums
5+ from pyparsing import Suppress , CaselessKeyword , Word , alphas , alphanums , delimitedList
66
77from .table_structure import TableStructure , TableField
88
@@ -216,7 +216,7 @@ def convert_table_structure(self, mysql_structure: TableStructure) -> TableStruc
216216 name = field .name ,
217217 field_type = clickhouse_field_type ,
218218 ))
219- clickhouse_structure .primary_key = mysql_structure .primary_key
219+ clickhouse_structure .primary_keys = mysql_structure .primary_keys
220220 clickhouse_structure .preprocess ()
221221 return clickhouse_structure
222222
@@ -519,9 +519,26 @@ def parse_mysql_table_structure(self, create_statement, required_table_name=None
519519 if line .lower ().startswith ('constraint' ):
520520 continue
521521 if line .lower ().startswith ('primary key' ):
522- pattern = 'PRIMARY KEY (' + Word (alphanums + '_`' ) + ')'
522+ # pattern = 'PRIMARY KEY (' + Word(alphanums + '_`') + ')'
523+ # result = pattern.parseString(line)
524+ # structure.primary_key = strip_sql_name(result[1])
525+
526+ # Define identifier to match column names, handling backticks and unquoted names
527+ identifier = (Suppress ('`' ) + Word (alphas + alphanums + '_' ) + Suppress ('`' )) | Word (
528+ alphas + alphanums + '_' )
529+
530+ # Build the parsing pattern
531+ pattern = CaselessKeyword ('PRIMARY' ) + CaselessKeyword ('KEY' ) + Suppress ('(' ) + delimitedList (
532+ identifier )('column_names' ) + Suppress (')' )
533+
534+ # Parse the line
523535 result = pattern .parseString (line )
524- structure .primary_key = strip_sql_name (result [1 ])
536+
537+ # Extract and process the primary key column names
538+ primary_keys = [strip_sql_name (name ) for name in result ['column_names' ]]
539+
540+ structure .primary_keys = primary_keys
541+
525542 continue
526543
527544 #print(" === processing line", line)
@@ -541,16 +558,16 @@ def parse_mysql_table_structure(self, create_statement, required_table_name=None
541558 #print(' ---- params:', field_parameters)
542559
543560
544- if not structure .primary_key :
561+ if not structure .primary_keys :
545562 for field in structure .fields :
546563 if 'primary key' in field .parameters .lower ():
547- structure .primary_key = field .name
564+ structure .primary_keys . append ( field .name )
548565
549- if not structure .primary_key :
566+ if not structure .primary_keys :
550567 if structure .has_field ('id' ):
551- structure .primary_key = 'id'
568+ structure .primary_keys = [ 'id' ]
552569
553- if not structure .primary_key :
570+ if not structure .primary_keys :
554571 raise Exception (f'No primary key for table { structure .table_name } , { create_statement } ' )
555572
556573 structure .preprocess ()
0 commit comments