package SQL::Abstract::More;
use strict;
use warnings;

# no "use parent ..." here -- for the moment the inheritance is specified dynamically in the
# import() method -- inheriting either from SQL::Abstract or SQL::Abstract::Classic.
# This is deprecated and will no longer be supported in the next version

use mro 'c3'; # implements next::method

use Params::Validate  qw/validate SCALAR SCALARREF CODEREF ARRAYREF HASHREF
                                  UNDEF  BOOLEAN/;
use Scalar::Util      qw/blessed reftype/;


# remove all previously defined or imported functions
use namespace::clean;

# declare error-reporting functions from SQL::Abstract
sub puke(@); sub belch(@);  # these will be defined later in import()

our $VERSION = '1.49_01';
our @ISA;

sub import {
  my $class = shift;

  # the parent class may be specified from an environment variable ...
  my $parent_sqla = $ENV{SQL_ABSTRACT_MORE_EXTENDS};

  # ... or from param -extends => .. when calling import() ...
  $parent_sqla = $_[1] if @_ >= 2 && $_[0] eq '-extends';

  # ... but choosing the parent is deprecated!
  ! $parent_sqla
    or warn "explicitly specification of $parent_sqla as parent class to SQL::Abstract::More is deprecated; "
          . "future versions will no longer offer that possibility";

  # default parent class .. this will be mandatory in the next version. Later versions may have no parent at all.
  $parent_sqla ||= 'SQL::Abstract::Classic';

  # syntactic sugar : 'Classic' is expanded into SQLA::Classic
  $parent_sqla = 'SQL::Abstract::Classic' if $parent_sqla eq 'Classic';

  # make sure that import() is never called with different parents
  if (my $already_isa = $ISA[0]) {
    $already_isa eq $parent_sqla
      or die "cannot use SQL::Abstract::More -extends => '$parent_sqla', "
           . "this module was already loaded with -extends => '$already_isa'";

    # the rest of the import() job was already performed, so just return from here
    return;
  }

  # load the parent, inherit from it, import puke() and belch()
  eval qq{use parent '$parent_sqla';
          *puke  = \\&${parent_sqla}::puke;
          *belch = \\&${parent_sqla}::belch;
         };

  # local override of some methods for insert() and update()
  _setup_insert_inheritance($parent_sqla);
  _setup_update_inheritance($parent_sqla);
}



#----------------------------------------------------------------------
# Utility functions -- not methods -- declared _after_
# namespace::clean so that they can remain visible by external
# modules. In particular, DBIx::DataModel imports these functions.
#----------------------------------------------------------------------

# shallow_clone(): copies of the top-level keys and values, blessed into the same class
sub shallow_clone {
  my ($orig, %override) = @_;

  my $class = ref $orig
    or puke "arg must be an object";
  my $clone = {%$orig, %override};
  return bless $clone, $class;
}


# does(): cheap version of Scalar::Does
my %meth_for = (
  ARRAY  => '@{}',
  HASH   => '%{}',
  SCALAR => '${}',
  CODE   => '&{}',
 );
sub does ($$) {
  my ($data, $type) = @_;
  my $reft = reftype $data;
  return defined $reft && $reft eq $type
      || blessed $data && overload::Method($data, $meth_for{$type});
}



#----------------------------------------------------------------------
# global variables
#----------------------------------------------------------------------

# builtin methods for "Limit-Offset" dialects
my %limit_offset_dialects = (
  LimitOffset     => sub {my ($self, $limit, $offset) = @_;
                          $offset ||= 0;
                          return "LIMIT ? OFFSET ?", $limit, $offset;},
  LimitXY         => sub {my ($self, $limit, $offset) = @_;
                          $offset ||= 0;
                          return "LIMIT ?, ?", $offset, $limit;},
  LimitYX         => sub {my ($self, $limit, $offset) = @_;
                          $offset ||= 0;
                          return "LIMIT ?, ?", $limit, $offset;},
  OffsetFetchRows => sub {my ($self, $limit, $offset) = @_;
                          $offset ||= 0;
                          return "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY", $offset, $limit;},
  RowNum          => sub {
    my ($self, $limit, $offset) = @_;
    # HACK below borrowed from SQL::Abstract::Limit. Not perfect, though,
    # because it brings back an additional column. Should borrow from 
    # DBIx::Class::SQLMaker::LimitDialects, which does the proper job ...
    # but it says : "!!! THIS IS ALSO HORRIFIC !!! /me ashamed"; so
    # I'll only take it as last resort; still exploring other ways.
    # See also L<DBIx::DataModel> : within that ORM an additional layer is
    # added to take advantage of Oracle scrollable cursors (for Oracle < 12c).
    my $sql = "SELECT * FROM ("
            .   "SELECT subq_A.*, ROWNUM rownum__index FROM (%s) subq_A "
            .   "WHERE ROWNUM <= ?"
            .  ") subq_B WHERE rownum__index >= ?";

    no warnings 'uninitialized'; # in case $limit or $offset is undef
    # row numbers start at 1
    return $sql, $offset + $limit, $offset + 1;
  },
 );

# builtin join operators with associated sprintf syntax
my %common_join_syntax = (
  '<=>' => '%s INNER JOIN %s ON %s',
   '=>' => '%s LEFT OUTER JOIN %s ON %s',
  '<='  => '%s RIGHT OUTER JOIN %s ON %s',
  '=='  => '%s NATURAL JOIN %s',
  '>=<' => '%s FULL OUTER JOIN %s ON %s',
);
my %right_assoc_join_syntax = %common_join_syntax;
s/JOIN %s/JOIN (%s)/ foreach values %right_assoc_join_syntax;

# specification of parameters accepted by the new() method
my %params_for_new = (
  table_alias           => {type => SCALAR|CODEREF,   default  => '%s AS %s'          },
  column_alias          => {type => SCALAR|CODEREF,   default  => '%s AS %s'          },
  limit_offset          => {type => SCALAR|CODEREF,   default  => 'LimitOffset'       },
  join_syntax           => {type => HASHREF,          default  => \%common_join_syntax},
  join_assoc_right      => {type => BOOLEAN,          default  => 0                   },
  max_members_IN        => {type => SCALAR,           optional => 1                   },
  multicols_sep         => {type => SCALAR|SCALARREF, optional => 1                   },
  has_multicols_in_SQL  => {type => BOOLEAN,          optional => 1                   },
  sql_dialect           => {type => SCALAR,           optional => 1                   },
  select_implicitly_for => {type => SCALAR|UNDEF,     optional => 1                   },
);

# builtin collection of parameters, for various databases
my %sql_dialects = (
 MsAccess  => {join_assoc_right     => 1,
               join_syntax          => \%right_assoc_join_syntax},
 BasisJDBC => {column_alias         => "%s %s",
               max_members_IN       => 255                      },
 MySQL_old => {limit_offset         => "LimitXY"                },
 Oracle    => {limit_offset         => "RowNum",
               max_members_IN       => 999,
               table_alias          => '%s %s',
               column_alias         => '%s %s',
               has_multicols_in_SQL => 1,                       },
);
$sql_dialects{Oracle12c} = {%{$sql_dialects{Oracle}}, limit_offset => "OffsetFetchRows"};


# operators for compound queries
my @set_operators = qw/union union_all intersect minus except/;

# specification of parameters accepted by select, insert, update, delete
my %params_for_select = (
  -columns      => {type => SCALAR|ARRAYREF,         default  => '*'},
  -from         => {type => SCALAR|SCALARREF|ARRAYREF},
  -where        => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  (map {-$_ => {type => ARRAYREF, optional => 1}} @set_operators),
  -group_by     => {type => SCALAR|ARRAYREF,         optional => 1},
  -having       => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -order_by     => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -page_size    => {type => SCALAR,                  optional => 1},
  -page_index   => {type => SCALAR,                  optional => 1,
                                                     depends  => '-page_size'},
  -limit        => {type => SCALAR,                  optional => 1},
  -offset       => {type => SCALAR,                  optional => 1,
                                                     depends  => '-limit'},
  -for          => {type => SCALAR|UNDEF,            optional => 1},
  -want_details => {type => BOOLEAN,                 optional => 1},
  -as           => {type => SCALAR,                  optional => 1},
);
my %params_for_insert = (
  -into         => {type => SCALAR},
  -values       => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -select       => {type => HASHREF,                 optional => 1},
  -columns      => {type => ARRAYREF,                optional => 1},
  -returning    => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -add_sql      => {type => SCALAR,                  optional => 1},
);
my %params_for_update = (
  -table        => {type => SCALAR|SCALARREF|ARRAYREF},
  -set          => {type => HASHREF},
  -where        => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -order_by     => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -limit        => {type => SCALAR,                  optional => 1},
  -returning    => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -add_sql      => {type => SCALAR,                  optional => 1},
);
my %params_for_delete = (
  -from         => {type => SCALAR},
  -where        => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -order_by     => {type => SCALAR|ARRAYREF|HASHREF, optional => 1},
  -limit        => {type => SCALAR,                  optional => 1},
  -add_sql      => {type => SCALAR,                  optional => 1},
);
my %params_for_WITH = (
  -table        => {type => SCALAR},
  -columns      => {type => SCALAR|ARRAYREF,         optional => 1},
  -as_select    => {type => HASHREF},
  -final_clause => {type => SCALAR,                  optional => 1},
);



#----------------------------------------------------------------------
# object creation
#----------------------------------------------------------------------

sub new {
  my $class = shift;

  # make sure @ISA is populated, in case import() was not already called
  $class->import() if !@ISA;

  # accept params either as hash or as hashref
  my %params = does($_[0], 'HASH') ? %{$_[0]} : @_;

  # extract params for this subclass
  my %more_params;
  foreach my $key (keys %params_for_new) {
    $more_params{$key} = delete $params{$key} if exists $params{$key};
  }

  # import params from SQL dialect, if any ... but explict params above had precedence
  my $dialect = delete $more_params{sql_dialect};
  if ($dialect) {
    my $dialect_params = $sql_dialects{$dialect}
      or puke "no such sql dialect: $dialect";
    $more_params{$_} ||= $dialect_params->{$_} foreach keys %$dialect_params;
  }

  # check parameters for this class
  my @more_params = %more_params;
  my $more_self   = validate(@more_params, \%params_for_new);

  # check some of the params for parent -- because SQLA doesn't do it :-(
  !$params{quote_char} || exists $params{name_sep}
    or belch "when 'quote_char' is present, 'name_sep' should be present too";

  # call parent constructor
  my $self = $class->next::method(%params);

  # inject additional attributes into $self 
  $self->{$_} = $more_self->{$_} foreach keys %$more_self;

  # arguments supplied as scalars are transformed into coderefs
  ref $self->{column_alias} or $self->_make_aliasing_sub('column_alias');
  ref $self->{table_alias}  or $self->_make_aliasing_sub('table_alias');
  ref $self->{limit_offset} or $self->_choose_LIMIT_OFFSET_dialect;

  # compute the regex for parsing join specifications - depending on 'join_syntax' attribute
  my @join_ops = sort {length($b) <=> length($a) || $a cmp $b}
                      keys %{$self->{join_syntax}};
  my $joined_ops = join '|', map quotemeta, @join_ops;
  $self->{join_regex} = qr[
     ^              # initial anchor 
     ($joined_ops)? # $1: join operator (i.e. '<=>', '=>', etc.))
     ([[{])?        # $2: opening '[' or '{'
     (.*?)          # $3: content of brackets
     []}]?          # closing ']' or '}'
     $              # final anchor
   ]x;

  return $self;
}



#----------------------------------------------------------------------
# support for WITH or WITH RECURSIVE
#----------------------------------------------------------------------

sub with {
  my $self = shift;

  ! $self->{WITH}
    or puke "calls to methods with() or with_recursive() cannot be chained";

  @_
    or puke "->with() : missing arguments";

  # create a copy of the current object with an additional attribute WITH
  my $clone = shallow_clone($self, WITH => {sql => "", bind => []});

  # assemble SQL and bind values for each table expression
  my @table_expressions = does($_[0], 'ARRAY') ? @_ : ( [ @_]);
  foreach my $table_expression (@table_expressions) {
    my %args = validate(@$table_expression, \%params_for_WITH);
    my @cols = does($args{-columns}, 'ARRAY') ? @{$args{-columns}}
             : $args{-columns}                ? ($args{-columns})
             :                                  ();
    my ($sql, @bind) = $self->select(%{$args{-as_select}});
    $clone->{WITH}{sql} .= ", " if $clone->{WITH}{sql};
    $clone->{WITH}{sql} .= $self->_quote($args{-table});
    $clone->{WITH}{sql} .= "(" . join(", ", map {$self->_quote($_)} @cols) . ")"   if @cols;
    $clone->{WITH}{sql} .= " AS ($sql) ";
    $clone->{WITH}{sql} .= $args{-final_clause} . " "      if $args{-final_clause};
    push @{$clone->{WITH}{bind}}, @bind;
  }

  # add the initial keyword WITH 
  substr($clone->{WITH}{sql}, 0, 0) = 'WITH ';

  return $clone;
}

sub with_recursive {
  my $self = shift;

  my $new_instance = $self->with(@_);
  $new_instance->{WITH}{sql} =~ s/^WITH\b/WITH RECURSIVE/;

  return $new_instance;
}

sub _prepend_WITH_clause {
  my ($self, $ref_sql, $ref_bind) = @_;

  return if !$self->{WITH};

  substr($$ref_sql, 0, 0) = $self->{WITH}{sql};
  unshift @$ref_bind, @{$self->{WITH}{bind}};
}


#----------------------------------------------------------------------
# the select method
#----------------------------------------------------------------------

sub select {
  my $self = shift;

  # if this method was called with positional args, just delegate to the parent
  return $self->next::method(@_) if !&_called_with_named_args;

  # parse arguments
  my %args = validate(@_, \%params_for_select);

  # infrastructure for collecting fragments of sql and bind args
  my ($sql, @bind) = ("");
  my $add_sql_bind = sub {$sql .= shift; push @bind, @_}; # closure to add to ($sql, @bind)

  # parse columns and datasource
  my $from                                               = $self->_parse_datasource($args{-from});
  my ($cols, $post_select, $cols_bind, $aliased_columns) = $self->_parse_columns($args{-columns});

  # parse the WHERE conditions
  my ($where_sql, @where_bind) = $self->where($args{-where});
  
  # assemble the SELECT statement
  my $fields     = ref $cols ? join ", ", @$cols : $cols;  
  my $select_sql = join(' ', $self->_sqlcase('select'), $fields, $self->_sqlcase('from'), $from->{sql}) . $where_sql;
  $add_sql_bind->($select_sql, @$cols_bind, @{$from->{bind}}, @where_bind);
  
  # add @post_select clauses if needed (for ex. -distinct)
  my $all_post_select = join " ", @$post_select;
  $sql =~ s[^SELECT ][SELECT $all_post_select ]i if $all_post_select;

  # add set operators (UNION, INTERSECT, etc) if needed
  foreach my $set_op (@set_operators) {
    if (my $val_set_op = $args{-$set_op}) {
      my ($sql_set_op, @bind_set_op) = $self->_parse_set_operator($set_op => $val_set_op, $args{-columns}, $args{-from});
      $add_sql_bind->($sql_set_op, @bind_set_op);
    } 
  }
  
  # add GROUP BY if needed
  if ($args{-group_by}) {
    my $sql_grp = $self->where(undef, $args{-group_by});
    $sql_grp =~ s/\bORDER\b/GROUP/i;
    $add_sql_bind->($sql_grp);
  }

  # add HAVING if needed (often together with -group_by, but not always)
  if ($args{-having}) {
    my ($sql_having, @bind_having) = $self->where($args{-having});
    $sql_having =~ s/\bWHERE\b/HAVING/i;
    $add_sql_bind->(" $sql_having", @bind_having);
  }

  # add ORDER BY if needed
  if (my $order = $args{-order_by}) {
    $add_sql_bind->($self->_order_by($order));
  }

  # add pagination if needed (either -page_* args or -limit/-offset)
  $self->_translate_page_into_limit_offset(\%args) if $args{-page_index} or $args{-page_size};
  if (defined $args{-limit}) {
    my ($limit_sql, @limit_bind) = $self->limit_offset(@args{qw/-limit -offset/});
    if ($limit_sql =~ /%s/) {
      $sql = sprintf $limit_sql, $sql; # rewrite the whole $sql
      push @bind, @limit_bind;
    }
    else {
      $add_sql_bind->(" $limit_sql", @limit_bind);
    }
  }

  # add FOR clause if needed
  my $for = exists $args{-for} ? $args{-for} : $self->{select_implicitly_for};
  $add_sql_bind->(" FOR $for") if $for;

  # add alias if select() is used as a subquery
  if (my $alias = $args{-as}) {
    $sql = "($sql)|$alias";
  }

  # initial WITH clause
  $self->_prepend_WITH_clause(\$sql, \@bind);

  # return results
  return $args{-want_details} ? {aliased_tables  => $from->{aliased_tables},
                                 aliased_columns => $aliased_columns,
                                 sql             => $sql,
                                 bind            => \@bind}
                              : ($sql, @bind);
}


sub _parse_columns {
  my ($self, $columns) = @_;

  # the -columns arg can be an arrayref or a plain scalar => unify into an array
  my @cols = ref $columns ? @$columns : ($columns);

  # initial members of the columns list starting with "-" are extracted into a 
  # separate list @post_select, later re-injected into the SQL (for ex. '-distinct')
  my @post_select;
  push @post_select, shift @cols while @cols && $cols[0] =~ s/^-//;

  # loop over columns, handling aliases and subqueries
  my @cols_bind;
  my %aliased_columns;
  foreach my $col (@cols) {
    # deal with subquery of shape \ [$sql, @bind]
    if (_is_subquery($col)) {
      my ($sql, @col_bind) = @$$col;
      $col = _parenthesize_select($sql);
      push @cols_bind, @col_bind;
    }

    # check for a column alias; if present, register it in the alias table
    ($col, my $alias)        = $self->_parse_alias($col);
    $aliased_columns{$alias} = $col if $alias ;

    # quote the column SQL if necessary - excluding expressions with parens or commas
    # (such as SQL functions or parenthesized subqueries)
    $col = $self->_quote($col) unless $col =~ /[(),]/;

    # insert SQL aliasing if necessary
    $col = $self->column_alias($col, $self->_quote($alias)) if $alias;
  }

  return (\@cols, \@post_select, \@cols_bind, \%aliased_columns);
}
 




sub _parse_set_operator {
  my ($self, $set_op, $val_set_op, $cols, $from) = @_;

  my %sub_args = @$val_set_op;
  $sub_args{-columns} ||= $cols;
  $sub_args{-from}    ||= $from;
  local $self->{WITH}; # temporarily disable the WITH part during the recursive call to select()
  my ($sql, @bind) = $self->select(%sub_args);
  (my $sql_op = uc($set_op)) =~ s/_/ /g; # for ex. -union_all becomes 'UNION ALL'
  return (" $sql_op $sql", @bind);
}


sub _translate_page_into_limit_offset {
  my ($self, $args) = @_;

  not exists $args->{$_} or puke "-page_size conflicts with $_"  for qw/-limit -offset/;
  $args->{-limit} = $args->{-page_size};
  if ($args->{-page_index}) {
    $args->{-offset} = ($args->{-page_index} - 1) * $args->{-page_size};
  }
}



#----------------------------------------------------------------------
# insert
#----------------------------------------------------------------------

sub _setup_insert_inheritance {
  my ($parent_sqla) = @_;

  # if the parent has method '_expand_insert_value' (SQL::Abstract >= v2.0),
  # we need to override it in this subclass
  if ($parent_sqla->can('_expand_insert_value')) {
    *_expand_insert_value = sub {
      my ($self, $v) = @_;

      my $k = our $Cur_Col_Meta;

      if (ref($v) eq 'ARRAY') {
        if ($self->{array_datatypes} || $self->is_bind_value_with_type($v)) {
          return +{ -bind => [ $k, $v ] };
        }
        my ($sql, @bind) = @$v;
        $self->_assert_bindval_matches_bindtype(@bind);
        return +{ -literal => $v };
      }
      if (ref($v) eq 'HASH') {
        if (grep !/^-/, keys %$v) {
          belch "HASH ref as bind value in insert is not supported";
          return +{ -bind => [ $k, $v ] };
        }
      }
      if (!defined($v)) {
        return +{ -bind => [ $k, undef ] };
      }
      return $self->expand_expr($v);
    };

    # we also need to back-implement the _insert_values method from earlier versions of SQLA
    *_insert_values = sub {
      my $self = shift;
      my ($sql, @bind) = $self->SUPER::insert(FAKE_TABLE => @_);
      $sql =~ s/^.*\bVALUES\b/VALUES/i;
      return ($sql, @bind);
    };
    
  }

  # otherwise, if the parent is an old SQL::Abstract or it is SQL::Abstract::Classic
  elsif ($parent_sqla->can('_insert_values')) {

    # if the parent has no method '_insert_value', this is the old
    # monolithic _insert_values() method. We must override it
    if (!$parent_sqla->can('_insert_value')) {
      *_insert_values = sub {
         my ($self, $data) = @_;

         my (@values, @all_bind);
         foreach my $column (sort keys %$data) {
           my ($values, @bind) = $self->_insert_value($column, $data->{$column});
           push @values, $values;
           push @all_bind, @bind;
         }
         my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
         return ($sql, @all_bind);
      };
    }

    # now override the _insert_value() method
    *_insert_value = sub {

      # unfortunately, we can't just override the ARRAYREF part, so the whole
      # parent method is copied here

      my ($self, $column, $v) = @_;

      my (@values, @all_bind);
      $self->_SWITCH_refkind($v, {

        ARRAYREF => sub {
          if ($self->{array_datatypes} # if array datatype are activated
                || $self->is_bind_value_with_type($v)) { # or if this is a bind val
            push @values, '?';
            push @all_bind, $self->_bindtype($column, $v);
          }
          else {                  # else literal SQL with bind
            my ($sql, @bind) = @$v;
            $self->_assert_bindval_matches_bindtype(@bind);
            push @values, $sql;
            push @all_bind, @bind;
          }
        },

        ARRAYREFREF => sub {        # literal SQL with bind
          my ($sql, @bind) = @${$v};
          $self->_assert_bindval_matches_bindtype(@bind);
          push @values, $sql;
          push @all_bind, @bind;
        },

        # THINK : anything useful to do with a HASHREF ?
        HASHREF => sub {       # (nothing, but old SQLA passed it through)
          #TODO in SQLA >= 2.0 it will die instead
          belch "HASH ref as bind value in insert is not supported";
          push @values, '?';
          push @all_bind, $self->_bindtype($column, $v);
        },

        SCALARREF => sub {          # literal SQL without bind
          push @values, $$v;
        },

        SCALAR_or_UNDEF => sub {
          push @values, '?';
          push @all_bind, $self->_bindtype($column, $v);
        },

      });

      my $sql = CORE::join(", ", @values);
      return ($sql, @all_bind);
    }
  }
  else {
    puke "unexpected parent class, cannot setup inheritance rules for insert()";
  }
}



sub insert {
  my $self = shift;

  my ($sql, @bind) = ("");
  my $add_sql_bind = sub {$sql .= shift; push @bind, @_}; # closure for adding to ($sql, @bind)

  if (not &_called_with_named_args) {
    ($sql, @bind) = $self->next::method(@_);
  } 
  else {
    # extract named args
    my %args = validate(@_, \%params_for_insert);

    $args{-into} or puke "insert(..) : need -into arg";
    my $source = $self->_parse_datasource($args{-into});
    $add_sql_bind->($self->_sqlcase('insert into') . " " . $source->{sql},
                    @{$source->{bind}}, # in principle always empty for an insert, but just for consistency's sake
                   );
    
    if (my $values = $args{-values}) {
      !$args{-select}  or puke "insert(-into => .., -values => ...) : incompatible with -select => ";

      if (does($values, 'HASH')) {
        !$args{-columns} or puke "insert(-into => .., -values => {...}) : incompatible with -columns => ";
        my $quoted_cols = join ", ", map {$self->_quote($_)} sort keys %$values;
        $add_sql_bind->("($quoted_cols)");
      }
      elsif (does($values, 'ARRAY')) {
        if (my $cols = $args{-columns}) {
          $cols = [$cols] if ! ref $cols;
          @$cols == @$values or puke "insert(-into => .., -columns => [...], -values => [...]) : numbers of columns do not match";
          my %merged; @merged{@$cols} = @$values;
          $values = \%merged;
          # NOTE: in doing so we lost the order of @$cols. In principle this has no impact on the final
          # result, but nevertheless is not very satisfactory. In a future version when we no longer need 
          # to support SQLA 2.0, we should have our own version of $self->_insert_cols_values($cols, $values); 

          my $quoted_cols = join ", ", map {$self->_quote($_)} sort @$cols;
          $add_sql_bind->("($quoted_cols)");
        }
        else {
          # Code and comments below borrowed from SQL::Abstract!
          #
          # fold the list of values into a hash of column name - value pairs
          # (where the column names are artificially generated, and their
          # lexicographical ordering keep the ordering of the original list)
          my $i = "a"; # incremented values will be in lexicographical order
          $values = { map { ($i++ => $_) } @$values };
        }
      }
      else {
        puke "insert(-into => .., -values => ...) : -values must be a hashref or an arrayref";
      }

      my ($val_sql, @val_bind)   = $self->_insert_values($values);
      $add_sql_bind->(" $val_sql", @val_bind);
    }
    elsif ($args{-select}) {
      local $self->{WITH}; # temporarily disable the WITH part during the subquery
      if (my $cols = $args{-columns}) {
        $cols = [$cols] if ! ref $cols;
        my $quoted_cols = join ", ", map {$self->_quote($_)} @$cols;
        $add_sql_bind->("($quoted_cols)");
      }
      my ($select_sql, @select_bind) = $self->select(%{$args{-select}});
      $add_sql_bind->(" $select_sql", @select_bind);
    }
    else {
      puke "insert(-into => ..) : need either -values arg or -select arg";
    }

    # THINK: should also support some syntax for generating INSERT INTO Foo(a, b, c) VALUES (1, 2, 3), (4, 5, 6), ...
    # Probably a variant like -columns => [qw/a b c/], -values => [[1, 2, 3], [4, 5, 6], ..]

    # deal with -returning arg
    if ($args{-returning}) {
      my ($into, $returning) = $self->_compute_returning($args{-returning});
      my ($r_sql, @r_bind)   = $self->_insert_returning($returning); # TODO : implement directly instead of calling SQLA
      $add_sql_bind->($r_sql, @r_bind);
    
      # inject more stuff if using Oracle's "RETURNING ... INTO ..."
      if ($into) {
        $add_sql_bind->($self->_sqlcase(' into ') . join(", ", ("?") x @$into),
                        @$into);
      }
    }
    
    # SQL to add after the INSERT keyword
    $sql =~ s/\b(INSERT)\b/$1 $args{-add_sql}/i if $args{-add_sql};
  };

  # initial WITH clause
  $self->_prepend_WITH_clause(\$sql, \@bind);

  return ($sql, @bind);
}

#----------------------------------------------------------------------
# update
#----------------------------------------------------------------------


sub _setup_update_inheritance {
  my ($parent_sqla) = @_;

  # if the parent has method '_expand_update_set_value' (SQL::Abstract >= v2.0),
  # we need to override it in this subclass
  if ($parent_sqla->can('_expand_update_set_values')) {
    *_parent_update            = $parent_sqla->can('update');
    *_expand_update_set_values = sub {
      my ($self, undef, $data) = @_;
      $self->expand_expr({ -list => [
        map {
          my ($k, $set) = @$_;
          $set = { -bind => $_ } unless defined $set;
          +{ -op => [ '=', { -ident => $k }, $set ] };
        }
        map {
          my $k = $_;
          my $v = $data->{$k};
          (ref($v) eq 'ARRAY'
            ? ($self->{array_datatypes} || $self->is_bind_value_with_type($v)
                ? [ $k, +{ -bind => [ $k, $v ] } ]
                : [ $k, +{ -literal => $v } ])
            : do {
                local our $Cur_Col_Meta = $k;
                [ $k, $self->_expand_expr($v) ]
              }
          );
        } sort keys %$data
      ] });
    };
  }


  # otherwise, if the parent is an old SQL::Abstract or it is SQL::Abstract::Classic
  else {
    # if the parent has method '_update_set_values()', it is a SQLA version >=1.85.
    # We can just use its update() method as _parent_update().
    if ($parent_sqla->can('_update_set_values')) {
      *_parent_update = $parent_sqla->can('update');
    }

    # otherwise, it's the old monolithic update() method. We need to supply our own
    # version as _parent_update().
    else {
      *_parent_update = sub {
         my $self    = shift;
         my $table   = $self->_table(shift);
         my $data    = shift || return;
         my $where   = shift;
         my $options = shift;

         # first build the 'SET' part of the sql statement
         puke "Unsupported data type specified to \$sql->update"
           unless ref $data eq 'HASH';

         my ($sql, @all_bind) = $self->_update_set_values($data);
         $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
                 . $sql;

         if ($where) {
           my($where_sql, @where_bind) = $self->where($where);
           $sql .= $where_sql;
           push @all_bind, @where_bind;
         }

         if ($options->{returning}) {
           my ($returning_sql, @returning_bind) = $self->_update_returning($options);
           $sql .= $returning_sql;
           push @all_bind, @returning_bind;
         }

         return wantarray ? ($sql, @all_bind) : $sql;
       };
      *_update_returning = sub {
         my ($self, $options) = @_;

         my $f = $options->{returning};

         my $fieldlist = $self->_SWITCH_refkind($f, {
           ARRAYREF     => sub {join ', ', map { $self->_quote($_) } @$f;},
           SCALAR       => sub {$self->_quote($f)},
           SCALARREF    => sub {$$f},
         });
         return $self->_sqlcase(' returning ') . $fieldlist;
      };
    }

    # now override or supply the _update_set_values() method
    *_update_set_values = sub {
      my ($self, $data) = @_;

      my (@set, @all_bind);
      for my $k (sort keys %$data) {
        my $v = $data->{$k};
        my $r = ref $v;
        my $label = $self->_quote($k);

        $self->_SWITCH_refkind($v, {
          ARRAYREF => sub {
            if ($self->{array_datatypes}                  # array datatype
                || $self->is_bind_value_with_type($v)) {  # or bind value with type
              push @set, "$label = ?";
              push @all_bind, $self->_bindtype($k, $v);
            }
            else {                          # literal SQL with bind
              my ($sql, @bind) = @$v;
              $self->_assert_bindval_matches_bindtype(@bind);
              push @set, "$label = $sql";
              push @all_bind, @bind;
            }
          },
          ARRAYREFREF => sub { # literal SQL with bind
            my ($sql, @bind) = @${$v};
            $self->_assert_bindval_matches_bindtype(@bind);
            push @set, "$label = $sql";
            push @all_bind, @bind;
          },
          SCALARREF => sub {  # literal SQL without bind
            push @set, "$label = $$v";
          },
          HASHREF => sub {
            my ($op, $arg, @rest) = %$v;

            puke 'Operator calls in update must be in the form { -op => $arg }'
              if (@rest or not $op =~ /^\-(.+)/);

            local $self->{_nested_func_lhs} = $k;
            my ($sql, @bind) = $self->_where_unary_op($1, $arg);

            push @set, "$label = $sql";
            push @all_bind, @bind;
          },
          SCALAR_or_UNDEF => sub {
            push @set, "$label = ?";
            push @all_bind, $self->_bindtype($k, $v);
          },
        });
      }
      # generate sql
      my $sql = CORE::join ', ', @set;
      return ($sql, @all_bind);
    };
  }
}

sub update {
  my $self = shift;

  my ($sql, @bind);

  if (not &_called_with_named_args) {
    ($sql, @bind) = $self->next::method(@_);
  } 
  else {
    my %args = validate(@_, \%params_for_update);

    # first build the 'SET' part of the sql statement
    does($args{-set}, 'HASH') or puke "Unsupported data type specified to \$sql->update";
    ($sql, @bind) = $self->_update_set_values($args{-set});

    # add the initial part of the statement
    my $join_info = $self->_compute_join_info($args{-table});
    my $table     = defined $join_info  ? $join_info->{sql}
                                        : $self->_parse_table($args{-table})->{sql};
    substr($sql, 0, 0) = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ');

    # add the 'WHERE' part
    if ($args{-where}) {
      my ($where_sql, @where_bind) = $self->where($args{-where});
      $sql .= $where_sql;
      push @bind, @where_bind;
    }

    # deal with -returning arg
    my ($into, $returning) = $self->_compute_returning($args{-returning});
    $sql .= $self->_update_returning($returning) if $returning;

    # merge with bind values from $join_info
    unshift @bind, @{$join_info->{bind}} if $join_info;

    # handle additional args if needed
    $self->_handle_additional_args_for_update_delete(\%args, \$sql, \@bind, qr/UPDATE/);

    # deal with Oracle's "RETURNING ... INTO ..."
    if ($into) {
      $sql .= ' INTO ' . join(", ", ("?") x @$into);
      push @bind, @$into;
    }
  }
  

  # initial WITH clause
  $self->_prepend_WITH_clause(\$sql, \@bind);

  return ($sql, @bind);
}






#----------------------------------------------------------------------
# delete
#----------------------------------------------------------------------

sub delete {
  my $self = shift;

  my ($sql, @bind);

  if (not &_called_with_named_args) {
    ($sql, @bind) = $self->next::method(@_);
  } 
  else {
    my %args = validate(@_, \%params_for_delete);
    ($sql, @bind)      = $self->where($args{-where});
    substr($sql, 0, 0) = $self->_sqlcase('delete from ') . $self->_parse_table($args{-from})->{sql};

    # handle additional args if needed
    $self->_handle_additional_args_for_update_delete(\%args, \$sql, \@bind, qr/DELETE/);
  }
  
  # initial WITH clause
  $self->_prepend_WITH_clause(\$sql, \@bind);

  return ($sql, @bind);
}



#----------------------------------------------------------------------
# auxiliary methods for insert(), update() and delete()
#----------------------------------------------------------------------

sub _compute_returning {
  my ($self, $arg_returning) = @_; 

  my ($returning_into, $old_API_options);

  if ($arg_returning) {
    # if present, "-returning" may be a scalar, arrayref or hashref; the latter
    # is interpreted as .. RETURNING ... INTO ...

    if (does $arg_returning, 'HASH') {
      my @keys = sort keys %$arg_returning
        or puke "-returning => {} : the hash is empty";

      $old_API_options = {returning => \@keys};
      $returning_into  = [@{$arg_returning}{@keys}];
    }
    else {
      $old_API_options = {returning => $arg_returning};
    }
  }

  return ($returning_into, $old_API_options);
}


sub _handle_additional_args_for_update_delete {
  my ($self, $args, $sql_ref, $bind_ref, $keyword_regex) = @_;

  if (defined $args->{-order_by}) {
    my ($sql_ob, @bind_ob) = $self->_order_by($args->{-order_by});
    $$sql_ref .= $sql_ob;
    push @$bind_ref, @bind_ob;
  }
  if (defined $args->{-limit}) {
    # can't call $self->limit_offset(..) because there shouldn't be any offset
    $$sql_ref .= $self->_sqlcase(' limit ?');
    push @$bind_ref, $args->{-limit};
  }
  if (defined $args->{-add_sql}) {
    $$sql_ref =~ s/\b($keyword_regex)\b/$1 $args->{-add_sql}/i;
  }
}


sub _order_by {
  my ($self, $order) = @_;

  # force scalar into an arrayref
  $order = [$order] if not ref $order;

  # restructure array data
  if (does $order, 'ARRAY') {
    my @clone = @$order;      # because we will modify items

    # '-' and '+' prefixes are translated into {-desc/asc => } hashrefs
    foreach my $item (@clone) {
      next if !$item or ref $item;
      $item =~ s/^-//  and $item = {-desc => $item} and next;
      $item =~ s/^\+// and $item = {-asc  => $item};
    }
    $order = \@clone;
  }

  return $self->next::method($order);
}

#----------------------------------------------------------------------
# other public methods
#----------------------------------------------------------------------

# same pattern for 3 invocation methods
sub table_alias  {my $self = shift; my $meth = $self->{table_alias};  $self->$meth(@_)}
sub column_alias {my $self = shift; my $meth = $self->{column_alias}; $self->$meth(@_)}
sub limit_offset {my $self = shift; my $meth = $self->{limit_offset}; $self->$meth(@_)}



# readonly accessor methods
foreach my $key (qw/join_syntax  join_assoc_right
                    max_members_IN multicols_sep  has_multicols_in_SQL/) {
  no strict 'refs';
  *{$key} = sub {shift->{$key}};
}


# invocation method for 'join'
sub join {
  my $self = shift;

  # start from the right if right-associative
  @_ = reverse @_ if $self->{join_assoc_right};

  # shift first single item (a table) before reducing pairs (op, table)
  my $first_source = shift;
  my $accumulator  = $self->_parse_datasource($first_source);

  # reduce pairs (op, table)
  while (@_) {
    # shift 2 items : next join specification and next table
    my $join_spec   = shift;
    my $next_source = shift or puke "->join(): improper number of operands";

    $join_spec   = $self->_parse_join_spec($join_spec) unless ref $join_spec;
    $next_source = $self->_parse_datasource($next_source);
    $accumulator = $self->_single_join($accumulator, $join_spec, $next_source);
  }

  return $accumulator; # {sql=> .., bind => [..], aliased_tables => {..}}
}


# utility for merging several "where" clauses
sub merge_conditions {
  my $self = shift;
  my %merged;

  foreach my $cond (@_) {
    if    (does $cond, 'HASH')  {
      foreach my $col (sort keys %$cond) {
        $merged{$col} = $merged{$col} ? [-and => $merged{$col}, $cond->{$col}]
                                      : $cond->{$col};
      }
    }
    elsif (does $cond, 'ARRAY') {
      $merged{-nest} = $merged{-nest} ? {-and => [$merged{-nest}, $cond]}
                                      : $cond;
    }
    elsif ($cond) {
      $merged{$cond} = \"";
    }
  }
  return \%merged;
}

# utility for calling either bind_param or bind_param_inout
our $INOUT_MAX_LEN = 99; # chosen arbitrarily; see L<DBI/bind_param_inout>
sub bind_params {
  my ($self, $sth, @bind) = @_;
  $sth->isa('DBI::st') or puke "sth argument is not a DBI statement handle";
  foreach my $i (0 .. $#bind) {
    my $val = $bind[$i];
    if (does $val, 'SCALAR') {
      # a scalarref is interpreted as an INOUT parameter
      $sth->bind_param_inout($i+1, $val, $INOUT_MAX_LEN);
    }
    elsif (does $val, 'ARRAY' and
             my ($bind_meth, @args) = $self->is_bind_value_with_type($val)) {
      # either 'bind_param' or 'bind_param_inout', with 2 or 3 args
      $sth->$bind_meth($i+1, @args);
    }
    else {
      # other cases are passed directly to DBI::bind_param
      $sth->bind_param($i+1, $val);
    }
  }
}

sub is_bind_value_with_type {
  my ($self, $val) = @_;

  # compatibility with DBIx::Class syntax of shape [\%args => $val],
  # see L<DBIx::Class::ResultSet/"DBIC BIND VALUES">
  if (   @$val == 2
      && does($val->[0], 'HASH')
      && grep {$val->[0]{$_}} qw/dbd_attrs sqlt_size
                                 sqlt_datatype dbic_colname/) {
    my $args = $val->[0];
    if (my $attrs = $args->{dbd_attrs}) {
      return (bind_param => $val->[1], $attrs);
    }
    elsif (my $size = $args->{sqlt_size}) {
      return (bind_param_inout => $val, $size);
    }
    # other options like 'sqlt_datatype', 'dbic_colname' are not supported
    else {
      puke "unsupported options for bind type : " . CORE::join(", ", sort keys %$args);
    }

    # NOTE : the following DBIx::Class shortcuts are not supported
    #  [ $name => $val ] === [ { dbic_colname => $name }, $val ]
    #  [ \$dt  => $val ] === [ { sqlt_datatype => $dt }, $val ]
    #  [ undef,   $val ] === [ {}, $val ]
  }

  # in all other cases, this is not a bind value with type
  return ();
}

#----------------------------------------------------------------------
# private utility methods for 'join'
#----------------------------------------------------------------------

sub _compute_join_info {
  my ($self, $table_arg) = @_;

  if (does($table_arg, 'ARRAY') && $table_arg->[0] eq '-join') {
    return $self->join(@{$table_arg}[1 .. $#$table_arg]); # drop initial '-join'
  }
  else {
    return;
  }
}


sub _parse_alias {
  my ($self, $input_sql) = @_;

  return $input_sql =~ /^\s*             # ignore insignificant leading spaces
                         (\S.*?)         # $1: any non-empty string, no starting with space (but may include '|')
                         (?<!\|)         # no final '|' in the previous string
                         \|              # literal '|' (the last in the string)
                         (\pL[\w\s]*?)   # $2 : alias name: initial letter, then word chars or spaces
                         $/x    

  #         sql         alias
  #         ===         =====
         ? ($1,         $2   )
         : ($input_sql, undef);
}  


sub _parse_datasource {
  my ($self, $source) = @_;

  if (my $join_info = $self->_compute_join_info($source)) {
    return $join_info;
  }
  elsif (_is_subquery($source)) {
    # separate the $sql and @bind parts
    my ($sql, @bind) = @$$source;

    my $table_spec = $self->_parse_table(_parenthesize_select($sql), -dont_quote_table);
    $table_spec->{bind} = \@bind;
    return $table_spec;
  }
  elsif (does($source, 'ARRAY')) {
    # compatibility with old SQL::Abstract -- deprecated
    my @table_specs = map {$self->_parse_table($_)} @$source;
    return {sql            => (CORE::join ', ', map {$_->{sql}}               @table_specs),
            bind           => [                 map {@{$_->{bind}}}           @table_specs],
            aliased_tables => {                 map {%{$_->{aliased_tables}}} @table_specs}};
  }
  elsif (does($source, 'SCALAR')) {
    # reference to a SQL string --> handled as is without quoting
    return $self->_parse_table($$source, -dont_quote_table);
  }
  else {
    return $self->_parse_table($source);
  }
}



sub _parse_table {
  my ($self, $table, $dont_quote_table) = @_; # $dont_quote_table: just a boolean

  ($table, my $alias) = $self->_parse_alias($table);
 
  my $table_spec = {
    bind           => [],
    name           => ($alias || $table),
    aliased_tables => {$alias ? ($alias => $table) : ()},
   };

  $table = $self->_quote($table) unless $dont_quote_table;

  $table_spec->{sql} = $alias ? $self->table_alias($table, $self->_quote($alias)) : $table;

  return $table_spec;
}

sub _parse_join_spec {
  my ($self, $join_spec) = @_;

  # parse the join specification
  $join_spec
    or puke "empty join specification";
  my ($op, $bracket, $cond_list) = ($join_spec =~ $self->{join_regex})
    or puke "incorrect join specification : $join_spec\n$self->{join_regex}";
  $op        ||= '<=>';
  $bracket   ||= '{';
  $cond_list ||= '';

  # extract constants (strings between quotes), replaced by placeholders
  my $regex = qr/'       # initial quote
                 (       # begin capturing group
                  [^']*    # any non-quote chars
                  (?:        # begin non-capturing group
                     ''        # pair of quotes
                     [^']*     # any non-quote chars
                  )*         # this non-capturing group 0 or more times
                 )       # end of capturing group
                 '       # ending quote
                /x;
  my $placeholder = '_?_'; # unlikely to be counfounded with any value 
  my @constants;
  while ($cond_list =~ s/$regex/$placeholder/) {
    push @constants, $1;
  };
  s/''/'/g for @constants;  # replace pairs of quotes by single quotes

  # accumulate conditions as pairs ($left => \"$op $right")
  my @conditions;
  my @using;
  foreach my $cond (split /,\s*/, $cond_list) {
    # parse the condition (left and right operands + comparison operator)
    my ($left, $cmp, $right) = split /([<>=!^]{1,2})/, $cond;
    if ($cmp && $right) {
      # if operands are not qualified by table/alias name, add sprintf hooks
      $left  = '%1$s.' . $left   unless $left  =~ /\./;
      $right = '%2$s.' . $right  unless $right =~ /\./ or $right eq $placeholder;

      # add this pair into the list; right operand is either a bind value
      # or an identifier within the right table
      $right = $right eq $placeholder ? shift @constants : {-ident => $right};
      push @conditions, $left, {$cmp => $right};
    }
    elsif ($cond =~ /^\w+$/) {
      push @using, $cond;
    }
    else {puke "can't parse join condition: $cond"}
  }

  # build join hashref
  my $join_hash = {operator  => $op};
  $join_hash->{using} = \@using                        if @using;
  $join_hash->{condition}
    = $bracket eq '[' ? [@conditions] : {@conditions}  if @conditions;

  return $join_hash;
}

sub _single_join {
  my $self = shift;

  # if right-associative, restore proper left-right order in pair
  @_ = reverse @_ if $self->{join_assoc_right};
  my ($left, $join_spec, $right) = @_;

  # syntax for assembling all elements
  my $syntax = $self->{join_syntax}{$join_spec->{operator}};

  my ($sql, @bind);

  { no if $] ge '5.022000', warnings => 'redundant';
    # because sprintf instructions  may _intentionally_ omit %.. parameters

    if ($join_spec->{using}) {
      not $join_spec->{condition}
        or puke "join specification has both {condition} and {using} fields";

      $syntax =~ s/\bON\s+%s/USING (%s)/;
      $sql = CORE::join ",", map {$self->_quote($_)} @{$join_spec->{using}};
    }
    elsif ($join_spec->{condition}) {
      not $join_spec->{using}
        or puke "join specification has both {condition} and {using} fields";

      # compute the "ON" clause
      ($sql, @bind) = $self->where($join_spec->{condition});
      $sql =~ s/^\s*WHERE\s+//;

      # substitute left/right tables names for '%1$s', '%2$s'
      $sql = sprintf $sql, $left->{name}, $right->{name};
    }

    # build the final sql
    $sql = sprintf $syntax, $left->{sql}, $right->{sql}, $sql;
  }

  # add left/right bind parameters (if any) into the list
  unshift @bind, @{$left->{bind}}, @{$right->{bind}};

  # build result and return
  my %result = (sql => $sql, bind => \@bind);
  $result{name} = ($self->{join_assoc_right} ? $left : $right)->{name};
  $result{aliased_tables} = $left->{aliased_tables};
  foreach my $alias (keys %{$right->{aliased_tables}}) {
    $result{aliased_tables}{$alias} = $right->{aliased_tables}{$alias};
  }

  return \%result;
}


#----------------------------------------------------------------------
# override of parent's "_where_field_IN"
#----------------------------------------------------------------------

sub _where_field_IN {
  my ($self, $k, $op, $vals) = @_;

  # special algorithm if the key is multi-columns (contains a multicols_sep)
  if ($self->{multicols_sep}) {
    my @cols = split m[$self->{multicols_sep}], $k;
    if (@cols > 1) {
      if ($self->{has_multicols_in_SQL}) {
        # DBMS accepts special SQL syntax for multicolumns
        return $self->_multicols_IN_through_SQL(\@cols, $op, $vals);
      }
      else {
        # DBMS doesn't accept special syntax, so we must use boolean logic
        return $self->_multicols_IN_through_boolean(\@cols, $op, $vals);
      }
    }
  }

  # special algorithm if the number of values exceeds the allowed maximum
  my $max_members_IN = $self->{max_members_IN};
  if ($max_members_IN && does($vals, 'ARRAY')
                      &&  @$vals > $max_members_IN) {
    my @vals = @$vals;
    my @slices;
    while (my @slice = splice(@vals, 0, $max_members_IN)) {
      push @slices, \@slice;
    }
    my @clauses = map {{-$op, $_}} @slices;
    my $connector = $op =~ /^not/i ? '-and' : '-or';
    unshift @clauses, $connector;
    my ($sql, @bind) = $self->where({$k => \@clauses});
    $sql =~ s/\s*where\s*\((.*)\)/$1/i;
    return ($sql, @bind);
  }


  # otherwise, call parent method
  $vals = [@$vals] if blessed $vals; # because SQLA dies on blessed arrayrefs
  return $self->next::method($k, $op, $vals);
}


sub _multicols_IN_through_SQL {
  my ($self, $cols, $op, $vals) = @_;

  # build initial sql
  my $n_cols   = @$cols;
  my $sql_cols = CORE::join(',', map {$self->_quote($_)} @$cols);
  my $sql      = "($sql_cols) " . $self->_sqlcase($op);

  # dispatch according to structure of $vals
  return $self->_SWITCH_refkind($vals, {

    ARRAYREF => sub {    # list of tuples
      # deal with special case of empty list (like the parent class)
      my $n_tuples = @$vals;
      if (!$n_tuples) {
        my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
        return ($sql);
      }

      # otherwise, build SQL and bind values for the list of tuples
      my @bind;
      foreach my $val (@$vals) {
        does($val, 'ARRAY')
          or $val = [split  m[$self->{multicols_sep}], $val];
        @$val == $n_cols
          or puke "op '$op' with multicols: tuple with improper number of cols";
        push @bind, @$val;
      }
      my $single_tuple = "(" . CORE::join(',', (('?') x $n_cols)) . ")";

      my $all_tuples   = CORE::join(', ', (($single_tuple) x $n_tuples));
      $sql            .= " ($all_tuples)";
      return ($sql, @bind);
    },

    SCALARREF => sub {   # literal SQL
      $sql .= " ($$vals)";
      return ($sql);
    },

    ARRAYREFREF => sub { # literal SQL with bind
      my ($inner_sql, @bind) = @$$vals;
      $sql .= " ($inner_sql)";
      return ($sql, @bind);
    },

    FALLBACK => sub {
      puke "op '$op' with multicols requires a list of tuples or literal SQL";
    },

   });
}


sub _multicols_IN_through_boolean {
  my ($self, $cols, $op, $vals) = @_;

  # can't handle anything else than a list of tuples
  does($vals, 'ARRAY') && @$vals
    or puke "op '$op' with multicols requires a non-empty list of tuples";

  # assemble SQL
  my $n_cols   = @$cols;
  my $sql_cols = CORE::join(' AND ', map {$self->_quote($_) . " = ?"} @$cols);
  my $sql      = "(" . CORE::join(' OR ', (("($sql_cols)") x @$vals)) . ")";
  $sql         = "NOT $sql" if $op =~ /\bnot\b/i;

  # assemble bind values
  my @bind;
  foreach my $val (@$vals) {
    does($val, 'ARRAY')
      or $val = [split  m[$self->{multicols_sep}], $val];
    @$val == $n_cols
      or puke "op '$op' with multicols: tuple with improper number of cols";
    push @bind, @$val;
  }

  # return the whole thing
  return ($sql, @bind);
}



#----------------------------------------------------------------------
# override parent's methods for decoding arrayrefs
#----------------------------------------------------------------------

sub _where_hashpair_ARRAYREF {
  my ($self, $k, $v) = @_;

  if ($self->is_bind_value_with_type($v)) {
    $self->_assert_no_bindtype_columns;
    my $sql = CORE::join ' ', $self->_convert($self->_quote($k)),
                              $self->_sqlcase($self->{cmp}),
                              $self->_convert('?');
    my @bind = ($v);
    return ($sql, @bind);
  }
  else {
    return $self->next::method($k, $v);
  }
}


sub _where_field_op_ARRAYREF {
  my ($self, $k, $op, $vals) = @_;

  if ($self->is_bind_value_with_type($vals)) {
    $self->_assert_no_bindtype_columns;
    my $sql = CORE::join ' ', $self->_convert($self->_quote($k)),
                              $self->_sqlcase($op),
                              $self->_convert('?');
    my @bind = ($vals);
    return ($sql, @bind);
  }
  else {
    return $self->next::method($k, $op, $vals);
  }
}

sub _assert_no_bindtype_columns {
  my ($self) = @_;
  $self->{bindtype} ne 'columns'
    or puke 'values of shape [$val, \%type] are not compatible'
          . 'with ...->new(bindtype => "columns")';
}



#----------------------------------------------------------------------
# method creations through closures
#----------------------------------------------------------------------

sub _make_aliasing_sub {
  my ($self, $syntax_field) = @_;
  my $syntax = $self->{$syntax_field};
  $self->{$syntax_field} = sub {
    my ($self, $name, $alias) = @_;
    return $alias ? sprintf($syntax, $name, $alias) : $name;
  };
}

sub _choose_LIMIT_OFFSET_dialect {
  my $self = shift;
  my $dialect = $self->{limit_offset};
  my $method = $limit_offset_dialects{$dialect}
    or puke "no such limit_offset dialect: $dialect";
  $self->{limit_offset} = $method;
}


#----------------------------------------------------------------------
# utility functions (not methods)
#----------------------------------------------------------------------

sub _called_with_named_args {
  return $_[0] && !ref $_[0]  && substr($_[0], 0, 1) eq '-';
}


sub _is_subquery {
  my $arg = shift;
  return does($arg, 'REF') && does($$arg, 'ARRAY');
}


sub _parenthesize_select {
  my ($sql) = @_;
  $sql =~ s{^(select\b.*)}{($1)}is; # if subquery is a plain SELECT, put it in parenthesis
  return $sql;
}




1; # End of SQL::Abstract::More

__END__

=head1 NAME

SQL::Abstract::More - Generate SQL from Perl data structures, like SQL::Abstract, with more features

=head1 SYNOPSIS

  use SQL::Abstract::More;
  my $sqla = SQL::Abstract::More->new();
  my ($sql, @bind);

  # ex1: named parameters, select DISTINCT, ORDER BY, LIMIT/OFFSET
  ($sql, @bind) = $sqla->select(
   -columns  => [-distinct => qw/col1 col2/],
   -from     => 'Foo',
   -where    => {bar => {">" => 123}},
   -order_by => [qw/col1 -col2 +col3/],  # BY col1, col2 DESC, col3 ASC
   -limit    => 100,
   -offset   => 300,
  );

  # ex2: column aliasing, join
  ($sql, @bind) = $sqla->select(
    -columns => [         qw/Foo.col_A|a           Bar.col_B|b /],
    -from    => [-join => qw/Foo           fk=pk   Bar         /],
  );

  # ex3: INTERSECT (or similar syntax for UNION)
  ($sql, @bind) = $sqla->select(
    -columns => [qw/col1 col2/],
    -from    => 'Foo',
    -where   => {col1 => 123},
    -intersect => [ -columns => [qw/col3 col4/],
                    -from    => 'Bar',
                    -where   => {col3 => 456},
                   ],
  );

  # ex4 : subqueries
  my $subq1 = [ $sqla->select(-columns => 'f|x', -from => 'Foo',
                              -union   => [-columns => 'b|x',
                                           -from    => 'Bar',
                                           -where   => {barbar => 123}],
                              -as      => 'Foo_union_Bar',
                              ) ];
  my $subq2 = [ $sqla->select(-columns => 'MAX(amount)',
                              -from    => 'Expenses',
                              -where   => {exp_id => {-ident => 'x'}, date => {">" => '01.01.2024'}},
                              -as      => 'max_amount',
                              ) ];
  ($sql, @bind) = $sqla->select(
     -columns  => ['x', \$subq2],
     -from     => \$subq1,
     -order_by => 'x',
    );

  # ex5: passing datatype specifications
  ($sql, @bind) = $sqla->select(
   -from     => 'Foo',
   -where    => {bar => [{dbd_attrs => {ora_type => ORA_XMLTYPE}}, $xml]},
  );
  my $sth = $dbh->prepare($sql);
  $sqla->bind_params($sth, @bind);
  $sth->execute;

  # ex6: multicolumns-in
  $sqla = SQL::Abstract::More->new(
    multicols_sep        => '/',
    has_multicols_in_SQL => 1,
  );
  ($sql, @bind) = $sqla->select(
   -from     => 'Foo',
   -where    => {"foo/bar/buz" => {-in => ['1/a/X', '2/b/Y', '3/c/Z']}},
  );

  # ex7: merging several criteria
  my $merged = $sqla->merge_conditions($cond_A, $cond_B, ...);
  ($sql, @bind) = $sqla->select(..., -where => $merged, ..);

  # ex8: insert / update / delete
  ($sql, @bind) = $sqla->insert(
    -add_sql => 'OR IGNORE',        # SQLite syntax
    -into    => $table,
    -values  => {col => $val, ...},
  );
  ($sql, @bind) = $sqla->insert(
    -into    => $table,
    -columns => [qw/a b/],
    -select  => {-from => 'Bar', -columns => [qw/x y/], -where => ...},
  );
  ($sql, @bind) = $sqla->update(
    -table => $table,
    -set   => {col => $val, ...},
    -where => \%conditions,
  );
  ($sql, @bind) = $sqla->delete (
    -from  => $table
    -where => \%conditions,
  );

  # ex9 : initial WITH clause -- example borrowed from https://sqlite.org/lang_with.html
  ($sql, @bind) = $sqla->with_recursive(
    [ -table     => 'parent_of',
      -columns   => [qw/name parent/],
      -as_select => {-columns => [qw/name mom/],
                     -from    => 'family',
                     -union   => [-columns => [qw/name dad/], -from => 'family']},
     ],

    [ -table     => 'ancestor_of_alice',
      -columns   => [qw/name/],
      -as_select => {-columns   => [qw/parent/],
                     -from      => 'parent_of',
                     -where     => {name => 'Alice'},
                     -union_all => [-columns => [qw/parent/],
                                    -from    => [qw/-join parent_of {name} ancestor_of_alice/]],
                 },
     ],
    )->select(
     -columns  => 'family.name',
     -from     => [qw/-join ancestor_of_alice {name} family/],
     -where    => {died => undef},
     -order_by => 'born',
    );


=head1 DESCRIPTION

This module generates SQL from Perl data structures. It was heavily 
inspired by the venerable L<SQL::Abstract> and used to inherit from it,
retaining full compatibility with the parent class, but with many improvements.
The current version inherits from L<SQL::Abstract::Classic> instead, and the 
next version will probably stand on its own, without any parent class, but still
maintaining the original API, so clients will not be affected. 
The reasons for this move are developed below under
L</History of SQL::Abstract and future of SQL::Abstract::More>.

Here is a short overview of additional features brought by the present module
over the historical C<SQL::Abstract> API:

=over

=item *

methods take arguments as I<named parameters> instead of positional parameters.
This is more flexible for identifying and assembling various SQL clauses,
like C<-where>, C<-order_by>, C<-group_by>, etc.

=item *

additional SQL constructs like C<-union>, C<-group_by>, C<join>, C<-with_recursive>, etc.
are supported;

=item *

subqueries can be used in a column list or as a datasource (i.e C<< SELECT ... FROM (SELECT ..) >>),
even as members of a join;

=item *

C<WHERE .. IN> clauses can range over multiple columns (tuples);

=item *

values passed to C<select>, C<insert> or C<update> can directly incorporate
information about datatypes, in the form of arrayrefs of shape
C<< [{dbd_attrs => \%type}, $value] >>;

=item *

prefixes C<-> or C<+> can be supplied in front of column names in ORDER BY, for specifying 
the sorting order;


=item *

several I<SQL dialects> can adapt the generated SQL to various DBMS vendors.

=back

This module was originally designed for the specific needs of
L<DBIx::DataModel>, but is published as a standalone distribution,
because it may possibly be useful for other needs.

Unfortunately, this module cannot be used with L<DBIx::Class>, because
C<DBIx::Class> creates its own instance of C<SQL::Abstract>
and has no API to let the client instantiate from any other class.


=head1 CLASS METHODS

=head2 new

  my $sqla = SQL::Abstract::More->new(%options);

where C<%options> may contain any of the options for the parent
class (see L<SQL::Abstract::Classic/new>), plus the following :

=over

=item table_alias

A C<sprintf> format description for generating table aliasing clauses.
The default is C<%s AS %s>.

The argument can also be a method coderef :

  SQL::Abstract::More->new(table_alias => sub {
    my ($self, $table, $alias) = @_;
    my $syntax_for_aliased_table = ...;
    return $syntax_for_aliased_table;
   })

That method should not call C<< $self->_quote() >> because
arguments C<$table> and C<$alias> are already quoted if necessary.

=item column_alias

A C<sprintf> format description for generating column aliasing clauses.
The default is C<%s AS %s>.

Like for C<table_alias>, the argument can also be a method coderef.

=item limit_offset

Name of a "limit-offset dialect", which can be one of
C<LimitOffset>, C<LimitXY>, C<LimitYX>, C<OffsetFetchRows> or C<RowNum>.
Most of thoses are copied from L<SQL::Abstract::Limit> -- see that module for explanations.
The C<OffsetFetchRows> dialect is a local addition and corresponds to Oracle syntax
in version 12c or above (C<OFFSET ? ROWS FETCH ? ROWS ONLY>).

Unlike the L<SQL::Abstract::Limit> implementation,
limit and offset values are treated here as regular values,
with placeholders '?' in the SQL; values are postponed to the
C<@bind> list.

The argument can also be a coderef. That coderef takes C<$self, $limit, $offset>
as arguments, and should return C<($sql, @bind)>. If C<$sql> contains
C<%s>, it is treated as a C<sprintf> format string, where the original
SQL is injected into C<%s>.


=item join_syntax

A hashref where keys are abbreviations for join
operators to be used in the L</join> method, and 
values are associated SQL clauses with placeholders
in C<sprintf> format. The default is described
below under the L</join> method.


=item join_assoc_right

A boolean telling if multiple joins should be associative 
on the right or on the left. Default is false (i.e. left-associative).

=item max_members_IN

An integer specifying the maximum number of members in a "IN" clause.
When the supplied value list exceeds that number,
C<SQL::Abstract::More> automatically splits it into separate
clauses connected by 'OR' (or connected by 'AND' if used with the
C<-not_in> operator).

  my $sqla = SQL::Abstract::More->new(max_members_IN => 3);
  ($sql, @bind) = $sqla->select(
   -from     => 'Foo',
   -where    => {foo => {-in     => [1 .. 5]}},
                 bar => {-not_in => [6 .. 10]}},
  );
  # .. WHERE (     (foo IN (?,?,?) OR foo IN (?, ?))
  #            AND (bar NOT IN (?,?,?) AND bar NOT IN (?, ?)) )


=item multicols_sep

A string or compiled regular expression used as a separator for
"multicolumns". This separator can then be used on the left-hand side
and right-hand side of an C<IN> operator, like this :

  my $sqla = SQL::Abstract::More->new(multicols_sep => '/');
  ($sql, @bind) = $sqla->select(
   -from     => 'Foo',
   -where    => {"x/y/z" => {-in => ['1/A/foo', '2/B/bar']}},
  );

Alternatively, tuple values on the right-hand side can also be given
as arrayrefs instead of plain scalars with separators :

   -where    => {"x/y/z" => {-in => [[1, 'A', 'foo'], [2, 'B', 'bar']]}},

but the left-hand side must stay a plain scalar because an array reference
wouldn't be a proper key for a Perl hash; in addition, the presence
of the separator in the string is necessary to trigger the special
algorithm for multicolumns.

The generated SQL depends on the boolean flag C<has_multicols_in_SQL>,
as explained in the next paragraph.

=item has_multicols_in_SQL

A boolean flag that controls which kind of SQL will be generated for
multicolumns. If the flag is B<true>, this means that the underlying DBMS
supports multicolumns in SQL, so we just generate tuple expressions.
In the example from the previous paragraph, the SQL and bind values
would be :

   # $sql  : "WHERE (x, y, z) IN ((?, ?, ?), (?, ?, ?))"
   # @bind : [ qw/1 A foo 2 B bar/ ]

It is also possible to use a subquery, like this :

  ($sql, @bind) = $sqla->select(
   -from     => 'Foo',
   -where    => {"x/y/z" => {-in => \[ 'SELECT (a, b, c) FROM Bar '
                                       . 'WHERE a > ?', 99]}},
  );
  # $sql  : "WHERE (x, y, z) IN (SELECT (a, b, c) FROM Bar WHERE a > ?)"
  # @bind : [ 99 ]

If the flag is B<false>, the condition on tuples will be
automatically converted using boolean logic :

   # $sql  : "WHERE (   (x = ? AND y = ? AND z = ?) 
                     OR (x = ? AND y = ? AND z = ?))"
   # @bind : [ qw/1 A foo 2 B bar/ ]

If the flag is false, subqueries are not allowed.


=item select_implicitly_for

A value that will be automatically added as a C<-for> clause in
calls to L</select>. This default clause can always be overridden
by an explicit C<-for> in a given select :

  my $sqla = SQL::Abstract->new(-select_implicitly_for => 'READ ONLY');
  ($sql, @bind) = $sqla->select(-from => 'Foo');
    # SELECT * FROM FOO FOR READ ONLY
  ($sql, @bind) = $sqla->select(-from => 'Foo', -for => 'UPDATE');
    # SELECT * FROM FOO FOR UPDATE
  ($sql, @bind) = $sqla->select(-from => 'Foo', -for => undef);
    # SELECT * FROM FOO

=item sql_dialect

This is actually a "meta-argument" : it injects a collection
of regular arguments, tuned for a specific SQL dialect.
Dialects implemented so far are :

=over

=item MsAccess

For Microsoft Access. Overrides the C<join> syntax to be right-associative.

=item BasisJDBC

For Livelink Collection Server (formerly "Basis"), accessed
through a JDBC driver. Overrides the C<column_alias> syntax.
Sets C<max_members_IN> to 255.

=item MySQL_old

For old versions of MySQL. Overrides the C<limit_offset> syntax.
Recent versions of MySQL do not need that because they now
implement the regular "LIMIT ? OFFSET ?" ANSI syntax.

=item Oracle

For old versions of Oracle. Overrides the C<limit_offset> to use the "RowNum" dialect
(beware, this injects an additional column C<rownum__index> into your
resultset). Also sets C<max_members_IN> to 999 and C<has_multicols_in_SQL> to true.

=item Oracle12c

For Oracle starting from version 12c. Like the "Oracle" dialect, except for
C<limit_offset> which uses C<OffsetFetchRows>.


=back

=back


=head1 INSTANCE METHODS

=head2 Main API methods

=head3 select

  # positional parameters, directly passed to the parent class (deprecated API)
  ($sql, @bind) = $sqla->select($table, $columns, $where, $order);

  # named parameters, handled in this class 
  ($sql, @bind) = $sqla->select(
    -columns  => \@columns,
      # OR: -columns => [-distinct => @columns],
    -from     => $table || \@joined_tables,
    -where    => \%where,
    -union    => [ %select_subargs ], # OR -intersect, -minus, etc
    -order_by => \@order,
    -group_by => \@group_by,
    -having   => \%having_criteria,
    -limit => $limit, -offset => $offset,
      # OR: -page_size => $size, -page_index => $index,
    -for      => $purpose,
    -as       => $subquery_alias,
   );

  my $details = $sqla->select(..., want_details => 1);
  # keys in %$details: sql, bind, aliased_tables, aliased_columns

If called with positional parameters, as in L<SQL::Abstract>, 
C<< select() >> just forwards the call to the parent class. Otherwise, if
called with named parameters, as in the example above, some additional
SQL processing is performed.

The following named arguments can be specified :

=over

=item C<< -columns => \@columns >> 

C<< \@columns >>  is a reference to an array
of SQL column specifications (i.e. column names, C<*>, SQL functions or expressions, etc.).

A '|' in a column is translated into a column aliasing clause:
this syntax without spaces is convenient when
using Perl's C<< qw/.../ >> operator, as in

  -columns => [ qw/table1.longColumn|t1lc table2.longColumn|t2lc/ ]

Note: if the C<< qw/.../ >> operator contains expressions
with commas, Perl will issue a warning "Possible attempt to separate words with commas";
this can be avoided by specifying C<< no warnings 'qw' >>. Another solution is of course
to use an arrayref of explicit quoted strings instead of the C<< qw/.../ >> operator. 
Explicit quoted strings are also necessary when a column name or alias name contains spaces.

SQL column aliasing is generated through the L</column_alias> method.
If L<SQL::Abstract/quote_char> is defined, aliased columns will be quoted,
unless they contain parentheses or commas, in which case they are considered as
SQL expressions for which the user should handle the quoting himself.
For example if C<quote_char> is "`", 

  -columns => [ qw/foo.bar|fb length(buz)|lbuz/ ]

will produce

  SELECT `foo`.`bar` AS `fb`, length(buz) AS `lbuz`

and not

  SELECT `foo`.`bar` AS `fb`, length(`buz`) AS `lbuz`


Initial items in C<< @columns >> that start with a minus sign
are shifted from the array, i.e. they are not considered as column
names, but are re-injected later into the SQL (without the minus sign), 
just after the C<SELECT> keyword. This is especially useful for 

  $sqla->select(..., -columns => [-DISTINCT => @columns], ...);

However, it may also be useful for other purposes, like
vendor-specific SQL variants :

   # MySQL features
  ->select(..., -columns => [-STRAIGHT_JOIN    => @columns], ...);
  ->select(..., -columns => [-SQL_SMALL_RESULT => @columns], ...);

   # Oracle hint
  ->select(..., -columns => ["-/*+ FIRST_ROWS (100) */" => @columns], ...);

Within the columns array, it is also possible to insert a 
subquery expressed as a reference to an arrayref, as explained in
L<SQL::Abstract/"Literal SQL with placeholders and bind values (subqueries)">.
It is recommanded to generate the subquery through another call to C<select()> with 
an L</-as> parameter (explained below), which will enclose the SQL into parenthesis and add an alias
for that column:

  # build the subquery -- stored in an arrayref
  my $subquery = [ $sqla->select(
      -columns => 'COUNT(*)',
      -from    => 'Foo',
      -where   => {bar_id => {-ident => 'Bar.bar_id'},
                   height => {-between => [100, 200]}},
      -as      => 'count_foos',
    ) ];
  
  # main query
  my ($sql, @bind) = $sqla->select(
         -from    => 'Bar',
         -columns => ['col1', 'col2', \$subquery, , 'col4'], # reference to an arrayref !
         -where   => {color => 'green'},
       );

This will produce SQL :

  SELECT col1, col2,
         (SELECT COUNT(*) FROM Foo WHERE bar_id=Bar.bar_id and height BETWEEN ? AND ?) AS count_foos,
         col4
    FROM Bar WHERE color = ?        

The resulting C<@bind> array combines bind values coming from both the subquery
and from the main query, i.e. C<< (100, 200, 'green') >>.


Instead of an arrayref, the argument to C<-columns> can also be just a string, like for example
C<< "c1 AS foobar, MAX(c2) AS m_c2, COUNT(c3) AS n_c3" >>;
however this is mainly for backwards compatibility.
The recommended way is to use the arrayref notation as explained above:

  -columns => [ qw/  c1|foobar   MAX(c2)|m_c2   COUNT(c3)|n_c3  / ]

If omitted, C<< -columns >> takes '*' as default argument.


=item C<< -from => $table || \@joined_tables || \$subquery >> 

The argument to C<-from> can be :

=over

=item *

a plain string, interpreted as a table name. Like for column aliases,
a table alias can be given, using a vertical bar as separator:

  -from => 'Foobar|fb', # SELECT .. FROM Foobar AS fb

=item *

a join specification, given as an arrayref starting with the keyword C<-join>, followed
by a list of table and join conditions as expected by the L</join> method (explained below):

  -from => [-join => qw/Foo fk=pk Bar/],


=item *

a I<reference> to a subquery arrayref, in the form C<< [$sql, @bind] >>.
Like for subqueries in columns, it is recommanded to generate the subquery through
another call to C<< select() >> with an L</-as> parameter, interpreted this time
as a I<table alias> instead of a column alias:

  my $subq = [ $sqla->select(-columns => 'f|x', -from => 'Foo',
                             -union   => [-columns => 'b|x',
                                          -from    => 'Bar',
                                          -where   => {barbar => 123}],
                             -as      => 'Foo_union_Bar',
                             ) ];
  my ($sql, @bind) = $sqla->select(-from     => \$subq,
                                   -order_by => 'x');

which produces

  SELECT * FROM (      SELECT f AS x FROM Foo 
                 UNION SELECT b AS x FROM Bar WHERE ( barbar = ? )
                ) AS Foo_union_Bar 
  ORDER BY x


=item *

a simple arrayref that does not start with C<-join>. This is
for compatibility with the old L<SQL::Abstract> API. Members of the
array are interpreted as a list of table names, that will be joined
by C<", ">. Join conditions should then be expressed separately in the
C<-where> part. 

  $sqla->select(-from => [qw/Foo Bar Buz/], ...) # SELECT FROM Foo, Bar, Buz ..

This syntax is deprecated; preferably use the C<-join> feature instead.

=item *

a simple scalarref. This is for compatibility with the old
L<SQL::Abstract> API. The result is equivalent to passing the scalar
directly, except that no quoting will be applied.

  $sqla->select(-from => \ "Foo", ...) # SELECT FROM Foo ..

This syntax is deprecated.

=back

=item C<< -where => $criteria >>

Like in L<SQL::Abstract>, C<< $criteria >> can be 
a plain SQL string like C<< "col1 IN (3, 5, 7, 11) OR col2 IS NOT NULL" >>;
but the recommanded way is to rather supply a reference to a hash or array of
conditions that will be translated into SQL clauses, like
for example C<< {col1 => 'val1', col2 => {'<>' => 'val2'}} >>.
The structure of that hash or array can be nested to express complex
boolean combinations of criteria, including parenthesized subqueries; see
L<SQL::Abstract/"WHERE CLAUSES"> for a detailed description.

When using hashrefs or arrayrefs,  values can be "bind values with types"
to be passed to the underlying L<DBI> layer;
see the L</"BIND VALUES WITH TYPES"> section below.

=item C<< -union => [ %select_subargs ] >>

=item C<< -union_all => [ %select_subargs ] >>

=item C<< -intersect => [ %select_subargs ] >>

=item C<< -except => [ %select_subargs ] >>

=item C<< -minus => [ %select_subargs ] >>

generates a compound query using set operators such as C<UNION>,
C<INTERSECT>, etc. The argument C<%select_subargs> contains a nested
set of parameters like for the main select (i.e. C<-columns>,
C<-from>, C<-where>, etc.); however, arguments C<-columns> and
C<-from> can be omitted, in which case they will be copied from the
main select(). Several levels of set operators can be nested.

=item C<< -group_by => "string" >>  or C<< -group_by => \@array >> 

adds a C<GROUP BY> clause in the SQL statement. Grouping columns are
specified either by a plain string or by an array of strings.

=item C<< -having => "string" >>  or C<< -having => \%criteria >> 

adds a C<HAVING> clause in the SQL statement. In most cases this is used
together with a C<GROUP BY> clause.
This is like a C<-where> clause, except that the criteria
are applied after grouping has occurred.


=item C<< -order_by => \@order >>

C<< \@order >> is a reference to a list 
of columns for sorting. Columns can 
be prefixed by '+' or '-' for indicating sorting directions,
so for example C<< -orderBy => [qw/-col1 +col2 -col3/] >>
will generate the SQL clause
C<< ORDER BY col1 DESC, col2 ASC, col3 DESC >>.

Column names C<asc> and C<desc> are treated as exceptions to this
rule, in order to preserve compatibility with L<SQL::Abstract>.
So C<< -orderBy => [-desc => 'colA'] >> yields
C<< ORDER BY colA DESC >> and not C<< ORDER BY desc DEC, colA >>.
Any other syntax supported by L<SQL::Abstract> is also
supported here; see L<SQL::Abstract/"ORDER BY CLAUSES"> for examples.

The whole C<< -order_by >> parameter can also be a plain SQL string
like C<< "col1 DESC, col3, col2 DESC" >>.

=item C<< -page_size => $page_size >>

specifies how many rows will be retrieved per "page" of data.
Default is unlimited (or more precisely the maximum 
value of a short integer on your system).

=item C<< -page_index => $page_index >>

specifies the page number (starting at 1). Default is 1.
When present, the combination of CC<< -page_size >> and CC<< -page_index >>
is automatically translated into a combination of CC<< -limit >> and CC<< -offset >>.

=item C<< -limit => $limit >>

limit to the number of rows that will be retrieved.

=item C<< -offset => $offset >>

offest to the first row that will be part of the result.
Defaults to 0.

=item C<< -for => $clause >> 

specifies an additional clause to be added at the end of the SQL statement,
like C<< -for => 'READ ONLY' >> or C<< -for => 'UPDATE' >>.

=item C<< -as => $alias >>

The C<< $sql >> part is rewritten as C<< ($sql)|$alias >>.
This is convenient when the result is to be used as a subquery
within another C<< select() >> call.

=item C<< -want_details => 1 >>

If true, the return value will be a hashref instead of the usual
C<< ($sql, @bind) >>, containing more details:

=over

=item sql

generated SQL

=item bind

bind values

=item aliased_tables

a hashref of  C<< {table_alias => table_name} >> encountered while
parsing the C<-from> parameter.

=item aliased_columns

a hashref of  C<< {column_alias => column_name} >> encountered while
parsing the C<-columns> parameter.

=back

This method is mainly for use by L<DBIx::DataModel>.


=back



=head3 insert

  # positional parameters, directly passed to the parent class (deprecated API)
  ($sql, @bind) = $sqla->insert($table, \@values || \%fieldvals, \%options);

  # named parameters, handled in this class
  ($sql, @bind) = $sqla->insert(
    -into      => $table,
    -values    => {col => $val, ...},
    -returning => $return_structure,
    -add_sql   => $keyword,
  );

  # insert from a subquery
  ($sql, @bind) = $sqla->insert(
    -into    => $destination_table,
    -columns => \@columns_into
    -select  => {-from => $source_table, -columns => \@columns_from, -where => ...},
  );

When using named arguments, C<-into> is mandatory and either C<-values> or C<-select>
must be present. Legal arguments are:

=over

=item C<< -into => $table >> 

String containing the name of the table to insert into.

=item C<< -values >> 

A hashref that maps column names to the values to insert, like for example

  $sqla->insert(-into => 'Foo', -values => {foo => 123, bar => 'buz'});

The generated SQL will have column names in alphabetical order, i.e. 

  INSERT INTO Foo(bar, foo) VALUES (?, ?) # @bind contains ['buz', 123]

A less common variant is to supply an arrayref instead of a hashref,
in which case the generated SQL will have no column names

  $sqla->insert(-into => 'Users', -values => [qw/John Doe/]);
  # INSERT INTO Users VALUES (?, ?) # @bind contains ['John', 'Doe']

Like for L</select>, values can have associated
SQL types; see L</"BIND VALUES WITH TYPES">.

=item C<< -select >> 

Used to generate SQL of shape C<< INSERT INTO ... SELECT ... >>, i.e. the
values to insert come from a subquery. The argument to C<< -select >>
is a hashref containing arguments to be passed to the L</select> method.

=item C<< -columns >> 

The C<-columns> parameter takes an arrayref; it usually goes together with C<< -select >> 
and specifies the names of the columns to insert into. 

This parameter can also be used with the arrayref form of C<< -values >>:

  $sqla->insert(-into => 'Foo', -columns => [qw/foo bar/], -values => [123, 'buz']);

=item C<< -returning >> 

Optional parameter only supported by some database vendors (see L<SQL::Abstract/insert>);
if the C<$return_structure> is 

=over

=item *

a scalar or an arrayref, it is passed directly to the parent method

=item *

a hashref, it is interpreted as a SQL clause "RETURNING .. INTO ..",
as required in particular by Oracle. Hash keys are field names, and
hash values are references to variables that will receive the
results. Then it is the client code's responsibility
to use L<DBD::Oracle/bind_param_inout> for binding the variables
and retrieving the results, but the L</bind_params> method in the
present module is there for help. Example:

  ($sql, @bind) = $sqla->insert(
    -into      => $table,
    -values    => {col => $val, ...},
    -returning => {key_col => \my $generated_key},
  );

  my $sth = $dbh->prepare($sql);
  $sqla->bind_params($sth, @bind);
  $sth->execute;
  print "The new key is $generated_key";

=back

=item C<< -add_sql >> 

Optional parameter used with some specific SQL dialects for
injecting additional SQL keywords after the C<INSERT> keyword. Examples:

  $sqla->insert(..., -add_sql => 'IGNORE')     # produces "INSERT IGNORE ..."    -- MySQL
  $sqla->insert(..., -add_sql => 'OR IGNORE')  # produces "INSERT OR IGNORE ..." -- SQLite

=back

=head3 update

  # positional parameters, directly passed to the parent class (deprecated API)
  ($sql, @bind) = $sqla->update($table, \%fieldvals, \%where);

  # named parameters, handled in this class
  ($sql, @bind) = $sqla->update(
    -table     => $table,
    -set       => {col => $val, ...},
    -where     => \%conditions,
    -order_by  => \@order,
    -limit     => $limit,
    -returning => $return_structure,
    -add_sql   => $keyword,
  );

This works in the same spirit as the L</insert> method above.
Positional parameters are supported for backwards compatibility
with the old API; but named parameters should be preferred because
they improve the readability of the client's code.

Few DBMS would support parameters C<-order_by> and C<-limit>, but
MySQL does -- see L<http://dev.mysql.com/doc/refman/5.6/en/update.html>.

The optional parameter C<-returning> works like for the L</insert> method.

The optional parameter C<-add_sql> is used with some specific SQL dialects, for
injecting additional SQL keywords after the C<UPDATE> keyword. Examples :

  $sqla->update(..., -add_sql => 'IGNORE')     # produces "UPDATE IGNORE ..."    -- MySQL
  $sqla->update(..., -add_sql => 'OR IGNORE')  # produces "UPDATE OR IGNORE ..." -- SQLite

=head3 delete

  # positional parameters, directly passed to the parent class (deprecated API)
  ($sql, @bind) = $sqla->delete($table, \%where);

  # named parameters, handled in this class 
  ($sql, @bind) = $sqla->delete (
    -from     => $table
    -where    => \%conditions,
    -order_by => \@order,
    -limit    => $limit,
    -add_sql  => $keyword,
  );

Positional parameters are supported for backwards compatibility
with the old API; but named parameters should be preferred because
they improve the readability of the client's code.

Few DBMS would support parameters C<-order_by> and C<-limit>, but
MySQL does -- see L<http://dev.mysql.com/doc/refman/5.6/en/update.html>.

The optional parameter C<-add_sql> is used with some specific SQL dialects, for
injecting additional SQL keywords after the C<DELETE> keyword. Examples :

  $sqla->delete(..., -add_sql => 'IGNORE')     # produces "DELETE IGNORE ..."    -- MySQL
  $sqla->delete(..., -add_sql => 'OR IGNORE')  # produces "DELETE OR IGNORE ..." -- SQLite


=head3 with_recursive, with

  my $new_sqla = $sqla->with_recursive( # or: $sqla->with(

    [ -table     => $CTE_table_name,
      -columns   => \@CTE_columns,
      -as_select => \%select_args ],

    [ -table     => $CTE_table_name2,
      -columns   => \@CTE_columns2,
      -as_select => \%select_args2 ],
    ...

   );
   ($sql, @bind) = $new_sqla->insert(...);
  
  # or, if there is only one table expression
  my $new_sqla = $sqla->with_recursive(
      -table     => $CTE_table_name,
      -columns   => \@CTE_columns,
      -as_select => \%select_args,
     );


Returns a cloned instance enriched with an encapsulated I<common table expression (CTE)>.
The CTE is kind of local view that can be used as a table name for the rest of the SQL statement
- see L<https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL> for
an explanation of such expressions. Oracle uses a different term for the same concept:
I<subquery factoring clauses>.

Further calls to C<select>, C<insert>, C<update> and C<delete> on that new instance
will automatically prepend a C<WITH> or C<WITH RECURSIVE> clause before the usual
SQL statement.

Arguments to C<with_recursive()> are expressed as a list of arrayrefs; each arrayref
corresponds to one table expression, with the following named parameters :

=over

=item C<-table>

The name to be assigned to the table expression

=item C<-columns>

An optional list of column aliases to be assigned to the
columns resulting from the internal select

=item C<-as_select>

The implementation of the table expression, given as a hashref
of arguments following the same syntax as the L</select> method.

=item C<-final_clause>

An optional SQL clause that will be added after the table expression.
This may be needed for example for an Oracle I<cycle clause>, like

  ($sql, @bind) = $sqla->with_recursive(
    -table        => ...,
    -as_select    => ...,
    -final_clause => "CYCLE x SET is_cycle TO '1' DEFAULT '0'",
   )->select(...);


=back

If there is only one table expression, its arguments can be passed directly
as an array instead of a single arrayref.

CTEs can be I<recursive>, so that a single SQL query is able to traverse a tree of nested data.
See the example from the L</SYNOPSIS>, borrowed from L<https://sqlite.org/lang_with.html> and 
translated into C<SQL::Abstract::More> syntax.



=head3 join

  my $join_info = $sqla->join(
    <table0> <join_1> <table_1> ... <join_n> <table_n>
  );
  my $sth = $dbh->prepare($join_info->{sql});
  $sth->execute(@{$join_info->{bind}})
  while (my ($alias, $aliased) = each %{$join_info->{aliased_tables}}) {
    say "$alias is an alias for table $aliased";
  }

Returns a hashref of information to be passed as a datasource to the L</select> method,
for generating a SQL JOIN clause. Therefore this method is seldom called directly,
but rather indirectly through

  $sqla->select(-from => [-join => ....], ...);

It takes as input a list containing an odd number of elements, 
where the odd positions indicate I<tables>
and the even positions indicate I<join conditions>.
Both table and join conditions can be given either in the form of hashrefs
or as plain strings in a mini domain-specific language. The second option
is more convenient because all items in the list can be written
together as members of a C<< qw/.../ >> operator.
The following example gives an idea of the available syntax :

  ($sql, @bind) = $sqla->join(qw[
     Table1|t1       ab=cd                     Table2|t2
                 <=>{ef>gh,ij<kl,mn='foobar'}  Table3
                  =>{t1.op=qr}                 Table4
     ]);

This will generate

  Table1 AS t1 INNER JOIN Table2 AS t2 ON t1.ab = t2.cd
               INNER JOIN Table3       ON t2.ef > Table3.gh AND t2.ij < Table3.kl
                                                            AND t2.mn = ?
                LEFT JOIN Table4       ON t1.op = Table4.qr

with one bind value C<foobar>.

Details are explained in the next subsections.

=head4 tables participating in the join

Tables participating in a join are given as strings containing
the table name, possibly followed by a vertical bar
and an alias name. For example C<Table1> or C<Table1|t1>
are valid table specifications.

Table specifications are converted into internal hashrefs with keys
C<sql>, C<bind>, C<name>, C<aliased_tables>, like this :

  {
    sql            => "Table1 AS t1",
    bind           => [],
    name           => "t1",
    aliased_tables => {t1 => "Table1"},
  }

Such hashrefs can be passed directly as arguments, instead of the simple string representation.

=head4 join conditions

Join conditions between two tables are expressed as strings containing
an optional I<join operator>, possibly followed
by a pair of curly braces or square brackets
containing specific conditions.

Default builtin join operators are
C<< <=> >>, C<< => >>, C<< <= >>, C<< == >>,
corresponding to the following
SQL JOIN clauses :

  '<=>' => '%s INNER JOIN %s ON %s',
   '=>' => '%s LEFT OUTER JOIN %s ON %s',
  '<='  => '%s RIGHT JOIN %s ON %s',
  '=='  => '%s NATURAL JOIN %s',
  '>=<' => '%s FULL OUTER JOIN %s ON %s',

This operator table can be overridden through
the C<join_syntax> parameter of the L</new> method.

The join conditions are expressed as a comma-separated list
of binary column comparisons, like for example

  {ab=cd,Table1.ef<Table2.gh}

Table names may be explicitly given using dot notation,
or may be implicit, in which case they will be filled
automatically from the names of operands on the
left-hand side and right-hand side of the join.

Strings within quotes will be treated as bind values instead
of column names; pairs of quotes within such values become
single quotes. Ex.

  {ab=cd,ef='foo''bar',gh<ij}

becomes

  ON Table1.ab=Table2.cd AND Table1.ef=? AND Table1.gh<Table2.ij
  # bind value: "foo'bar"

In accordance with L<SQL::Abstract> common conventions,
if the list of comparisons is within curly braces, it will
become an C<AND>; if it is within square brackets, it will
become an C<OR>.

Join specifications expressed as strings
are converted into internal hashrefs with keys
C<operator> and either C<condition> or C<using>, like this :

  {
    operator  => '<=>',
    condition => { '%1$s.ab' => {'=' => {-ident => '%2$s.cd'}},
                   '%1$s.ef' => {'<' => {-ident => '%2$s.gh'}}},
  }

The C<operator> value is a key into the C<join_syntax> table; the associated
value is a C<sprintf> format string, with placeholders for the left and
right operands, and the join condition.  The C<condition> value is a
structure suitable for being passed as argument to
L<SQL::Abstract/where>.  Places where the names of left/right tables
(or their aliases) are expected should be expressed as C<sprintf>
placeholders, i.e.  respectively C<%1$s> and C<%2$s>. Usually the
right-hand side of the condition refers to a column of the right
table; in such case the C<-ident> operator must be present to indicate
that this is an identifier, not a value.
Only when the right-hand side is a string constant
(string within quotes) does it become a bind value : for example

  ->join(qw/Table1 {ab=cd,ef='foobar'}) Table2/)

is parsed into

  [ 'Table1',
    { operator  => '<=>',
      condition => { '%1$s.ab' => {'=' => {-ident => '%2$s.cd'}},
                     '%1$s.ef' => {'=' => 'foobar'} },
    },
    'Table2',
  ]

Hashrefs for join specifications as shown above can be passed directly
as arguments, instead of the simple string representation.
For example the L<DBIx::DataModel> ORM uses such hashrefs for communicating
with C<SQL::Abstract::More>.

=head4 joins with USING clause instead of ON

In most DBMS, when column names on both sides of a join are identical, the join
can be expressed as

  SELECT * FROM T1 INNER JOIN T2 USING (A, B)

instead of

  SELECT * FROM T1 INNER JOIN T2 ON T1.A=T2.A AND T1.B=T2.B

The advantage of this syntax with a USING clause is that the joined
columns will appear only once in the results, and they do not need to
be prefixed by a table name when mentioned in the select list or
in the WHERE part of the SQL.

To express joins with the USING syntax in C<SQL::Abstract::More>, just
mention the column names within curly braces, without any equality
operator. For example

  ->join(qw/Table1 {a,b} Table2 {c} Table3/)

will generate

  SELECT * FROM Table1 INNER JOIN Table2 USING (a,b)
                       INNER JOIN Table3 USING (c)

In this case the internal hashref representation has the following shape :

  {
    operator  => '<=>',
    using     => [ 'a', 'b'],
  }

Internal hashrefs must have I<either> a C<condition> field I<or> a C<using> field; it is
an error to have both.


=head4 hashref returned by join()

The structure returned by C<join()> is a hashref with the following keys :

=over

=item sql

a string containing the generated SQL

=item bind

an arrayref of bind values

=item aliased_tables

a hashref where keys are alias names and values are names of aliased tables.

=back





=head2 Auxiliary methods

=head3 table_alias


  my $sql = $sqla->table_alias($table_name, $alias);

Returns the SQL fragment for aliasing a table.
If C<$alias> is empty, just returns C<$table_name>.

=head3 column_alias

Like C<table_alias>, but for column aliasing.

=head3 limit_offset

  ($sql, @bind) = $sqla->limit_offset($limit, $offset);

Generates C<($sql, @bind)> for a LIMIT-OFFSET clause.


=head3 merge_conditions

  my $conditions = $sqla->merge_conditions($cond_A, $cond_B, ...);

This utility method takes a list of "C<where>" conditions and
merges all of them in a single hashref. For example merging

  ( {a => 12, b => {">" => 34}}, 
    {b => {"<" => 56}, c => 78} )

produces 

  {a => 12, b => [-and => {">" => 34}, {"<" => 56}], c => 78});


=head3 bind_params

  $sqla->bind_params($sth, @bind);

For each C<$value> in C<@bind>:

=over 

=item *

if the value is a scalarref, call

  $sth->bind_param_inout($index, $value, $INOUT_MAX_LEN)

(see L<DBI/bind_param_inout>). C<$INOUT_MAX_LEN> defaults to
99, which should be good enough for most uses; should you need another value, 
you can change it by setting

  local $SQL::Abstract::More::INOUT_MAX_LEN = $other_value;

=item *

if the value is an arrayref that matches L</is_bind_value_with_type>,
then call the method and arguments returned by L</is_bind_value_with_type>.

=item *

for all other cases, call

  $sth->bind_param($index, $value);

=back

This method is useful either as a convenience for Oracle
statements of shape C<"INSERT ... RETURNING ... INTO ...">
(see L</insert> method above), or as a way to indicate specific
datatypes to the database driver.

=head3 is_bind_value_with_type

  my ($method, @args) = $sqla->is_bind_value_with_type($value);


If C<$value> is a ref to a pair C<< [\%args, $orig_value] >> :


=over 

=item *

if  C<%args> is of shape C<< {dbd_attrs => \%sql_type} >>,
then return C<< ('bind_param', $orig_value, \%sql_type) >>.

=item *

if  C<%args> is of shape C<< {sqlt_size => $num} >>,
then return C<< ('bind_param_inout', $orig_value, $num) >>.

=back

Otherwise, return C<()>.



=head1 BIND VALUES WITH TYPES

At places where L<SQL::Abstract> would expect a plain value,
C<SQL::Abstract::More> also accepts a pair, i.e. an arrayref of 2
elements, where the first element is a type specification, and the
second element is the value. This is convenient when the DBD driver needs
additional information about the values used in the statement.

The usual type specification is a hashref C<< {dbd_attrs => \%type} >>,
where C<\%type> is passed directly as third argument to
L<DBI/bind_param>, and therefore is specific to the DBD driver.

Another form of type specification is C<< {sqlt_size => $num} >>,
where C<$num> will be passed as buffer size to L<DBI/bind_param_inout>.

Here are two examples:

  ($sql, @bind) = $sqla->insert(
   -into   => 'Foo',
   -values => {bar => [{dbd_attrs => {ora_type => ORA_XMLTYPE}}]},
  );
  ($sql, @bind) = $sqla->select(
   -from  => 'Foo',
   -where => {d_begin => {">" => [{dbd_attrs => {ora_type => ORA_DATE}}, 
                                  $some_date]}},
  );


When using this feature, the C<@bind> array will contain references
that cannot be passed directly to L<DBI> methods; so you should use
L</bind_params> from the present module to perform the appropriate
bindings before executing the statement.


=head1 UTILITY FUNCTIONS

=head2 shallow_clone

  my $clone = SQL::Abstract::More::shallow_clone($some_object, %override);

Returns a shallow copy of the object passed as argument. A new hash is created
with copies of the top-level keys and values, and it is blessed into the same
class as the original object. This is different from the full recursive copy
performed by L<Clone/clone>.

The optional C<%override> hash is also copied into C<$clone>; it can be used
to add other attributes or to override existing attributes in C<$some_object>.

=head2 does()

  if (SQL::Abstract::More::does $ref, 'ARRAY') {...}

Very cheap version of a C<does()> method, that
checks whether a given reference can act as an ARRAY, HASH, SCALAR or
CODE. This was designed for the limited internal needs of this module
and of L<DBIx::DataModel>; for more complete implementations of a
C<does()> method, see L<Scalar::Does>, L<UNIVERSAL::DOES> or
L<Class::DOES>.


=head1 History of SQL::Abstract and future of SQL::Abstract::More

=head2 Historical versions of SQL::Abstract

L<SQL::Abstract> was initially designed by Nathan Wiger. Several people
later contributed to various improvements until version 1.81, but the basic architecture
remained essentially the same. 

Then the maintenance of L<SQL::Abstract> was passed to Matt Trout who after many years
rewrote it with a largely different architecture, published under v2.000001. 
Matt's ambition was to provide a cleaner internal representation
of SQL fragments through an abstract syntax tree (AST) on which various transformations could
be performed before generating the final SQL code. These new AST features are quite powerful,
but it is not clear if anybody ever used them -- and since Matt passed away, we cannot ask him.

Despite the fact that Matt took great care to preserve backwards compatibility with
previous versions of C<SQL::Abstract>, the changes were deep, and some differences
in behavior were observable. Not everybody agreed with the changes, so in 2019
Peter Rabbitson published a fork of the old version 1.81 under the name L<SQL::Abstract::Classic>.


=head2 Evolution strategy for SQL::Abstract::More

Several years later, neither C<SQL::Abstract> nor C<SQL::Abstract::Classic> are actively
maintained, so they will probably stay in a frozen state. Under these conditions it no
longer makes sense for C<SQL::Abstract::More> to try to support both. So the strategy
is to drop C<SQL::Abstract> v2, relying on sole C<SQL::Abstract::Classic> for this version, and
then to drop it too, forking the relevant code into a standalone C<SQL::Abstract::More>.
In the present version, however, it is still possible (but deprecated) to inherit from
C<SQL::Abstract> v2 through the environment variable C<SQL_ABSTRACT_MORE_EXTENDS> or 
through an C<-extends> parameter:

  use SQL::Abstract::More -extends => 'SQL::Abstract';

=head2 Related work

Readers in search for a SQL generation module may also want to
review L<SQL::Wizard>, a 2026 proposal with a fresh implementation around an internal abstract tree,
but offering an external API quite close to C<SQL::Abstract::More>.

=head1 AUTHOR

Laurent Dami, C<dami@cpan.org>

=head1 ACKNOWLEDGEMENTS

=over

=item *

L<https://github.com/djerius> : support for table aliases in update() and delete(); tests and pull requests for better handling of quote_char

=item *

L<https://github.com/rouzier> : support for C<-having> without C<-order_by>

=item *

L<https://github.com/ktat> : fix for C<< -from => ['table'] >>

=item *

L<https://metacpan.org/author/DAKKAR> : signaling a regression for C<< -from => \ 'table' >>

=back


=head1 SUPPORT

You can find documentation for this module with the perldoc command.

    perldoc SQL::Abstract::More


The same documentation is also available at
L<https://metacpan.org/module/SQL::Abstract::More>


=head1 LICENSE AND COPYRIGHT

Copyright 2011-2026 Laurent Dami.

This program is free software; you can redistribute it and/or modify it
under the terms of either: the GNU General Public License as published
by the Free Software Foundation; or the Artistic License.

See https://dev.perl.org/licenses/ for more information.

=cut


