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