读取文件匹配'Alter Table'与'Modify'并返回表名的代码问题求助
Fixing Cross-Line 'Modify' Detection After 'Alter Table'
Got it, let's tackle this problem! Your current code only checks for Modify in the same line as Alter Table, but we need to track when we've entered an Alter Table context and keep scanning subsequent lines until we find Modify (or reach the end of the statement/file).
Core Approach
We'll use a simple state-tracking system:
- A flag (
in_alter_context) to mark when we've found anAlter Tablestatement and need to look forModify - Store the target table name once we extract it from the
Alter Tableline - Keep scanning lines until we either find
Modify(return the table name) or exit theAlter Tablecontext (e.g., hit a semicolon that ends the statement)
Example Solution (Python)
Here's a revised code snippet that handles cross-line cases:
def find_modify_after_alter_table(file_path): in_alter_context = False target_table = None with open(file_path, 'r') as f: for line in f: stripped_line = line.strip() # Handle case-insensitive matching for SQL keywords lower_line = stripped_line.lower() # Check if we've hit an ALTER TABLE statement if 'alter table' in lower_line: # Extract the table name (adjust logic if your SQL uses quoted names) parts = stripped_line.split() try: # Find the index of 'Table'/'TABLE' and grab the next word as table name table_keyword_idx = parts.index('Table') if 'Table' in parts else parts.index('TABLE') target_table = parts[table_keyword_idx + 1] # Clean up any trailing punctuation (commas, semicolons, parentheses) target_table = target_table.rstrip(',();') in_alter_context = True except (ValueError, IndexError): # Skip malformed ALTER TABLE lines that don't have a clear table name continue # If we're in an ALTER TABLE context, look for MODIFY elif in_alter_context: if 'modify' in lower_line: return target_table # Reset context if we hit the end of the SQL statement (semicolon) if ';' in stripped_line: in_alter_context = False target_table = None # If we finish scanning without finding MODIFY return "未找到Modify"
Key Improvements Explained
- State Tracking: The
in_alter_contextflag lets us continue checking lines after the initialAlter Tableline - Case Insensitivity: Uses
lower_lineto match SQL keywords regardless of capitalization (common in SQL syntax) - Table Name Cleaning: Removes trailing punctuation to handle cases like
ALTER TABLE users MODIFY ...orALTER TABLE users, - Statement Boundary Handling: Resets the context when a semicolon is found, so we don't accidentally match
Modifyfrom a different SQL statement
Optional Adjustments
- If your table names use quotes (e.g.,
ALTER TABLE "user_data"), update the table extraction logic to strip quotes - To collect all tables with
Modifyinstead of returning the first one, change the function to append to a list and return it at the end - Add logging to debug which lines are being processed if you need to troubleshoot edge cases
内容的提问来源于stack exchange,提问作者shri Bin
相关产品推荐
相关产品推荐

