so Search.tsf and Search.rdf work
[freeside.git] / FS / FS / h_Common.pm
1 package FS::h_Common;
2
3 use strict;
4 use FS::Record qw(dbdef);
5 use Carp qw(confess);
6
7 =head1 NAME
8
9 FS::h_Common - History table "mixin" common base class
10
11 =head1 SYNOPSIS
12
13 package FS::h_tablename;
14 @ISA = qw( FS::h_Common FS::tablename ); 
15
16 sub table { 'h_table_name'; }
17
18 sub insert { return "can't insert history records manually"; }
19 sub delete { return "can't delete history records"; }
20 sub replace { return "can't modify history records"; }
21
22 =head1 DESCRIPTION
23
24 FS::h_Common is intended as a "mixin" base class for history table classes to
25 inherit from.
26
27 =head1 METHODS
28
29 =over 4
30
31 =item sql_h_search END_TIMESTAMP [ START_TIMESTAMP ] 
32
33 Returns an a list consisting of the "SELECT" and "EXTRA_SQL" SQL fragments to
34 search for the appropriate history records created before END_TIMESTAMP
35 and (optionally) not cancelled before START_TIMESTAMP.
36
37 =cut
38
39 sub sql_h_search {
40   my( $self, $end ) = ( shift, shift );
41
42   my $table = $self->table;
43   my $real_table = ($table =~ /^h_(.*)$/) ? $1 : $table;
44   my $pkey = dbdef->table($real_table)->primary_key
45     or die "can't (yet) search history table $real_table without a primary key";
46
47   unless ($end) {
48     confess 'Called sql_h_search without END_TIMESTAMP';
49   }
50
51   my $notcancelled = '';
52   if ( scalar(@_) && $_[0] ) {
53     $notcancelled = "AND 0 = ( SELECT COUNT(*) FROM $table as notdel
54                                 WHERE notdel.$pkey = maintable.$pkey
55                                 AND notdel.history_action = 'delete'
56                                 AND notdel.history_date > maintable.history_date
57                                 AND notdel.history_date <= $_[0]
58                              )";
59   }
60
61   (
62     "DISTINCT ON ( $pkey ) *",
63
64     "AND history_date <= $end
65      AND (    history_action = 'insert'
66            OR history_action = 'replace_new'
67          )
68      $notcancelled
69      ORDER BY $pkey ASC, history_date DESC",
70
71      '',
72
73      'AS maintable',
74   );
75
76 }
77
78 =item sql_h_searchs END_TIMESTAMP [ START_TIMESTAMP ] 
79
80 Like sql_h_search, but limited to the single most recent record (before
81 END_TIMESTAMP)
82
83 =cut
84
85 sub sql_h_searchs {
86   my $self = shift;
87   my($select, $where, $cacheobj, $as) = $self->sql_h_search(@_);
88   $where .= ' LIMIT 1';
89   ($select, $where, $cacheobj, $as);
90 }
91
92 =back
93
94 =head1 BUGS
95
96 =head1 SEE ALSO
97
98 L<FS::Record>, schema.html from the base documentation
99
100 =cut
101
102 1;
103