Skip to content

Instantly share code, notes, and snippets.

@NigelThorne
Created July 3, 2011 23:24
Show Gist options
  • Save NigelThorne/1062709 to your computer and use it in GitHub Desktop.
Save NigelThorne/1062709 to your computer and use it in GitHub Desktop.
A simple script to beautify a PGSQL file. (Also an AutoHotKey script to beautify the currently selected text)
# Please fork this and make it better :)
#
# A valid solution follows these rules:
# 1 - The output should be the same sql as the input with different whitespace.
# 2 - Running the script on a file that is already beautified should do nothing.
sql = File.read(ARGV[0])
clean = sql.
gsub(/\t/, " ").
gsub(/--[^\n]*\n/){|m| m + "END_OF_LINE"}.
gsub(/\n */, " ").
gsub(/ +SELECT */i, "\n SELECT\n ").
gsub(/\(SELECT */i, "(\n SELECT\n ").
gsub(/( +|^)CASE/i, "\n CASE").
gsub(/( +|^)WHEN/i, "\n WHEN").
gsub(/( +|^)THEN/i, "\n THEN").
gsub(/( +|^)ELSE/i, "\n ELSE").
gsub(/( +|^)END/i, "\n END").
gsub(/( +|^)FROM/i, "\n FROM").
gsub(/( +|^)WHERE/i, "\n WHERE").
gsub(/( +|^)AND/i, "\n AND").
gsub(/( +|^)RETURNS/i, "\n RETURNS").
gsub(/((LEFT|RIGHT|OUTER|INNER) +)*JOIN/i){|m| "\n "+m}.
gsub(/, *\n */m, ", ").
gsub(/, /, ",\n ").
gsub(/\n *(\n *)*\n/m, "\n").
gsub(/\;(\n *)*/m, ";\n\n").
gsub(/--.*?(END_OF_LINE)/m){|m| m.gsub("\n",'').gsub(/END_OF_LINE/,"\n")}.
gsub(/ARRAY[ \n\t]*\[[ \n\t]*[^,]([ \n\t]*,[ \n\t]*[^,]{0,10})+[ \n\t]*\]/im){|m| m.gsub(/[ \n\t]+/,' ')}.
to_s
puts clean
; This is an AutoHotKey file to apply the beautify.rb transformation to the selected text when
; window ctrl R is pressed
#^R::
ClipSaved := ClipboardAll
clipboard = ; Start off empty to allow ClipWait to detect when the text has arrived.
Send ^c
ClipWait ; Wait for the clipboard to contain text.
FileDelete , c:\temp\tmp_ahk_clip.txt
FileAppend , %clipboard% , c:\temp\tmp_ahk_clip.txt
RunWait, %comspec% /c ""c:\beautify.rb" c:\temp\tmp_ahk_clip.txt > c:\temp\tmp_ahk_clip_out.txt" ,,Hide
FileRead, clipboard, c:\temp\tmp_ahk_clip_out.txt
Send ^v
Clipboard := ClipSaved
ClipSaved = ; Free the memory
return
@NigelThorne
Copy link
Author

I use this all the time. I'd love someone to try using Parslet or something to deal with comments and brackets and nested selects, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment