summaryrefslogtreecommitdiffstats
path: root/lib/Jaos/DBI.pm
blob: 6fcdad6bd090e3bdaf7c41deee18f15126dd5f6c (plain)
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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
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
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
package Jaos::DBI;
use strict;
use warnings;
use Carp;
use vars qw($cache);
use base qw/Class::Data::Inheritable Class::Accessor/;
use DBI ();

our $VERSION = 0.3.2;
our $if_active = ($DBI::VERSION >= '1.40') ? 3 : 0;
$cache = {};

=head1 NAME

Jaos::DBI - Jaos DBI object similar to Class::DBI

=head1 SYNOPSIS

  # subclassing
  package Users;
  use base qw/Jaos::DBI/;
  use strict;
  use warnings;

  __PACKAGE__->db_dsn('dbi:Pg:dbname=foo');
  __PACKAGE__->db_user('you');
  __PACKAGE__->db_password('secret');
  __PACKAGE__->db_options({RaiseError => 0, AutoCommit => 1, PrintError => 0});

  __PACKAGE__->table('users');
  __PACKAGE__->columns(qw/id nick password email logged_in role/);
  __PACKAGE__->primary_column('id');
  __PACKAGE__->virtual_columns(qw/join_id join_name/);
  __PACKAGE__->sequence('users_id_seq');
  __PACKAGE__->base_select('select a.*,b.join_id,b.join_name from foo a join bar b on a.id=b.foo');
  __PACKAGE__->has_a(role => 'Role');
  __PACKAGE__->manual_update(1); # 0/1
  __PACKAGE__->cache(1); # 0/1
  __PACKAGE__->cache_servers( qw/ 127.0.0.1:11211 10.1.1.2:11212 / );
  __PACKAGE__->compress_threshold( 10_000 );
  __PACKAGE__->cache_expires(60); # in seconds

  __PACKAGE__->setup(); # initiates database connection callback and accessors
  1;

  # using subclass
  use Users;

  # examine the class properties
  print "table: ", Users->table, "\n";
  print "columns: ", join(',', Users->columns ), "\n";
  print "primary key: ", Users->primary_column, "\n";
  print "virtual columns: ", join(',', Users->virtual_columns ), "\n";

  # retrieve objects
  # using various search options
  my @objs = Users->search(email => 'foo@bar.com',{ order_by => 'id', limit => '2'});
  my @objs = Users->search_like(email => '%@bar.com',{ order_by => 'id', limit => '2'});
  my @objs = Users->search_ilike(email => '%@bar.com',{ order_by => 'id', offset => '2'});
  my @objs = Users->search_or(email => 'john.doe@bar.com', name => 'john');
  my @objs = Users->search_or_like(email => 'john.doe@%', name => '%john%');
  my @objs = Users->search_or_ilike(email => 'john.doe@%', name => '%john%');
  my @objs = Users->search_where('name in (select name from other_user_table)');
  # all
  my @objs = Users->retrieve_all();
  # by primary column value (primary key)
  my $obj = Users->retrieve($id);

  # insert (or alias create)
  my $user = Users->insert(nick => 'zaphod', email => 'foo@bar.org');
  my $user = Users->create(nick => 'zaphod', email => 'foo@bar.org');
  $user = Users->find_or_create(nick => 'zaphod', email => 'foo@bar.org');

  # modify
  $user->email('newaddress@foo.com'); # setting attribute updates the database
  $user->delete();
  $user->update() unless $user->manual_update;
  $user->update() if $user->is_changed;
  User->delete(nick => 'zaphod', email => 'newaddress@foo.com');

=head1 DESCRIPTION

Jaos::DBI provides a convenient abstraction layer to a database in the same
vein as Class::DBI and its spinoffs.

The aim is to keep it simple and avoid the db statement hit from Class::DBI
and make it easier to use views, complex sql joins for basic class definitions,
and get rid of the large requirements for external modules used by Class::DBI.

Cache::Memcached is used optionally for network available object caching.

=cut

__PACKAGE__->mk_classdata('_table');
__PACKAGE__->mk_classdata('_columns');
__PACKAGE__->mk_classdata('_virtual_columns');
__PACKAGE__->mk_classdata('_primary_column');
__PACKAGE__->mk_classdata('_sequence');
__PACKAGE__->mk_classdata('_db_handle');
__PACKAGE__->mk_classdata('_db_dsn');
__PACKAGE__->mk_classdata('_db_user');
__PACKAGE__->mk_classdata('_db_password');
__PACKAGE__->mk_classdata('_db_options');
__PACKAGE__->mk_classdata('_base_select');
__PACKAGE__->mk_classdata('_manual_update' => 0); # 0/1
__PACKAGE__->mk_classdata('_is_changed' => 0); # 0/1
__PACKAGE__->mk_classdata('_has_a');
__PACKAGE__->mk_classdata('_cache');
__PACKAGE__->mk_classdata('_cache_servers' => ['127.0.0.1:11211']);
__PACKAGE__->mk_classdata('_compress_threshold' => 10_000);
__PACKAGE__->mk_classdata('_cache_expires' => 60); # in seconds

=head1 METHODS

=head2 setup

Initializes the Class; creates a database handle callback and sets up the accessors for columns, primary_column, and virtual_columns.  Must have a table name, dsn, user, and pass specified prior to calling __PACKAGE__->setup().

=cut 

sub setup
{
  my $class = shift;

  my @columns = $class->columns;
  push @columns,$class->primary_column if $class->primary_column;
  push @columns,$class->virtual_columns if $class->virtual_columns;
  $class->mk_accessors(@columns);
  $class->mk_classdata(
    '_jaos_dbh' => sub {
      unless ($class->_db_handle && $class->_db_handle->ping) {
        $class->_db_handle(DBI->connect_cached(
          $class->_db_dsn,
          $class->_db_user,
          $class->_db_password,
          $class->_db_options
        )) or croak $DBI::errstr;
      }
      return $class->_db_handle;
    }
  );

  my $self = $class->SUPER::new(@_);

  return $self;
}

=head2 db_dsn

Get or set the database dsn.

 __PACKAGE__->db_dsn('dbi:Pg:dbname=foo');

=cut

sub db_dsn
{
  my $self = shift;
  if (@_) {
    $self->_db_dsn(@_);
  }
  $self->_db_dsn();
}

=head2 db_user

Get or set the database user.

 __PACKAGE__->db_user('user');

=cut

sub db_user
{
  my $self = shift;
  if (@_) {
    $self->_db_user(@_);
  }
  $self->_db_user();
}

=head2 db_password

Get or set the database password.

 __PACKAGE__->db_passwd('secret');

=cut

sub db_password
{
  my $self = shift;
  if (@_) {
    $self->_db_password(@_);
  }
  $self->_db_password();
}

=head2 db_options

Get or set the database options.

 __PACKAGE__->db_options({ Autocommit => 1});

=cut

sub db_options
{
  my $self = shift;
  if (@_) {
    $self->_db_options(@_);
  }
  $self->_db_options();
}

=head2 base_select

This sets the basic select statement that is used to retrieve information.  This can be used to create complex joins or subselects that further where clauses can be built from.

 __PACKAGE__->base_select('select a.*,b.field from table a left join table2 b on a.field=b.field');

=cut

sub base_select
{
  my $self = shift;
  if (@_) {
    $self->_base_select(@_);
  }
  $self->_base_select();
}

=head2 table

Gets or sets the table name for the subclass or instance.

 __PACKAGE__->table('foo');
 my $table = __PACKAGE__->table();

=cut

sub table
{
  my $self = shift;
  if (@_) {
    $self->_table(@_);
  }
  $self->_table();
}

=head2 columns

Get or set the tables column names.

 __PACKAGE_->columns(qw/one two three/);
 my @columns = __PACKAGE__->columns();

=cut

sub columns
{
  my $self = shift;
  if (@_) {
    $self->_columns([@_]);
  }
  @{$self->_columns() || [] };
}

=head2 primary_column

Get or set the tables primary column;

 __PACKAGE_->primary_column('id);

=cut

sub primary_column
{
  my $self = shift;
  if (@_) {
    $self->_primary_column(@_);
  }
  $self->_primary_column();
}

=head2 virtual_columns

These are virtual columns that may result from a base_select join.  Accessors will be created for them just as if they were columns.

 __PACKAGE__->virtual_columns(qw/join_id join_name/);

=cut

sub virtual_columns
{
  my $self = shift;
  if (@_) {
    $self->_virtual_columns([@_]);
  }
  @{$self->_virtual_columns() || [] };
}

=head2 manual_update

Get or set the option to stop auto update on modification. Must call __PACKAGE__->update() manually.

=cut

sub manual_update
{
  my $self = shift;
  if (@_) {
    $self->_manual_update(@_);
  }
  $self->_manual_update();
}

=head2 is_changed

Returns true if object has been modified.

=cut

sub is_changed
{
  my $self = shift;
  if (@_) {
    $self->_is_changed(@_);
  }
  $self->_is_changed();
}

=head2 sequence

Get or set the tables sequence.  This is used to generate unique primary keys.

 __PACKAGE__->sequence('users_id_seq');

=cut

sub sequence
{
  my $self = shift;
  if (@_) {
    $self->_sequence(@_);
  }
  $self->_sequence() || undef;
}

=head2 sequence_nextval

Returns the next value for the tables sequence.

 my $new_id = __PACKAGE__->sequence_nextval();

=cut

sub sequence_nextval
{
  my ($self) = @_;
  return undef unless $self->sequence;

  my $sql = 'select nextval(\'' . $self->sequence .'\')';
  my $val = $self->_jaos_dbh()->()->selectrow_arrayref($sql);
  return $val->[0] ? $val->[0] : undef;
}

=head2 sequence_currval

Returns the current value for the tables sequence.

 my $current_id = __PACKAGE__->sequence_currval();

=cut

sub sequence_currval
{
  my ($self) = @_;
  return undef unless $self->sequence;

  my $sql = 'select currval(\'' . $self->sequence .'\')';
  my $val = $self->_jaos_dbh()->()->selectrow_arrayref($sql);
  return $val->[0] ? $val->[0] : undef;
}

=head2 prepare

Returns a statement handle for the specified sql;

 __PACKAGE__->prepare('select * from foo');

=cut

sub prepare
{
  my $self = shift;
  my $sql = shift;

  $self->_jaos_dbh()->()->prepare_cached($sql);
}

=head2 insert

Inserts a row into the database, returning an object representing that row.  This calls __PACKAGE__->sequence_nextval for the primary column.

 my $new_obj = __PACKAGE__->insert(column1 => $value1, column2 => $value2);

=cut

sub insert
{
  my ($self,%opts) = @_;
  my $table = $self->table;
  my @columns = keys %opts;
  my $sql = "insert into $table (";
  my $seq = undef;

  $seq = $self->sequence_nextval();

  if ($seq) {
    push @columns, $self->primary_column;
    $opts{$self->primary_column} = $seq;
  }
  $sql .= join(',',@columns) . ') values (';
  $sql .= join(',',('?') x scalar(keys %opts)) . ')';

  eval {
    my $stmt = $self->prepare($sql) or croak "Faild to prepare [$sql]";
    $stmt->execute(map {$opts{$_} ? $opts{$_} : undef} @columns) or $stmt->finish(),croak "[$sql]" . $!;
    $stmt->finish();
  };
  if ($@) {
    carp $@;
    return undef;
  };

  $seq = $self->sequence_currval();
  
  if ($seq) {
    return $self->_add_obj_to_cache($self->retrieve($seq));
  } else {
    if (my ($r) = $self->search(%opts)) {
      return $self->_add_obj_to_cache($r);
    }
    return undef;
  }
}

=head2 create

Alias to insert.

=cut

sub create
{
  my $self = shift;
  $self->insert(@_);
}

=head2 find_or_create

This attempts to find a row with the column values specified, or creates one.  Calls __PACKAGE__->search(@_) and __PACKAGE__->insert(@_) if search returns undef.

 my $obj = __PACKAGE__->find_or_create(column1 => $value, column2 => $value);

=cut

sub find_or_create
{
  my $self = shift;
  my $table = $self->table;

  if (my ($r) = $self->search(@_)) {
    return $self->_add_obj_to_cache($r);
  }
  return $self->insert(@_);
}

=head2 search

Searches the table and returns a list of matching objects.

 my @objs = __PACKAGE__->search(column1 => $value1, column2 => $value2,{ order_by => 'col3', offset => 10, limit => 10 });

 Supports optional hashref passed as the last argument, within which order_by, offset, and limit may be specified.

=cut

sub search
{
  my $self = shift;
  return $self->_do_search('and','=',undef,@_);
}

=head2 search_like

Searches the table and returns a list of matching objects using column like $value rather than column = $value.

 my @objs = __PACKAGE__->search_like(column1 => "%$value1%", column2 => "%$value2%");

=cut

sub search_like
{
  my $self = shift;
  return $self->_do_search('and','like',undef,@_);
}

=head2 search_ilike

same as search_like but insensitive

=cut

sub search_ilike
{
  my $self = shift;
  return $self->_do_search('and','ilike',undef,@_);
}

=head2 search_or

search where given key/values use or instead of and

=cut

sub search_or
{
  my $self = shift;
  return $self->_do_search('or','=',undef,@_);
}

=head2 search_or_like

search where given like key/values use or instead of and

=cut

sub search_or_like
{
  my $self = shift;
  return $self->_do_search('or','like',undef,@_);
}

=head2 search_or_ilike

search insensitive where given ilike key/values use or instead of and

=cut

sub search_or_ilike
{
  my $self = shift;
  return $self->_do_search('or','ilike',undef,@_);
}

=head2 search_where

Searches the table and returns a list of matching objects using the specified where clause

 my @objs = __PACKAGE__->search_where('id = foo');

=cut

sub search_where
{
  my $self = shift;
  return $self->_do_search(undef,undef,@_);
}

sub _do_search
{
  my ($self,$join,$type,$where,@opts) = @_;
  my $class = ref($self) || $self;
  my $table = $self->table;
  my $sql = $self->base_select || "select * from $table";
  my @values = ();

  my ($search_opts,%data,@columns);
  if (@opts) {
    $search_opts = @opts % 2 ? pop @opts : {};
    %data = @opts;
    @columns = (keys %data) if %data;
  }

  if ($where) {
    $sql .= ' where ' . $where;
  } elsif (@columns) {
    $sql .= ' where ';
    $sql .= join(" $join ",map { "$_ $type ?" } @columns);
  }
  if ($search_opts) {
    $sql .= " order by $search_opts->{order_by}" if $search_opts->{order_by};
    $sql .= " limit $search_opts->{limit}" if $search_opts->{limit};
    $sql .= " offset $search_opts->{offset}" if $search_opts->{offset};
  }

  if (@columns) {
    @values = map {$data{$_} ? $data{$_} : undef} @columns;
  }

  my $result = [];
  eval {
    my $stmt = $self->prepare($sql) or croak "Failed to prepare [$sql]";
    $stmt->execute(@values) or $stmt->finish(),croak "[$sql]" . $!;
    $result = [ map { $class->SUPER::new($_) } @{$stmt->fetchall_arrayref({})} ];
    $stmt->finish();
  };
  if ($@) {
    carp $@;
    return ();
  }
  
  return (scalar(@$result) > 0) ? @$result : ();

}

=head2 delete

Deletes either the referring object, if called as $obj->delete, or provides a class method to delete all all rows matching the arguments if called as __PACKAGE__->delete();

 $obj->delete();
 __PACKAGE__->delete(column1 => $value1, column2 => $value2);

=cut

sub delete
{
  my ($self,%opts) = @_;
  my $table = $self->table;
  my $sql = undef;
  my @values = ();

  if (%opts) {
    my @columns = keys %opts;

    $sql = "delete from $table where ";
    $sql .= join(' and ', map { "$_ = ?" } @columns);

    @values = map { $opts{$_} ? $opts{$_} : undef } @columns;
  } elsif (ref $self) {

    $sql = "delete from $table where ";
    if ( $self->primary_column ) {
      $sql .= $self->primary_column() . ' = ?';
    } else {
      $sql .= join(' and ',map { "$_ = ?" } $self->columns);
    }

    if ($self->primary_column) {
      @values = ($self->get($self->primary_column()));
    } else {
      @values = map { $self->{$_} } $self->columns;
    }

  } else {
    return;
  }

  eval {
    my $stmt = $self->prepare($sql) or croak "Failed to prepare [$sql]";
    $stmt->execute(@values) or $stmt->finish(),croak "[$sql]" . $!;
    $stmt->finish();
  };
  if ($@) {
    carp $@;
    return;
  }

  if ( ref $self ) {
    $self->_del_self_from_cache();
    undef %$self;
  }
  return 1;

}

=head2 get

Get a column value.

 __PACKAGE__->get('column');

=cut

=head2 set 

Set a column value.  This updates the column in the table row represented by the object.

 __PACKAGE__->set('column',$value);

=cut 

sub set
{
  my ($self, $key) = splice(@_, 0, 2);

  $self->SUPER::set($key, @_);

  # only actual columns get updated, not virtual_columns
  if ($self->_columns && grep { /$key/ } @{$self->_columns} ) {

    if ($self->manual_update) {
      $self->is_changed(1);
    } else {
      $self->_update($key)
    }

  }

}

=head2 get

Get a column value.  If a relationship has been defined, this returns the object related to.

=cut

sub get
{
  my ($self,$key) = @_;

  if (my $relationships = $self->_has_a()) {

    if (my $class = $relationships->{$key}) {

      no strict 'refs';
      if (! exists ${"$class\::"}{ISA} ) {
        eval "use $class;";
        croak $@ if $@;
      }

      if (my $col_val = $self->SUPER::get($key)) {

        if (my $obj = $class->retrieve($self->SUPER::get($key))) {
          return $self->_add_obj_to_cache($obj);
        } else {
          return undef;
        }

      } else {
        return undef;
      }

    }

  }
  return $self->SUPER::get($key);
}

=head2 update

Commit changes to database.  Only useful when manual update is set.

=cut

sub update
{
  my $self = shift;
  $self->_update();
}

sub _update
{
  my ($self,$key) = @_;
  my $table = $self->table;
  my $primary_column = $self->primary_column;
  my $sql = undef;
  my @values = ();
  return undef unless ref $self;
  return undef unless $primary_column;
  return undef unless $self->_columns; # don't update virtual_columns only

  if ($key) {
    $sql = "update $table set $key = ? where $primary_column = ?";
    @values = ($self->$key,$self->get($self->primary_column));
  } else {
    my @columns = $self->columns;
    $sql = "update $table set ";
    $sql .= join(',', map { "$_ = ?" } @columns);
    $sql .= " where $primary_column = ?";
    @values = map { $self->{$_} } @columns;
    push @values, $self->get($self->primary_column);
  }

  my $stmt;
  eval {
    my $stmt = $self->prepare($sql) or croak "Failed to prepare [$sql]";
    $stmt->execute(@values) or $stmt->finish(),croak "[$sql]" . $!;
    $stmt->finish();
  };
  if ($@) {
    carp $@;
    return;
  }

  $self->_is_changed(0);
  $self->_del_self_from_cache();
  return 1;
}

=head2 retrieve_all

Return all rows in the table;

 my @objs = __PACKAGE__->retrieve_all();

=cut

sub retrieve_all
{
  my ($self) = @_;

  return $self->search();
}

=head2 retrieve

Return row mathing the specified key against the primary column.

 my $obj = __PACKAGE__->retrieve($id);

=cut

sub retrieve
{
  my ($self,$key) = @_;

  if (my $existing = $self->_lookup_obj_in_cache($key)) {
    return $existing;
  }

  unless ($self->primary_column) {
    carp "No primary key set for " . $self->table;
    return undef;
  }

  if (my ($r) = $self->search_where( $self->primary_column . " = " . $key )) {
    return $r;
  }
  return undef;
}

=head2 begin_work

Start transaction.  Calls DBI begin_work().

=cut

sub begin_work
{
  my ($self) = @_;
  $self->_jaos_dbh()->()->begin_work();
}

=head2 commit

Commit transaction.  Calls DBI commit().

=cut

sub commit
{
  my ($self) = @_;
  $self->_jaos_dbh()->()->commit();
}

=head2 rollback

Rollback transaction.  Calls DBI rollback().

=cut

sub rollback
{
  my ($self) = @_;
  $self->_jaos_dbh()->()->rollback();
}

=head2 has_a

Defines one to one relationships.

 __PACKAGE__->has_a( foo => 'Foo::Bar::Foo' );

=cut

sub has_a
{
  my $self = shift;

  my $relationships = $self->_has_a() || {};
  if (my ($column,$class) = @_) {
    $relationships->{$column} = $class;
  }

  $self->_has_a($relationships);
}

=head2 cache

Enable or disable the use of internal caching using Cache::Memcached.

 __PACKAGE__->cache(1);

=cut

sub cache
{
  my $self = shift;

  if (@_) {

    $self->_cache(@_);

    if ($_[0]) {
      eval {
        require Cache::Memcached;
        $Jaos::DBI::cache = Cache::Memcached->new({
          servers => $self->_cache_servers(),
          compress_threshold => $self->_compress_threshold(),
        });
      };
      if ($@) {
        carp $@,'...disabling caching';
        $self->_cache(0);
      }
    }

  }

  $self->_cache;
}

=head2 cache_servers

Specify the caching servers to use (see Cache::Memcached)

 __PACKAGE__->cache_servers( qw/ 127.0.0.1:11211 10.1.1.2:11212 / );

=cut

sub cache_servers
{
  my $self = shift;
  if (@_) {
    $self->_cache_servers([@_]);
  }
  $self->_cache_servers();
}

=head2 compress_threshold

Specify the caching servers to use (see Cache::Memcached)

 __PACKAGE__->compress_threshold( 10_000 );

=cut

sub compress_threshold
{
  my $self = shift;
  if (@_) {
    $self->_compress_threshold(@_);
  }
  $self->_compress_threshold();
}

=head2 cache_expires

Sets the expiration time on the persistant cached objects in seconds.

 __PACKAGE__->cache_expires(60); # in seconds

=cut

sub cache_expires
{
  my $self = shift;
  if (@_) {
    $self->_cache_expires(@_);
  }
  $self->_cache_expires();
}

sub _add_obj_to_cache
{
  my ($self,$obj) = @_;
  my $class = ref($obj) || return $obj;
  return undef unless $obj;
  return $obj unless $self->_cache;

  if (my $key = $obj->primary_column) {
    if (my $id = $obj->{$key}) {
      $Jaos::DBI::cache->set("$class:$id",$obj,$self->_cache_expires);
    }
  }

  return $obj;
}

sub _lookup_obj_in_cache
{
  my ($self,$key) = @_;
  return undef unless $self->_cache;
  my $class = ref($self) || $self;

  if (my $obj = $Jaos::DBI::cache->get("$class:$key")) {
    return $obj || undef;
  }

  return undef;
}

sub _del_obj_from_cache
{
  my ($self,$key) = @_;
  return unless $self->_cache;
  my $class = ref($self) || $self;
  
  $Jaos::DBI::cache->delete("$class:$key");
}

sub _del_self_from_cache
{
  my $self = shift;
  return unless $self->_cache;
  return unless ref($self);

  if (my $key = $self->primary_column) {
    $self->_del_obj_from_cache($self->{$key});
  }
}

=head1 AUTHOR

Jason Woodward <woodwardj@jaos.org>

=head1 LICENSE

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself.

=cut

1;