NAME

Mojo::SQL::Statement - SQL statement container

SYNOPSIS

use Mojo::SQL::Statement;

my $stmt  = Mojo::SQL::Statement->new->parse('SELECT * FROM users WHERE name = ?', 'sebastian');
my $query = $stmt->to_query;

DESCRIPTION

Mojo::SQL::Statement is a container for an SQL statement and its bind values. Statements are composable by passing one as a value to another, in which case its parts and values are spliced in recursively.

ATTRIBUTES

Mojo::SQL::Statement implements the following attributes.

parts

my $parts = $stmt->parts;
$stmt     = $stmt->parts(['SELECT * FROM users WHERE name = ', '']);

The literal SQL fragments around each placeholder, as an array reference. There is always one more fragment than placeholder.

values

my $values = $stmt->values;
$stmt      = $stmt->values(['sebastian']);

The bind values for each placeholder, as an array reference.

METHODS

Mojo::SQL::Statement inherits all methods from Mojo::Base and implements the following new ones.

parse

$stmt = $stmt->parse('SELECT * FROM users WHERE name = ?', 'sebastian');

Parse an SQL string with ? placeholders and bind values into "parts" and "values". Mojo::SQL::Statement values are spliced in recursively, allowing partial statements to be composed. Literal question marks can be escaped with ??.

parse_unsafe

$stmt = $stmt->parse_unsafe("AND role = 'admin'");
$stmt = $stmt->parse_unsafe('AND ?', "role = 'admin'");

Parse an SQL string where every ? slot is replaced literally by the corresponding value. The result has no placeholders or bind values; use with care, and make sure to escape values yourself with the appropriate escaping functions for your database. Literal question marks can be escaped with ??.

to_array

my $array = $stmt->to_array;
my $array = $stmt->to_array({placeholder => '?'});

Render the statement to an array reference containing the SQL text and bind values, ready to be passed to a database driver. Accepts the same options as "to_query".

to_list

my @list = $stmt->to_list;
my @list = $stmt->to_list({placeholder => '?'});

Same as "to_array" but returns a list.

to_query

my $query = $stmt->to_query;
my $query = $stmt->to_query({placeholder => '?'});

Render the statement to a query hash reference with text and values keys, ready to be passed to a database driver.

These options are currently available:

placeholder
placeholder => '?'

Placeholder character to use, defaults to numbered placeholders like $1 and $2.

to_string

my $string = $stmt->to_string;
my $string = $stmt->to_string({placeholder => '?'});

Render just the SQL string portion of the statement. Accepts the same options as "to_query".

SEE ALSO

Mojo::SQL, Mojolicious, https://mojolicious.org.