forked from reportico-web/reportico
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swsql.php
executable file
·671 lines (585 loc) · 19.7 KB
/
swsql.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
<?php
/*
Reportico - PHP Reporting Tool
Copyright (C) 2010-2014 Peter Deed
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* File: swsql.php
*
* Contains functionality for parsing SQL statements and
* converting them to queries that can be used by the
* Reportico engine
*
* @link http://www.reportico.org/
* @copyright 2010-2014 Peter Deed
* @author Peter Deed <[email protected]>
* @package Reportico
* @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* @version $Id: swsql.php,v 1.17 2014/05/17 15:12:32 peter Exp $
*/
/**
* Class reportico_sql_parser
*
* Parses SQL statements entered by user during
* report design mode and imports them into
* the Reportico engine
*/
class reportico_sql_parser
{
var $sql;
var $sql_raw;
var $columns = array();
var $tables = array();
var $table_text;
var $where = "";
var $group = "";
var $orders = array();
var $status_message = "";
var $unique = false;
var $columnoffset = 0; // Positon in sql where select columns exists
var $whereoffset = 0; // Positon in sql where WHERE clause exists or would exist
var $haswhere = false; // Does the sql have a where clause?
function __construct( $in_sql )
{
$this->sql = $in_sql;
}
function import_into_query( &$in_query )
{
$in_query->sql_raw = $this->sql_raw;
//When importing into query, we need to ensure that we remove
// any columns already existing which do not appear in the
// new query
$delete_columns = array();
foreach ( $in_query->columns as $k => $v )
{
if ( $v->in_select )
{
$delete_columns[$v->query_name] = true;
}
}
foreach ( $this->columns as $col )
{
$qn = $col["name"];
if ( $col["alias"] )
$qn = $col["alias"];
$in_query->create_criteria_column(
$qn, $col["table"], $col["name"], "char", 30, "####", true);
if ( array_key_exists($qn, $delete_columns ) )
{
$delete_columns[$qn] = false;
}
}
$ct = 0;
$tabtext = "";
foreach ( $this->tables as $col )
{
if ( $ct++ > 0 )
$tabtext .= ",";
switch ( $col["jointype"] )
{
case "outer":
$tabtext .= "outer ";
break;
case "inner":
case "default":
}
$tabtext .= $col["name"];
if ( $col["alias"] )
$tabtext .= " ".$col["alias"];
}
$in_query->table_text = $tabtext;
$in_query->table_text = $this->table_text;
$in_query->where_text = false;
if ( substr($in_query->where_text, 0, 9) == "AND 1 = 1" )
{
$in_query->where_text = substr($in_query->where_text, 9);
}
if ( $this->group )
$in_query->group_text = "GROUP BY ".$this->group;
else
$in_query->group_text = "";
// Delete existing order columns
$in_query->order_set = array();
foreach ( $this->orders as $col )
{
if ( ($qc = get_query_column($col["name"], $in_query->columns)) )
$in_query->create_order_column( $col["name"], $col["type"] );
}
// Now remove from the parent query any columns which were not in the
// imported SQL
foreach ( $delete_columns as $k => $v )
{
if ( $v )
{
$in_query->remove_column($k);
}
}
// Now order the query columns in the reportico query to reflect the order specified in
// the select statement
$pos = 0;
$xx = false;
foreach ( $this->columns as $col )
{
$pos2 = 0;
$cut = false;
foreach ( $in_query->columns as $k => $v )
{
if ( $v->query_name == $col["alias"] )
{
$cut = array_splice($in_query->columns, $pos2, 1 );
break;
}
$pos2++;
}
if ( $cut )
{
array_splice($in_query->columns, $pos, 0,
$cut );
}
$pos++;
}
$in_query->rowselection = "all";
if ( $this->unique )
$in_query->rowselection = "unique";
}
function display()
{
echo "Columns<br>\n=======<br>\n";
foreach ( $this->columns as $col )
{
echo $col["table"].".".$col["name"];
echo " (".$col["alias"].")";
echo " => ",$col["expression"];
echo "<br>\n";
}
echo "<br>\nTables<br>\n======<br>\n";
foreach ( $this->tables as $col )
{
echo $col["name"];
echo " (".$col["alias"].")";
echo " - ".$col["jointype"];
echo "<br>\n";
}
echo "<br>\nWhere<br>\n=====<br>\n";
echo $this->where;
echo "<br>\n";
echo "<br>\nOrder<br>\n=====<br>\n";
foreach ( $this->orders as $col )
{
echo $col["name"]." ";
echo $col["type"];
echo "<br>\n";
}
}
// **
// Parses the report main SQL in order to extract the report columns to return
// It performs this first trying to find the SELECT part of the query which contains the columns
// Given that a single SQL statement may have many SELECT elements ( a WITH statement, th emain select,
// embedded select in a where clause ) any of them could bring back the report columns.
// **
function parse($warn_empty_aliases = true)
{
$err = false;
$this->sql_raw = $this->sql;
// First extract every element of of the sql which begins with SELECT ..... FROM
$matches = array();
preg_match_all ( "/.*SELECT\s*(.*)\sFROM\s.*/isU", $this->sql, $matches, PREG_OFFSET_CAPTURE );
$sql =& $this->sql;
// Find the main query SELECT column list which may be hidden among other many selects in
// a the users statement. The trick is to find the columns belonging to a select that
// is not preceded by a "(" indicating a sub select.
$col = "";
$selpos = -1;
$frompos = -1;
$ptr = 0;
$brackets = 0;
$doublequotes = 0;
while ( $ptr < strlen($sql) )
{
$bit = substr($sql, $ptr, 1);
$bit4 = substr($sql, $ptr, 4);
$bit6 = substr($sql, $ptr, 6);
$bit7 = substr($sql, $ptr, 7);
$inc = 1;
if ( $bit == "\"" && $doublequotes == 0)
$doublequotes++;
else if ( $bit == "\"" )
$doublequotes--;
else if ( $bit == "(" )
$brackets++;
else if ( $bit == ")" )
$brackets--;
else if ( preg_match ("/SELECT\s/i", $bit7) )
{
if ( $brackets == 0 && $doublequotes == 0 )
{
$selpos = $ptr + 7;
$inc = 7;
}
}
else if ( preg_match("/\sFROM\s/i", $bit6 ) )
{
if ( $selpos > -1 && $brackets == 0 && $doublequotes == 0 )
{
$frompos = $ptr;
$inc = 5;
break;
}
}
$ptr += $inc;
}
$columnoffset = $frompos;
// Find the main query SELECT column list which may be hidden among other many selects in
// a the users statement. The trick is to find the columns belonging to a select that
// is not preceded by a "(" indicating a sub select.
if ( $selpos == -1 || $frompos == -1 )
{
trigger_error("no SELECT clause specified. Query must contain a 'SELECT'", E_USER_ERROR);
}
else
{
$col = substr ( $sql, $selpos, $frompos - $selpos );
if ( $col )
{
$this->parse_column_list($this->sql_raw, $col, $selpos ,$warn_empty_aliases );
// Now find the location where the WHERE is or where it would be if there isnt one
$wherematch = array();
if ( preg_match ( "/.*(\[\s*WHERE\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->haswhere = false;
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*\s+WHERE(\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ))
{
$this->haswhere = true;
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+GROUP BY\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+GROUP BY\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+GROUP BY\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+HAVING\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+ORDER BY\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+LIMIT\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else if ( preg_match ( "/.*(\s+PROCEDURE\s+.*)/siU", $sql, $wherematch, PREG_OFFSET_CAPTURE, $this->columnoffset ) )
{
$this->whereoffset = $wherematch[1][1];
}
else
{
$this->whereoffset = strlen ( $sql ) ;
}
}
}
$upd_match = "/^\s*UPDATE\s*(.*)/is";
$del_match = "/^\s*DELETE\s*(.*)/is";
if ( preg_match($upd_match, $sql, $cpt ) )
{
trigger_error("Update statements are not allowed in designer queries", E_USER_ERROR);
$sel_type = "UPDATE";
$this->sql_raw = "#". $this->sql_raw;
$this->whereoffset = 0;
}
if ( preg_match($del_match, $sql, $cpt ) )
{
trigger_error("Delete statements are not allowed designer queries", E_USER_ERROR);
$sel_type = "DELETE";
$this->sql_raw = "#". $this->sql_raw;
$this->whereoffset = 0;
}
return $this->whereoffset;
}
function tokenise_columns( $in_string )
{
$escaped = false;
$level_stack = array();
$in_dquote = false;
$in_squote = false;
$rbracket_level = 0;
$sbracket_level = 0;
$collist = array();
$cur = false;
for ( $ct = 0; $ct < strlen($in_string); $ct++ )
{
if ( $ct == 0 )
{
$collist[] = "";
end($collist);
$ky = key($collist);
$cur =& $collist[$ky];
}
$ch = substr($in_string,$ct,1);
$ok_to_add = true;
switch ( $ch )
{
case ",":
if ( !($in_dquote || $in_squote || $rbracket_level > 0 || $sbracket_level > 0) )
{
$collist[] = "";
end($collist);
$ky = key($collist);
$cur =& $collist[$ky];
$ok_to_add = false;
}
break;
case "\"":
if ( $in_dquote )
$in_dquote = false;
else
if ( !$in_squote )
$in_dquote = true;
break;
case "'":
if ( $in_squote )
$in_squote = false;
else
if ( !$in_dquote )
$in_squote = true;
break;
case "(":
if ( !$in_squote && !$in_dquote )
$rbracket_level++;
break;
case ")":
if ( !$in_squote && !$in_dquote )
$rbracket_level--;
break;
case "[":
if ( !$in_squote && !$in_dquote )
$sbracket_level++;
break;
case "]":
if ( !$in_squote && !$in_dquote )
$sbracket_level--;
break;
}
if ($ok_to_add )
$cur .= $ch;
}
return $collist;
}
// -----------------------------------------------------------------------------
// Function : parse_column_list
// ----------------------------
// Analyses each column in a user SQL statement
//
// If user has provided expressions in sql without aliases then an autogenerated
// alias is added in
// ----------------------------------------------------------------------------
function parse_column_list( &$original_sql, $in_string, $offset_in_original_sql ,$warn_empty_aliases )
{
$tmpsql = $original_sql;
$rolling_new_alias_offset = $offset_in_original_sql ;
$collist = $this->tokenise_columns($in_string);
foreach ( $collist as $k => $colitem )
{
$auto_gen_alias = false;
if ( !$this->parse_column($k + 1, trim($colitem), $auto_gen_alias ,$warn_empty_aliases ) )
return false;
$rolling_new_alias_offset += strlen($colitem);
if ( $auto_gen_alias )
{
$tmpsql = substr($tmpsql, 0, $rolling_new_alias_offset).
" $auto_gen_alias". substr($tmpsql, $rolling_new_alias_offset);
$rolling_new_alias_offset += strlen($auto_gen_alias) + 1;
}
$rolling_new_alias_offset += 1;
}
$original_sql = $tmpsql;
return true;
}
// -----------------------------------------------------------------------------
// Function : parse_column
// -----------------------
// Will take a column item from an SQL statement and parse it to identify
// any alias, table identifier or expression
// ----------------------------------------------------------------------------
function parse_column( $in_colno, $in_string, &$auto_gen_alias ,$warn_empty_aliases )
{
$err = false;
$colalias = "";
$colname = "";
$coltable = "";
$colexp = "";
// Check for an alias ( any final word which is preceded by any non
// numeric or expression character
// Split out the last two elements
if ( preg_match("/(.+\))([^\s]*)\s*\$/s", $in_string, $out_match) )
{
if ( preg_match ( "/^[[:alpha:]]\w+$/s", $out_match[2] ) )
{
$colalias = $out_match[2];
$colname = $out_match[1];
$colexp = $colname;
}
else
{
if ( preg_match("/[^0-9A-Za-z_\r\n\t .]/", $in_string ) )
{
$colalias = "column".$in_colno;
$auto_gen_alias = $colalias;
if ( $warn_empty_aliases )
handle_debug("Expression <b>($in_string)</b> is unnamed and will be given the name <b>$colalias</b>. You might like to provide your own column alias for this expression.", 0);
}
$colname = $in_string;
$colexp = $in_string;
}
}
else
if ( preg_match("/(.+)\s+(.*)\s*\$/s", $in_string, $out_match) )
{
if ( preg_match ( "/^[[:alpha:]]\w+$/s", $out_match[2] ) )
{
$colalias = $out_match[2];
$colname = $out_match[1];
$colexp = $colname;
}
else
if ( preg_match ( "/^[a-zA-Z]$/s", $out_match[2] ) )
{
$colalias = $out_match[2];
$colname = $out_match[1];
$colexp = $colname;
}
else
{
if ( preg_match("/[^0-9A-Za-z_\r\n\t .]/", $in_string ) )
{
$colalias = "column".$in_colno;
$auto_gen_alias = $colalias;
if ( $warn_empty_aliases )
handle_debug("Expression <b>($in_string)</b> is unnamed and will be given the name <b>$colalias</b>. You might like to provide your own column alias for this expression.", 0);
}
$colname = $in_string;
$colexp = $in_string;
}
}
else
{
// Single column value only so assume no alias
if ( preg_match("/[^0-9A-Za-z_\r\n\t .]/", $in_string ) )
{
$colalias = "column".$in_colno;
$auto_gen_alias = $colalias;
if ( $warn_empty_aliases )
handle_debug("Expression <b>($in_string)</b> is unnamed and will be given the name <b>$colalias</b>. You might like to provide your own column alias for this expression.", 0);
}
$colname = $in_string;
$colexp = $in_string;
}
// Now with what's left of the column try to ascertain a table name
// and column part
if ( preg_match("/^(\w+)\.(\w+)$/", $colname, $out_match) )
{
$coltable = $out_match[1];
$colname = $out_match[2];
}
$this->columns[] = array(
"name" => $colname,
"table" => $coltable,
"alias" => $colalias,
"expression" => $colexp
)
;
return true;
}
// -----------------------------------------------------------------------------
// Function : test_query
//
// Checks syntax of report query by attempting to run user query. In order to
// avoid long execution times, the WHERE clause is modified to include a 1 = 0
// test so that no rows are returned and therefore execution time is quick
// -----------------------------------------------------------------------------
function test_query($in_query, $sql)
{
$conn =& $in_query->datasource->ado_connection;
if ( $this->haswhere )
{
// In order to test an SQL statement with a where clause add an "1 = 0 AND "
$tmp = substr ( $sql, $this->whereoffset );
$tmp = substr ( $sql, 0, $this->whereoffset );
$tmp .= " 1 = 0 AND";
$tmp .= substr( $sql, $this->whereoffset );
$sql = $tmp;
}
else
{
// No where statement add a WHERE 1 = 0
$tmp = substr ( $sql, $this->whereoffset );
$tmp = substr ( $sql, 0, $this->whereoffset );
$tmp .= " WHERE 1 = 0 ";
$tmp .= substr( $sql, $this->whereoffset );
$sql = $tmp;
}
// Remove any meta_sql criteria links between "[" and "]"
$sql = preg_replace("/WHERE 1 = 1/i", "WHERE 1 = 0", $sql);
$sql = preg_replace("/\[.*\]/U", '', $sql);
// Replace External parameters specified by {USER_PARAM,xxxxx}
if ( preg_match_all ( "/{USER_PARAM,([^}]*)}/", $sql, $matches ) )
{
foreach ( $matches[0] as $k => $v )
{
$param = $matches[1][$k];
if ( isset($in_query->user_parameters[$param] ) )
{
$sql = preg_replace("/{USER_PARAM,$param}/", $in_query->user_parameters[$param], $sql);
}
else
{
trigger_error("User parameter $param, specified but not provided to reportico", E_USER_ERROR);
}
}
}
$sql = reportico_assignment::reportico_meta_sql_criteria($in_query->parent_query, $sql, false, false, "MAINTAIN");
$errorCode = false;
$errorMessage = false;
$recordSet = false;
try
{
$recordSet = $conn->Execute($sql) ;
}
catch( PDOException $Exception ) {
$errorNumber = $Exception->getCode();
$errorMessage = $Exception->getMessage();
// PHP Fatal Error. Second Argument Has To Be An Integer, But PDOException::getCode Returns A
// String.
}
// Begin Target Output
if (!$recordSet)
{
if ( $errorMessage )
handle_error( "Error in Connection: ".$errorMessage. "<BR><BR>(Note that if the error warns of a missing temporary table that will be created at runtime, it is safe to ignore this message)");
else
handle_error( "Error ( ".$conn->ErrorNo().") in Connection: ".$conn->ErrorMsg(). "<BR><BR>(Note that if the error warns of a missing temporary table that will be created at runtime, it is safe to ignore this message)");
return false;
}
else
return true;
}
}