DBLayer.pm 13.8 KB
Newer Older
1
2
# AWITPT DataObj backend for DBLayer
# Copyright (C) 2014-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
#
# 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 3 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, see <http://www.gnu.org/licenses/>.

=encoding utf8

=head1 NAME

21
AWITPT::DataObj::Backend::DBLayer - AWITPT DataObj backend for DBLayer
Nigel Kukard's avatar
Nigel Kukard committed
22
23
24
25
26
27

=head1 SYNOPSIS

	#
	# Create a child class
	#
28
	package DataObj::myobject;
Nigel Kukard's avatar
Nigel Kukard committed
29
30
31
32

	use strict;
	use warnings;

33
34
35
	use AWITPT::DataObj::Backend::DBLayer 1.00;
	use parent, -norequire 'AWITPT::DataObj::Backend::DBLayer';

Nigel Kukard's avatar
Nigel Kukard committed
36
37
38
39
40
41
42
43
	our $VERSION = '1.00';

	# Return the configuration for this object
	sub config
	{
		my $config = {
			# Set table name
			'table' => "testtable",
44
45
			# Optional: set column mapping
			'table_columns' => { 'Property1' => "property_column", 'Property2' => "property_column2" },
Nigel Kukard's avatar
Nigel Kukard committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
			# Setup our data definition
			'properties' => {
				'ID' => {
					'options' => DATAOBJ_PROPERTY_ID
				},
				'Name' => {
					'validate' => { 'type' => 'text', 'length' => 2 }
				}
			}
		};
		return $config;
	}

=head1 DESCRIPTION

61
62
The C<AWITPT::DataObj::Backend::DBLayer> class provides an abstraction layer between a data definition and the underlying database, allowing easy
access to table data. This class inherits all methods from C<AWITPT::DataObj>.
Nigel Kukard's avatar
Nigel Kukard committed
63
64
65
66

=cut


67
package AWITPT::DataObj::Backend::DBLayer;
Nigel Kukard's avatar
Nigel Kukard committed
68
69
70
71

use strict;
use warnings;

72
73
use AWITPT::DataObj 3.01;
use parent -norequire, 'AWITPT::DataObj';
Nigel Kukard's avatar
Nigel Kukard committed
74

Nigel Kukard's avatar
Nigel Kukard committed
75

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

78
79
our (@ISA,@EXPORT,@EXPORT_OK);
@EXPORT = qw(
Nigel Kukard's avatar
Nigel Kukard committed
80
81
82
83
);
@EXPORT_OK = qw(
);

84

Nigel Kukard's avatar
Nigel Kukard committed
85
86
87
88
89
90
91
92
93
94
use AWITPT::Util 2.00 qw(
		hashifyLCtoMC
);
use AWITPT::DB::DBLayer;
use Data::Dumper;



=head1 METHODS

95
C<AWITPT::DataObj::Backend::DBLayer> provides the below manipulation methods.
Nigel Kukard's avatar
Nigel Kukard committed
96
97
98
99
100
101
102
103
104
105
106
107

=cut



=head2 config

	# Data object configuration
	sub config
	{
		retrun {
			'table' => "mytable"
108
			'table_columns' => { 'Property1' => "property_column", 'Property2' => "property_column2" },
Nigel Kukard's avatar
Nigel Kukard committed
109
			'properties' => {
110
111
112
113
114
				'Description' => {
					<OPTIONS>,
					<VALIDATION>,
					<RELATIONS>
				}
Nigel Kukard's avatar
Nigel Kukard committed
115
116
117
118
			}
		}
	}

119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
See L<AWITPT::DataObj> for additional options, validation and relations.

=head3 Table Name

The table name is specified using the 'table' configuration option.

	'table' => "tableNameHere'


=head3 Table Column Mapping

Sometimes properties do not have the same column name. In this case we can specify a property to column mapping.

	'table_columns' => { 'PropertyName' => 'ColumnName' },

NB: Capitalization here is very important!
Nigel Kukard's avatar
Nigel Kukard committed
135

136
=back
Nigel Kukard's avatar
Nigel Kukard committed
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

=cut



=head2 table

	print(STDERR "Table: ".$dataObj->table());

The C<table> method returns the data object table name.

=cut

# Return table name
sub table
{
	my $self = shift;


	return $self->{'_table'};
}



=head2 records

	my @records = $dataObj->records();

The C<records> method returns an array of data object records.

=cut

# Get records as an array of objects
sub records
{
	my $self = shift;


175
176
177
178
179
	# Get list of columns we need
	my @columns = $self->_tableProperties2Columns(
		$self->_propertiesWithout(DATAOBJ_PROPERTY_NOLOAD)
	);

Nigel Kukard's avatar
Nigel Kukard committed
180
181
182
183
184
185
186
187
	# Do select query
	my ($sth,$numResults) = DBSelectSearch(
		sprintf("
				SELECT
					%s
				FROM
					%s
			",
188
			join(',',@columns),
Nigel Kukard's avatar
Nigel Kukard committed
189
			$self->table()
Nigel Kukard's avatar
Nigel Kukard committed
190
191
192
193
194
		)
	);

	# Make sure we have a result
	if (!defined($numResults)) {
Nigel Kukard's avatar
Nigel Kukard committed
195
196
		my $error = AWITPT::DB::DBLayer::error();
		$self->_error("Database query failed: '$error'");
Nigel Kukard's avatar
Nigel Kukard committed
197
		$self->_log(DATAOBJ_LOG_WARNING,"Database query failed: %s",$error);
Nigel Kukard's avatar
Nigel Kukard committed
198
199
200
201
		return;
	}

	# Add each row as another record
202
203
204
205
	my @records = ( );
	while (my $row = hashifyLCtoMC($sth->fetchrow_hashref(),@columns)) {
		# Translate hash from row to record
		my $data = $self->_tableRow2Record($row);
Nigel Kukard's avatar
Nigel Kukard committed
206
		# We use clone to clone the current child class, and reset to reset the object entirely
207
		my $record = $self->clone()->reset()->_loadHash($data);
Nigel Kukard's avatar
Nigel Kukard committed
208
209
210
211
212
213
214
215
216
217
218
219
220
221
		push(@records,$record);
	}

	return \@records;
}



=head2 load

	$dataObj->load($id);

	$dataObj->load('Name' => 'Joe Soap');

Nigel Kukard's avatar
Nigel Kukard committed
222
The C<load> method is used to load a single record from the database. It has 2 forms of invocation, either by specifying one
Nigel Kukard's avatar
Nigel Kukard committed
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
parameter which is assumed to be the value of the ID field, or by specifying a hash of key-value pairs.

Only the first matching record is returned, if multiple records exist the result can be any one of them being returned.

=cut

# Load Record
# - The load defaults to loading on ID, but a hash can be provided to load on various matches
sub load
{
	my ($self,@params) = @_;


	my %matches;

	# One param means that we're just grabbing an ID
	if (@params == 1) {
240
241
242
243
244
245
246
247
248
249
250
251
252
		# Validate the ID property name
		my $IDProperty = $self->_property_id();
		if (!defined($IDProperty)) {
			# Report error and return
			$self->_error("Invalid invocation of load(), object has no property with option DATAOBJ_PROPERTY_ID");
			$self->_log(DATAOBJ_LOG_ERROR,
				"Invalid invocation of load(), object has no property with option DATAOBJ_PROPERTY_ID");
			return;
		}
		# Grab column name for the ID property
		my $IDColumn = $self->_tableProperty2Column($IDProperty);
		$matches{$IDColumn} = shift(@params);

Nigel Kukard's avatar
Nigel Kukard committed
253
254
255
256
257
258
259
260
	# More params, means we grabbing based on a "search"
	} else {
		%matches = @params;
	}

	# Build SQL statement
	my @whereItems;
	my @whereValues;
261
262
263
264
	foreach my $property (keys %matches) {
		# Grab column name
		my $column = $self->_tableProperty2Column($property);
		# Add to where arrays we'll use later
Nigel Kukard's avatar
Nigel Kukard committed
265
		push(@whereItems,"$column = ?");
266
		push(@whereValues,$matches{$property});
Nigel Kukard's avatar
Nigel Kukard committed
267
268
	}

269
270
271
272
273
	# Get list of columns we need
	my @columns = $self->_tableProperties2Columns(
		$self->_propertiesWithout(DATAOBJ_PROPERTY_NOLOAD)
	);

Nigel Kukard's avatar
Nigel Kukard committed
274
275
276
277
278
279
280
281
282
283
	# Do SQL select
	my $sth = DBSelect(
		sprintf('
				SELECT
					%s
				FROM
					%s
				WHERE
					%s
			',
284
			join(',',@columns),
Nigel Kukard's avatar
Nigel Kukard committed
285
			$self->table(),
Nigel Kukard's avatar
Nigel Kukard committed
286
287
288
289
290
			join(' AND ',@whereItems)
		),
		@whereValues
	);

Nigel Kukard's avatar
Nigel Kukard committed
291
292
293
294
	# Check result
	if (!defined($sth)) {
		my $error = AWITPT::DB::DBLayer::error();
		$self->_error("Database query failed: '$error'");
Nigel Kukard's avatar
Nigel Kukard committed
295
		$self->_log(DATAOBJ_LOG_WARNING,"Database query failed: %s",$error);
Nigel Kukard's avatar
Nigel Kukard committed
296
297
298
		return;
	}

Nigel Kukard's avatar
Nigel Kukard committed
299
	# Grab row
300
301
302
	my $row = hashifyLCtoMC($sth->fetchrow_hashref(),@columns);
	# Translate hash from row to record
	my $data = $self->_tableRow2Record($row);
Nigel Kukard's avatar
Nigel Kukard committed
303

304
305
	# Load the hash into the object
	$self->_loadHash($data);
Nigel Kukard's avatar
Nigel Kukard committed
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327

	return $self;
}



=head2 commit

	$dataObj->commit();

The C<commit> method is used to commit the record to the database, this means updating it if it exists or inserting it if it does
not yet exist.


On success this method will return the L<AWITPT::DB::DBLayer> result for DBUpdate or DBInsert. When no data has changed a string
containing "0E0" will be returned. On error undef on will be returned.

=cut

# Commit record to database
sub commit
{
328
329
	my ($self,@params) = @_;

Nigel Kukard's avatar
Nigel Kukard committed
330

331
332
	# We must call the parent _commit()
	$self->SUPER::commit(@params);
Nigel Kukard's avatar
Nigel Kukard committed
333
334
335
336
337
338

	# Abort if we don't have updates
	my $changed = $self->changed();
	my %data;

	# Loop with changed and add to data
339
	foreach my $property ($self->_propertiesWithout(DATAOBJ_PROPERTY_NOSAVE)) {
Nigel Kukard's avatar
Nigel Kukard committed
340
		# If its a changed item add it to the data we going to pass to the DB
341
342
343
344
345
346
		if (exists($changed->{$property})) {
			# Get column name
			my $column = $self->_tableProperty2Column($property);
			# Add property data
			$data{$column} = $changed->{$property};
			$self->_log(DATAOBJ_LOG_DEBUG2,"Property '%s' changed, column '%s' added to commit",$property,$column);
Nigel Kukard's avatar
Nigel Kukard committed
347
348
		}
	}
Nigel Kukard's avatar
Nigel Kukard committed
349
	# If we have no values which changed, return 0E0
Nigel Kukard's avatar
Nigel Kukard committed
350
351
352
353
354
355
356
357
358
359
	if (!%data) {
		return "0E0";
	}

	# We have an ID so its an update
	my $res;
	if (my $id = $self->getID()) {

		# Update database record
		if (!defined($res = DBUpdate($self->table(),$id,%data))) {
Nigel Kukard's avatar
Nigel Kukard committed
360
361
			my $error = AWITPT::DB::DBLayer::error();
			$self->_error("Database update failed: '$error'");
Nigel Kukard's avatar
Nigel Kukard committed
362
			$self->_log(DATAOBJ_LOG_WARNING,"Database update failed: %s",$error);
Nigel Kukard's avatar
Nigel Kukard committed
363
364
365
			return;
		}

Nigel Kukard's avatar
Nigel Kukard committed
366
		$self->_log(DATAOBJ_LOG_DEBUG2,"Updating table '%s' row ID '%s' with: %s",$self->table(),$id,Dumper(\%data));
Nigel Kukard's avatar
Nigel Kukard committed
367
368
369
370
371
372
373


	# No ID means its an insert
	} else {

		# Insert database record
		if (!defined($res = DBInsert($self->table(),%data))) {
Nigel Kukard's avatar
Nigel Kukard committed
374
375
			my $error = AWITPT::DB::DBLayer::error();
			$self->_error("Database insert failed: '$error'");
Nigel Kukard's avatar
Nigel Kukard committed
376
			$self->_log(DATAOBJ_LOG_WARNING,"Database insert failed: %s",$error);
Nigel Kukard's avatar
Nigel Kukard committed
377
378
379
			return;
		}

380
381
382
383
384
		# Check if we have an ID property
		if (defined(my $IDProperty = $self->_property_id())) {
			# If we do set it to $res, which is the LastID returned by the above
			$self->_set($IDProperty,$res);
		}
Nigel Kukard's avatar
Nigel Kukard committed
385

386
		$self->_log(DATAOBJ_LOG_DEBUG2,"Inserted into table '%s' row ID '%s' with: %s",$self->table(),$res,Dumper(\%data));
Nigel Kukard's avatar
Nigel Kukard committed
387
388
389
390
391
392
393
394
395
396
397
398
399
	}

	return $res;
}



=head2 remove

	$dataObj->remove();

	$dataObj->remove('Name' => "Sam", 'Surname' => "Soap");

Nigel Kukard's avatar
Nigel Kukard committed
400
401
The C<remove> method is used to remove the data object from the database. The function can take an optional set of parameters which
will be used in the SQL DELETE WHERE statement instead of using the current object ID.
Nigel Kukard's avatar
Nigel Kukard committed
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419

If no paremeters are given the current object ID is removed and the ID property removed from the data object. If a set of optional
parameters is given, the ID property is NOT removed.

=cut

# Remove Record
# - The remove defaults to removing on ID, but a hash can be provided to load on various matches
sub remove
{
	my ($self,@params) = @_;


	my %matches;

	# Are we going to remove the ID from this object at the end on success?
	my $removeID = 0;

420
	# If we don't have any params, we are removing ourselves
Nigel Kukard's avatar
Nigel Kukard committed
421
422
423
424
425
426
427
428
	if (!@params) {
		# We can only remove ourselves if our ID is set
		my $id = $self->getID();
		if (defined($id) && $id > 0) {
			$matches{'ID'} = $self->getID();
			$removeID = 1;
		} else {
			$self->_error("Failed to remove object, no ID set");
429
			$self->_log(DATAOBJ_LOG_ERROR,"Failed to remove object from database, no ID is set");
Nigel Kukard's avatar
Nigel Kukard committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
			return;
		}

	# One param means that we're just deleting by ID
	} elsif (@params == 1) {
		$matches{'ID'} = shift(@params);

	# More params, means we grabbing based on a "search"
	} else {
		%matches = @params;
	}

	# Build SQL statement
	my @whereItems;
	my @whereValues;
445
446
447
448
	foreach my $property (keys %matches) {
		# Grab column name
		my $column = $self->_tableProperty2Column($property);
		# Add to where arrays we'll use later
Nigel Kukard's avatar
Nigel Kukard committed
449
		push(@whereItems,"$column = ?");
450
		push(@whereValues,$matches{$property});
Nigel Kukard's avatar
Nigel Kukard committed
451
452
	}

Nigel Kukard's avatar
Nigel Kukard committed
453
	$self->_log(DATAOBJ_LOG_DEBUG2,"Removing record from table '%s' with: %s",$self->table(),Dumper(\%matches));
Nigel Kukard's avatar
Nigel Kukard committed
454
455
456
457
458
459
460
461
462

	# Do SQL delete
	my $rows = DBDo(
		sprintf('
				DELETE FROM
					%s
				WHERE
					%s
			',
Nigel Kukard's avatar
Nigel Kukard committed
463
			$self->table(),
Nigel Kukard's avatar
Nigel Kukard committed
464
465
466
467
468
469
470
			join(' AND ',@whereItems)
		),
		@whereValues
	);

	# Make sure we got something back
	if (!defined($rows)) {
471
		$self->_error("Database remove failed: %s",AWITPT::DB::DBLayer::error());
Nigel Kukard's avatar
Nigel Kukard committed
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
		return;
	}

	# If we should remove the ID signifying we not in the db, then do it
	if ($removeID) {
		$self->_set('ID',undef);
	}

	# Return number removed
	return $rows;
}



#
# INTERNAL METHODS BELOW
#



# Reset internals of the object
sub _init
{
Nigel Kukard's avatar
Nigel Kukard committed
495
	my ($self,@params) = @_;
Nigel Kukard's avatar
Nigel Kukard committed
496
497


498
	# Initialize parent, VERY important
Nigel Kukard's avatar
Nigel Kukard committed
499
	$self->SUPER::_init(@params);
Nigel Kukard's avatar
Nigel Kukard committed
500

501
502
	# Grab our configuration so we can initialize our customizations
	my $config = $self->config();
Nigel Kukard's avatar
Nigel Kukard committed
503
504
505
506

	# First, lets see if we have a mandatory table to set
	if (!defined($config->{'table'})) {
		$self->_log(DATAOBJ_LOG_ERROR,"No 'table' defined!");
507
		return;
Nigel Kukard's avatar
Nigel Kukard committed
508
	}
509

Nigel Kukard's avatar
Nigel Kukard committed
510
511
	# Set the table name
	$self->{'_table'} = $config->{'table'};
512
	$self->_addInternalProperty('_table');
Nigel Kukard's avatar
Nigel Kukard committed
513

514
515
516
517
518
519
520
521
522
523
524
525
	# Set the table column mapping
	$self->{'_table_map_property2column'} = $config->{'table_columns'} // { };
	$self->_addInternalProperty('_table_map_property2column');

	# Create reverse mapping of table columns to property
	$self->{'_table_map_column2property'} = { };
	$self->_addInternalProperty('_table_map_column2property');
	foreach my $property ($self->_properties()) {
		my $column = $self->_tableProperty2Column($property);
		$self->{'_table_map_column2property'}->{$column} = $property;
	}

Nigel Kukard's avatar
Nigel Kukard committed
526
527
528
529
530
	return $self;
}



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
# Return table column mapping for a property
sub _tableProperty2Column
{
	my ($self,$property) = @_;


	return $self->{'_table_map_property2column'}->{$property} // $property;
}



# Return table property mapping for a column
sub _tableColumn2Property
{
	my ($self,$column) = @_;


	return $self->{'_table_map_column2property'}->{$column} // $column;
}



# Return table columns
sub _tableProperties2Columns
{
	my ($self,@properties) = @_;


	my @columns;

	# Retrieve and translate properties into columns
	foreach my $property (@properties) {
		push(@columns,$self->_tableProperty2Column($property));
	}

	return @columns;
}



# Return row from a record
sub _tableRecord2Row
{
	my ($self,$record) = @_;


	my $row = { };

	# Re-key the hash with property names
	foreach my $item (keys %{$row}) {
		my $newKey = $self->_tableProperty2Column($item);
		$row->{$newKey} = $record->{$item};
	}

	return $row;
}



# Return record from row
sub _tableRow2Record
{
	my ($self,$row) = @_;


	my $record = { };

	# Re-key the hash with property names
	foreach my $item (keys %{$row}) {
		my $newKey = $self->_tableColumn2Property($item);
		$record->{$newKey} = $row->{$item};
	}

	return $record;
}


Nigel Kukard's avatar
Nigel Kukard committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622

1;
__END__

=head1 AUTHORS

Nigel Kukard E<lt>nkukard@lbsd.netE<gt>

=head1 BUGS

All bugs should be reported via the project issue tracker
L<http://gitlab.devlabs.linuxassist.net/awit-frameworks/awit-perl-toolkit/issues/>.

=head1 LICENSE AND COPYRIGHT

623
Copyright (C) 2014-2017, AllWorldIT
Nigel Kukard's avatar
Nigel Kukard committed
624
625
626
627
628
629
630
631
632
633
634

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 3 of the License, or
(at your option) any later version.

=head1 SEE ALSO

L<AWITPT::DB::DBLayer>.

=cut