This file is indexed.

/usr/share/perl5/Lire/DlfSchema.pm is in lire 2:2.1.1-2.1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
package Lire::DlfSchema;

use strict;

use vars qw/ %SCHEMA_CACHE /;

use Carp;
use Locale::TextDomain 'lire';
use XML::Parser;

use Lire::Config::Build qw/ ac_info /;
use Lire::Config;
use Lire::DataTypes qw/ check_xml_name check_superservice check_type /;
use Lire::Field;
use Lire::DerivedSchema;
use Lire::ExtendedSchema;
use Lire::DlfQuery;
use Lire::I18N qw/ bindtextdomain dgettext dgettext_para /;
use Lire::Utils qw/ sql_quote_name check_param check_object_param /;

BEGIN {
    %SCHEMA_CACHE = ();
};

=pod

=head1 NAME

Lire::DlfSchema - Interface to Lire DLF Schema XML specifications

=head1 SYNOPSIS

In DLF converters:

    use Lire::DlfSchema;

    my $schema = Lire::DlfSchema::load_schema( "email" );
    my $fields = $schema->fields();

    my $dlf_id = $schema->field( 'dlf_id' );
    my $dlf_src = $schema->field( 'dlf_source' );

=head1 DESCRIPTION

This module is the interface to the Lire DLF Schemas defined in XML
files. A schema defines the order of the fields along with their
names, descriptions and types.

Each DlfSchema have at least two predefined fields: 

=over

=item dlf_id

This is an integer which uniquely identify a DLF record in its stream.
Its used to link the record to its extended schemas fields and also to
link the record to the derived schemas records.

=item dlf_source

This is an identifier which can be used to track the record the
ImportJob that created it.

=back

=head1 ACCESSING A SCHEMA OBJECT

The way to access a schema for a superservice is through the
load_schema() module function. You use it like this:

    my $schema = Lire::DlfSchema::load_schema( $superservice);

This function will return a schema object which can then be used to
query information about the schema. This function will die() on error.

=cut


sub load_schema {
    my ( $name ) = @_;

    check_param ( $name, 'name', \&check_xml_name,
                  'invalid schema identifier' );

    my $super = $name;
    if ($name =~ /^(\w+)-/ ) {
	$super = $1;
    }

    croak "invalid superservice: $super"
      unless Lire::DlfSchema->has_superservice( $super );

    return $SCHEMA_CACHE{$name}
      if $SCHEMA_CACHE{$name};

    my $file = Lire::DlfSchema->_schema_file( $name );
    croak "can't find XML schema definition for $name in ",
      join( ":", @{Lire::Config->get( 'lr_schemas_path' )} ),"\n"
        unless defined $file;

    my $file_h;
    open ( $file_h, "$file")
      or croak "can't open XML schema $file for $name schema: $!";

    my $parser = new XML::Parser ( 'Handlers'	=> {
						    'Init'  => \&Init,
						    'Final' => \&Final,
						    'Start' => \&Start,
						    'End'   => \&End,
						    'Char'  => \&Char,
						   },
				   'Namespaces' => 1,
				   'NoLWP'      => 1,
				 );
    my $dlf_schema = eval { $parser->parse( $file_h ) };
    croak "error while parsing XML definition of $name: $@"
      if $@;
    close $file_h;

    # Sanity checks
    croak "$file has '", $dlf_schema->superservice(), "' as superservice attribute when it should have '", $super, "'\n"
	if $dlf_schema->superservice() ne $super;
    croak "$file has '", $dlf_schema->id(), "' as id attribute when it should have '", $name, "'\n"
      if $dlf_schema->id() ne $name;

    return $SCHEMA_CACHE{$name} = $dlf_schema;
}

sub new {
    my ( $class, %attr ) = @_;

    check_param( $attr{'superservice'}, 'superservice',
                 \&check_superservice );
    check_param( $attr{'timestamp'}, 'timestamp',
                 \&check_xml_name );

    my $self = bless { 'id'		 => $attr{'superservice'},
                       'superservice'    => $attr{'superservice'},
                       'timestamp_field' => $attr{'timestamp'},
                       'fields_by_pos'   => [],
                       'fields_by_name'  => {},
                       'title'	    => undef,
                       'description'	    => undef,
                     }, $class;

    $self->add_field( new Lire::Field( 'name' => 'dlf_id',
                                       'type' => 'id',
                                       'label' => __( 'Dlf ID' ),
                                       'description' => '<para>' . __( <<EOD ) . '</para>'  ) );
This field contains an integer which uniquely identify this DLF record
in the stream.
EOD

    $self->add_field( new Lire::Field( 'name' => 'dlf_source',
                                       'type' => 'string',
                                       'label' => __( 'Dlf Source' ),
                                       'description' => '<para>' . __( <<EOD ) . '</para>'  ) );
This field contains an identifier relating the record to the process
that created it.
EOD

    bindtextdomain( "lire-" . $self->superservice(),
                    ac_info( 'LR_PERL5LIB' ) . "/LocaleData" );

    return $self;
}

sub check {
    my ( $self ) = @_;
    # Verify that the schema is valid

    # Check that the timestamp attribute is valid
    croak ( "field $self->{'timestamp_field'} doesn't exists" )
      unless $self->has_field( $self->{'timestamp_field'} );

    my $field = $self->timestamp_field;
    croak ( "field $self->{'timestamp_field'} isn't of type timestamp" )
      unless $field->type() eq "timestamp";

    return 1;
}

=pod

=head2 has_superservice( $superservice )

Returns true if there is superservice named $schema_name available. An
error will be thrown if the schema name isn't valid for a superservice.

=cut

sub has_superservice {
    my ($self, $superservice ) = @_;

    check_param( $superservice, 'superservice',
                 sub { return ( check_xml_name($_[0])
                                && index($_[0], "-") == -1 ) },
                 'invalid superservice schema name' );

    return ( defined $SCHEMA_CACHE{$superservice}
             || defined $self->_schema_file( $superservice ) );
}

=pod

=head2 has_schema( $schema_name )

Returns true if there is $schema_name available. An error will be
thrown if the schema name isn't valid.

=cut

sub has_schema {
    my ( $self, $schema_name ) = @_;

    check_param( $schema_name, 'schema_name', \&check_xml_name,
                 'invalid schema name' );

    return ( defined $SCHEMA_CACHE{$schema_name} 
             ||defined $self->_schema_file( $schema_name ) );
}

sub _schema_file {
    my ( $self, $schema_name ) = @_;

    foreach my $dir ( @{Lire::Config->get( 'lr_schemas_path' )} ) {
        return "$dir/$schema_name.xml"
          if -f "$dir/$schema_name.xml";
    }

    return undef;
}

=pod

=head2 superservices()

Returns the name of the available superservices in an array.

=cut

sub superservices {
    my $self = $_[0];

    return grep { /^[^-]+$/ } $self->schemas();
}

=pod

=head2 schemas()

Returns the name of the available schemas in an array.

=cut

sub schemas {
    my $self = $_[0];

    my @schemas = keys %SCHEMA_CACHE;
    foreach my $dir ( @{ Lire::Config->get( 'lr_schemas_path' ) } ) {
        next unless -d $dir && -r $dir;
        opendir my $dh, $dir
          or croak "opendir failed on '$dir': $!";
        foreach my $file ( readdir $dh ) {
            next unless $file =~ /^([a-zA-Z][-\w.:]+)\.xml$/;
            push @schemas, $1
              unless grep { $_ eq $1 } @schemas;
        }
        closedir $dh;
    }

    return @schemas;
}

=pod

=head1 SCHEMA OBJECT METHODS

=head2 id()

    my $id = $schema->id();

This method will return the id of the schema. This will be the
superservice's name for superservice's main schema. (There are other
types of schemas (derived and extended schemas) for which the id will be
different than the superservice's name.)

=cut

sub id {
    return $_[0]->{'id'};
}

=pod

=head2 superservice()

    my $super = $schema->superservice();

This method will return the superservice's name of the schema.

=cut

sub superservice {
    return $_[0]->{'superservice'};
}

=pod

=head2 title( [$new_title] )

This method will return (or change) the human readable title of the
schema. (This is the content of the title element in the XML
specification.)

=cut

sub title {
    my $self = $_[0];

    if ( @_ == 2 ) {
        check_param( $_[1], 'title' );
        $self->{'title'} = $_[1];
    }
    return dgettext( "lire-$self->{'superservice'}", $self->{'title'} );
}

=pod

=head2 description( [$new_description] )

This method will return (or change) the description of the schema.
(This is the content of the description element in the XML
specification.) Be aware that this will most likely contain DocBook
markup.

=cut

sub description {
    my $self = $_[0];

    if ( @_ == 2 ) {
        $self->{'description'} = $_[1];
    }
    return dgettext_para( "lire-$self->{'superservice'}",
                          $self->{'description'} );
}

=pod

=head2 field_by_pos()

    my $field = $schema->field_by_pos( 0 );

This method takes an integer as parameter and return the field at that
position in the schema. Fields are indexed starting at 0. This method
will die() if an invalid position is passed as parameter.

The method returns a Lire::Field(3pm) object.

=cut

sub field_by_pos {
    my ( $self, $pos ) = @_;
    croak "invalid field number: $pos"
      unless $pos < @{$self->{'fields_by_pos'}} && $pos >= 0;

    return $self->{'fields_by_pos'}[$pos];
}

=pod

=head2 add_field( $field )

Adds the Lire::Field $field to this schema.

=cut

sub add_field {
    my ( $self, $field ) = @_;

    check_object_param( $field, 'field', 'Lire::Field' );

    push @{$self->{'fields_by_pos'}}, $field;
    $self->{'fields_by_name'}{$field->name()} = $field;
    $field->{'pos'} = $#{$self->{'fields_by_pos'}};

    return;
}

=pod

=head2 has_field()

    if ( $schema->has_field( 'test ) ) { 
	print "schema has field 'test'\n"; 
    }

This method takes a string as parameter and returns a boolean value.
That value will be true if there is a field in the schema with that
name, it will be false otherwise.

=cut

sub has_field {
    my ($self, $name ) = @_;

    return exists $self->{'fields_by_name'}{$name};
}


=pod

=head2 field()

    my $field = $schema->field( 'from_email' );

This method takes a field's name as parameter and returns the
Lire::Field(3pm) object describing that field in the schema. The
method will die() if there is no field with that name in the schema.

=cut

sub field {
    my ( $self, $name ) = @_;

    croak "no field by that name: $name"
      unless $self->has_field( $name );

    return $self->{'fields_by_name'}{$name};
}

=pod

=head2 fields()

    my $fields = $schema->fields();
    my @fields = $schema->fields();

In array context, this method will return an array containing all the
fields (as Lire::Field(3pm) objects) in the schema. The order of the
fields in the array is the order of the fields in the schema.

In scalar context, it will return an array reference. This method is
more efficient than creating an array. DO NOT MODIFY THE RETURNED
ARRAY.

=cut

sub fields {
    return wantarray ? @{$_[0]{'fields_by_pos'}} : $_[0]{'fields_by_pos'};
}

=pod

=head2 field_names()

Returns the name of the fields in this schema. The names are in the
same order than the fields.

=cut

sub field_names {
    return map { $_->name() } $_[0]->fields();
}

=pod

=head2 field_count()

    my $number_of_field = $schema->field_count;

This method returns the number of fields in the schema.

=cut

sub field_count {
    return scalar @{$_[0]->{'fields_by_pos'}};
}

=pod

=head2 timestamp_field()

    my $time_field = $schema->timestamp_field;

This method will return the Lire::Field(3pm) object representing the
timestamp field in the schema. The timestamp field is the one that
defines the sort order of the DLF records.

=cut

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

    return $self->field( $self->{'timestamp_field'} );
}

=pod

=head2 is_schema_compatible()

    if ( $schema->is_schema_compatible( $other_schema ) ) {

    }

This method takes a Lire::DlfSchema(3pm) object as parameter and returns a
boolean value. That value will be true if the schema passed as parameter is
compatible with the other, it will be false otherwise.

For a superservice's schema, the only compatible schema is an object
representing the same superservice's schema.

=cut

sub is_schema_compatible {
    my ( $self, $schema ) = @_;

    return $schema eq $self->{'id'};
}

=pod

=head2 can_join_schema( $schema ) 

Returns true if $schema can be joined with this schema. For a
DlfSchema, this will be true only when $schema is an ExtendedSchema of
this schema.

=cut

sub can_join_schema {
    my ( $self, $schema ) = @_;

    check_object_param( $schema, 'schema', 'Lire::DlfSchema' );

    return ( $schema->isa( 'Lire::ExtendedSchema' )
             && $schema->base() eq $self );
}

sub ascii_dlf_escape_field {
    # Escape the value :
    #   replace space with _
    #   replace 8 bit chars with ?
    #   replace control chars with ?
    return $_[0] =~ tr/ \200-\377\000-\037/_?/;
}

# This method is part of the old style, now deprecated, DLF converter API.

# It takes as parameters a list of field's names that are available in
# the DLF output by the converter. (Not all services in a given
# superservice will support the whole or the same subset of the
# superservice's fields. Unsupported fields should contain the value
# C<LIRE_NOTAVAIL> in the output DLF.)

# This method will return an anonymous subroutine that should be used by
# the DLF converter to create the DLF records. The generated subroutine
# takes as parameter a hash reference representing the DLF record to
# create. It returns an array reference representing the DLF record's
# fields. It will make sure that the field's values are in the correct
# order, that the unavailable fields are marked correctly, that missing
# fields are defaulted and that the field's values are escaped
# appropriately.

# The hash's keys should be the DLF record's field names with the value
# of the field associated to the key. All the fields that are available
# (as specified when the method is called) which are undefined or that
# aren't present in the hash will be set in the output DLF record to the
# field's default value specified in the schema. Extra keys in the hash
# will be ignored. Fields that aren't supported (as specified when the
# subroutine was created by the make_hashref2asciidlf_func() method)
# will contain the C<LIRE_NOTAVAIL> value.

# One can write an ASCII DLF by printing the returned array reference
# using a space as the join delimiter:

#     my $dlf = $dlf_maker->( $hash_dlf );
#     print join( " ", @$dlf ), "\n";

# See the SYNOPSIS section for an example.

# Beware!  New DLF convertors should use the Lire::DlfConverterProcess
# interface.
sub make_hashref2asciidlf_func {
    my ( $self, @fields ) = @_;

    my %avail = map { $_ => 1 } @fields;
    my @ascii_dlf_tmpl = ();
    foreach my $field ( @{$self->fields}) {
	push @ascii_dlf_tmpl, [ $field->name, $field->default() ];
    }

    return sub {
	my ($hash) = @_;

	my $dlf = [];
	foreach my $field_tmpl ( @ascii_dlf_tmpl ) {
	    my $name	= $field_tmpl->[0];
	    my $value;
	    if ( $avail{$name} ) {
		if (defined $hash->{$name} && length $hash->{$name}) {
		    $value = $hash->{$name};
		} else {
		    $value = $field_tmpl->[1]; # Use default
		}
		ascii_dlf_escape_field( $value );
	    } else {
		$value = "LIRE_NOTAVAIL";
	    }
	    push @$dlf, $value;
	}

	return $dlf;
    };
}


=pod

=head1 SQL Related Methods

These methods are used to map DLF record into SQL tables.

=head2 sql_table()

Returns the SQL table used to hold the DLF records of this schema.

=cut

sub sql_table {
    my ( $self, $prefix, $suffix ) = @_;

    $prefix = ""
      unless defined $prefix;
    $suffix = ""
      unless defined $suffix;

    return sql_quote_name( $prefix . 'dlf_' . $_[0]->{'id'} . $suffix );
}

=pod

=head2 create_sql_schema( $dlf_store, [ $remove ] )

This will create the SQL schemas necessary to hold the DLF records for
this schema in the Lire::DlfStore. If $remove is true, a DROP TABLE
will be done before creating the schema.

=cut

sub create_sql_schema {
    my ($self, $store, $remove ) = @_;

    check_object_param( $store, 'store', 'Lire::DlfStore' );

    $store->_dbh()->do( "DROP TABLE " . $self->sql_table() )
      if $remove;
    $store->_dbh()->do( $self->_create_sql_table_query() );

    my $idx_sql = sprintf( "CREATE INDEX %s ON %s ( %s )",
                           $self->sql_table( "", "_" . $self->{'timestamp_field'} . "_idx"),
                           $self->sql_table(),
                           $self->{'timestamp_field'} );
    $store->_dbh()->do( $idx_sql );

    return;
}

sub _create_sql_table_query {
    return "CREATE TABLE " . $_[0]->sql_table() . " "
      . $_[0]->_sql_fields_def();
}

=pod

=head2 needs_sql_schema_migration( $dlf_store )

This method will return true if the SQL schema isn't up-to-date in the
DlfStore. The method migrate_sql_schema() can be used to bring the
schema up to date.

=cut

sub needs_sql_schema_migration {
    my ( $self, $store ) = @_;

    check_object_param( $store, 'store', 'Lire::DlfStore' );

    my $create_sql = $self->_create_sql_table_query();

    # SQLite will remove trailing newline
    chomp $create_sql;

    my $sql = "SELECT sql FROM sqlite_master WHERE type = 'table' AND name=?";
    my $sth = $store->_dbh()->prepare( $sql );
    $sth->execute( $self->sql_table() );
    my $table_def = $sth->fetchrow_arrayref();
    $sth->finish();

    return $table_def && $table_def->[0] ne $create_sql;
}

=pod

=head2 migrate_sql_schema( $dlf_store )

Updates the SQL schemas to the current version.

=cut

sub migrate_sql_schema {
    my ( $self, $store ) = @_;

    check_object_param( $store, 'store', 'Lire::DlfStore' );

    # SQLite doesn't support ALTER TABLE
    # Find the list of fields in common
    my @fields = $self->_find_fields_in_schema( $store );

    # Create temporary backup
    my $sql = sprintf( "CREATE TEMP TABLE %s AS SELECT * FROM %s",
                       $self->sql_table( "temp_" ),
                       $self->sql_table() );
    $store->_dbh()->do( $sql  );

    # Recreate the schema
    $self->create_sql_schema( $store, 1 );

    # Migrate the data
    my @common_fields = ();
    foreach my $f ( @fields ) {
        push @common_fields, $f if $self->has_field( $f );
    }

    $sql = $self->_migration_insert_query( \@common_fields );
    $store->_dbh()->do( $sql );
    $store->_dbh()->do( "DROP TABLE " . $self->sql_table( "temp_" ) );
    return;
}

sub _find_fields_in_schema {
    my ( $self, $store ) = @_;

    # Since DBD::SQLite doesn't support the column_info API
    # we run a query to find the fields present in the schema.
    my $sth = $store->_dbh()->prepare( "SELECT * FROM " . $self->sql_table()
                                       . " LIMIT 1" );
    $sth->execute();

    my @fields = @{$sth->{'NAME'}};
    $sth->finish();

    return @fields;
}

sub _migration_insert_query {
    my ( $self, $common_fields ) = @_;

    # New fields will be set to NULL
    # Old fields aren't migrated

    my $field_list = join (", ", map { sql_quote_name( $_ ) } @$common_fields);
    return sprintf( "INSERT INTO %s (%s) SELECT %s FROM %s",
                    $self->sql_table(),
                    $field_list, $field_list,
                    $self->sql_table( "temp_" ) );
}

sub _sql_fields {
    return $_[0]->fields();
}

sub _sql_fields_def {
    my $self = $_[0];

    my @defs = ();
    foreach my $f ( $self->_sql_fields() ) {
        push @defs, "    " . sql_quote_name( $f->name() ) . " " . 
          $f->sql_type();
    }

    return "(\n" . join( ",\n", @defs ) . "\n)\n";
}


=pod

=head2 dlf_query( $sort_spec )

Returns a Lire::DlfQuery object which can be use to return all DLF
records sorted according to $sort_spec. Sort spec is a white-space
delimited list of sort field names. They must be present in the
current schema. If the field's name is prefixed by '-', descending
sort order will be used.

=cut

sub dlf_query {
    my ( $self, $sort_spec ) = @_;

    my $query = new Lire::DlfQuery( $self->{'id'} );
    foreach my $f ( $self->fields() ) {
        $query->add_field( $f->name() );
    }

    $query->set_sort_spec( $sort_spec )
      if $sort_spec;

    return $query;
}

=pod

=head2 insert_sql_query()

Returns the INSERT SQL statement that should be used to insert DLF
records in the stream. A DBI::st handle prepared with that query needs
to be passed as parameter to execute_insert_query().

=cut

sub sql_insert_query {
    my $self = $_[0];

    my @fields = map { $_->name() } $self->_sql_fields();
    return "INSERT INTO " . $self->sql_table() . " ("
      . join( ", ", map { sql_quote_name( $_ ) } @fields ) . ") VALUES ("
      . join( ",", ("?") x scalar @fields  ) . ")";
}

=pod

=head2 sql_clean_query( $with_time )

Returns the DELETE statement that can be use to delete the DLF records
in this schema. If $with_time is true, the query can be use for
selective cleaning. One bind timestamp parameter should be passed when
the query is executed and all records which are older than this
timestamp will be deleted.

=cut

sub sql_clean_query {
    my ($self, $with_time) = @_;

    my $table = $self->sql_table();
    if ( $with_time ) {
        my $ts_field = sql_quote_name( $self->{'timestamp_field'} );
        return qq{DELETE FROM $table WHERE $ts_field < ?};
    } else {
        return "DELETE FROM $table";
    }
}

=pod

=head2 sql_clean_period_query()

Returns the DELETE statement that can be use to delete the DLF records
in this schema. The query should be passed two bind parameters. These
parameters will be the time boundaries between which records should be
deleted from the schema.

=cut

sub sql_clean_period_query {
    my $self = $_[0];

    my $table = $self->sql_table();
    my $ts_field = sql_quote_name( $self->{'timestamp_field'} );
    return qq{DELETE FROM $table WHERE $ts_field >= ? AND $ts_field < ?};
}

use vars qw( $LDSML_NS %LDSML_ELEMENTS );

BEGIN {
    %LDSML_ELEMENTS = map { $_ => 1 } qw( dlf-schema derived-schema
					  extended-schema field
					  title description );
    $LDSML_NS = "http://www.logreport.org/LDSML/";
}

sub Init {
    my ($expat) = @_;

    $expat->{'lire_curr_schema'} = undef;
    $expat->{'lire_curr_field'}  = undef;
    $expat->{'lire_curr_desc'}   = undef;

    return;
}

sub Final {
    my ( $expat ) = @_;

    return $expat->{'lire_curr_schema'};
}

sub Start {
    my ( $expat, $name ) = @_;

    my $ns = $expat->namespace($name);
    $ns ||= ""; # Remove warnings
    if ( $ns eq $LDSML_NS ) {
	# This is one of our element
	error( $expat, "unknown element: $name" )
	  unless exists $LDSML_ELEMENTS{$name};

	{
	    no strict 'refs';

	    my $sub = $name . "_start";
	    $sub =~ s/-/_/g;	# Hyphen aren't allowed in element name

	    $sub->( @_ );
	};
    } else {
	# If we are in lire:description, this is probably a
	# DocBook element, append it to the current description.
	my $lire_desc = $expat->generate_ns_name( "description", $LDSML_NS );
	if ( $expat->within_element( $lire_desc ) ) {
	    $expat->{'lire_curr_desc'} .= $expat->original_string();
	} else {
	    error( $expat, "unknown element: $name" );
	}
    }
    return;
}

sub End {
    my ( $expat, $name ) = @_;

    my $ns = $expat->namespace($name);
    $ns ||= ""; # Remove warnings
    if ( $ns eq $LDSML_NS ) {
	# This is one of our element
	error( $expat, "unknown element: $name" )
	  unless exists $LDSML_ELEMENTS{$name};

	{
	    no strict 'refs';

	    my $sub = $name . "_end";
	    $sub =~ s/-/_/g;	# Hyphen aren't allowed in element name

	    $sub->( @_ );
	}
    } else {
	# If we are in lire:description, this is probably a
	# DocBook element, append it to the current description.
	my $lire_desc = $expat->generate_ns_name( "description", $LDSML_NS );
	if ( $expat->within_element( $lire_desc ) ) {
	    $expat->{'lire_curr_desc'} .= $expat->original_string();
	} else {
	    error( $expat, "unknown element: $name" );
	}
    }
    return;
}

sub Char {
    my ( $expat, $str ) = @_;

    # Character should only appear in title and description
    my $lire_title = $expat->generate_ns_name( "title", $LDSML_NS );
    my $lire_desc  = $expat->generate_ns_name( "description", $LDSML_NS );

    if ( $expat->in_element( $lire_title )) {
	$expat->{'lire_curr_title'} .= $str;
    } elsif ( $expat->within_element( $lire_desc )) {
	# Use original_string because we don't want parsed entities.
	$expat->{'lire_curr_desc'}  .= $expat->original_string();
    }
    return;
}

sub dlf_schema_start {
    my ( $expat, $name, %attr ) = @_;

    eval {
	$expat->{'lire_curr_schema'} = new Lire::DlfSchema( %attr );
    };
    error( $expat, $@ ) if $@;
    return;
}

sub dlf_schema_end {
    my ( $expat, $name ) = @_;
    eval {
	$expat->{'lire_curr_schema'}->check();
    };
    error( $expat, $@ ) if $@;
    return;
}

sub derived_schema_start {
    my ( $expat, $name, %attr ) = @_;

    eval {
	$expat->{'lire_curr_schema'} = new Lire::DerivedSchema( %attr );
    };
    error( $expat, $@ ) if $@;
    return;
}

sub derived_schema_end {
    my ( $expat, $name ) = @_;
    eval {
	$expat->{'lire_curr_schema'}->check();
    };
    error( $expat, $@ ) if $@;
    return;
}

sub extended_schema_start {
    my ( $expat, $name, %attr ) = @_;

    eval {
	$expat->{'lire_curr_schema'} = new Lire::ExtendedSchema( %attr );
    };
    error( $expat, $@ ) if $@;
    return;
}

sub extended_schema_end {
    my ( $expat, $name ) = @_;
    eval {
	$expat->{'lire_curr_schema'}->check();
    };
    error( $expat, $@ ) if $@;
    return;
}

sub error {
    my ( $expat, $msg ) = @_;

    my $line = $expat->current_line();

    croak $msg, " at line ", $line, "\n";
    return;
}

sub field_start {
    my ( $expat, $name, %attr ) = @_;

    check_param( $attr{'name'}, 'name', \&check_xml_name,
                 'invalid field name' );
    check_param( $attr{'type'}, 'type', \&check_type,
                 'invalid value for type attribute' );

    $expat->{'lire_curr_field'} =
      new Lire::Field( 'name' => $attr{'name'},
                       'i18n_domain' => 'lire-'. $expat->{'lire_curr_schema'}->superservice(),
                       'type'	    => $attr{'type'},
                       'label'    => $attr{'label'},
                     );

    return;
}

sub field_end {
    my ( $expat, $name ) = @_;

    $expat->{'lire_curr_schema'}->add_field( $expat->{'lire_curr_field'} );
    delete $expat->{'lire_curr_field'};

    return;
}

sub title_start {
    my ( $expat, $name ) = @_;

    $expat->{'lire_curr_title'} = "";
    return;
}

sub in_schema_element {
    my ( $expat ) = @_;
    my $lire_dlf_schema = $expat->generate_ns_name( "dlf-schema", $LDSML_NS );
    my $lire_ext_schema = $expat->generate_ns_name( "extended-schema",
						    $LDSML_NS );
    my $lire_der_schema = $expat->generate_ns_name( "derived-schema",
						    $LDSML_NS );

    return $expat->in_element( $lire_dlf_schema ) ||
      $expat->in_element( $lire_ext_schema ) ||
      $expat->in_element( $lire_der_schema );

}

sub title_end {
    my ( $expat, $name ) = @_;

    my $lire_field = $expat->generate_ns_name( "field", $LDSML_NS );

    if ( $expat->in_element( $lire_field)) {
	$expat->{'lire_curr_field'}{'title'} = $expat->{'lire_curr_title'};
    } elsif ( in_schema_element( $expat ) ) {
	$expat->{'lire_curr_schema'}{'title'} = $expat->{'lire_curr_title'};
    } else {
	error( $expat, "encountered unexpected title" );
    }
    return;
}

sub description_start {
    my ( $expat, $name ) = @_;

    $expat->{'lire_curr_desc'} = "";
    return;
}

sub description_end {
    my ( $expat, $name ) = @_;

    my $lire_field = $expat->generate_ns_name( "field", $LDSML_NS );

    if ( $expat->in_element( $lire_field)) {
	$expat->{'lire_curr_field'}{'description'} = $expat->{'lire_curr_desc'};
    } elsif ( in_schema_element( $expat )) {
	$expat->{'lire_curr_schema'}{'description'} = $expat->{'lire_curr_desc'};
    } else {
	error( $expat, "encountered unexpected description" );
    }
    return;
}

# keep perl happy
1;

__END__

=pod

=head1 SEE ALSO

Lire::Field(3pm), Lire::ExtendedSchema(3pm), Lire::DlfConverter(3pm),
Lire::DerivedSchema(3pm)

=head1 AUTHOR

  Francis J. Lacoste <flacoste@logreport.org>

=head1 VERSION

$Id: DlfSchema.pm,v 1.58 2006/07/23 13:16:28 vanbaal Exp $

=head1 COPYRIGHT

Copyright (C) 2001, 2002, 2004 Stichting LogReport Foundation LogReport@LogReport.org

This file is part of Lire.

Lire 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.

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 (see COPYING); if not, check with
http://www.gnu.org/copyleft/gpl.html.

=cut