| 1 | package CWB::Web::Cache; | ||
| 2 | # -*-cperl-*- | ||
| 3 | |||
| 4 | ## | ||
| 5 | ## Short overview of module and cache architecture: | ||
| 6 | ## | ||
| 7 | ## The CWB::Web::Cache module uses a cache directory to keep selected named queries | ||
| 8 | ## persistent between CQP sessions. It is mainly intended for use in simple Web front-ends. | ||
| 9 | ## Therefore, it is neither completely safe in heavy-duty CGI applications (where race | ||
| 10 | ## conditions may occur) nor optimised for speed. First, a CWB::Web::Cache object is created | ||
| 11 | ## for an existing CQP process (using the CWB::CQP module) and must be initialised with settings | ||
| 12 | ## for the cache directory path and caching strategy. In order to make a named query result | ||
| 13 | ## (of the running CQP process) persistent, it is stored in the disk cache directory, and a unique | ||
| 14 | ## identifier is returned to the calling program. This identifier can then be used to recover | ||
| 15 | ## the persistent named query in a subsequent session (unless the result has already expired from | ||
| 16 | ## the cache, which case must be handled by the caller). | ||
| 17 | ## | ||
| 18 | ## The CWB::Web::Cache module can also execute simple CQP queries and make their results | ||
| 19 | ## persistent. The query results are identified by corpus, query string, and an optional sort | ||
| 20 | ## (stored as metadata) rather than a single unique identifier, and can be shared among different | ||
| 21 | ## processes using the same cache directory. When a persistent query result has expired from the | ||
| 22 | ## cache, it is re-created in a way transparent to the calling program (by re-executing the query | ||
| 23 | ## expression in the CQP process). | ||
| 24 | ## | ||
| 25 | ## The cache directory contains two subdirectories and an optional CONFIG file: | ||
| 26 | ## index/ ... text files as 'markers' for cached queries (may contain 'metadata' about the cached query) | ||
| 27 | ## data/ ... named query results stored in CQP's internal format | ||
| 28 | ## A persistent named query is stored in a file with the name <corpus>:<query_name> in the data/ | ||
| 29 | ## subdirectory (e.g. DICKENS:ResultA-1121, where the numerical suffix is used to create a unique filename | ||
| 30 | ## if necessary). A text file with the same name is created in the index/ directory and may hold | ||
| 31 | ## meta-information about the cached query result. Storing a named query proceeds in the following steps: | ||
| 32 | ## 1. create cache directory and subdirectories if they do not exist | ||
| 33 | ## 1a recover cache settings (size, expiration time, ...) from CONFIG file unless initialised by program (OPTIONAL) | ||
| 34 | ## 2. if cache directory size exceeds allowed maximum (checked with "du -k"), delete oldest query results | ||
| 35 | ## from cache until size has been reduced sufficiently (index file is always deleted first to keep other | ||
| 36 | ## processes from trying to read data while it is being erased); if expiration time is set, all files | ||
| 37 | ## older than the specified limit are removed first | ||
| 38 | ## 3. extend query name with numerical suffix to unique filename if necessary (checking files in index directory) | ||
| 39 | ## 4. create empty file with unique name in index directory to "lock" data file for other processes | ||
| 40 | ## 5. set CQP DataDirectory to data subdirectory, copy named query to unique name and save to disk | ||
| 41 | ## 6. overwrite index file with meta-information (OPTIONAL) | ||
| 42 | ## Recovering the named query result requires the following steps: | ||
| 43 | ## 1. if cache directory and subdirectories do not exist, return "expired" status | ||
| 44 | ## 2. check index directory for unique filename specified by caller, return "expired" if not found | ||
| 45 | ## 3. touch index file so it won't be deleted by another process cleaning up the cache while we're reading it; | ||
| 46 | ## this also ensures that frequently accessed query results do not expire from the cache (or makes it | ||
| 47 | ## very unlikely, at least) | ||
| 48 | ## 4. set CQP DataDirectory to data subdirectory and load cached query results from disk into CQP process | ||
| 49 | ## (force loading with "size <unique_name>;" command) | ||
| 50 | ## 5. return internal name of restored query result to calling process | ||
| 51 | ## | ||
| 52 | ## Running a persistent query involves the following steps: | ||
| 53 | ## 1. create a numeric hash key from the query expression (perhaps also the optional sort clause) | ||
| 54 | ## 2. find all index files that match the given corpus and the hash key (possibly extended with numerical suffix) | ||
| 55 | ## 3. check metadata stored in index files for exact query expression and sort clause | ||
| 56 | ## 4. if found, recover query result with the retrieve() method (which touches the index file) | ||
| 57 | ## and return unique query name to caller (which may copy it to a simple name if desired) | ||
| 58 | ## 5. otherwise, execute the specified query in the CQP process; if an index file matching the query | ||
| 59 | ## string but not the sort clause has been found, the corresponding query result may be loaded instead, | ||
| 60 | ## which is presumably faster than re-running the query (OPTIONAL, unless sort clause included in hash key) | ||
| 61 | ## 6. sort the query result according to the specified sort clause (otherwise, unsort the result) | ||
| 62 | ## 7. use the store() method to create unique filename and cache query result, storing query expression | ||
| 63 | ## and sort clause as metadata in index file; note that it is important to create an empty index file first, | ||
| 64 | ## to keep other processes (executing the same query) from loading the data file while it is being written | ||
| 65 | ## 8. return name of query result to caller (need not be the unique identifier) | ||
| 66 | ## | ||
| 67 | ## Note that there is no support for a user-defined error handler, as all error conditions are serious | ||
| 68 | ## internal faults and deserve to die (or rather croak). A named query that has expired from the cache | ||
| 69 | ## is a normal result rather than an error condition and must be expected by the caller. | ||
| 70 | |||
| 71 | 1 | ▶ | use Carp; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 72 | 1 | ▶ | use DirHandle; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 73 | 1 | ▶ | use CWB; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 74 | use CWB::CQP; | ||
| 75 | |||
| 76 | ## CWB::Web::Cache object struct: | ||
| 77 | ## 'cqp' => CWB::CQP object | ||
| 78 | ## 'dir' => cache directory | ||
| 79 | ## 'index' => index subdirectory | ||
| 80 | ## 'data' => data subdirectory | ||
| 81 | ## 'size' => maximum size of data directory (in MBytes, default = 5MB) | ||
| 82 | ## 'expire' => time after which query results expire from cache (in hours, default = 24h) | ||
| 83 | |||
| 84 | ## $cache = new CWB::Web::Cache -cqp => $cqp, -cachedir => $dir, [-cachesize => $cache_size,] [-cachetime => $expiration_time]; | ||
| 85 | ## object constructor, must be initialised with CQP object and cache directory (optional parameters have default values) | ||
| 86 | sub new { | ||
| 87 | my $class = shift; | ||
| 88 | my %arg = (-cqp => undef, -cachedir => undef, -cachesize => 5, -cachetime => 24); | ||
| 89 | # default cache size is 5 MB, default expiration time is 24 hours | ||
| 90 | croak 'Usage: $cache = new CWB::Web::Cache -cqp => $cqp, -cachedir => $dir, [-cachesize => $cache_size,] [-cachetime => $expiration_time];' | ||
| 91 | unless named_args(\%arg, @_); | ||
| 92 | my $self = {}; | ||
| 93 | my $cqp = $arg{-cqp}; | ||
| 94 | croak 'Error: argument -cqp must be CWB::CQP object.' | ||
| 95 | unless ref $cqp eq "CWB::CQP"; | ||
| 96 | $self->{'cqp'} = $cqp; | ||
| 97 | my $dir = $arg{-cachedir}; | ||
| 98 | $self->{'dir'} = $dir; | ||
| 99 | $self->{'index'} = "$dir/index"; | ||
| 100 | $self->{'data'} = "$dir/data"; | ||
| 101 | my $size = $arg{-cachesize}; | ||
| 102 | croak 'Error: maximal cache size must be valid number > 0.' | ||
| 103 | unless $size + 0 > 0; | ||
| 104 | $self->{'size'} = $size; | ||
| 105 | my $expire = $arg{-cachetime}; | ||
| 106 | croak 'Error: expiration time must be valid number > 0.' | ||
| 107 | unless $expire + 0 > 0; | ||
| 108 | $self->{'expire'} = $expire; | ||
| 109 | return bless($self, $class); | ||
| 110 | } | ||
| 111 | |||
| 112 | ## use default object destructor (no cleaning up to be done) | ||
| 113 | |||
| 114 | ## INTERNAL: $ok = named_args(\%arghash, @pairs); | ||
| 115 | ## process named args (-name => $value) from list @pairs; carps about wrong or missing arguments and returns false in this case; | ||
| 116 | ## values are stored in %arghash which must be initialised with acceptable parameters and their default values (undef for required parameter) | ||
| 117 | sub named_args { | ||
| 118 | my $arg = shift; | ||
| 119 | if ((@pairs % 2) != 0) { | ||
| 120 | carp "Odd number of elements in named argument list (@_)."; | ||
| 121 | return 0; | ||
| 122 | } | ||
| 123 | while (@_) { | ||
| 124 | my $name = shift; | ||
| 125 | my $value = shift; | ||
| 126 | if (not exists $arg->{$name}) { | ||
| 127 | carp "Illegal named argument: $name => '$value'."; | ||
| 128 | return 0; | ||
| 129 | } | ||
| 130 | $arg->{$name} = $value; | ||
| 131 | } | ||
| 132 | my @missing = grep { not defined $arg->{$_} } keys %$arg; | ||
| 133 | if (@missing) { | ||
| 134 | carp "Required argument(s) [@missing] not specified."; | ||
| 135 | return 0; | ||
| 136 | } | ||
| 137 | return 1; | ||
| 138 | } | ||
| 139 | |||
| 140 | ## INTERNAL: @files = list_directory($dir); | ||
| 141 | ## get directory listing from DirHandle module (local file names only!), skipping anything that doesn't look like an identifier | ||
| 142 | sub list_directory { | ||
| 143 | my $dir = shift; | ||
| 144 | my $dh = new DirHandle $dir; | ||
| 145 | return () | ||
| 146 | unless defined $dh; | ||
| 147 | my @files = grep {/^[A-Z0-9_-]+:/} $dh->read; | ||
| 148 | undef $dh; | ||
| 149 | return @files; | ||
| 150 | } | ||
| 151 | |||
| 152 | ## INTERNAL: $kbytes = directory_size($dir); | ||
| 153 | ## determine size of directory with "du -ks" (returns size in kbytes) | ||
| 154 | sub directory_size { | ||
| 155 | my $dir = shift; | ||
| 156 | my @output = (); | ||
| 157 | CWB::Shell::Cmd("du -ks $dir", \@output); | ||
| 158 | croak "Can't parse output of 'du -ks $dir' (@output)" | ||
| 159 | unless @output == 1 and $output[0] =~ /^([0-9]+)\s+\S+/; | ||
| 160 | my $size = $1; | ||
| 161 | return $size; | ||
| 162 | } | ||
| 163 | |||
| 164 | ## INTERNAL: delete_files(@files); | ||
| 165 | ## unlink list of files and croak() in case of an error | ||
| 166 | sub delete_files { | ||
| 167 | foreach my $file (@_) { | ||
| 168 | croak "Error: can't unlink file $file ($!)" | ||
| 169 | unless 1 == unlink $file; | ||
| 170 | } | ||
| 171 | } | ||
| 172 | |||
| 173 | ## INTERNAL: @filenames = $cache->index_files; | ||
| 174 | ## INTERNAL: @matching_files = $cache->index_files($substring); | ||
| 175 | sub index_files { | ||
| 176 | my $self = shift; | ||
| 177 | my @files = list_directory($self->{'index'}); | ||
| 178 | if (@_) { | ||
| 179 | my $sub = shift; | ||
| 180 | @files = grep { index($_, $sub) >= 0 } @files; | ||
| 181 | } | ||
| 182 | return @files; | ||
| 183 | } | ||
| 184 | |||
| 185 | ## INTERNAL: $cache->make_dirs; | ||
| 186 | ## ensure that cache directory and subdirectories exist, otherwise create them | ||
| 187 | sub make_dirs { | ||
| 188 | my $self = shift; | ||
| 189 | my $dir = $self->{'dir'}; | ||
| 190 | my $index = $self->{'index'}; | ||
| 191 | my $data = $self->{'data'}; | ||
| 192 | unless (-d $dir) { | ||
| 193 | CWB::Shell::Cmd("mkdir $dir"); | ||
| 194 | CWB::Shell::Cmd("chmod 777 $dir"); | ||
| 195 | } | ||
| 196 | unless (-d $index) { | ||
| 197 | CWB::Shell::Cmd("mkdir $index"); | ||
| 198 | CWB::Shell::Cmd("chmod 777 $index"); | ||
| 199 | } | ||
| 200 | unless (-d $data) { | ||
| 201 | CWB::Shell::Cmd("mkdir $data"); | ||
| 202 | CWB::Shell::Cmd("chmod 777 $data"); | ||
| 203 | } | ||
| 204 | } | ||
| 205 | |||
| 206 | ## INTERNAL: $cache->sweep_cache; | ||
| 207 | ## check size of cache data directory and delete old files when it exceeds the limit | ||
| 208 | sub sweep_cache { | ||
| 209 | my $self = shift; | ||
| 210 | my $force = shift; | ||
| 211 | $force = (defined $force and $force eq "-force") ? 1 : 0; | ||
| 212 | my $index = $self->{'index'}; | ||
| 213 | my $data = $self->{'data'}; | ||
| 214 | my $max_size = $self->{'size'} * 1024; # maximal allowed size in kBytes | ||
| 215 | my $expire = $self->{'expire'} / 24; # maximal storage time in days | ||
| 216 | my $size = directory_size($data); | ||
| 217 | return # return if cache size is below threshold (unless called with "-force") | ||
| 218 | unless $force or $size > $max_size; | ||
| 219 | # remove 'dangling' data files where index is missing (if there are any) | ||
| 220 | my @files = grep { not -f "$index/$_" } list_directory($data); | ||
| 221 | if (@files) { | ||
| 222 | delete_files(map { "$index/$_"} @files); | ||
| 223 | } | ||
| 224 | # delete all files that are older than the maximal expiration time | ||
| 225 | @files = grep { -M "$index/$_" > $expire } list_directory($index); | ||
| 226 | if (@files) { | ||
| 227 | delete_files(map { "$index/$_"} @files); | ||
| 228 | delete_files(map { "$data/$_"} @files); | ||
| 229 | } | ||
| 230 | $size = directory_size($data); # return if these steps have already reduced the cache size | ||
| 231 | return unless $size > $max_size; | ||
| 232 | # finally, sort remaining files by age (oldest first) and find out how many must be removed to reduce cache size below limit | ||
| 233 | @files = | ||
| 234 | sort { $b->[1] <=> $a->[1] } | ||
| 235 | map { [$_, (-M "$index/$_"), (-s "$data/$_" || 0) / 1024] } | ||
| 236 | list_directory($index); | ||
| 237 | my $req_size = $size - 0.8 * $max_size; # reduce to 80% of maximal cache size to reduce number of relatively slow cache sweeps | ||
| 238 | my $cum_size = 0; | ||
| 239 | while (@files and $cum_size < $req_size) { | ||
| 240 | my $f = shift @files; | ||
| 241 | my $file = $f->[0]; | ||
| 242 | unless (-M "$index/$file" < $f->[1]) { # just to be sure that index file hasn't been touched in the meantime | ||
| 243 | delete_files("$index/$file"); | ||
| 244 | if (-f "$data/$file") { | ||
| 245 | delete_files("$data/$file"); | ||
| 246 | } | ||
| 247 | $cum_size += $f->[2]; | ||
| 248 | } | ||
| 249 | } | ||
| 250 | $size = directory_size($data); # check that cache sweep was successful | ||
| 251 | croak 'Error: cache sweep failed for directory '.$self->{'dir'} | ||
| 252 | if $size > $max_size; | ||
| 253 | } | ||
| 254 | |||
| 255 | ## @lines = $cache->get_metadata($unique_name); | ||
| 256 | ## read metadata for unique filename (read from index file), returns () if index file does not exist | ||
| 257 | sub get_metadata { | ||
| 258 | my $self = shift; | ||
| 259 | my $file = shift; | ||
| 260 | my $index = $self->{'index'}; | ||
| 261 | my @lines = (); | ||
| 262 | if (-f "$index/$file") { | ||
| 263 | my $fh = CWB::OpenFile "$index/$file"; | ||
| 264 | while (<$fh>) { | ||
| 265 | chomp; | ||
| 266 | push @lines, $_; | ||
| 267 | } | ||
| 268 | $fh->close; | ||
| 269 | } | ||
| 270 | return @lines; | ||
| 271 | } | ||
| 272 | |||
| 273 | ## $unique_name = $cache->store($named_query [, @metadata]); | ||
| 274 | ## make named query result $named_query (which must be fully qualified with corpus name) persistent, | ||
| 275 | ## returning unique name for retrieval; optional metadata is s(tored in index file when the data file has been created | ||
| 276 | sub store { | ||
| 277 | my $self = shift; | ||
| 278 | my $name = shift; | ||
| 279 | my $index = $self->{'index'}; | ||
| 280 | my $data = $self->{'data'}; | ||
| 281 | my $cqp = $self->{'cqp'}; | ||
| 282 | croak "Error: query name $name illegal or not fully specified." | ||
| 283 | unless $name =~ /^([A-Z0-9_-]+):([A-Za-z0-9_-]+)$/; | ||
| 284 | my $corpus = $1; | ||
| 285 | my $localname = $2; | ||
| 286 | # create cache directory and subdirectories if necessary | ||
| 287 | $self->make_dirs; | ||
| 288 | # check size of cache directory and remove old entries if necessary | ||
| 289 | $self->sweep_cache; | ||
| 290 | # extend $name to unique filename (in index directory) | ||
| 291 | my %index_file = map {$_ => 1} $self->index_files("$name-"); | ||
| 292 | my $ext = 1; | ||
| 293 | while (exists $index_file{"$name-$ext"}) { | ||
| 294 | $ext++; | ||
| 295 | } | ||
| 296 | my $unique = "$name-$ext"; | ||
| 297 | my $unique_local = "$localname-$ext"; | ||
| 298 | # now create empty index file to "lock" the unique name from other processes | ||
| 299 | my $fh = CWB::OpenFile "> $index/$unique"; | ||
| 300 | $fh->close; | ||
| 301 | CWB::Shell::Cmd("chmod 666 $index/$unique"); | ||
| 302 | # set DataDirectory in CQP session and re-activate base corpus | ||
| 303 | $cqp->exec("set DataDirectory '$data'"); | ||
| 304 | $cqp->exec("$corpus"); | ||
| 305 | # copy named query to unique name and store it in data directory | ||
| 306 | $cqp->exec("$unique_local = $name"); | ||
| 307 | $cqp->exec("save $unique"); | ||
| 308 | CWB::Shell::Cmd("chmod 666 $data/$unique"); | ||
| 309 | # re-write index file if caller has passed metadata | ||
| 310 | if (@_) { | ||
| 311 | $fh = CWB::OpenFile "> $index/$unique"; | ||
| 312 | while (@_) { | ||
| 313 | my $line = shift; | ||
| 314 | chomp $line; # normalize whitespace in metadata (esp. linebreaks) | ||
| 315 | $line =~ s/\s+/ /g; | ||
| 316 | print $fh "$line\n"; | ||
| 317 | } | ||
| 318 | $fh->close; | ||
| 319 | } | ||
| 320 | return $unique; | ||
| 321 | } | ||
| 322 | |||
| 323 | ## $size = $cache->retrieve($unique_name); | ||
| 324 | ## load persistent query result identified by $unique_name into CQP process, | ||
| 325 | ## returning number of matches (>= 0) or 'undef' if the query result has expired from the cache | ||
| 326 | sub retrieve { | ||
| 327 | my $self = shift; | ||
| 328 | my $unique = shift; | ||
| 329 | my $index = $self->{'index'}; | ||
| 330 | my $data = $self->{'data'}; | ||
| 331 | my $cqp = $self->{'cqp'}; | ||
| 332 | my $expire = $self->{'expire'} / 24; # maximal storage time in days | ||
| 333 | croak "Error: illegal unique query name $unique" | ||
| 334 | unless $unique =~ /^([A-Z0-9_-]+):([A-Za-z0-9_-]+)$/; | ||
| 335 | my $corpus = $1; | ||
| 336 | my $unique_local = $2; | ||
| 337 | return undef # may have expired from cache during sweep ... | ||
| 338 | unless -f "$index/$unique"; | ||
| 339 | if (-M "$index/$unique" > $expire) { # ... or because it exceeded the maximal storage time | ||
| 340 | $self->sweep_cache("-force"); # delete expired files so they won't hide exact matches | ||
| 341 | return undef; | ||
| 342 | } | ||
| 343 | CWB::Shell::Cmd("touch $index/$unique"); # touch index file to mark last access time | ||
| 344 | # set DataDirectory in CQP session and re-activate base corpus | ||
| 345 | $cqp->exec("set DataDirectory '$data'"); | ||
| 346 | $cqp->exec("$corpus"); | ||
| 347 | # force loading of named query result in CQP session | ||
| 348 | my ($size) = $cqp->exec("size $unique"); | ||
| 349 | return $size; | ||
| 350 | } | ||
| 351 | |||
| 352 | ## ($unique_name [, $matching_lines]) = $cache->retrieve_matching($prefix, ["-partial",] @metadata); | ||
| 353 | ## load persistent query result which is a unique extension of $prefix and matches the specified metadata; | ||
| 354 | ## if flag -partial is specified, a query result matching only the first N lines of @metadata will also | ||
| 355 | ## be accepted; N is returned as $matching_lines and must be checked by the caller | ||
| 356 | sub retrieve_matching { | ||
| 357 | my $self = shift; | ||
| 358 | my $prefix = shift; | ||
| 359 | my $partial = 0; | ||
| 360 | if (@_ and lc($_[0]) eq "-partial") { | ||
| 361 | $partial = 1; | ||
| 362 | shift @_; | ||
| 363 | } | ||
| 364 | my $index = $self->{'index'}; | ||
| 365 | my $data = $self->{'data'}; | ||
| 366 | my $cqp = $self->{'cqp'}; | ||
| 367 | my $expire = $self->{'expire'} / 24; # maximal storage time in days | ||
| 368 | croak "Error: query name prefix $prefix is illegal or not fully specified." | ||
| 369 | unless $prefix =~ /^([A-Z0-9_-]+):([A-Za-z0-9_-]+)$/; | ||
| 370 | my $corpus = $1; | ||
| 371 | my $prefix_local = $2; | ||
| 372 | my @unique = $self->index_files($prefix); # find matching unique names in index directory | ||
| 373 | # normalise specified metadata and compare to each matching index file in turn | ||
| 374 | my @metadata = (); | ||
| 375 | while (@_) { | ||
| 376 | my $line = shift; | ||
| 377 | chomp $line; # normalize whitespace in metadata (esp. linebreaks) | ||
| 378 | $line =~ s/\s+/ /g; | ||
| 379 | push @metadata, $line; | ||
| 380 | } | ||
| 381 | my $N = @metadata; | ||
| 382 | my $best_N = 0; # find best match for metadata among matching filenames | ||
| 383 | my $best_unique = ""; | ||
| 384 | foreach my $unique (@unique) { | ||
| 385 | my @md_unique = $self->get_metadata($unique); | ||
| 386 | my $i = 0; | ||
| 387 | while ($i < $N and $i < @md_unique) { | ||
| 388 | last unless $metadata[$i] eq $md_unique[$i]; | ||
| 389 | $i++; | ||
| 390 | } | ||
| 391 | # $i now holds the number of matching lines of metadata | ||
| 392 | if ($i > $best_N) { | ||
| 393 | $best_N = $i; | ||
| 394 | $best_unique = $unique; | ||
| 395 | } | ||
| 396 | } | ||
| 397 | if ($partial) { | ||
| 398 | return ($best_unique, $best_N) # retrieve query result if (partial) match has been found, return unique name and matching lines | ||
| 399 | if $best_N > 0 and defined $self->retrieve($best_unique); | ||
| 400 | } | ||
| 401 | else { | ||
| 402 | return $best_unique # retrieve query result if match has been found and return unique name if successful | ||
| 403 | if $best_N == $N and defined $self->retrieve($best_unique); | ||
| 404 | } | ||
| 405 | return undef; # return 'undef' if there was no match (or the match could not be retrieved from the cache) | ||
| 406 | } | ||
| 407 | |||
| 408 | ## $query_name = $cache->query(-corpus => $corpus, -query => $query_expr, ...); | ||
| 409 | ## execute CQP query (and optional subquery) on corpus $corpus and make its results persistent; | ||
| 410 | ## if query has already been executed, the results are retrieved from the disk cache unless they're expired; | ||
| 411 | ## results are automatically sorted with optional sort clause (e.g. 'by word %cd reverse') and stored | ||
| 412 | ## in sort order; optional cut specifies maximum number of matches (so a single query cannot occupy the | ||
| 413 | ## entire cache directory) and defaults to a value allowing at least 4 queries to be cached simultaneously | ||
| 414 | sub query { | ||
| 415 | my $self = shift; | ||
| 416 | my %arg = (-corpus => undef, | ||
| 417 | -query => undef, | ||
| 418 | -subquery => "", | ||
| 419 | -sort => "", -keyword => "", | ||
| 420 | -cut => int(($self->{'size'} * 1024 * 1024 / 4) / 16)); | ||
| 421 | # -cut defaults to average file size of at most 1/4 of cache size (in bytes, assuming approx. 16 bytes per match) | ||
| 422 | croak 'Usage: $cache->query(-corpus => $corpus, -query => $query, [-subquery => $subquery,] [-sort => $sort_clause,] [-keyword => $keyword_command,] [-cut => $max_matches]);' | ||
| 423 | unless named_args(\%arg, @_); | ||
| 424 | my $corpus = $arg{-corpus}; | ||
| 425 | my $query = $arg{-query}; | ||
| 426 | my $subquery = $arg{-subquery}; | ||
| 427 | my $sort = $arg{-sort}; | ||
| 428 | my $keyword = $arg{-keyword}; | ||
| 429 | my $cut = $arg{-cut}; | ||
| 430 | croak "Error: invalid corpus name $corpus" | ||
| 431 | unless $corpus =~ /^[A-Z0-9_-]+$/; | ||
| 432 | $query =~ s/(\s*\;\s*)+$//; # delete trailing ";" from query so we can append cut statement | ||
| 433 | if ($subquery) { | ||
| 434 | # don't limit first query if we want to run a subquery, because (i) we may be filtering out matches with the subquery | ||
| 435 | # and (ii) the subquery might have more matches than the original, so a cut clause on the subquery is required | ||
| 436 | if ($subquery =~ s/!\s*$//) { | ||
| 437 | # if subquery is used as a filter, we need to move the "!" behind the "cut" clause | ||
| 438 | $subquery .= "cut $cut !"; | ||
| 439 | } | ||
| 440 | else { | ||
| 441 | $subquery .= " cut $cut"; | ||
| 442 | } | ||
| 443 | } | ||
| 444 | else { | ||
| 445 | $query .= " cut $cut"; | ||
| 446 | } | ||
| 447 | |||
| 448 | # compute hash key from normalised query string | ||
| 449 | my $hv = 0; | ||
| 450 | my $normal = $query; | ||
| 451 | $normal =~ s/\s+/ /g; | ||
| 452 | for my $i (0 .. (length($normal) - 1)) { | ||
| 453 | use integer; | ||
| 454 | $hv = ($hv * 33) ^ ($hv >> 27) ^ ord(substr($normal, $i, 1)); | ||
| 455 | } | ||
| 456 | $hv = abs($hv); | ||
| 457 | my $name = "PQ$hv"; | ||
| 458 | |||
| 459 | # try to retrieve cached query result matching query string, sort clause, and set keyword command | ||
| 460 | my ($unique, $matching_lines) = $self->retrieve_matching("$corpus:$name", "-partial", $query, $subquery, $keyword, $sort); | ||
| 461 | if (defined $unique) { | ||
| 462 | return $unique | ||
| 463 | if $matching_lines == 4; # return exact match | ||
| 464 | } | ||
| 465 | else { | ||
| 466 | $matching_lines = 0; | ||
| 467 | } | ||
| 468 | |||
| 469 | # if query result was not found in cache, run query and subquery, sort result, and execute set keyword command | ||
| 470 | my $cqp = $self->{'cqp'}; | ||
| 471 | $cqp->exec("$corpus"); | ||
| 472 | if ($matching_lines >= 2) { # copy query result from partial match ... | ||
| 473 | $cqp->exec("$name = $unique"); | ||
| 474 | } | ||
| 475 | else { # ... or execute query in query lock mode (highly recommended for CGI scripts) | ||
| 476 | if ($subquery) { | ||
| 477 | $cqp->exec_query("$name-TEMP = $query"); # run primary query, assign to temporary name, then run subquery | ||
| 478 | my ($N) = $cqp->exec("size $name-TEMP"); | ||
| 479 | if ($N > 0) { | ||
| 480 | $cqp->exec("$name-TEMP"); | ||
| 481 | $cqp->exec_query("$name = $subquery"); | ||
| 482 | $cqp->exec("$corpus"); | ||
| 483 | } | ||
| 484 | else { # don't run subquery if primary returns no matches | ||
| 485 | $cqp->exec("$name = $name-TEMP"); | ||
| 486 | } | ||
| 487 | $cqp->exec("discard $name-TEMP"); | ||
| 488 | } | ||
| 489 | else { | ||
| 490 | $cqp->exec_query("$name = $query"); # run primary query only | ||
| 491 | } | ||
| 492 | } | ||
| 493 | my ($N) = $cqp->exec("size $name"); | ||
| 494 | if ($N > 0) { | ||
| 495 | if ($matching_lines < 3) { # no match or partial match without appropriate keyword | ||
| 496 | if ($keyword eq "") { | ||
| 497 | $cqp->exec("set $name keyword NULL") # if $keyword == "", make sure to delete keywords that may have been loaded from partial match | ||
| 498 | if $matching_lines >= 2; | ||
| 499 | ## but only if the result has been loaded from cache with a non-empty set keyword clause ($matching_lines >= 2) | ||
| 500 | ## in order to avoid overwriting keyword anchors that have been set directly in the query (CQP v3.4.16 and newer) | ||
| 501 | } | ||
| 502 | else { | ||
| 503 | $cqp->exec("set $name keyword $keyword"); # otherwise execute keyword command | ||
| 504 | } | ||
| 505 | } | ||
| 506 | ## sort command cannot have matched in partial match -> execute | ||
| 507 | $cqp->exec("sort $name $sort"); # "unsorts" (i.e. sorts in cpos order) if $sort == "" | ||
| 508 | } | ||
| 509 | |||
| 510 | # make query result persistent and return its unique name | ||
| 511 | return $self->store("$corpus:$name", $query, $subquery, $keyword, $sort); | ||
| 512 | } | ||
| 513 | |||
| 514 | |||
| 515 | return 1; | ||
| 516 | |||
| 517 | __END__ | ||