SQL::Beautify - Beautify SQL statements by adding line breaks indentation


        my $sql = SQL::Beautify->new;


        my $nice_sql = $sql->beautify;


Beautifies SQL statements by adding line breaks indentation.


new(query => '', spaces => 4, space => ' ', break => "\n", wrap => {})

Constructor. Takes a few options.

query => ''

Initialize the instance with a SQL string. Defaults to an empty string.

spaces => 4

Number of spaces that make one indentation level. Defaults to 4.

space => ' '

A string that is used as space. Default is an ASCII space character.

break => "\n"

String that is used for linebreaks. Default is "\n".

wrap => {}

Use this if you want to surround certain tokens with markup stuff. Known token types are "keywords" and "constants" for now. The value of each token type should be an array with two elements, one that is placed before the token and one that is placed behind it. For example, use make keywords red using terminal color escape sequences.

        { keywords => [ "\x1B[0;31m", "\x1B[0m" ] }
uc_keywords => 1|0

When true (1) all SQL keywords will be uppercased in output. Default is false (0).


Appends another chunk of SQL.


Sets the query to the new query string. Overwrites anything that was added with prior calls to query or add.


Beautifies the internally saved SQL string and returns the result.

add_keywords($keyword, $another_keyword, \@more_keywords)

Add any amount of keywords of arrays of keywords to highlight.

add_rule($rule, $token)

Add a custom formatting rule. The first argument is the rule, a string containing one or more commands (explained below), separated by dashes. The second argument may be either a token (string) or a list of strings. Tokens are grouped by rules internally, so you may call this method multiple times with the same rule string and different tokens, and the rule will apply to all of the tokens.

The following formatting commands are known at the moment:

token - insert the token this rule applies to
over - increase indentation level
back - decrease indentation level
break - insert line break
push - push current indentation level to an internal stack
pop - restore last indentation level from the stack
reset - reset internal indentation level stack

push, pop and reset should be rarely needed.

NOTE: Custom rules override default rules. Some default rules do things that can't be done using custom rules, such as changing the format of a token depending on the last or next token.

NOTE: I'm trying to provide sane default rules. If you find that a custom rule of yours would make more sense as a default rule, please create a ticket.


Needs more tests.

Please report bugs in the CPAN bug tracker.

This module is not complete (known SQL keywords, special formatting of keywords), so if you want see something added, just send me a patch.


Copyright (C) 2009 by Jonas Kramer. Published under the terms of the Artistic License 2.0.