DBLayer.pm 16.2 KB
Newer Older
Nigel Kukard's avatar
Nigel Kukard committed
1
# Common database layer module
2
# Copyright (C) 2009-2017, AllWorldIT
Nigel Kukard's avatar
Nigel Kukard committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Copyright (C) 2008, LinuxRulz
# Copyright (C) 2005-2007 Nigel Kukard  <nkukard@lbsd.net>
#
# 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.



Nigel Kukard's avatar
Nigel Kukard committed
22
## @class AWITPT::DB::DBLayer
Nigel Kukard's avatar
Nigel Kukard committed
23
# Database layer module which makes life a bit esier
Nigel Kukard's avatar
Nigel Kukard committed
24
package AWITPT::DB::DBLayer;
Nigel Kukard's avatar
Nigel Kukard committed
25
26
27
28

use strict;
use warnings;

29
30
31
32
use parent 'Exporter';


our $VERSION = 2.01;
Nigel Kukard's avatar
Nigel Kukard committed
33

Nigel Kukard's avatar
Nigel Kukard committed
34
# Exporter stuff
Nigel Kukard's avatar
Nigel Kukard committed
35
our (@EXPORT);
Nigel Kukard's avatar
Nigel Kukard committed
36
@EXPORT = qw(
37
	DBInit
Nigel Kukard's avatar
Nigel Kukard committed
38
39
40
	DBConnect
	DBSelect
	DBDo
41
42
	DBUpdate
	DBInsert
Nigel Kukard's avatar
Nigel Kukard committed
43
44
45
46
47
48
49
50
51
52
53
54
55
56
	DBLastInsertID
	DBBegin
	DBCommit
	DBRollback
	DBQuote
	DBFreeRes

	DBSelectNumResults
	DBSelectSearch
);

use POSIX qw( strftime );
use Date::Parse;

Nigel Kukard's avatar
Nigel Kukard committed
57
use AWITPT::DB::DBILayer;
Nigel Kukard's avatar
Nigel Kukard committed
58
59
60
61
62
63
64
65


# Database handle
my $dbh = undef;

# Our current error message
my $error = "";

Nigel Kukard's avatar
Nigel Kukard committed
66
67


Nigel Kukard's avatar
Nigel Kukard committed
68
## @internal
Nigel Kukard's avatar
Nigel Kukard committed
69
# @fn _error($err)
Nigel Kukard's avatar
Nigel Kukard committed
70
71
72
# This function is used to set the last error for this class
#
# @param err Error message
Nigel Kukard's avatar
Nigel Kukard committed
73
sub _error
Nigel Kukard's avatar
Nigel Kukard committed
74
75
{
	my $err = shift;
Nigel Kukard's avatar
Nigel Kukard committed
76
77


Nigel Kukard's avatar
Nigel Kukard committed
78
79
80
81
82
83
84
	my ($package,$filename,$line) = caller;
	my (undef,undef,undef,$subroutine) = caller(1);

	# Set error
	$error = "$subroutine($line): $err";
}

Nigel Kukard's avatar
Nigel Kukard committed
85
86


Nigel Kukard's avatar
Nigel Kukard committed
87
## @internal
88
# @fn error
Nigel Kukard's avatar
Nigel Kukard committed
89
90
91
# Return current error message
#
# @return Last error message
92
sub error
Nigel Kukard's avatar
Nigel Kukard committed
93
94
95
96
97
98
99
100
101
102
103
104
{
	my $err = $error;

	# Reset error
	$error = "";

	# Return error
	return $err;
}



105
106
107
108
109
110
111
112
113
114
115
116
117
118
## @fn DBInit($dbconfig)
# Initialize the database for use
#
# @param DSN Database DSN
# @li DSN - Database DSN
# @li Username - Optional database username
# @li Password - Optional database password
# @li TablePrefix - Optional database table prefix
sub DBInit
{
	my $dbconfig = shift;


	if (!defined($dbconfig)) {
Nigel Kukard's avatar
Nigel Kukard committed
119
		_error("The dbconfig hash is not defined");
Nigel Kukard's avatar
Nigel Kukard committed
120
		return;
121
122
123
	}

	if (ref($dbconfig) ne "HASH") {
Nigel Kukard's avatar
Nigel Kukard committed
124
		_error("The dbconfig option is not a hash");
Nigel Kukard's avatar
Nigel Kukard committed
125
		return;
126
127
128
	}

	if (!defined($dbconfig->{'DSN'})) {
Nigel Kukard's avatar
Nigel Kukard committed
129
		_error("The dbconfig hash does not contain 'DSN'");
Nigel Kukard's avatar
Nigel Kukard committed
130
		return;
131
132
133
	}

	# Check if we created
Nigel Kukard's avatar
Nigel Kukard committed
134
	$dbh = AWITPT::DB::DBILayer->new($dbconfig);
135
136
137
138
139
140
141
142
143
144
145
146
147

	return $dbh;
}



## @fn DBInit($dbconfig)
# Initialize the database for use
#
sub DBConnect
{
	my $res;

148
149
150
151
152
153

	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

154
	if ($res = $dbh->connect()) {
155
		_error($dbh->error());
156
157
158
159
160
161
162
	}

	return $res;
}



Nigel Kukard's avatar
Nigel Kukard committed
163
164
165
166
167
168
## @fn setHandle($handle)
# Initialize database handle
#
# @param handle Set internal database handle we use
sub setHandle
{
Nigel Kukard's avatar
Nigel Kukard committed
169
	my $handle = shift;
Nigel Kukard's avatar
Nigel Kukard committed
170

Nigel Kukard's avatar
Nigel Kukard committed
171

172
	return $dbh = $handle;
Nigel Kukard's avatar
Nigel Kukard committed
173
174
175
}


Nigel Kukard's avatar
Nigel Kukard committed
176

Nigel Kukard's avatar
Nigel Kukard committed
177
178
179
180
181
182
183
184
## @fn DBSelect($query,@params)
# Return database selection results...
#
# @param query Query to run
#
# @return DBI statement handle, undef on error
sub DBSelect
{
185
	my ($query,@params) = @_;
Nigel Kukard's avatar
Nigel Kukard committed
186

Nigel Kukard's avatar
Nigel Kukard committed
187

188
189
190
191
192
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
193
194
195
196
197
198
199
200
	my $table_prefix = $dbh->table_prefix();

	# Replace table prefix macro
	$query =~ s/\@TP\@/$table_prefix/g;

	# Prepare query
	my $sth;
	if (!($sth = $dbh->select($query,@params))) {
201
		_error("Error executing select: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
202
		return;
Nigel Kukard's avatar
Nigel Kukard committed
203
204
205
206
207
208
	}

	return $sth;
}


Nigel Kukard's avatar
Nigel Kukard committed
209

Nigel Kukard's avatar
Nigel Kukard committed
210
211
212
213
214
215
216
217
218
219
220
## @fn DBDo($command)
# Perform a command
#
# @param command Command to run
#
# @return DBI statement handle, undef on error
sub DBDo
{
	my (@params) = @_;


221
222
223
224
225
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
226
227
228
229
230
231
232
233
234
235
236
237
238
	my $table_prefix = $dbh->table_prefix();

	# Check type of params we have
	if (ref($params[0]) eq 'HASH') {
		my $queryHash = $params[0];
		my $dbType = $dbh->type();

		# Check DB type is defined, if not use *
		if (defined($queryHash->{$dbType})) {
			@params = @{$queryHash->{$dbType}};
		} elsif (defined($queryHash->{'*'})) {
			@params = @{$queryHash->{'*'}};
		} else {
Nigel Kukard's avatar
Nigel Kukard committed
239
			_error("Error executing, database type in query not fund and no '*' query found");
Nigel Kukard's avatar
Nigel Kukard committed
240
			return;
Nigel Kukard's avatar
Nigel Kukard committed
241
242
243
244
245
246
247
248
249
250
251
252
253
		}
	}

	# Grab command and data
	my $command = shift(@params);
	my @data = @params;

	# Replace table prefix macro
	$command =~ s/\@TP\@/$table_prefix/g;

	# Prepare query
	my $sth;
	if (!($sth = $dbh->do($command,@data))) {
254
255
		# Remove newlines...
		$command =~ s/(\n|\s{2,})/ /g;
256
		_error("Error executing command '$command': ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
257
		return;
Nigel Kukard's avatar
Nigel Kukard committed
258
259
260
261
262
263
	}

	return $sth;
}


Nigel Kukard's avatar
Nigel Kukard committed
264

265
266
267
268
269
270
271
272
273
274
275
276
277
## @fn DBUpdate($table,$id,%columnData)
# Do an update of a database record
#
# @param table Table to update
# @param id ID value of the row
# @param columnData Hash of columns to update
#
# @return DBI statement handle, undef on error
sub DBUpdate
{
	my ($table,$id,%data) = @_;


278
279
280
281
282
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

283
284
285
286
287
288
289
290
291
292
	# Loop with columns and add them to our list of updates to do
	my @columns;
	my @values;
	foreach my $column (keys %data) {
		push(@columns,"$column = ?");
		push(@values,$data{$column});
	}

	# Make sure we have at least one thing to update
	if (@columns < 1) {
Nigel Kukard's avatar
Nigel Kukard committed
293
		_error("Nothing to update");
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
		return;
	}

	# Update user
	my $sth = DBDo(
		sprintf('
				UPDATE
					@TP@%s
				SET
					%s
				WHERE
					ID = ?
			',
			$table,
			join(',',@columns)
		),
		@values,
		$id
	);

	return $sth;
}



## @fn DBInsert($table,%columnData)
# Insert data into DB
#
# @param table Table to update
# @param columnData Hash of columns to insert
#
# @return DBI statement handle, undef on error
sub DBInsert
{
	my ($table,%data) = @_;


331
332
333
334
335
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

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
	# Loop with columns and add them to our list
	my @columns;
	my @placeholders;
	my @values;
	foreach my $column (keys %data) {
		push(@columns,$column);
		push(@placeholders,'?');
		push(@values,$data{$column});
	}

	# Add user
	my $sth = DBDo(
		sprintf('
				INSERT INTO @TP@%s
					(%s)
				VALUES
					(%s)
			',
			$table,
			join(',',@columns),
			join(',',@placeholders)
		),
		@values
	);

	# Return last insert ID if we succeeded
	if (defined($sth)) {
		return DBLastInsertID($table,"ID");
	}

	return;
}



Nigel Kukard's avatar
Nigel Kukard committed
371
372
373
374
375
376
377
378
379
380
381
382
## @fn DBLastInsertID($table,$column)
# Function to get last insert id
#
# @param table Table to check
# @param column Column to get last insert on
#
# @return Last insert ID or undef on error
sub DBLastInsertID
{
	my ($table,$column) = @_;


383
384
385
386
387
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
388
	my $res;
389
	if (!($res = $dbh->lastInsertID($table,$column))) {
390
		_error("Error getting last inserted id: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
391
		return;
Nigel Kukard's avatar
Nigel Kukard committed
392
393
394
395
396
397
	}

	return $res;
}


Nigel Kukard's avatar
Nigel Kukard committed
398

Nigel Kukard's avatar
Nigel Kukard committed
399
400
401
402
403
404
405
## @fn DBBegin
# Function to begin a transaction
#
# @return 1 on success, undef on error
sub DBBegin
{
	my $res;
406
407
408
409
410
411
412


	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
413
	if (!($res = $dbh->begin())) {
414
		_error("Error beginning transaction: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
415
		return;
Nigel Kukard's avatar
Nigel Kukard committed
416
417
418
419
420
421
	}

	return $res;
}


Nigel Kukard's avatar
Nigel Kukard committed
422

Nigel Kukard's avatar
Nigel Kukard committed
423
424
425
426
427
428
429
## @fn DBCommit
# Function to commit a transaction
#
# @return 1 on success, undef on error
sub DBCommit
{
	my $res;
430
431
432
433
434
435
436


	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
437
	if (!($res = $dbh->commit())) {
438
		_error("Error committing transaction: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
439
		return;
Nigel Kukard's avatar
Nigel Kukard committed
440
441
442
443
444
445
	}

	return $res;
}


Nigel Kukard's avatar
Nigel Kukard committed
446

Nigel Kukard's avatar
Nigel Kukard committed
447
448
449
450
451
452
453
## @fn DBRollback
# Function to rollback a transaction
#
# @return 1 on success, undef on error
sub DBRollback
{
	my $res;
454
455
456
457
458
459
460


	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
461
	if (!($res = $dbh->rollback())) {
462
		_error("Error rolling back transaction: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
463
		return;
Nigel Kukard's avatar
Nigel Kukard committed
464
465
466
467
468
469
	}

	return $res;
}


Nigel Kukard's avatar
Nigel Kukard committed
470

Nigel Kukard's avatar
Nigel Kukard committed
471
472
473
474
475
476
477
478
479
480
481
## @fn DBQuote($variable)
# Function to quote a database variable
#
# @param variable Variable to quote
#
# @return Quoted variable
sub DBQuote
{
	my $variable = shift;


482
483
484
485
486
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
487
488
489
490
	return $dbh->quote($variable);
}


Nigel Kukard's avatar
Nigel Kukard committed
491

Nigel Kukard's avatar
Nigel Kukard committed
492
493
494
495
496
497
498
499
500
## @fn DBFreeRes($sth)
# Function to cleanup DB query
#
# @param sth Statement handle to cleanup
sub DBFreeRes
{
	my $sth = shift;


501
502
503
504
505
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
506
507
508
509
510
511
	if ($sth) {
		$sth->finish();
	}
}


Nigel Kukard's avatar
Nigel Kukard committed
512

Nigel Kukard's avatar
Nigel Kukard committed
513
514
515
# Function to get table prefix
sub DBTablePrefix
{
516
517
518
519
520
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
521
522
523
524
	return $dbh->table_prefix();
}


Nigel Kukard's avatar
Nigel Kukard committed
525

Nigel Kukard's avatar
Nigel Kukard committed
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
#
# Value Added Functions
#


## @fn DBSelectNumResults($query)
# Return how many results came up from the specific SELECT query
#
# @param query Query to perform, minus "SELECT COUNT(*) AS num_results"
#
# @return Number of results, undef on error
sub DBSelectNumResults
{
	my $query = shift;


542
543
544
545
546
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
547
548
549
	# Prepare query
	my $sth;
	if (!($sth = $dbh->select("SELECT COUNT(*) AS num_results $query"))) {
550
		_error("Error executing select: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
551
		return;
Nigel Kukard's avatar
Nigel Kukard committed
552
553
554
555
556
	}

	# Grab row
	my $row = $sth->fetchrow_hashref();
	if (!defined($row)) {
557
		_error("Failed to get results from a select: ".$dbh->error());
Nigel Kukard's avatar
Nigel Kukard committed
558
		return;
Nigel Kukard's avatar
Nigel Kukard committed
559
560
561
562
563
564
565
566
567
568
	}

	# Pull number
	my $num_results = $row->{'num_results'};
	$sth->finish();

	return $num_results;
}


Nigel Kukard's avatar
Nigel Kukard committed
569

Nigel Kukard's avatar
Nigel Kukard committed
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
## @fn DBSelectSearch($query,$search,$filters,$sorts)
# Select results from database and return the total number aswell
#
# @param query Base query
#
# @param search Search hash ref
# @li Filter - Filter based on this...
# [filter] => Array (
#	[0] => Array (
#		[field] => Name
#		[data] => Array (
#			[type] => string
#			[value] => hi there
#		)
#	)
# )
# { 'data' => { 'comparison' => 'gt', 'value' => '5', 'type' => 'numeric' }, 'field' => 'ID' }
# @li Start - Start item number, indexed from 0 onwards
# @li Limit - Limit number of results
# @li Sort - Sort by this item
# @li SortDirection - Sort in this direction, either ASC or DESC
#
# @param filters Filter hash ref
# Hash:  'Column' -> 'Table.DBColumn'
#
# @param sorts Hash ref of valid sort criteria, indexed by what we get, pointing to the DB column in the query
# Hash:  'Column' -> 'Table.DBColumn'
#
# @return Number of results, undef on error
sub DBSelectSearch
{
	my ($query,$search,$filters,$sorts) = @_;


604
605
606
607
608
	if (!defined($dbh)) {
		_error("Database not initialized");
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
609
610
611
612
613
614
615
616
617
618
619
620
	# Stuff we need to add to the SQL query
	my @where; # Where clauses
	my $sqlWhere = "";
	my $sqlLimit = "";
	my $sqlOffset = "";
	my $sqlOrderBy = "";
	my $sqlOrderByDirection = "";

	# Check if we're searching
	if (defined($search) && ref($search)) {
		# Check it is a hash
		if (ref($search) ne "HASH") {
Nigel Kukard's avatar
Nigel Kukard committed
621
			_error("Parameter 'search' is not a HASH");
Nigel Kukard's avatar
Nigel Kukard committed
622
			return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
623
624
625
626
627
		}
		# Check if we need to filter
		if (defined($search->{'Filter'})) {
			# We need filters in order to use filtering
			if (!defined($filters)) {
Nigel Kukard's avatar
Nigel Kukard committed
628
				_error("Parameter 'search' element 'Filter' requires 'filters' to be defined");
Nigel Kukard's avatar
Nigel Kukard committed
629
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
630
631
632
633
			}

			# Check type of Filter
			if (ref($search->{'Filter'}) ne "ARRAY") {
Nigel Kukard's avatar
Nigel Kukard committed
634
				_error("Parameter 'search' element 'Filter' is of invalid type, it must be an ARRAY'");
Nigel Kukard's avatar
Nigel Kukard committed
635
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
636
637
638
639
640
641
642
643
644
645
			}

			# Loop with filters
			foreach my $item (@{$search->{'Filter'}}) {
				my $data = $item->{'data'};  # value, type, comparison
				my $field = $item->{'field'};
				my $column = $filters->{$field};

				# Check if field is in our allowed filters
				if (!defined($filters->{$field})) {
Nigel Kukard's avatar
Nigel Kukard committed
646
					_error("Parameter 'search' element 'Filter' has invalid field item '$field' according to 'filters'");
Nigel Kukard's avatar
Nigel Kukard committed
647
					return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
648
649
650
				}
				# Check data
				if (!defined($data->{'type'})) {
Nigel Kukard's avatar
Nigel Kukard committed
651
					_error("Parameter 'search' element 'Filter' requires field data element 'type' for field '$field'");
Nigel Kukard's avatar
Nigel Kukard committed
652
					return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
653
654
				}
				if (!defined($data->{'value'})) {
Nigel Kukard's avatar
Nigel Kukard committed
655
					_error("Parameter 'search' element 'Filter' requires field data element 'value' for field '$field'");
Nigel Kukard's avatar
Nigel Kukard committed
656
					return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
				}

				# match =, LIKE, IN (
				# matchEnd '' or )
				my $match;
				my $matchEnd = "";
				# value is the DBQuote()'d value
				my $value;

				# Check what type of comparison
				if ($data->{'type'} eq "boolean") {
					$match = '=';
					$value = DBQuote($data->{'value'});


				} elsif ($data->{'type'} eq "date") {

					# The comparison type must be defined
					if (!defined($data->{'comparison'})) {
Nigel Kukard's avatar
Nigel Kukard committed
676
						_error("Parameter 'search' element 'Filter' requires field data element 'comparison' for date field ".
Nigel Kukard's avatar
Nigel Kukard committed
677
								"'$field'");
Nigel Kukard's avatar
Nigel Kukard committed
678
						return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
679
680
681
682
683
684
685
686
687
688
689
					}

					# Check comparison type
					if ($data->{'comparison'} eq "gt") {
						$match = ">";

					} elsif ($data->{'comparison'} eq "lt") {
						$match = "<";

					} elsif ($data->{'comparison'} eq "eq") {
						$match = "=";
690
691
692
693
694
695

					} elsif ($data->{'comparison'} eq "ge") {
						$match = ">=";

					} elsif ($data->{'comparison'} eq "le") {
						$match = "<=";
Nigel Kukard's avatar
Nigel Kukard committed
696
697
698
					}
					# Convert to ISO format
					my $unixtime = str2time($data->{'value'});
699
700
					my @d = localtime($unixtime);
					$value = DBQuote(sprintf("%4d-%02d-%02d", $d[5]+1900, $d[4]+1, $d[3]));
Nigel Kukard's avatar
Nigel Kukard committed
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719


				} elsif ($data->{'type'} eq "list") {
					# Quote all values
					my @valueList;
					foreach my $i (split(/,/,$data->{'value'})) {
						push(@valueList,DBQuote($i));
					}

					$match = "IN (";
					# Join up 'xx','yy','zz'
					$value = join(',',@valueList);
					$matchEnd = ")";


				} elsif ($data->{'type'} eq "numeric") {

					# The comparison type must be defined
					if (!defined($data->{'comparison'})) {
Nigel Kukard's avatar
Nigel Kukard committed
720
						_error("Parameter 'search' element 'Filter' requires field data element 'comparison' for numeric field ".
Nigel Kukard's avatar
Nigel Kukard committed
721
								"'$field'");
Nigel Kukard's avatar
Nigel Kukard committed
722
						return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
723
724
725
726
727
728
729
730
731
732
733
					}

					# Check comparison type
					if ($data->{'comparison'} eq "gt") {
						$match = ">";

					} elsif ($data->{'comparison'} eq "lt") {
						$match = "<";

					} elsif ($data->{'comparison'} eq "eq") {
						$match = "=";
734
735
736
737
738
739

					} elsif ($data->{'comparison'} eq "ge") {
						$match = ">=";

					} elsif ($data->{'comparison'} eq "le") {
						$match = "<=";
Nigel Kukard's avatar
Nigel Kukard committed
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
					}

					$value = DBQuote($data->{'value'});


				} elsif ($data->{'type'} eq "string") {
					$match = "LIKE";
					$value = DBQuote("%".$data->{'value'}."%");

				}

				# Add to list
				push(@where,"$column $match $value $matchEnd");
			}

			# Check if we have any WHERE clauses to add ...
			if (@where > 0) {
				# Check if we have WHERE clauses in the query
				if ($query =~ /\sWHERE\s/i) {
					# If so start off with AND
					$sqlWhere .= "AND ";
				} else {
					$sqlWhere = "WHERE ";
				}
				$sqlWhere .= join(" AND ",@where);
			}
		}

		# Check if we starting at an OFFSET
		if (defined($search->{'Start'})) {
			# Check if Start is valid
			if ($search->{'Start'} < 0) {
Nigel Kukard's avatar
Nigel Kukard committed
772
				_error("Parameter 'search' element 'Start' invalid value '".$search->{'Start'}."'");
Nigel Kukard's avatar
Nigel Kukard committed
773
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
774
775
776
777
778
779
780
781
782
			}

			$sqlOffset = sprintf("OFFSET %i",$search->{'Start'});
		}

		# Check if results will be LIMIT'd
		if (defined($search->{'Limit'})) {
			# Check if Limit is valid
			if ($search->{'Limit'} < 1) {
Nigel Kukard's avatar
Nigel Kukard committed
783
				_error("Parameter 'search' element 'Limit' invalid value '".$search->{'Limit'}."'");
Nigel Kukard's avatar
Nigel Kukard committed
784
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
785
786
787
788
789
790
791
792
793
			}

			$sqlLimit = sprintf("LIMIT %i",$search->{'Limit'});
		}

		# Check if we going to be sorting
		if (defined($search->{'Sort'})) {
			# We need sorts in order to use sorting
			if (!defined($sorts)) {
Nigel Kukard's avatar
Nigel Kukard committed
794
				_error("Parameter 'search' element 'Filter' requires 'filters' to be defined");
Nigel Kukard's avatar
Nigel Kukard committed
795
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
796
797
798
799
			}

			# Check if sort is defined
			if (!defined($sorts->{$search->{'Sort'}})) {
Nigel Kukard's avatar
Nigel Kukard committed
800
				_error("Parameter 'search' element 'Sort' invalid item '".$search->{'Sort'}."' according to 'sorts'");
Nigel Kukard's avatar
Nigel Kukard committed
801
				return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
			}

			# Build ORDER By
			$sqlOrderBy = "ORDER BY ".$sorts->{$search->{'Sort'}};

			# Check for sort ORDER
			if (defined($search->{'SortDirection'})) {

				# Check for valid directions
				if (lc($search->{'SortDirection'}) eq "asc") {
					$sqlOrderByDirection = "ASC";

				} elsif (lc($search->{'SortDirection'}) eq "desc") {
					$sqlOrderByDirection = "DESC";

				} else {
Nigel Kukard's avatar
Nigel Kukard committed
818
					_error("Parameter 'search' element 'SortDirection' invalid value '".$search->{'SortDirection'}."'");
Nigel Kukard's avatar
Nigel Kukard committed
819
					return (undef,-1);
Nigel Kukard's avatar
Nigel Kukard committed
820
821
822
823
824
825
826
827
828
				}
			}
		}
	}

	# Select row count, pull out   "SELECT .... "  as we replace this in the NumResults query
	(my $queryCount = $query) =~ s/^\s*SELECT\s.*\sFROM/FROM/is;
	my $numResults = DBSelectNumResults("$queryCount $sqlWhere");
	if (!defined($numResults)) {
Nigel Kukard's avatar
Nigel Kukard committed
829
		return;
Nigel Kukard's avatar
Nigel Kukard committed
830
831
832
833
834
	}

	# Add Start, Limit, Sort, Direction
	my $sth = DBSelect("$query $sqlWhere $sqlOrderBy $sqlOrderByDirection $sqlLimit $sqlOffset");
	if (!defined($sth)) {
Nigel Kukard's avatar
Nigel Kukard committed
835
		return;
Nigel Kukard's avatar
Nigel Kukard committed
836
837
838
839
840
841
	}

	return ($sth,$numResults);
}


Nigel Kukard's avatar
Nigel Kukard committed
842

Nigel Kukard's avatar
Nigel Kukard committed
843
1;