I am formatting a python sql string, and it goes outside the declare block which should…
- User
I am formatting a python sql string, and it goes outside the declare block which should only be modified inside this method and nothing else. what could be wrong in my code that it is modifying the string outside of the declare scope?
sql_query = """ use db_name go
declare @cursor_table_name cursor, @var1 tinyint , @var2 smallint , @var3 varchar(10) , @var4 int , @var5 varchar(64) , @var6 int , @var7 varchar(64) , @var8 varchar(1)
declare cursor_table_name insensitive cursor for select var1 , var2 , ... var8 from db_name..table_name for read only
open cursor_table_name
fetch cursor_table_name into @var1 , @var2 , @var3 , @var4 , @var5 , @var6 , @var7 , @var8
while @@sqlstatus = 0 begin fetch cursor_table_name into @var1 , @var2 , @var3 , @var4 , @var5 , @var6 , @var7 , @var8
endclose cursor_table_name
deallocate cursor_table_name """
def format_declare_block(sql): lines = sql.strip().split('\n') formatted_lines = [] variable_lines = []
for line in lines: print(f"Processing line: {line}") # Debug: Show each line being processed if line.strip().startswith('declare'): formatted_lines.append(line) elif line.strip().startswith('@'): variable_lines.append(line) else: if variable_lines: # If we have collected variable lines, process them formatted_lines.extend(format_variable_lines(variable_lines)) variable_lines = [] formatted_lines.append(line) # Append any remaining variable lines if variable_lines: formatted_lines.extend(format_variable_lines(variable_lines)) return '\n'.join(formatted_lines)def format_variable_lines(variable_lines): max_length = 0 variable_parts = []
for var_line in variable_lines: # Get current leading spaces leading_spaces = var_line[:len(var_line) - len(var_line.lstrip())] # Ensure the line starts with two spaces print(f"Leading spaces before adjustment: '{leading_spaces}'") # Debug leading spaces # Add two leading spaces if not present if var_line.strip() and not leading_spaces.endswith(' '): leading_spaces += ' ' print(f"Adjusted leading spaces: '{leading_spaces}'") # Debug leading spaces after adjustment parts = [part.strip() for part in var_line.split(',') if part.strip()] variable_parts.extend(parts) for part in parts: name = part.split()[0] max_length = max(max_length, len(name)) max_length += 1 # Add space for alignment # Format the lines aligned_parts = [] for part in variable_parts: name_type = part.split() if len(name_type) > 1: aligned_parts.append(f'{leading_spaces}{name_type[0]:<{max_length}} {name_type[1]}') else: aligned_parts.append(part.strip()) # Should not normally happen return [',\n'.join(aligned_parts)] - Assistant