Skip to content

Instantly share code, notes, and snippets.

@HermesPasser
Last active August 18, 2022 18:45
Show Gist options
  • Select an option

  • Save HermesPasser/ebdf079ca4d540cfdbcec313dfad2d41 to your computer and use it in GitHub Desktop.

Select an option

Save HermesPasser/ebdf079ca4d540cfdbcec313dfad2d41 to your computer and use it in GitHub Desktop.
Naive SQL formatter for scripts with really long subqueries
def next_char(file)
begin
file.readchar
rescue EOFError
nil
end
end
if ARGV.empty?
puts "No SQL file was given"
exit(1)
end
input_filename = ARGV[0]
output_filename = input_filename.split('.')[0] + '.fmt.sql'
input = open(input_filename, 'r')
output = open(output_filename, 'a')
in_quotes = false
buffer = []
loop do
char = next_char input
break if char.nil?
if char == '('
buffer.push "\n\t"
while !char.nil? && !(char == ')' && !in_quotes)
buffer.push char
in_quotes = !in_quotes if ['"', "'"].include? char
char = next_char input
end
buffer.push char
char = next_char input
if char == ','
# para '(),(),()' virar '(),\n(),\n()' no lugar de '()\n,()\n,()'
buffer.push char
output << buffer.join
buffer.clear
else
output << buffer.join
buffer.clear
buffer.push "\n"
buffer.push char
end
else
buffer.push char
end
end
output << buffer.join
input.close
output.close
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment