lib/Org/ReadTables.pm

filter: Statementstmt 84.6% 11 / 13 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 5 / 5 Podpod n/a totaltotal 88.8% 16 / 18 CC 1 SCAR 0.6
CC
1
Cov
85%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.1
↑ Summary
1 #
2 # from directory above this, use e.g.,
3 #
4 # $ prove -l lib t/prove.t
5 #
6  
7 package Org::ReadTables v0.0.4 {
8  
9 2 ▶ use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 2 ▶ use List::Util qw(any);
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 2 ▶ use feature 'signatures';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶ no warnings qw(experimental::signatures);
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 ################
16 # Parse tables from an Org-mode file into our database
17 #
18 ################
19  
20 0 ▶ use Org::Parser;
Subroutine BEGIN: called CC=1 SCAR=2.6
21  
22 sub new ($class, %args) {
23 my $self = bless {}, $class;
24 foreach my $arg (qw(dbh table tables cb cb_table)) {
25 $self->{$arg} = $args{$arg} if defined $args{$arg};
26 }
27 if (defined $self->{dbh}) {
28 if (ref $self->{dbh}) {
29 if (!$self->{dbh}->can('insert')) {
30 warn "Database handle should provide an 'insert' method";
31 }
32 } else {
33 warn "'dbh' should be a database handle";
34 }
35 }
36 return $self;
37 }
38  
39 sub errors ($self) {
40 return $self->{errors};
41 }
42  
43 sub inserted ($self, $table = undef) {
44 if (defined $table) {
45 return defined $self->{inserted} && exists $self->{inserted}->{$table} ? $self->{inserted}->{$table} : undef;
46 } else {
47 return $self->{inserted}; # All tables
48 }
49 return $self->{inserted};
50 }
51  
52 sub saved ($self, $table = undef) {
53 if (defined $table) {
54 return defined $self->{saved} && exists $self->{saved}->{$table} ? $self->{saved}->{$table} : undef;
55 } else {
56 return $self->{saved}; # All tables
57 }
58 }
59  
60 sub secondary ($self, $table = undef) {
61 if (defined $table) {
62 return defined $self->{alt} && exists $self->{alt}->{$table} ? $self->{alt}->{$table} : undef;
63 } else {
64 return $self->{alt}; # All tables
65 }
66 }
67  
68 sub parse ($self, $text, $default_table = undef) {
69  
70 state $table; # as a 'state' so the nested 'walk' subroutine can use it
71 state $db;
72 state $errors = [];
73 state $inserted = 0; # 'state' so it can be seen by 'walk'
74 state $saved; # ...and by 'flush_row'
75 state $self_copy;
76 state $fixed_columns;
77 state $pivot;
78 state $data_column;
79 state $caption;
80  
81 sub flush_row {
82 my ($columns, $values) = @_;
83 my $save_fields;
84 return unless defined $table && length($table);
85 foreach my $generated ( 0 .. (defined $pivot ? scalar $pivot->{column_ids}->@* -1 : 0) ) {
86 $save_fields = { defined $fixed_columns ? %$fixed_columns : () }; # Start with a copy of any fixed columns
87 if (defined $pivot) {
88 # Save ordinary columns
89 foreach my $c ($pivot->{ordinary_column_ids}->@*) {
90 $save_fields->{$columns->[$c]} = $values->[$c];
91 }
92 $save_fields->{$pivot->{column_name}} = $pivot->{columns}->[$generated];
93 next unless defined ( $save_fields->{$pivot->{data_column}} = $values->[$pivot->{column_ids}->[$generated]]);
94 } else {
95 @{$save_fields}{@{$columns}} = @{$values};
96 }
97 if ( defined $self_copy->{cb} ) {
98 if ( $self_copy->{cb}->($table, $save_fields) ) {
99 do { push @{$saved->{$table}}, $save_fields; 1; };
100 $inserted++;
101 }
102 } elsif ( defined $db ?
103 eval { $db->insert($table, $save_fields); 1; } :
104 do { push @{$saved->{$table}}, $save_fields; 1; } ) {
105 $inserted++;
106 } else {
107 push @{$errors} , [ $save_fields, $@ ];
108 }
109 }
110 }
111  
112 sub walk {
113 # Ignore leading TableHLine
114 # Find first row(s) with TableCell and accumulate column names
115 # Require a TableHLine to proceed
116 # For each TableRow, accumulate column values and save row.
117 #
118 # NOTE: Must call an extra time with a 'fake' TableRow afterwards,
119 # to flush the final row.
120  
121 my ($el, $level) = @_;
122  
123 state $in_header;
124 state $found_header_row;
125 state $column;
126 state $is_data_row;
127 state @columns;
128 state @values;
129 if ((ref $el) =~ /Table\z/i) {
130 $in_header = 1;
131 $found_header_row = 0;
132 $inserted = 0;
133 @columns = ();
134 @values = ();
135 $pivot = defined $data_column ? {data_column => $data_column} : undef;
136 } elsif ((ref $el) =~ /TableHLine\z/i) {
137 if ($found_header_row) {
138 #
139 # Skip this table if the callback returns a false value.
140 #
141 @columns = map {lc} @columns if $in_header;
142 my @reported_columns = @columns;
143 if (defined $pivot) { # Remove pivoted columns
144 if (defined $pivot->{data_column} && (!exists $pivot->{column_ids} || !scalar $pivot->{column_ids}->@*)) {
145 # 'data' was used as a fixed value, without any pivot columns being defined.
146 $fixed_columns->{'data'} = $pivot->{data_column};
147 undef $pivot;
148 } else {
149 foreach my $c (0..$#columns) { # Exclude pivoted columns from ordinary processing
150 push $pivot->{ordinary_column_ids}->@*, $c unless any { $_==$c } $pivot->{column_ids}->@*;
151 }
152 @reported_columns = map { $columns[$_] } $pivot->{ordinary_column_ids}->@*;
153 if (defined $pivot->{alt}) {
154 $self_copy->{alt}->{$table} = { lc($pivot->{column_name}) => $pivot->{alt} };
155 }
156 }
157 }
158 if ($in_header && defined $self_copy->{cb_table}) {
159 undef $table unless $self_copy->{cb_table}->({ name => $table,
160 nameref => \$table, # Modifiable
161 ( defined $fixed_columns ? (fixed => $fixed_columns) : ()),
162 columns => \@columns,
163 caption => $caption,
164 });
165 }
166 $in_header = 0;
167 }
168 } elsif ((ref $el) =~ /TableRow\z/i) {
169 if ($in_header) {
170 foreach my $c (0 .. scalar @columns-1) {
171 if ($columns[$c] =~ /(.+)>/) {
172 last unless defined $pivot; # Skip this row if no usable data column
173 if (!defined $pivot->{column_name}) { # Create new pivot table
174 $pivot->{column_name} = $1;
175 $pivot->{column_ids} = [grep { $_ != $c && defined $columns[$_] } 0 .. scalar @columns-1];
176 $pivot->{columns} = [@columns[$pivot->{column_ids}->@*]];
177 last;
178 } else { # Define a secondary table
179 my $row_name = $1;
180 foreach my $cci (0 .. scalar $pivot->{column_ids}->@* -1 ) { #
181 my $cc = ($pivot->{column_ids}->[$cci]);
182 my $col_key = lc( $pivot->{columns}->[$cci] );
183 my $row_key = lc( $row_name );
184 my $val = \$pivot->{alt}->{$col_key}->{$row_key};
185 $$val = length $$val ? "$$val $columns[$cc]" : $columns[$cc];
186 }
187 }
188 }
189 }
190 }
191 if ($is_data_row) { # Flush previous row
192 flush_row (\@columns, \@values);
193 $is_data_row = 0;
194 }
195 $found_header_row = 1;
196 $column = -1;
197 @values = ();
198 } elsif ((ref $el) =~ /TableCell\z/i) {
199 $column++;
200 } elsif ((ref $el) =~ /Text\z/i) {
201 if ($in_header) {
202 $columns[$column] = $el->as_string;
203 } else {
204 $values[$column] = $el->as_string;
205 $is_data_row = 1;
206 }
207 $is_data_row = 1 unless ($in_header);
208 }
209 }
210  
211 my $orgp = Org::Parser->new;
212 my $org_doc = $orgp->parse($text);
213 my @tables = $org_doc->find('Table');
214 $self_copy = $self;
215 $saved = {};
216 $errors = [];
217 $db = $self->{dbh};
218  
219 foreach my $t (@tables) {
220 # Look for NAME property as Settings element in
221 # prev_siblings; also look for PROPERTIES drawer
222 # (containing NAME property) in prev_siblings, ignoring
223 # whitespace-only Text elements
224 undef $table;
225 my $prev_elem = $t->prev_sibling;
226 undef $fixed_columns;
227 undef $pivot;
228 undef $data_column;
229  
230 if (defined $prev_elem) {
231 ELEMENT:
232 while (defined $prev_elem) {
233 # Only regard settings and drawers between headlines or tables.
234 last ELEMENT if ref $prev_elem eq 'Org::Element::Table';
235 # Formerly we looked for a
236 # 'Org::Element::Headline' here, but actually that
237 # would always be the *parent* element. Perhaps
238 # we want to default to
239 # »$t->headline->title->as_string« ?
240  
241 # NOTE: Internal links (»#+NAME: sometable«) are
242 # always followed by all-whitespace Text (see
243 # t/drawer.t in Org::Parser). Ignore them.
244 next ELEMENT if ref $prev_elem eq 'Org::Element::Text' &&
245 $prev_elem->as_string =~ /^\s*\z/;
246  
247 if (ref $prev_elem eq 'Org::Element::Setting') {
248 # e.g., »#+NAME: sometable«
249 if ($prev_elem-> name =~ /^name\z/i) {
250 $table = $prev_elem->args->[0];
251 } elsif ($prev_elem-> name =~ /^data\z/i) {
252 $data_column = $prev_elem->args->[0];
253 } elsif ($prev_elem-> name =~ /^caption\z/i) {
254 $caption = $prev_elem->args->[0];
255 } elsif ($prev_elem->name =~ /^property\z/i && scalar @{$prev_elem->args} > 1) {
256 # Double quotes may be used around a
257 # string with spaces; otherwise this will
258 # add a single space between words.
259 $fixed_columns->{$prev_elem->args->[0]} =
260 join(' ',@{$prev_elem->args}[1..scalar @{$prev_elem->args}-1]);
261 }
262 } elsif (ref $prev_elem eq 'Org::Element::Drawer') {
263 # We regard the internal-link-target syntax
264 # «#+NAME: some_table» as meaning, Insert the
265 # following orgmode table into database table
266 # `some_table` (see orgmode manual §4.2
267 # "Internal Links")
268 #
269 # TODO: Verify column names and skip
270 # non-existent ones; otherwise, adding
271 # properties that do not map to sql column
272 # names will result in errors and no rows
273 # inserted!
274 #
275 foreach my $k ( keys %{$prev_elem->properties} ) {
276 if ($k =~ /^name\z/i) {
277 $table = $prev_elem->properties->{$k};
278 } elsif ($k =~ /^data\z/i) {
279 $data_column = $prev_elem->properties->{$k};
280 } else {
281 $fixed_columns->{$k} = $prev_elem->properties->{$k};
282 }
283 }
284 last ELEMENT unless !defined $table;
285 # Only process one drawer. If neither NAME nor
286 # default table (from new() or in parse()
287 # call) is given, this attached table will be
288 # skipped (see below).
289 }
290 }
291 continue {
292 $prev_elem = $prev_elem->prev_sibling;
293 }
294 }
295 $table //= $default_table // $self->{table};
296  
297 # TODO: When NAME property is encountered, check against our `table` or
298 # `tables` attributes to verify we can load this data
299 next unless defined $table;
300 if (defined $self->{tables} && ref $self->{tables} eq 'ARRAY') {
301 next unless any { $table eq $_ } @{$self->{tables}};
302 }
303  
304 $t->walk(\&walk); # Process all rows in this table
305 walk(Org::Element::TableRow->new, 0); # Flush last row in final table
306 $self->{errors} = $errors;
307 $self->{inserted}->{$table} += $inserted ;
308 $self->{saved} = $saved;
309 }
310 return $inserted;
311 }
312  
313 };
314  
315 1;
316  
317 =encoding utf8
318  
319 =head1 NAME
320  
321 Org::ReadTables - Import Org Mode tables into arrays, or
322 directly into database tables
323  
324 =head1 SYNOPSIS
325  
326 use Org::ReadTables;
327  
328 my $op = Org::ReadTables->new( dbh => $dbh,
329 table => 'example',
330 tables => ['a_table']
331 );
332 # or:
333 # When called without a 'dbh' argument, saves values
334 # which can be retrieved via the 'saved' method.
335 #
336 my $op = Org::ReadTables->new( cb => \&row_callback,
337 cb_table => \&table_callback,
338 );
339 # then:
340 $op->parse( $mojo_file->slurp );
341  
342 =head1 DESCRIPTION
343  
344 L<Org::ReadTables> loads data from one or more C<Emacs> Org Mode
345 tables in an org file into a L<DBI> style database which supports the
346 C<SQL::Abstract/insert> method. The underlying C<DBD> must also
347 support the C<returning> option for insertion.
348  
349 For example, given the following .org file:
350  
351 #+NAME: LCCN_Serial
352 | LCCN | Publication | City | Start_Date | End_Date |
353 |------------+-----------------------+---------+------------+------------|
354 | sn92024097 | Adahooniłigii | Phoenix | | |
355 | sn87062098 | Arizona Daily Citizen | Tucson | | |
356 | sn84020558 | Arizona Republican | Phoenix | | 1930-11-10 |
357 | sn83045137 | Arizona Republic | Phoenix | 1930-11-11 | |
358  
359 and a database containing a table called lccn_serial, the C<parse>
360 method would insert four rows into it, in the fields whose names are
361 given in the column headings.
362  
363 The C<NAME:> org attribute specifies the table name; a default value
364 may be passed in the C<table> parameter to the C<new> method.
365 Additionally, a C<tables> array may be passed by reference against
366 which the names of such tables will be validated; table names not
367 listed will have their org tables skipped.
368  
369 Table names may also be specified in a C<Name> property (not
370 case-sensitive) in an Orgmode Drawer preceding the table. For
371 example:
372  
373 :PROPERTIES:
374 :Name: Locos
375 :END:
376 | Wheel Arrangement | Locomotive Type |
377 |-------------------+-----------------|
378 | oo-oo> | American |
379 | ooo-oo> | Mogul |
380  
381 Additionally, with the Drawer format, fixed column values may
382 optionally be specified:
383  
384 :PROPERTIES:
385 :Name: Locos
386 :Country: .us
387 :END:
388 | Wheel Arrangement | Locomotive Type |
389 |-------------------+-----------------|
390 | oo-oo> | American |
391 | ooo-oo> | Mogul |
392  
393 which would have the effect of adding a 'country' column to the right
394 of each record, all having the value '.us'.
395  
396 =head2 Pivot Tables
397  
398 When it is desirable to enter data two-dimensionally, a construct like
399 this may be used:
400  
401 :PROPERTIES:
402 :Name: sizes
403 :Data: size_desc
404 | class> | A | B | C |
405 | size_code | | | |
406 |------------+-------+-------+-----|
407 | 1 | 1-2 | 22-26 | |
408 | 2 | 3-4 | 26-30 | XS |
409 | 3 | 5-6 | 30-34 | S |
410  
411 where the `Data` property determines which field (column) is assigned
412 the pivoted value. The above table would generate eight data records
413 for the `sizes` table:
414  
415 size_code='1', class='A', size_desc='1-2'
416 size_code='1', class='B', size_desc='22-26'
417 size_code='2', class='A', size_desc='3-4'
418 size_code='2', class='B', size_desc='26-30'
419 size_code='2', class='C', size_desc='XS'
420 size_code='3', class='A', size_desc='5-6'
421 size_code='3', class='B', size_desc='30-34'
422 size_code='3', class='C', size_desc='S'
423  
424 Note that no record is created for class 'C' with size_code '1' as
425 that entry in the pivot table is blank.
426  
427 Values in consecutive rows with the same field name will be
428 concatenated, separated by a space. Train names in the table below
429 will be "Texas Eagle" and "Southwest Chief" for example.
430  
431 | Train_no> | 21 | 22 | 3 | 4 |
432 | Train_name> | Texas | Texas | Southwest | Southwest |
433 | Train_name> | Eagle | Eagle | Chief | Chief |
434 | Station | | | | |
435 |-------------+-------+-------+-----------+-----------|
436  
437 Also note, renaming pivot columns in the table callback is not
438 permitted.
439  
440 =head1 ATTRIBUTES
441  
442 L<Org::ReadTables> implements the following attributes.
443  
444 =head2 inserted
445  
446 Returns a hashref, each element's key being the name of a table into
447 which rows were inserted, and its value being the number of rows
448 inserted into that table.
449  
450 =head2 errors
451  
452 Returns a reference to an array, each entry in which itself be an
453 array whose values are:
454  
455 =over 4
456  
457 =item
458 a hash (the column names and values to be inserted), and
459  
460 =item
461 the resulting error report from that insertion
462  
463 =back
464  
465 =head1 METHODS
466  
467 =head2 new
468  
469 Creates a new Org::ReadTables object. Parameters include:
470  
471 =head3 dbh
472  
473 should be an open database handle from, e.g., L<DBD::SQLite>,
474 L<Mojo::SQLite> or L<Mojo::Pg>. Each row to be saved will invoke the
475 'insert' method of this handle (or, more generally, class instance);
476 no other methods will be called, so any object that has provides
477 'insert' may be used. For each found record, the insert() method of
478 this object will be called. Note that no protection is given here
479 against invalid column names or other database errors.
480  
481 =head3 cb
482  
483 Reference to a callback function to be called for each found record,
484 in tables which are processed. Parameters passed are the name of the
485 table, and a reference to a hash of the record's column-names and
486 values. The function should return the count of records successfully
487 saved (either 0 or 1, usually).
488  
489 =head3 cb_table
490  
491 Reference to a callback function to be called at the start of
492 processing of a new table, as they are found in the orgfile.
493 The callback will be passed one argument, a hash with keys:
494  
495 =over
496  
497 =item *
498  
499 name: A string with the name of the table
500  
501 =item *
502  
503 nameref: A reference to the table-name string. This may be changed by
504 the callback.
505  
506 =item *
507  
508 columns: A reference to the array of the names of the columns in the
509 table. The contents of the referred array may be maniuplated to match
510 the actual database field names, for example.
511  
512 =item *
513  
514 fixed: A reference to a hash of fixed column key/values. This may also
515 be changed by the callback.
516  
517 =item *
518  
519 caption: The caption, if any, attached above the table itself
520  
521 =item *
522  
523 data_column: The name of the data column in a pivot table
524  
525 =back
526  
527 ...and should return a true value if the table is to be processed or
528 saved, or a false or 'undef' value to skip the table (the 'cb'
529 callback will not be called for rows in such tables).
530  
531 =head3 table
532  
533 (optional) the default table name, which will be used for all unnamed
534 tables. Use an Orgmode property C<NAME> before each table to name it,
535 as:
536  
537 #+NAME: PostalAbbrev
538 | Code | State |
539 |------+---------|
540 | AZ | Arizona |
541 | FL | Florida |
542 | KS | Kansas |
543  
544 =head3 tables
545  
546 (optional) a reference to a list of valid table names to process
547 (others will be ignored). If C<tables> is not given, C<table> should
548 be present; otherwise for input not containing an Orgmode C<NAME>
549 property, no processing will occur.
550  
551 =head2 parse
552  
553 $op->parse($text, [$default_table]);
554  
555 Parses the given text which should be in Org Mode format. It is the
556 caller's responsibility to slurp a file or other data source. The
557 optional second parameter will be used as the default name of any
558 table not having an Orgmode C<NAME> property, overriding any C<table>
559 value provided via the C<new> method.
560  
561 =head2 saved
562  
563 $op->saved();
564 $op->saved->($selected_table);
565  
566 Returns a hash of the tables read; each key is a table name, the value
567 being an array of hashes of the rows. If a table name is passed,
568 returns the array of hashes only for that particular table, or undef
569 if no such table existed in any input.
570  
571 =head2 inserted
572  
573 $op->inserted();
574 $op->inserted->($selected_table);
575  
576 With no parameter, returns a hash of the tables processed and a count
577 of rows found (and presumably inserted) in each. With a parameter,
578 returns the count of rows for that table, or undef if no such table
579 was processed.
580  
581 =head1 BUGS
582  
583 Report any issues to the author.
584  
585 =head1 AUTHOR
586  
587 William Lindley, C<wlindley@cpan.org>
588  
589 =head1 COPYRIGHT AND LICENSE
590  
591 Copyright 2025, William Lindley.
592  
593 This library is free software; you may redistribute it and/or modify it under
594 the terms of the Artistic License version 2.0.
595  
596 =head1 SEE ALSO
597  
598 L<Org::Parser>, L<https://orgmode.org/>
599  
600 =cut
↑ Summary