-
Notifications
You must be signed in to change notification settings - Fork 3
/
DBIStore.pm
469 lines (383 loc) · 13.3 KB
/
DBIStore.pm
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
# See bottom of file for license and copyright information
package Foswiki::Contrib::DBIStoreContrib::DBIStore;
=begin TML
---+ package Foswiki::Contrib::DBIStoreContrib::DBIStore;
Implements a Foswiki::Store shim to add to Store.
For Foswiki 1.2.0 and later, it's a partial implementation of the Store class
that will be inserted into the object hierarchy at object creation time.
For Foswiki <1.2.0 (which does not support recordChange) it is simply a
set of functions used by the DBIStoreContribPlugin to maintain the DB.
Object that listens to low level store events, and maintains an SQL
database (on the other side of DBI).
=cut
use strict;
use warnings;
use DBI;
use Foswiki::Meta;
use Error ':try';
use Assert;
use Encode;
use constant MONITOR => Foswiki::Contrib::DBIStoreContrib::MONITOR;
# TODO: SMELL: convert to using $session->{store} perhaps?
our $db; # singleton instance of this class
our $personality; # personality module for the selected DSN
our ( $CQ, $TEXT );
our @TABLES = keys(%Foswiki::Meta::VALIDATE); # META: types
# @ISA not used, as its set by magic, and we don't want to import more functions
# our @ISA = ('Foswiki::Store::Store');
# SMELL: I don't understand this. Sven changed the code, and
# now I'm lost :-(
# Construct singleton object, just used as a handle
sub new {
my $class = shift;
return $db if $db;
$db = $class->SUPER::new(@_) unless defined($db);
return $db;
}
# Used by plugin instead of new() until I can work out what Sven did.
# Mutually exclusive with new()
sub createShim {
my $class = shift;
return $db if $db;
$db = bless( {}, $class ) unless $db;
return $db;
}
sub DESTROY {
my $this = shift;
if ( defined $this->{handle} ) {
$this->{handle}->disconnect(); # SMELL: keep around in FCGI?
$this->{handle} = undef;
}
}
# Connect on demand - PRIVATE
sub _connect {
my ( $this, $session, $hard_reset ) = @_;
return 1 if $this->{handle} && !$hard_reset;
if ($Foswiki::inUnitTestMode) {
# Change the DSN to a SQLite test db, which is held in the data
# area; that way it will be ripped down by -clean
$Foswiki::cfg{Extensions}{DBIStoreContrib}{DSN} =
"dbi:SQLite:dbname=$Foswiki::cfg{DataDir}/TemporarySQLiteCache";
$Foswiki::cfg{Extensions}{DBIStoreContrib}{Username} = '';
$Foswiki::cfg{Extensions}{DBIStoreContrib}{Password} = '';
}
# $this->{schema} re-expresses the schema declared in Meta::VALIDATE by
# organising it as a hash keyed on table name e.g. 'FILEATTACHMENT'
# and sub-keyed on attribute name e.g. 'name'
$this->{schema} = {};
foreach my $type (@TABLES) {
my @keys;
foreach my $g (qw(require allow other)) {
if ( defined $Foswiki::Meta::VALIDATE{$type}->{$g} ) {
push( @keys, @{ $Foswiki::Meta::VALIDATE{$type}->{$g} } );
}
}
foreach my $key (@keys) {
$this->{schema}->{$type}->{$key} = 1;
}
}
print STDERR "CONNECT $Foswiki::cfg{Extensions}{DBIStoreContrib}{DSN}...\n"
if MONITOR;
$this->{handle} = DBI->connect(
$Foswiki::cfg{Extensions}{DBIStoreContrib}{DSN},
$Foswiki::cfg{Extensions}{DBIStoreContrib}{Username},
$Foswiki::cfg{Extensions}{DBIStoreContrib}{Password},
{ RaiseError => 1, AutoCommit => 0 }
) or die $DBI::errstr;
print STDERR "Connected\n" if MONITOR;
# Custom code to put DB's into ANSI mode and clean up error reporting
personality()->startup();
$CQ = personality()->string_quote();
$TEXT = personality()->text_type();
# Check if the DB is initialised with a quick sniff of the tables
# to see if all the ones we expect are there
if ( personality()->table_exists( 'metatypes', 'topic' ) ) {
return 1 unless ($hard_reset);
print STDERR "HARD RESET\n" if MONITOR;
# Hard reset; strip down all existing tables
my $tables = $this->{handle}->selectcol_arrayref( <<SQL );
SELECT name FROM metatypes
SQL
push( @$tables, 'topic' );
push( @$tables, 'metatypes' );
foreach my $table (@$tables) {
$this->{handle}->do("DROP TABLE \"$table\"")
if personality()->table_exists($table);
}
}
# No tables, or we've had a hard reset
print STDERR "Loading DB schema\n" if MONITOR;
$this->_createTables();
unless ($Foswiki::inUnitTestMode) {
print STDERR "Schema loaded; preloading content\n" if MONITOR;
$this->_preload($session);
print STDERR "DB preloaded\n" if MONITOR;
}
return 1;
}
# Create the table for the given META - PRIVATE
sub _createTableForMETA {
my ( $this, $t ) = @_;
my $cols =
join( ",\n", map { " \"$_\" $TEXT" } keys %{ $this->{schema}->{$t} } );
$this->{handle}->do(<<SQL);
CREATE TABLE "$t" (
tid INT,
$cols
)
SQL
# Add the table to the table of tables
$this->{handle}->do("INSERT INTO metatypes (name) VALUES ( '$t' )");
# If it's not a default table, add it to the list of tables
# (unless it's already there).
push( @TABLES, $t ) unless grep { $t } @TABLES;
}
# Create all the base tables in the DB (including all default META: tables) - PRIVATE
sub _createTables {
my $this = shift;
# Create the topic table. This links the web name, topic name,
# topic text and raw text of the topic.
$this->{handle}->do(<<SQL);
CREATE TABLE topic (
tid INT PRIMARY KEY,
web $TEXT,
name $TEXT,
text $TEXT,
raw $TEXT,
UNIQUE (tid)
)
SQL
# Now create the meta-table of known META: tables
$this->{handle}->do(<<SQL);
CREATE TABLE metatypes (
name $TEXT
)
SQL
# Create the tables for each known META: type
foreach my $t (@TABLES) {
print STDERR "Creating table for $t\n" if MONITOR;
$this->_createTableForMETA($t);
}
$this->{handle}->do('COMMIT') if personality()->requires_COMMIT();
}
# Load all existing webs and topics into the cache DB (expensive)
sub _preload {
my ( $this, $session ) = @_;
my $root = Foswiki::Meta->new($session);
my $wit = $root->eachWeb();
while ( $wit->hasNext() ) {
my $web = $wit->next();
$this->_preloadWeb( $web, $session );
}
$this->{handle}->do('COMMIT') if personality()->requires_COMMIT();
}
# Preload a single web - PRIVATE
sub _preloadWeb {
my ( $this, $w, $session ) = @_;
my $web = Foswiki::Meta->new( $session, $w );
my $tit = $web->eachTopic();
while ( $tit->hasNext() ) {
my $t = $tit->next();
my $topic = Foswiki::Meta->load( $session, $w, $t );
print STDERR "Preloading topic $w/$t\n" if MONITOR;
$this->insert($topic);
}
my $wit = $web->eachWeb();
while ( $wit->hasNext() ) {
$this->_preloadWeb( $w . '/' . $wit->next(), $session );
}
}
=begin TML
---++ ObjectMethod recordChange(%args)
Record that the store item changed, and who changed it
This is a private method to be called only from the store internals, but it can be used by
$Foswiki::Cfg{Store}{ImplementationClasses} to chain in to eveavesdrop on Store events
cuid => $cUID,
revision => $rev,
verb => $verb,
newmeta => $topicObject,
newattachment => $name
=cut
sub recordChange {
my ( $this, %args ) = @_;
# doing it first to make sure the record is chained
$this->SUPER::recordChange(%args);
# TODO: I'm not doing attachments yet
return if ( defined( $args{newattachment} ) );
return if ( defined( $args{oldattachment} ) );
writeDebug( $args{verb} . join( ',', keys(%args) ) ) if MONITOR;
if ( $args{verb} eq 'remove' ) {
$this->remove( $args{oldmeta} );
}
elsif ( $args{verb} eq 'insert' ) {
$this->insert( $args{newmeta} );
}
elsif ( $args{verb} eq 'update' ) {
$this->_update( $args{oldmeta}, $args{newmeta} );
}
else {
# WTF?
}
}
# Update a topic by removing the $old and ringing in the $new - or operations to
# that effect.
sub update {
my ( $this, $old, $new ) = @_;
# SMELL: there's got to be a better way
eval {
$this->_inner_remove($old);
$this->_inner_insert( $new || $old );
$this->{handle}->do('COMMIT');
};
if ($@) {
print STDERR "$@\n" if MONITOR;
die $@;
}
}
sub _convertToUTF8 {
my $text = shift;
$text = Encode::decode( $Foswiki::cfg{Site}{CharSet}, $text );
$text = Encode::encode( 'utf-8', $text );
return $text;
}
sub _inner_insert {
my ( $this, $mo ) = @_;
return unless defined $mo->topic();
$this->_connect( $mo->session() );
my $tid = $this->{handle}->selectrow_array('SELECT MAX(tid) FROM topic;')
|| 0;
$tid++;
print STDERR "\tInsert $tid\n" if MONITOR;
my $text = _convertToUTF8( $mo->text() );
my $esf = _convertToUTF8( $mo->getEmbeddedStoreForm() );
$this->{handle}
->do( 'INSERT INTO topic (tid,web,name,text,raw) VALUES (?,?,?,?,?)',
{}, $tid, $mo->web(), $mo->topic(), $text, $esf );
foreach my $type ( keys %$mo ) {
# Make sure it's registered.
next unless ( defined $Foswiki::Meta::VALIDATE{$type} );
# If it's not default, we may have to create the table
$this->_createTableForMETA($type)
unless personality()->table_exists($type);
# Insert this row
my $data = $mo->{$type};
foreach my $item (@$data) {
# Filter attrs by those legal in the schema
my @kn = grep { $this->{schema}->{$type}->{$_} } keys(%$item);
my @kl = ( 'tid', @kn );
my $sql =
"INSERT INTO \"$type\" ("
. join( ',', map { "\"$_\"" } @kl )
. ") VALUES ("
. join( ',', map { '?' } @kl ) . ")";
$this->{handle}
->do( $sql, {}, $tid, map { _convertToUTF8( $item->{$_} ) } @kn );
}
}
}
# Insert a topic into the topics table - PUBLIC
sub insert {
my ( $this, $mo ) = @_;
eval {
$this->_inner_insert($mo);
$this->{handle}->do('COMMIT');
};
if ($@) {
print STDERR "$@\n" if MONITOR;
die $@;
}
}
sub _inner_remove {
my ( $this, $mo ) = @_;
$this->_connect( $mo->session() );
my $sql = "SELECT tid FROM topic WHERE topic.web='" . $mo->web() . "'";
$sql .= " AND topic.name='" . $mo->topic() . "'" if defined $mo->topic();
my $tids = $this->{handle}->selectcol_arrayref($sql);
return unless scalar(@$tids);
my $tid = $tids->[0];
print STDERR "\tRemove $tid\n" if MONITOR;
foreach my $table ( 'topic', @TABLES ) {
$this->{handle}->do("DELETE FROM \"$table\" WHERE tid = '$tid'");
}
}
# Delete a topic identified by a Meta object from the table of topics
sub remove {
my ( $this, $mo ) = @_;
eval {
$this->_inner_remove($mo);
$this->{handle}->do('COMMIT');
};
if ($@) {
print STDERR "$@\n" if MONITOR;
die $@;
}
}
# STATIC method invoked by Foswiki::Store::QueryAlgorithms::DBIStoreContrib
# to perform the actual database query.
sub DBI_query {
my ( $session, $sql ) = @_;
ASSERT( $db, "Fatal error: queried before DBIStore shim is ready" )
if DEBUG;
my @names;
eval {
$db->_connect($session);
my $sth = $db->{handle}->prepare($sql);
$sth->execute();
while ( my @row = $sth->fetchrow_array() ) {
push( @names, "$row[0]/$row[1]" );
}
print STDERR "HITS: "
. scalar(@names) . "\n"
. join( "\n", map { "\t$_" } @names ) . "\n"
if MONITOR;
};
if ($@) {
print STDERR "$@\n" if MONITOR;
die $@;
}
return \@names;
}
# Static access to the database personaility module; used to get access to
# the regexp composition.
sub personality {
ASSERT( $db,
"Fatal error: trying to use personality before DBIStore is ready" )
if DEBUG;
unless ($personality) {
$Foswiki::cfg{Extensions}{DBIStoreContrib}{DSN} =~ /^dbi:(.*?):/i;
my $module = 'Foswiki::Contrib::DBIStoreContrib::Personality::' . $1;
eval "require $module";
if ($@) {
print STDERR $@;
die "Failed to load personality module $module";
}
$personality = $module->new($db);
}
return $personality;
}
# Reset the DB by dropping existing tables (if they exist) and preloading.
sub reset {
my ( $this, $session ) = @_;
# Connect with hard reset
eval { $this->_connect( $session, 1 ); };
if ($@) {
print STDERR "$@\n" if MONITOR;
die $@;
}
}
1;
__DATA__
Author: Crawford Currie http://c-dot.co.uk
Module of Foswiki - The Free and Open Source Wiki, http://foswiki.org/, http://Foswiki.org/
Copyright (C) 2010 Foswiki Contributors. All Rights Reserved.
Foswiki Contributors are listed in the AUTHORS file in the root
of this distribution. NOTE: Please extend that file, not this notice.
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. For
more details read LICENSE in the root of this distribution.
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.
As per the GPL, removal of this notice is prohibited.