In Python, I want to add a new function that receive this sql string, and format it…
- User
In Python, I want to add a new function that receive this sql string, and format it based on indentation rules, so this formatting should be related to the indentation of the variables. At most, a select or any other methods should have. I tried using sqlparse library but I think we need a custom formatted for this complex task.
The rules for the indentation are like this:
- Queries may consist of one or more lines and SQL statements must be separated by a blank line.
- Each nesting level must have three spaces, do not use tabs.
- Items of a similar nature should be placed in the same column.
Example of correct indented sql strings:
exec @w_error = sp_something @i_var1 = @w_var1 , @i_longer_var2 = @w_longer_var2 , @i_var3 = @w_var3 , @o_var_out1 = @w_var_out1 out , @o_var_longer_out2 = @w_var_longer_out2 outAnother example, this time in a select:
select @w_var1 = var1, @w_some_var2 = op_estado, @w_some_longer_var3 = op_migrada, @w_var4 = var4, from some_table where some_var = @w_some_varAs you can see, they are aligned not only by the "=", but also by "out" keyword and the commas. The comma code I already have a different method, so you can focus on the "=" and the "out" part.
- This often happens in INSERT queries: if necessary, use three columns in both the field area and the data area aligned one space after the longest column name, the nesting levels between the first and second part of an insert are independent.
Example of correct indented sql strings:
insert into some_table ( some_Var1, some_Var2, some_longer_var3, another_long_var4, some_var5, another_var6, small_var7, maybe_a_var8) values ( @i_some_Var1, @w_some_Var2, @i_some_longer_var3, @w_something, @w_some, @w_thing, 'N', 0) Here is my current code, it is working correctly up to the part of getting an unrelated "=" wrong here: select @w_error= @w_return and the code should output this (missing an space before the =): select @w_error = @w_return Here is my current working code: def format_sql(sql): lines = sql.split('\n') formatted_lines = [] current_block = [] def format_block(block): max_length_before_equals = max(len(line.split('=')[0].strip()) for line in block if '=' in line) formatted_block = [] for line in block: if '=' in line: parts = line.split('=') left_part = parts[0].rstrip().ljust(max_length_before_equals + 1) right_part = '= ' + parts[1].strip() formatted_block.append(left_part + right_part) else: formatted_block.append(line) return formatted_block for line in lines: stripped_line = line.strip() # Handle blank lines if not stripped_line: if current_block: formatted_lines.extend(format_block(current_block)) current_block = [] formatted_lines.append('') continue # Handle blocks with '=' or 'out' if '=' in stripped_line or 'out' in stripped_line: current_block.append(line) else: if current_block: formatted_lines.extend(format_block(current_block)) current_block = [] formatted_lines.append(line) # Handle the last block if it exists if current_block: formatted_lines.extend(format_block(current_block)) # Ensure no space between '!' and '=' for i, line in enumerate(formatted_lines): if '! =' in line: formatted_lines[i] = line.replace('! =', '!=') return '\n'.join(formatted_lines) ```sql exec @placeholder1 = p_placeholder2 @placeholder3 = @placeholder3, @placeholder4 = @placeholder4, @placeholder5 = @placeholder5, @placeholder6 = @placeholder6, @placeholder7 = @placeholder7, @placeholder8 = @placeholder8, @placeholder9 = @placeholder9, @placeholder10 = @placeholder10, @placeholder11 = @placeholder11, @placeholder12 = @placeholder12, @placeholder13 = @placeholder13, @placeholder14 = @placeholder14, @placeholder15 = @placeholder15, @placeholder16 = @placeholder16, @placeholder17 = @placeholder17 if @placeholder1 != 0 begin --ES ERROR select @placeholder18 = @placeholder1 goto ERROR end --ES ERROR select @placeholder19 = 0 select @placeholder20 = sum(placeholder21) from placeholder22 where placeholder23 = @placeholder13 and placeholder24 = @placeholder5 and placeholder25 = @placeholder4 and placeholder26 = 'I' and placeholder27 = 'P' - Assistant
- User
ValueError Traceback (most recent call last) Cell In[173], line 94 58 # Example SQL query 59 query = """
60 exec @placeholder1 = p_placeholder2 61 @placeholder3 = @placeholder3, (...) 91 and placeholder27 = 'P' 92 """ ---> 94 formatted_query = format_sql(query) 95 print(formatted_query)Cell In[173], line 48 46 else: 47 if current_block: ---> 48 formatted_lines.extend(format_block(current_block, indent_level)) 49 current_block = [] 50 formatted_lines.append(' ' * indent_level + line)
Cell In[173], line 9 7 def format_block(block, indent): 8 # Identify maximum length before '=' for alignment ----> 9 max_length_before_equals = max(len(line.split('=')[0].strip()) for line in block if '=' in line) if block else 0 10 formatted_block = [] 12 for line in block:
ValueError: max() iterable argument is empty
- Assistant
- User
ok I got no errors, but the output wasn't indented at all this time:
exec @placeholder1 = p_placeholder2 @placeholder3 = @placeholder3, @placeholder4 = @placeholder4, @placeholder5 = @placeholder5, @placeholder6 = @placeholder6, @placeholder7 = @placeholder7, @placeholder8 = @placeholder8, @placeholder9 = @placeholder9, @placeholder10 = @placeholder10, @placeholder11 = @placeholder11, @placeholder12 = @placeholder12, @placeholder13 = @placeholder13, @placeholder14 = @placeholder14, @placeholder15 = @placeholder15, @placeholder16 = @placeholder16, @placeholder17 = @placeholder17
- Assistant
- User
it works better now, but remember the indentation block ends in a line break since the sql commands are separated with a line break, I think that is the problem here or not? because your code just add an space in between the "!="
@placeholder17 = @placeholder17
if @placeholder1 ! = 0
- Assistant
- User
your code has a bug, it removes the already correctly set indentation, don't remove the indentation, just check if it has 3 spaces and add them if they are missing:
this was in the original code: begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
This is the output of your code of this part: begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
- Assistant
- User
ok there was an error the "! =" keeps appearing so I added this code below the handle of last block
...
Handle the last block if it exists
if current_block: formatted_lines.extend(format_block(current_block, indent_level)) for i, line in enumerate(formatted_lines): if '! =' in line: formatted_lines[i] = line.replace('! =', '!=')...
Also your last code solved for below the select but not the select line:
This is your output: begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
this is correct output (has correct spaces before select): begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
- Assistant
- User
dunno why but now with this last code it got worse, the select AND the go to both are without indentation:
begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
- Assistant
- User
no no don't make this code so specific, don't use select or goto, just do this, apply this formatting to only the "=" in the exec blocks only. After that apply to the select blocks only, and we go from there, let's start small. Simplify as much as you can
- Assistant
- User
ok, now keep the actual indentation of lines instead of removing, many times they start with the correct indentation
- Assistant
- User
ok that's better, now, don't add linebreaks after or before each block, assume they are correctly set or you could just check if there is one and don't add another one.
- Assistant
- User
ok this is looking good, now there is one thing, if you happen to find a != instead of a "=", keep it as it is, because now it is separating the = from the ! even farther:
if @w_return ! = 0 begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
- Assistant
- User
improved a little, but it still made spaces in between the "!=":
if @w_return ! = 0 begin --ES ERROR select @w_error = @w_return goto ERROR end --ES ERROR
Maybe you could try to use != or = when aligning the "="
- Assistant
- User
- Assistant
- User
- Assistant