Removed excess parentheses in generated SQL
[scpubgit/Q-Branch.git] / lib / SQL / Abstract / Tree.pm
1 package SQL::Abstract::Tree;
2
3 use strict;
4 use warnings;
5 no warnings 'qw';
6 use Carp;
7
8 use Hash::Merge qw//;
9
10 use base 'Class::Accessor::Grouped';
11
12 __PACKAGE__->mk_group_accessors( simple => $_ ) for qw(
13    newline indent_string indent_amount colormap indentmap fill_in_placeholders
14    placeholder_surround
15 );
16
17 my $merger = Hash::Merge->new;
18
19 $merger->specify_behavior({
20    SCALAR => {
21       SCALAR => sub { $_[1] },
22       ARRAY  => sub { [ $_[0], @{$_[1]} ] },
23       HASH   => sub { $_[1] },
24    },
25    ARRAY => {
26       SCALAR => sub { $_[1] },
27       ARRAY  => sub { $_[1] },
28       HASH   => sub { $_[1] },
29    },
30    HASH => {
31       SCALAR => sub { $_[1] },
32       ARRAY  => sub { [ values %{$_[0]}, @{$_[1]} ] },
33       HASH   => sub { Hash::Merge::_merge_hashes( $_[0], $_[1] ) },
34    },
35 }, 'SQLA::Tree Behavior' );
36
37 my $op_look_ahead = '(?: (?= [\s\)\(\;] ) | \z)';
38 my $op_look_behind = '(?: (?<= [\,\s\)\(] ) | \A )';
39
40 my $quote_left = qr/[\`\'\"\[]/;
41 my $quote_right = qr/[\`\'\"\]]/;
42
43 my $placeholder_re = qr/(?: \? | \$\d+ )/x;
44
45 # These SQL keywords always signal end of the current expression (except inside
46 # of a parenthesized subexpression).
47 # Format: A list of strings that will be compiled to extended syntax ie.
48 # /.../x) regexes, without capturing parentheses. They will be automatically
49 # anchored to op boundaries (excluding quotes) to match the whole token.
50 my @expression_start_keywords = (
51   'SELECT',
52   'UPDATE',
53   'INSERT \s+ INTO',
54   'DELETE \s+ FROM',
55   'FROM',
56   'SET',
57   '(?:
58     (?:
59         (?: (?: LEFT | RIGHT | FULL ) \s+ )?
60         (?: (?: CROSS | INNER | OUTER ) \s+ )?
61     )?
62     JOIN
63   )',
64   'ON',
65   'WHERE',
66   '(?: DEFAULT \s+ )? VALUES',
67   'EXISTS',
68   'GROUP \s+ BY',
69   'HAVING',
70   'ORDER \s+ BY',
71   'SKIP',
72   'FIRST',
73   'LIMIT',
74   'OFFSET',
75   'FOR',
76   'UNION',
77   'INTERSECT',
78   'EXCEPT',
79   'BEGIN \s+ WORK',
80   'COMMIT',
81   'ROLLBACK \s+ TO \s+ SAVEPOINT',
82   'ROLLBACK',
83   'SAVEPOINT',
84   'RELEASE \s+ SAVEPOINT',
85   'RETURNING',
86   'ROW_NUMBER \s* \( \s* \) \s+ OVER',
87 );
88
89 my $expr_start_re = join ("\n\t|\n", @expression_start_keywords );
90 $expr_start_re = qr/ $op_look_behind (?i: $expr_start_re ) $op_look_ahead /x;
91
92 # These are binary operator keywords always a single LHS and RHS
93 # * AND/OR are handled separately as they are N-ary
94 # * so is NOT as being unary
95 # * BETWEEN without paranthesis around the ANDed arguments (which
96 #   makes it a non-binary op) is detected and accomodated in
97 #   _recurse_parse()
98
99 # this will be included in the $binary_op_re, the distinction is interesting during
100 # testing as one is tighter than the other, plus mathops have different look
101 # ahead/behind (e.g. "x"="y" )
102 my @math_op_keywords = (qw/ < > != <> = <= >= /);
103 my $math_re = join ("\n\t|\n", map
104   { "(?: (?<= [\\w\\s] | $quote_right ) | \\A )"  . quotemeta ($_) . "(?: (?= [\\w\\s] | $quote_left ) | \\z )" }
105   @math_op_keywords
106 );
107 $math_re = qr/$math_re/x;
108
109 sub _math_op_re { $math_re }
110
111
112 my $binary_op_re = '(?: NOT \s+)? (?:' . join ('|', qw/IN BETWEEN R?LIKE/) . ')';
113 $binary_op_re = join "\n\t|\n",
114   "$op_look_behind (?i: $binary_op_re ) $op_look_ahead",
115   $math_re,
116   $op_look_behind . 'IS (?:\s+ NOT)?' . "(?= \\s+ NULL \\b | $op_look_ahead )",
117 ;
118 $binary_op_re = qr/$binary_op_re/x;
119
120 sub _binary_op_re { $binary_op_re }
121
122 my $all_known_re = join("\n\t|\n",
123   $expr_start_re,
124   $binary_op_re,
125   "$op_look_behind (?i: AND|OR|NOT|\\* ) $op_look_ahead",
126   (map { quotemeta $_ } qw/, ( )/),
127   $placeholder_re,
128 );
129
130 $all_known_re = qr/$all_known_re/x;
131
132 #this one *is* capturing for the split below
133 # splits on whitespace if all else fails
134 my $tokenizer_re = qr/ \s* ( $all_known_re ) \s* | \s+ /x;
135
136 # Parser states for _recurse_parse()
137 use constant PARSE_TOP_LEVEL => 0;
138 use constant PARSE_IN_EXPR => 1;
139 use constant PARSE_IN_PARENS => 2;
140 use constant PARSE_IN_FUNC => 3;
141 use constant PARSE_RHS => 4;
142
143 my $expr_term_re = qr/ ^ (?: $expr_start_re | \) ) $/x;
144 my $rhs_term_re = qr/ ^ (?: $expr_term_re | $binary_op_re | (?i: AND | OR | NOT | \, ) ) $/x;
145 my $func_start_re = qr/^ (?: \* | $placeholder_re | \( ) $/x;
146
147 my %indents = (
148    select        => 0,
149    update        => 0,
150    'insert into' => 0,
151    'delete from' => 0,
152    from          => 1,
153    where         => 0,
154    join          => 1,
155    'left join'   => 1,
156    on            => 2,
157    having        => 0,
158    'group by'    => 0,
159    'order by'    => 0,
160    set           => 1,
161    into          => 1,
162    values        => 1,
163    limit         => 1,
164    offset        => 1,
165    skip          => 1,
166    first         => 1,
167 );
168
169 my %profiles = (
170    console => {
171       fill_in_placeholders => 1,
172       placeholder_surround => ['?/', ''],
173       indent_string => ' ',
174       indent_amount => 2,
175       newline       => "\n",
176       colormap      => {},
177       indentmap     => \%indents,
178
179       eval { require Term::ANSIColor }
180         ? do {
181           my $c = \&Term::ANSIColor::color;
182
183           my $red     = [$c->('red')    , $c->('reset')];
184           my $cyan    = [$c->('cyan')   , $c->('reset')];
185           my $green   = [$c->('green')  , $c->('reset')];
186           my $yellow  = [$c->('yellow') , $c->('reset')];
187           my $blue    = [$c->('blue')   , $c->('reset')];
188           my $magenta = [$c->('magenta'), $c->('reset')];
189           my $b_o_w   = [$c->('black on_white'), $c->('reset')];
190           (
191             placeholder_surround => [$c->('black on_magenta'), $c->('reset')],
192             colormap => {
193               'begin work'            => $b_o_w,
194               commit                  => $b_o_w,
195               rollback                => $b_o_w,
196               savepoint               => $b_o_w,
197               'rollback to savepoint' => $b_o_w,
198               'release savepoint'     => $b_o_w,
199
200               select                  => $red,
201               'insert into'           => $red,
202               update                  => $red,
203               'delete from'           => $red,
204
205               set                     => $cyan,
206               from                    => $cyan,
207
208               where                   => $green,
209               values                  => $yellow,
210
211               join                    => $magenta,
212               'left join'             => $magenta,
213               on                      => $blue,
214
215               'group by'              => $yellow,
216               having                  => $yellow,
217               'order by'              => $yellow,
218
219               skip                    => $green,
220               first                   => $green,
221               limit                   => $green,
222               offset                  => $green,
223             }
224           );
225         } : (),
226    },
227    console_monochrome => {
228       fill_in_placeholders => 1,
229       placeholder_surround => ['?/', ''],
230       indent_string => ' ',
231       indent_amount => 2,
232       newline       => "\n",
233       colormap      => {},
234       indentmap     => \%indents,
235    },
236    html => {
237       fill_in_placeholders => 1,
238       placeholder_surround => ['<span class="placeholder">', '</span>'],
239       indent_string => '&nbsp;',
240       indent_amount => 2,
241       newline       => "<br />\n",
242       colormap      => {
243          select        => ['<span class="select">'  , '</span>'],
244          'insert into' => ['<span class="insert-into">'  , '</span>'],
245          update        => ['<span class="select">'  , '</span>'],
246          'delete from' => ['<span class="delete-from">'  , '</span>'],
247
248          set           => ['<span class="set">', '</span>'],
249          from          => ['<span class="from">'    , '</span>'],
250
251          where         => ['<span class="where">'   , '</span>'],
252          values        => ['<span class="values">', '</span>'],
253
254          join          => ['<span class="join">'    , '</span>'],
255          'left join'   => ['<span class="left-join">','</span>'],
256          on            => ['<span class="on">'      , '</span>'],
257
258          'group by'    => ['<span class="group-by">', '</span>'],
259          having        => ['<span class="having">',   '</span>'],
260          'order by'    => ['<span class="order-by">', '</span>'],
261
262          skip          => ['<span class="skip">',   '</span>'],
263          first         => ['<span class="first">',  '</span>'],
264          limit         => ['<span class="limit">',  '</span>'],
265          offset        => ['<span class="offset">', '</span>'],
266
267          'begin work'  => ['<span class="begin-work">', '</span>'],
268          commit        => ['<span class="commit">', '</span>'],
269          rollback      => ['<span class="rollback">', '</span>'],
270          savepoint     => ['<span class="savepoint">', '</span>'],
271          'rollback to savepoint' => ['<span class="rollback-to-savepoint">', '</span>'],
272          'release savepoint'     => ['<span class="release-savepoint">', '</span>'],
273       },
274       indentmap     => \%indents,
275    },
276    none => {
277       colormap      => {},
278       indentmap     => {},
279    },
280 );
281
282 sub new {
283    my $class = shift;
284    my $args  = shift || {};
285
286    my $profile = delete $args->{profile} || 'none';
287
288    die "No such profile '$profile'!" unless exists $profiles{$profile};
289
290    my $data = $merger->merge( $profiles{$profile}, $args );
291
292    bless $data, $class
293 }
294
295 sub parse {
296   my ($self, $s) = @_;
297
298   # tokenize string, and remove all optional whitespace
299   my $tokens = [];
300   foreach my $token (split $tokenizer_re, $s) {
301     push @$tokens, $token if (
302       defined $token
303         and
304       length $token
305         and
306       $token =~ /\S/
307     );
308   }
309   $self->_recurse_parse($tokens, PARSE_TOP_LEVEL);
310 }
311
312 sub _recurse_parse {
313   my ($self, $tokens, $state) = @_;
314
315   my $left;
316   while (1) { # left-associative parsing
317
318     my $lookahead = $tokens->[0];
319     if ( not defined($lookahead)
320           or
321         ($state == PARSE_IN_PARENS && $lookahead eq ')')
322           or
323         ($state == PARSE_IN_EXPR && $lookahead =~ $expr_term_re )
324           or
325         ($state == PARSE_RHS && $lookahead =~ $rhs_term_re )
326           or
327         ($state == PARSE_IN_FUNC && $lookahead !~ $func_start_re) # if there are multiple values - the parenthesis will switch the $state
328     ) {
329       return $left||();
330     }
331
332     my $token = shift @$tokens;
333
334     # nested expression in ()
335     if ($token eq '(' ) {
336       my $right = $self->_recurse_parse($tokens, PARSE_IN_PARENS);
337       $token = shift @$tokens   or croak "missing closing ')' around block " . $self->unparse($right);
338       $token eq ')'             or croak "unexpected token '$token' terminating block " . $self->unparse($right);
339
340       $left = $left ? [$left, [PAREN => [$right||()] ]]
341                     : [PAREN  => [$right||()] ];
342     }
343     # AND/OR and LIST (,)
344     elsif ($token =~ /^ (?: OR | AND | \, ) $/xi )  {
345       my $op = ($token eq ',') ? 'LIST' : uc $token;
346
347       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
348
349       # Merge chunks if logic matches
350       if (ref $right and $op eq $right->[0]) {
351         $left = [ (shift @$right ), [$left||(), map { @$_ } @$right] ];
352       }
353       else {
354         $left = [$op => [ $left||(), $right||() ]];
355       }
356     }
357     # binary operator keywords
358     elsif ( $token =~ /^ $binary_op_re $ /x ) {
359       my $op = uc $token;
360       my $right = $self->_recurse_parse($tokens, PARSE_RHS);
361
362       # A between with a simple LITERAL for a 1st RHS argument needs a
363       # rerun of the search to (hopefully) find the proper AND construct
364       if ($op eq 'BETWEEN' and $right->[0] eq 'LITERAL') {
365         unshift @$tokens, $right->[1][0];
366         $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
367       }
368
369       $left = [$op => [$left, $right] ];
370     }
371     # expression terminator keywords (as they start a new expression)
372     elsif ( $token =~ / ^ $expr_start_re $ /x ) {
373       my $op = uc $token;
374       my $right = $self->_recurse_parse($tokens, PARSE_IN_EXPR);
375       $left = $left ? [ $left,  [$op => [$right||()] ]]
376                    : [ $op => [$right||()] ];
377     }
378     # NOT
379     elsif ( $token =~ /^ NOT $/ix ) {
380       my $op = uc $token;
381       my $right = $self->_recurse_parse ($tokens, PARSE_RHS);
382       $left = $left ? [ @$left, [$op => [$right] ]]
383                     : [ $op => [$right] ];
384
385     }
386     elsif ( $token =~ $placeholder_re) {
387       $left = $left ? [ $left, [ PLACEHOLDER => [ $token ] ] ]
388                     : [ PLACEHOLDER => [ $token ] ];
389     }
390     # we're now in "unknown token" land - start eating tokens until
391     # we see something familiar
392     else {
393       my $right;
394
395       # check if the current token is an unknown op-start
396       if (@$tokens and $tokens->[0] =~ $func_start_re) {
397         $right = [ $token => [ $self->_recurse_parse($tokens, PARSE_IN_FUNC) || () ] ];
398       }
399       else {
400         $right = [ LITERAL => [ $token ] ];
401       }
402
403       $left = $left ? [ $left, $right ]
404                     : $right;
405     }
406   }
407 }
408
409 sub format_keyword {
410   my ($self, $keyword) = @_;
411
412   if (my $around = $self->colormap->{lc $keyword}) {
413      $keyword = "$around->[0]$keyword$around->[1]";
414   }
415
416   return $keyword
417 }
418
419 my %starters = (
420    select        => 1,
421    update        => 1,
422    'insert into' => 1,
423    'delete from' => 1,
424 );
425
426 sub pad_keyword {
427    my ($self, $keyword, $depth) = @_;
428
429    my $before = '';
430    if (defined $self->indentmap->{lc $keyword}) {
431       $before = $self->newline . $self->indent($depth + $self->indentmap->{lc $keyword});
432    }
433    $before = '' if $depth == 0 and defined $starters{lc $keyword};
434    return [$before, ''];
435 }
436
437 sub indent { ($_[0]->indent_string||'') x ( ( $_[0]->indent_amount || 0 ) * $_[1] ) }
438
439 sub _is_key {
440    my ($self, $tree) = @_;
441    $tree = $tree->[0] while ref $tree;
442
443    defined $tree && defined $self->indentmap->{lc $tree};
444 }
445
446 sub fill_in_placeholder {
447    my ($self, $bindargs) = @_;
448
449    if ($self->fill_in_placeholders) {
450       my $val = shift @{$bindargs} || '';
451       my $quoted = $val =~ s/^(['"])(.*)\1$/$2/;
452       my ($left, $right) = @{$self->placeholder_surround};
453       $val =~ s/\\/\\\\/g;
454       $val =~ s/'/\\'/g;
455       $val = qq('$val') if $quoted;
456       return qq($left$val$right)
457    }
458    return '?'
459 }
460
461 # FIXME - terrible name for a user facing API
462 sub unparse {
463   my ($self, $tree, $bindargs) = @_;
464   $self->_unparse($tree, [@{$bindargs||[]}], 0);
465 }
466
467 sub _unparse {
468   my ($self, $tree, $bindargs, $depth) = @_;
469
470   if (not $tree or not @$tree) {
471     return '';
472   }
473
474   $self->_parenthesis_unroll($tree);
475   my ($car, $cdr) = @{$tree}[0,1];
476
477   if (! defined $car or (! ref $car and ! defined $cdr) ) {
478     require Data::Dumper;
479     Carp::confess( sprintf ( "Internal error - malformed branch at depth $depth:\n%s",
480       Data::Dumper::Dumper($tree)
481     ) );
482   }
483
484   if (ref $car) {
485     return join (' ', map $self->_unparse($_, $bindargs, $depth), @$tree);
486   }
487   elsif ($car eq 'LITERAL') {
488     return $cdr->[0];
489   }
490   elsif ($car eq 'PLACEHOLDER') {
491     return $self->fill_in_placeholder($bindargs);
492   }
493   elsif ($car eq 'PAREN') {
494     return sprintf ('( %s )',
495       join (' ', map { $self->_unparse($_, $bindargs, $depth + 2) } @{$cdr} )
496         .
497       ($self->_is_key($cdr)
498         ? ( $self->newline||'' ) . $self->indent($depth + 1)
499         : ''
500       )
501     );
502   }
503   elsif ($car eq 'AND' or $car eq 'OR' or $car =~ / ^ $binary_op_re $ /x ) {
504     return join (" $car ", map $self->_unparse($_, $bindargs, $depth), @{$cdr});
505   }
506   elsif ($car eq 'LIST' ) {
507     return join (', ', map $self->_unparse($_, $bindargs, $depth), @{$cdr});
508   }
509   else {
510     my ($l, $r) = @{$self->pad_keyword($car, $depth)};
511
512     return sprintf "$l%s%s%s$r",
513       $self->format_keyword($car),
514       ( ref $cdr eq 'ARRAY' and ref $cdr->[0] eq 'ARRAY' and $cdr->[0][0] and $cdr->[0][0] eq 'PAREN' )
515         ? ''    # mysql--
516         : ' '
517       ,
518       $self->_unparse($cdr, $bindargs, $depth),
519     ;
520   }
521 }
522
523 # All of these keywords allow their parameters to be specified with or without parenthesis without changing the semantics
524 my @unrollable_ops = (
525   'ON',
526   'WHERE',
527   'GROUP \s+ BY',
528   'HAVING',
529   'ORDER \s+ BY',
530   'I?LIKE',
531 );
532 my $unrollable_ops_re = join ' | ', @unrollable_ops;
533 $unrollable_ops_re = qr/$unrollable_ops_re/xi;
534
535 sub _parenthesis_unroll {
536   my $self = shift;
537   my $ast = shift;
538
539   #return if $self->parenthesis_significant;
540   return unless (ref $ast and ref $ast->[1]);
541
542   my $changes;
543   do {
544     my @children;
545     $changes = 0;
546
547     for my $child (@{$ast->[1]}) {
548       # the current node in this loop is *always* a PAREN
549       if (! ref $child or ! @$child or $child->[0] ne 'PAREN') {
550         push @children, $child;
551         next;
552       }
553
554       # unroll nested parenthesis
555       while ( @{$child->[1]} && $child->[1][0][0] eq 'PAREN') {
556         $child = $child->[1][0];
557         $changes++;
558       }
559
560       # if the parenthesis are wrapped around an AND/OR matching the parent AND/OR - open the parenthesis up and merge the list
561       if (
562         ( $ast->[0] eq 'AND' or $ast->[0] eq 'OR')
563             and
564           $child->[1][0][0] eq $ast->[0]
565       ) {
566         push @children, @{$child->[1][0][1]};
567         $changes++;
568       }
569
570       # if the parent operator explcitly allows it nuke the parenthesis
571       elsif ( $ast->[0] =~ $unrollable_ops_re ) {
572         push @children, $child->[1][0];
573         $changes++;
574       }
575
576       # only *ONE* LITERAL or placeholder element
577       # as an AND/OR/NOT argument
578       elsif (
579         @{$child->[1]} == 1 && (
580           $child->[1][0][0] eq 'LITERAL'
581             or
582           $child->[1][0][0] eq 'PLACEHOLDER'
583         ) && (
584           $ast->[0] eq 'AND' or $ast->[0] eq 'OR' or $ast->[0] eq 'NOT'
585         )
586       ) {
587         push @children, $child->[1][0];
588         $changes++;
589       }
590
591       # only one element in the parenthesis which is a binary op
592       # and has exactly two grandchildren
593       # the only time when we can *not* unroll this is when both
594       # the parent and the child are mathops (in which case we'll
595       # break precedence) or when the child is BETWEEN (special
596       # case)
597       elsif (
598         @{$child->[1]} == 1
599           and
600         $child->[1][0][0] =~ SQL::Abstract::Tree::_binary_op_re()
601           and
602         $child->[1][0][0] ne 'BETWEEN'
603           and
604         @{$child->[1][0][1]} == 2
605           and
606         ! (
607           $child->[1][0][0] =~ SQL::Abstract::Tree::_math_op_re()
608             and
609           $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
610         )
611       ) {
612         push @children, $child->[1][0];
613         $changes++;
614       }
615
616       # a function binds tighter than a mathop - see if our ancestor is a
617       # mathop, and our content is:
618       # a single non-mathop child with a single PAREN grandchild which
619       # would indicate mathop ( nonmathop ( ... ) )
620       # or a single non-mathop with a single LITERAL ( nonmathop foo )
621       # or a single non-mathop with a single PLACEHOLDER ( nonmathop ? )
622       elsif (
623         @{$child->[1]} == 1
624           and
625         @{$child->[1][0][1]} == 1
626           and
627         $ast->[0] =~ SQL::Abstract::Tree::_math_op_re()
628           and
629         $child->[1][0][0] !~ SQL::Abstract::Tree::_math_op_re
630           and
631         (
632           $child->[1][0][1][0][0] eq 'PAREN'
633             or
634           $child->[1][0][1][0][0] eq 'LITERAL'
635             or
636           $child->[1][0][1][0][0] eq 'PLACEHOLDER'
637         )
638       ) {
639         push @children, $child->[1][0];
640         $changes++;
641       }
642
643
644       # otherwise no more mucking for this pass
645       else {
646         push @children, $child;
647       }
648     }
649
650     $ast->[1] = \@children;
651
652   } while ($changes);
653
654 }
655
656 sub format { my $self = shift; $self->unparse($self->parse($_[0]), $_[1]) }
657
658 1;
659
660 =pod
661
662 =head1 NAME
663
664 SQL::Abstract::Tree - Represent SQL as an AST
665
666 =head1 SYNOPSIS
667
668  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
669
670  print $sqla_tree->format('SELECT * FROM foo WHERE foo.a > 2');
671
672  # SELECT *
673  #   FROM foo
674  #   WHERE foo.a > 2
675
676 =head1 METHODS
677
678 =head2 new
679
680  my $sqla_tree = SQL::Abstract::Tree->new({ profile => 'console' });
681
682  $args = {
683    profile => 'console',      # predefined profile to use (default: 'none')
684    fill_in_placeholders => 1, # true for placeholder population
685    placeholder_surround =>    # The strings that will be wrapped around
686               [GREEN, RESET], # populated placeholders if the above is set
687    indent_string => ' ',      # the string used when indenting
688    indent_amount => 2,        # how many of above string to use for a single
689                               # indent level
690    newline       => "\n",     # string for newline
691    colormap      => {
692      select => [RED, RESET], # a pair of strings defining what to surround
693                              # the keyword with for colorization
694      # ...
695    },
696    indentmap     => {
697      select        => 0,     # A zero means that the keyword will start on
698                              # a new line
699      from          => 1,     # Any other positive integer means that after
700      on            => 2,     # said newline it will get that many indents
701      # ...
702    },
703  }
704
705 Returns a new SQL::Abstract::Tree object.  All arguments are optional.
706
707 =head3 profiles
708
709 There are four predefined profiles, C<none>, C<console>, C<console_monochrome>,
710 and C<html>.  Typically a user will probably just use C<console> or
711 C<console_monochrome>, but if something about a profile bothers you, merely
712 use the profile and override the parts that you don't like.
713
714 =head2 format
715
716  $sqlat->format('SELECT * FROM bar WHERE x = ?', [1])
717
718 Takes C<$sql> and C<\@bindargs>.
719
720 Returns a formatting string based on the string passed in
721
722 =head2 parse
723
724  $sqlat->parse('SELECT * FROM bar WHERE x = ?')
725
726 Returns a "tree" representing passed in SQL.  Please do not depend on the
727 structure of the returned tree.  It may be stable at some point, but not yet.
728
729 =head2 unparse
730
731  $sqlat->parse($tree_structure, \@bindargs)
732
733 Transform "tree" into SQL, applying various transforms on the way.
734
735 =head2 format_keyword
736
737  $sqlat->format_keyword('SELECT')
738
739 Currently this just takes a keyword and puts the C<colormap> stuff around it.
740 Later on it may do more and allow for coderef based transforms.
741
742 =head2 pad_keyword
743
744  my ($before, $after) = @{$sqlat->pad_keyword('SELECT')};
745
746 Returns whitespace to be inserted around a keyword.
747
748 =head2 fill_in_placeholder
749
750  my $value = $sqlat->fill_in_placeholder(\@bindargs)
751
752 Removes last arg from passed arrayref and returns it, surrounded with
753 the values in placeholder_surround, and then surrounded with single quotes.
754
755 =head2 indent
756
757 Returns as many indent strings as indent amounts times the first argument.
758
759 =head1 ACCESSORS
760
761 =head2 colormap
762
763 See L</new>
764
765 =head2 fill_in_placeholders
766
767 See L</new>
768
769 =head2 indent_amount
770
771 See L</new>
772
773 =head2 indent_string
774
775 See L</new>
776
777 =head2 indentmap
778
779 See L</new>
780
781 =head2 newline
782
783 See L</new>
784
785 =head2 placeholder_surround
786
787 See L</new>
788