cho45 (owner)

Revisions

gist: 193260 Download_button fork
public
Public Clone URL: git://gist.github.com/193260.git
Embed All Files: show embed
Perl #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#/usr/bin/perl
use strict;
use warnings;
use utf8;
use Encode;
use Perl6::Say;
use Data::Dumper;
sub p ($) { warn Dumper shift }
 
use SQL::Parser;
 
my $parser = SQL::Parser->new;
 
#p $parser->parse(q{SELECT * FROM foo});
#p $parser->structure;
#
#p $parser->parse(q{SELECT * FROM foo ORDER BY created DESC});
#p $parser->structure;
#
#p $parser->parse(q{SELECT * FROM foo WHERE name IN (?) ORDER BY created DESC});
#my $structure = $parser->structure;
 
p $parser->parse(q{SELECT * FROM foo WHERE name IN (?) AND id is not null AND created > 2 ORDER BY created DESC, id LIMIT 2,10});
my $structure = $parser->structure;
 
#p $parser->parse(q{SELECT *, created as test_foo FROM foo WHERE name IN (?) ORDER BY created DESC LIMIT 0,10});
#my $structure = $parser->structure;
 
#p $parser->parse(q{INSERT INTO blog (a, b, c) VALUES (?, ?, ?)});
#p $parser->structure;
 
use SQL::Abstract::Limit;
 
p $structure;
 
my $method = lc $structure->{command};
 
my $sql = SQL::Abstract::Limit->new( limit_dialect => "LimitOffset" );
 
my $tables = $structure->{org_table_names};
my $columns = $structure->{column_names};
my $where = [];
my $order = [];
my $limit = $structure->{limit_clause}->{limit};
my $offset = $structure->{limit_clause}->{offset};
 
for my $sort (@{ $structure->{sort_spec_list} }) {
my $name = (keys %$sort)[0];
my $dir = $sort->{$name} || "asc";
push @$order, {
"-$dir" => lc $name
};
}
 
sub construct_where {
my ($structure) = @_;
 
if (lc $structure->{op} eq "is") {
$structure->{op} = $structure->{neg} ? "!=" : "=";
}
 
my $op = ($structure->{op} =~ /^\w+$/) ?
sprintf("-%s%s", $structure->{neg} ? "not_" : "", lc $structure->{op}):
$structure->{op};
 
if ($op eq "-and" || $op eq "-or") {
+{
$op => [
construct_where($structure->{arg1}),
construct_where($structure->{arg2}),
]
}
} else {
+{
lc $structure->{arg1}->{value} => {
$op,
$structure->{arg2}->{value}
}
}
}
}
 
$where = construct_where($structure->{where_clause});
p $where;
 
my ($stmt, @bind) = $sql->$method( $tables, $columns, $where, $order, $limit, $offset );
p [$stmt, @bind];