-
Notifications
You must be signed in to change notification settings - Fork 28
/
sql2rst.pl
executable file
·1201 lines (1005 loc) · 37.6 KB
/
sql2rst.pl
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
#!/usr/bin/env perl
# See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 1st Feb 2011
# Generate an HTML documentation page from an SQL file.
#
# It needs to have a "javascript like" documentation above each table.
# See the content of the method sql_documentation_format();
####################################################################################
use strict;
#use warnings; # commented out because this script is a repeat offender
use File::Basename ();
use Getopt::Long;
use List::Util qw(max sum);
use Bio::EnsEMBL::Hive::DBSQL::DBConnection;
use Bio::EnsEMBL::Hive::Utils::GraphViz;
###############
### Options ###
###############
my ($sql_file,$fk_sql_file,$html_file,$db_team,$show_colour,$version,$header_flag,$sort_headers,$sort_tables,$intro_file,$embed_diagrams,$help,$help_format);
my ($url,$skip_conn,$db_connection);
usage() if (!scalar(@ARGV));
GetOptions(
'i=s' => \$sql_file,
'fk=s' => \$fk_sql_file,
'o=s' => \$html_file,
'd=s' => \$db_team,
'c!' => \$show_colour,
'v=i' => \$version,
'embed_diagrams!' => \$embed_diagrams,
'show_header!' => \$header_flag,
'sort_headers=i' => \$sort_headers,
'sort_tables=i' => \$sort_tables,
'url=s' => \$url,
'skip_connection' => \$skip_conn,
'intro=s' => \$intro_file,
'help!' => \$help,
'help_format' => \$help_format,
);
usage() if ($help);
sql_documentation_format() if ($help_format);
if (!$sql_file) {
print "> Error! Please give a sql file using the option '-i' \n";
usage();
}
$show_colour = 1 if (!defined($show_colour));
$header_flag = 1 if (!defined($header_flag));
$sort_headers = 1 if (!defined($sort_headers));
$sort_tables = 1 if (!defined($sort_tables));
$skip_conn = undef if ($skip_conn == 0);
# Dababase connection (optional)
if (defined($url) && !defined($skip_conn)) {
$db_connection = new Bio::EnsEMBL::Hive::DBSQL::DBConnection(
-url => $url,
) or die("DATABASE CONNECTION ERROR: Could not get a database adaptor for $url\n");
}
################
### Settings ##
################
my $default_colour = '#000'; # Black
my $documentation = {};
my $tables_names = {'default' => []};
my @header_names = ('default');
my @colours = ($default_colour);
my %legend;
my $in_doc = 0;
my $in_table = 0;
my $header = 'default';
my $table = '';
my $info = '';
my $nb_by_col = 15;
my $count_sql_col = 0;
my $tag_content = '';
my $tag = '';
my $parenth_count = 0;
my $header_colour;
my $pk = [];
my $SQL_LIMIT = 50;
#############
## Parser ##
#############
# Create a complex hash "%$documentation" to store all the documentation content
open my $sql_fh, '<', $sql_file or die "Can't open $sql_file : $!";
while (<$sql_fh>) {
chomp $_;
next if ($_ eq '');
next if ($_ =~ /^\s*(DROP|PARTITION)/i);
next if ($_ =~ /^\s*(#|--)/); # Escape characters
# Verifications
if ($_ =~ /^\/\*\*/) { $in_doc=1; next; } # start of a table documentation
if ($_ =~ /^\s*create\s+table\s+(if\s+not\s+exists\s+)?`?(\w+)`?/i) { # start to parse the content of the table
$pk = [];
if ($table eq $2) {
$in_table=1;
$parenth_count++;
}
else {
print STDERR "The documentation of the table $2 has not be found!\n";
}
next;
}
next if ($in_doc==0 and $in_table==0);
my $doc = remove_char($_);
#================================================#
# Parsing the documentation part of the SQL file #
#================================================#
if ($in_doc==1) {
# Header name
if ($doc =~ /^\@header\s*(.+)$/i and $header_flag == 1) {
$header = $1;
unless (exists $tables_names->{$header}) {
push (@header_names,$header);
$tables_names->{$header} = [];
}
next;
}
# Table name
elsif ($doc =~ /^\@table\s*(\w+)/i) {
$table = $1;
push(@{$tables_names->{$header}},$table);
$documentation->{$header}{'tables'}{$table} = { 'desc' => '', 'colour' => '', 'column' => [], 'example' => [], 'see' => [], 'info' => [] };
$tag = $tag_content = '';
}
# Description (used for both set, table and info tags)
elsif ($doc =~ /^\@(desc)\s*(.+)$/i) {
fill_documentation ($1,$2);
}
# Colour of the table header (used for both set, table) (optional)
elsif ($doc =~ /^\@(colour)\s*(.+)$/i) {
fill_documentation ($1,$2) if ($show_colour);
}
# Column
elsif ($doc =~ /^\@(column)\s*(.+)$/i) {
fill_documentation ($1,$2);
}
# Example
elsif ($doc =~ /^\@(example)\s*(.+)$/i) {
fill_documentation ($1,$2);
}
# See other tables
elsif ($doc =~ /^\@(see)\s*(\w+)\s*$/i) {
fill_documentation ($1,$2);
}
# Addtional information block
elsif ($doc =~ /^\@(info)\s*(.+)$/i) {
fill_documentation ();
$info = $2;
next;
}
# End of documentation
elsif ($doc =~ /^\*\//) { # End of the documentation block
fill_documentation (); # Add the last tag content to the documentation hash
$in_doc=0;
next;
}
# Add legend colour description
elsif ($doc =~ /^\@(legend)\s*(#\S+)\s+(.+)$/i) {
$legend{$2} = $3;
}
elsif ($doc =~ /^\s*(.+)$/) { # If a tag content is split in several lines
$tag_content .= " $1";
}
}
#=====================================================#
# Parsing of the SQL table to fetch the columns types #
#=====================================================#
elsif ($in_table==1) {
# END OF TABLE DEFINITION
# Can't do this easily with a simply regex as there are varying valid formats
# The end of the table definition is actually defined by 2nd enclosing bracket
# Regex counting VOODOO!
# This basically puts the regex in a list context
# before inc/dec'ing with it in a scalar context.
$parenth_count +=()= $doc =~ /\(/gi;
$parenth_count -=()= $doc =~ /\)/gi;
if ($parenth_count == 0) { # End of the sql table definition
if (scalar(@$pk)) {
add_column_index('primary key', join(',', @$pk));
}
if (scalar @{$documentation->{$header}{'tables'}{$table}{column}} > $count_sql_col) {
print STDERR "Description of a non existant column in the table $table!\n";
}
$in_table=0;
$count_sql_col = 0;
$table='';
$parenth_count = 0;
}
else {
#---------#
# INDEXES #
#---------#
# Remove the comments
$doc =~ s/--\s.*$//;
# Skip the blank lines
next if ($doc =~ /^\s+$/);
if ($doc =~ /FOREIGN\s+KEY\s+\((\S+)\)\s+REFERENCES\s+(\S+)\s*\((\S+)\)/i) { # foreign key
push @{$documentation->{$header}{'tables'}{$table}->{foreign_keys}}, [$1,$2,$3];
next;
}
elsif ($doc =~ /^\s*(primary\s+key)\s*\w*\s*\((.+)\)/i or $doc =~ /^\s*(unique)\s*\((.+)\)/i){ # Primary or unique;
add_column_index($1,$2);
next;
}
elsif ($doc =~ /^\s*(unique\s+)?(key|index)\s+([^\s\(]+)\s*\((.+)\)/i) { # Keys and indexes
add_column_index("$1$2",$4,$3);
next;
}
elsif ($doc =~ /^\s*(unique)\s+(\S*)\s*\((.+)\)/i) { # Unique
add_column_index("$1",$3,$2);
next;
}
elsif ($doc =~ /^\s*(key|index)\s+\((.+)\)/i) { # Keys
add_column_index("$1",$2);
next;
}
#----------------------------------#
# COLUMNS & TYPES & DEFAULT VALUES #
#----------------------------------#
my $col_name = '';
my $col_type = '';
my $col_def = '';
# All the type is contained in the same line (type followed by parenthesis)
if ($doc =~ /^\W*(\w+)\W+(\w+\s?\(.*\))/ ){
$col_name = $1;
$col_type = $2;
if ($doc =~ /default\s+([^,\s]+)\s*.*(,|#).*/i) { $col_def = $1; } # Default value
}
# The type is written in several lines
elsif ($doc =~ /^\W*(\w+)\W+(enum|set)(\s?\(.*)/i){ # The content is split in several lines
$col_name= $1;
$col_type="$2$3<br />";
my $end_type = 0;
while ($end_type != 1){
my $line = <$sql_fh>;
chomp $line;
$line = remove_char($line);
# Regex counting VOODOO again
$parenth_count +=()= $line =~ /\(/gi;
$parenth_count -=()= $line =~ /\)/gi;
if ($line =~ /\)/) { # Close parenthesis
$end_type=1;
$line =~ /^\s*(.+)\)/;
$col_type .= "$1)";
}
else { # Add the content of the line
$line =~ /^\s*(.+)/;
$col_type .= $1.'<br />';
}
if ($line =~ /default\s+([^,\s]+)\s*.*(,|#).*/i) { $col_def = $1; } # Default value
}
}
# All the type is contained in the same line (type without parenthesis)
elsif ($doc =~ /^\s*\W*(\w+)\W+(\w+)/ ){
$col_name = $1;
$col_type = $2;
if ($doc =~ /default\s*([^,\s]+)\s*.*(,|#).*/i) { $col_def = $1; } # Default value
}
# Default value
if (!defined($col_def) || $col_def eq '') {
$col_def = ($doc =~ /not\s+null/i ) ? '*not set*' : 'NULL';
}
add_column_type_and_default_value($col_name,$col_type,$col_def);
if ($doc =~ /\bprimary\s+key\b/i) {
push @$pk, $col_name;
}
}
}
}
close($sql_fh);
my %table_documentation;
foreach my $c (keys %$documentation) {
my $h = $documentation->{$c};
foreach my $table_name (keys %{$h->{tables}}) {
$table_documentation{$table_name} = $h->{tables}->{$table_name};
$h->{tables}->{$table_name}->{category} = $c;
}
}
if ($fk_sql_file) {
open $sql_fh, '<', $fk_sql_file or die "Can't open $fk_sql_file : $!";
while (<$sql_fh>) {
chomp $_;
next if ($_ eq '');
my $doc = remove_char($_);
if ($doc =~ /ALTER\s+TABLE\s+(\S+)\s+ADD.*FOREIGN\s+KEY\s+\((\S+)\)\s+REFERENCES\s+(\S+)\((\S+)\)/i) {
push @{$table_documentation{$1}->{foreign_keys}}, [$2,$3,$4];
} elsif ($doc =~ /ALTER.*FOREIGN/i) {
die "Unrecognized: $doc";
}
}
close($sql_fh);
}
sub table_box {
my ($graph, $table_name) = @_;
my $table_doc = $table_documentation{$table_name};
my @rows = map {sprintf('<tr><td bgcolor="white" port="port%s">%s%s</td></tr>', $_->{name}, ($_->{index} =~ /\bprimary\b/i ? '<B>PK</B> ' : ''), $_->{name})} @{$table_doc->{column}};
$graph->add_node($table_name,
'shape' => 'box',
'style' => 'filled,rounded',
'fillcolor' => $table_doc->{colour},
'label' => sprintf('<<table border="0"><th><td><font point-size="16">%s</font></td></th><hr/>%s</table>>', $table_name, join('', @rows)),
);
}
sub generate_whole_diagram {
my ($show_clusters, $column_links) = @_;
my $graph = Bio::EnsEMBL::Hive::Utils::GraphViz->new(
'label' => "$db_team schema diagram",
'fontsize' => 20,
$column_links
? ( 'rankdir' => 'LR', 'concentrate' => 'true', )
: ( 'splines' => 'ortho', ),
);
foreach my $table_name (sort keys %table_documentation) {
table_box($graph, $table_name);
}
foreach my $table_name (sort keys %table_documentation) {
foreach my $fk (@{$table_documentation{$table_name}->{foreign_keys}}) {
$graph->add_edge($table_name => $fk->[1],
'style' => 'dashed',
$column_links ? (
'from_port' => "$fk->[0]:e",
'to_port' => "$fk->[2]:w",
) : (),
);
}
}
if ($show_clusters) {
foreach my $h (sort keys %$documentation) {
my $cluster_id = clean_name($h);
my $c = blend_colors($documentation->{$h}->{colour}, '#FFFFFF', 0.8);
$graph->cluster_2_attributes()->{$cluster_id} = {
'cluster_label' => $h,
'style' => 'rounded,filled,noborder',
'fill_colour_pair' => ["#$c"],
};
my @cluster_nodes;
$graph->cluster_2_nodes()->{$cluster_id} = \@cluster_nodes;
foreach my $t (sort keys %{$documentation->{$h}->{tables}}) {
push @cluster_nodes, $t;
}
}
}
return $graph;
}
sub blend_colors {
my ($color1, $color2, $alpha) = @_;
my @rgb1 = map {hex($_)} unpack("(A2)*", substr $color1, 1);
my @rgb2 = map {hex($_)} unpack("(A2)*", substr $color2, 1);
my @rgb = map {int($rgb1[$_] + $alpha * ($rgb2[$_]-$rgb1[$_]))} 0..2;
my $c = join('', map {sprintf('%X', $_)} @rgb);
return $c;
}
sub sub_table_box {
my ($graph, $table_name, $fields) = @_;
my $table_doc = $table_documentation{$table_name};
my @rows;
my $has_ellipsis;
foreach my $c (@{$table_doc->{column}}) {
if ($fields->{$c->{name}}) {
push @rows, sprintf('<tr><td bgcolor="white" port="port%s">%s%s</td></tr>', $c->{name}, ($c->{index} =~ /\bprimary\b/i ? '<B>PK</B> ' : ''), $c->{name});
$has_ellipsis = 0;
} elsif (!$has_ellipsis) {
push @rows, '<tr><td bgcolor="white"><i>...</i></td></tr>';
$has_ellipsis = 1;
}
}
$graph->add_node($table_name,
'shape' => 'box',
'style' => 'filled,rounded',
'fillcolor' => $table_doc->{colour},
'label' => sprintf('<<table border="0"><th><td><font point-size="16">%s</font></td></th><hr/>%s</table>>', $table_name, join('', @rows)),
);
}
sub generate_sub_diagram {
my ($cluster, $column_links) = @_;
my $graph = Bio::EnsEMBL::Hive::Utils::GraphViz->new(
'label' => "$db_team schema diagram: $cluster tables",
'fontsize' => 20,
$column_links
? ( 'rankdir' => 'LR', 'concentrate' => 'true', )
: ( 'splines' => 'ortho', ),
);
foreach my $table_name (sort keys %{$documentation->{$cluster}->{tables}}) {
table_box($graph, $table_name);
}
my %clusters_to_draw = ($cluster => 1);
my %other_table_fields;
my @drawn_fks;
foreach my $table_name (sort keys %table_documentation) {
foreach my $fk (@{$table_documentation{$table_name}->{foreign_keys}}) {
if ($table_documentation{$table_name}->{category} eq $cluster) {
$other_table_fields{$fk->[1]}->{$fk->[2]} = 1;
$clusters_to_draw{ $table_documentation{$fk->[1]}->{category} } = 1;
push @drawn_fks, [$table_name, @$fk];
} elsif ($table_documentation{$fk->[1]}->{category} eq $cluster) {
$other_table_fields{$table_name}->{$fk->[0]} = 1;
$clusters_to_draw{ $table_documentation{$table_name}->{category} } = 1;
push @drawn_fks, [$table_name, @$fk];
}
}
}
foreach my $table_name (sort keys %other_table_fields) {
sub_table_box($graph, $table_name, $other_table_fields{$table_name} || {}) if $cluster ne $table_documentation{$table_name}->{category};
}
foreach my $fk (@drawn_fks) {
my $table_name = shift @$fk;
$graph->add_edge($table_name => $fk->[1],
'style' => 'dashed',
$column_links ? (
'from_port' => $fk->[0].':e',
'to_port' => $fk->[2].':w',
) : (),
);
}
foreach my $h (sort keys %clusters_to_draw) {
#next unless $h eq $cluster;
my $cluster_id = clean_name($h);
my $c = blend_colors($documentation->{$h}->{colour}, '#FFFFFF', 0.8);
$graph->cluster_2_attributes()->{$cluster_id} = {
'cluster_label' => $h,
($h eq $cluster) ?
( 'style' => 'rounded,filled,noborder', 'fill_colour_pair' => ["#$c"], )
: ( 'style' => 'filled,noborder', 'fill_colour_pair' => ['white'] ),
};
my @cluster_nodes;
$graph->cluster_2_nodes()->{$cluster_id} = \@cluster_nodes;
foreach my $t (sort keys %{$documentation->{$h}->{tables}}) {
push @cluster_nodes, $t if (($h eq $cluster) || $other_table_fields{$t});
}
}
return $graph;
}
sub clean_name {
my $n = shift;
$n =~ s/\s+/_/g;
$n =~ s/[\-\/]+/_/g;
return lc $n;
}
# Sort the headers names by alphabetic order
if ($sort_headers == 1) {
@header_names = sort(@header_names);
}
# Sort the tables names by alphabetic order
if ($sort_tables == 1) {
while ( my($header_name,$tables) = each (%{$tables_names})) {
@{$tables} = sort(@{$tables});
}
}
# Remove the empty headers (e.g. "default")
@header_names = grep {scalar(@{$tables_names->{$_}})} @header_names;
#####################
## Schema diagrams ##
#####################
my %diagram_dotcode;
if ($embed_diagrams) {
my $graph = generate_whole_diagram('show_clusters', 'column_links');
$diagram_dotcode{''} = $graph->as_debug();
foreach my $c (@header_names) {
my $graph = generate_sub_diagram($c, 'column_links');
$diagram_dotcode{$c} = $graph->as_debug();
}
}
#################
## RST content ##
#################
my $html_content = '';
# Legend link
if ($show_colour and scalar @colours > 1 and $header_flag != 1) {
$html_content .= qq{A colour legend is available at the <a href="#legend">bottom of the page</a>.\n<br /><br />};
}
#=============================================#
# List of tables by header (i.e. like a menu) #
#=============================================#
$html_content .= display_tables_list();
my $table_count = 1;
my $col_count = 1;
$html_content .= ".. raw:: latex\n\n \\begin{landscape}\n\n";
#========================================#
# Display the detailled tables by header #
#========================================#
my $header_id = 1;
foreach my $header_name (@header_names) {
my $tables = $tables_names->{$header_name};
#----------------#
# Header display #
#----------------#
my $category_title = $documentation->{$header_name}->{'colour'} ? sprintf(':schema_table_header:`<%s,square>%s`', $documentation->{$header_name}->{'colour'}, $header_name) : $header_name;
$html_content .= rst_title($category_title, '~') . "\n";
#------------------------#
# Additional information #
#------------------------#
$html_content .= rst_add_indent_to_block($documentation->{$header_name}{'desc'}, " ") . "\n\n" if $documentation->{$header_name}{'desc'};
if ($embed_diagrams) {
my $l = clean_name($header_name);
$html_content .= ".. schema_diagram::\n\n" . rst_add_indent_to_block($diagram_dotcode{$header_name}, ' ') . "\n\n";
}
#----------------#
# Tables display #
#----------------#
foreach my $t_name (@{$tables}) {
my $data = $documentation->{$header_name}{'tables'}{$t_name};
my $table_title = $documentation->{$header_name}->{'colour'} ? sprintf(':schema_table_header:`<%s,round>%s`', $documentation->{$header_name}->{'colour'}, $t_name) : $t_name;
$html_content .= rst_title($table_title, '+');
$html_content .= add_description($data) . "\n";
$html_content .= add_columns($t_name,$data);
$html_content .= add_examples($t_name,$data);
}
}
$html_content .= ".. raw:: latex\n\n \\end{landscape}\n\n";
######################
## HTML/output file ##
######################
my $output_fh;
if ($html_file) {
open $output_fh, '>', $html_file or die "Can't open $html_file : $!";
} else {
$output_fh = \*STDOUT;
}
print $output_fh slurp_intro($intro_file)."\n";
print $output_fh $html_content."\n";
close($output_fh);
sub rst_title {
my ($title, $underscore_symbol) = @_;
return $title . "\n" . ($underscore_symbol x length($title)) . "\n";
}
sub block_width {
my ($block) = @_;
my @lines = split /\n/, $block;
return max(map {length($_)} @lines);
}
sub column_width {
my ($data, $i) = @_;
return max(map {block_width($_->[$i])} @$data);
}
sub rst_list_table {
my ($data, $class) = @_;
my @widths = map {column_width($data, $_)} 0..(scalar(@{$data->[0]})-1);
my $w = ":widths: ".join(" ", @widths);
my $table_content = join("\n", map {rst_list_table_row($_)} @$data);
return ".. list-table::\n" . rst_add_indent_to_block(":header-rows: 1\n$w\n" . ($class ? ":class: $class\n" : "") . "\n" . $table_content, " ") . "\n\n";
}
sub rst_list_table_row {
my ($row) = @_;
my $first_cell = shift @$row;
return rst_add_indent_to_block($first_cell, " ", "* - ") . "\n" . join("\n", map {rst_add_indent_to_block($_, " ", " - ")} @$row);
}
sub rst_add_indent_to_block {
my ($block, $indent, $first_indent) = @_;
$first_indent //= $indent;
my @lines = split /\n/, $block;
my $first_line = shift @lines;
if (@lines) {
return $first_indent . $first_line . "\n" . join("\n", map {$indent . $_} @lines);
}
return $first_indent . $first_line;
}
sub rst_bullet_list {
my ($data, $list_symbol) = @_;
$list_symbol //= '-';
return join("\n", map {$list_symbol . " " . $_} @$data);
}
###############
## Methods ##
###############
# List the table names. Group them if possible
# By default there is one group, named "default" and it contains all the tables.
sub display_tables_list {
my $rest = '';
if ($embed_diagrams) {
$rest .= rst_title('Schema diagram', '=') . "\n";
$rest .= "The $db_team schema diagrams are automatically generated as PNG images with Graphviz, and show the links between columns of each table.\n";
$rest .= "Here follows the overall schema diagram, while the individual diagrams of each category are available below, together with the table descriptions.\n\n";
$rest .= ".. schema_diagram::\n\n" . rst_add_indent_to_block($diagram_dotcode{''}, ' ') . "\n\n";
}
$rest .= rst_title('Table list', '=') . "\n";
$rest .= "Here is the list of all the tables found in a typical $db_team database, grouped by categories.\n\n";
if (scalar(@header_names) == 1) {
return rst_bullet_list($tables_names->{$header_names[0]}) . "\n";
}
# Remove the empty headers (e.g. "default")
my @useful_header_names = grep {scalar(@{$tables_names->{$_}})} @header_names;
# No more than 3 categories at a time
my $max_headers_per_line = 3;
while (scalar(@useful_header_names)) {
my @headers_this_time = splice(@useful_header_names, 0, $max_headers_per_line);
my @first_row = map {$documentation->{$_}->{'colour'} ? sprintf(':schema_table_header:`<%s,square>%s`', $documentation->{$_}->{'colour'}, $_) : $_} @headers_this_time;
my @second_row = map {rst_bullet_list([map {$_.'_'} @{$tables_names->{$_}}])} @headers_this_time;
my @data = (\@first_row, \@second_row);
$rest .= rst_list_table(\@data, 'sql-schema-table');
}
return $rest;
}
# Method to pick up the documentation information contained in the SQL file.
# If the line starts by a @<tag>, the previous tag content is added to the documentation hash.
# This method allows to describe the content of a tag in several lines.
sub fill_documentation {
my $t1 = shift;
my $t2 = shift;
if ($tag ne '') {
# Description tag (info, table or header)
if ($tag eq 'desc') {
# Additional description
if ($info ne '') {
$tag_content = $info.'@info@'.$tag_content;
# Table: additional information
if ($table ne '') {
push(@{$documentation->{$header}{'tables'}{$table}{'info'}},$tag_content);
}
# Header: additional information
else {
if (!$documentation->{$header}{'info'}) {
$documentation->{$header}{'info'} = [];
}
push(@{$documentation->{$header}{'info'}},$tag_content);
}
$info = '';
}
# Header description
elsif(!$documentation->{$header}{'tables'}) {
$documentation->{$header}{'desc'} = $tag_content;
}
# Table description
else {
$documentation->{$header}{'tables'}{$table}{$tag} = $tag_content;
}
}
elsif ($tag eq 'colour') {
if(!$documentation->{$header}{'tables'}) {
$documentation->{$header}{'colour'} = $tag_content;
$header_colour = 1;
}
elsif ($table ne '') {
$documentation->{$header}{'tables'}{$table}{$tag} = $tag_content;
if (! grep {$tag_content eq $_} @colours) {
push (@colours,$tag_content);
}
}
}
elsif ($tag eq 'column') {
$tag_content =~ /(\w+)[\s\t]+(.*)/;
my $column = { 'name' => $1,
'type' => '',
'default' => '',
'index' => '',
'desc' => $2
};
if ($2 eq '') {
print STDERR "COLUMN: The description content of the column '$1' is missing in the table $table!\n";
}
push(@{$documentation->{$header}{'tables'}{$table}{$tag}},$column);
}
else{
push(@{$documentation->{$header}{'tables'}{$table}{$tag}},$tag_content);
}
}
# New tag initialised
if ($t1) {
$tag = $t1;
$tag_content = $t2;
}
else {
$tag = $tag_content = '';
}
}
# Method generating the HTML code to display the description content
sub add_description {
my $data = shift;
# Search if there are some @link tags in the description text.
my $desc = add_internal_link($data->{desc},$data);
return $desc . "\n";
}
# Method generating the HTML code of the table listing the columns of the given SQL table.
sub add_columns {
my $table = shift;
my $data = shift;
my $cols = $data->{column};
my @data;
my @header_row = ('Column', 'Type', 'Default value', 'Description', 'Index');
push @data, \@header_row;
foreach my $col (@$cols) {
my $name = $col->{name};
my $type = $col->{type};
my $default = $col->{default};
my $desc = $col->{desc};
my $index = $col->{index};
# links
$desc = add_internal_link($desc,$data);
$type = parse_column_type($type);
my @row = ("**$name**", $type, $default, $desc, $index);
push @data, \@row;
}
return rst_list_table(\@data);
}
# Method generating the HTML code to display the content of the tags @example (description + SQL query + Table of SQL query results)
sub add_examples {
my $table = shift;
my $data = shift;
my $examples = $data->{example};
my $html;
my $nb = (scalar(@$examples) > 1) ? 1 : '';
foreach my $ex (@$examples) {
my @lines = split("\n",$ex);
my $nb_display = ($nb ne '') ? " $nb" : $nb;
$html .= rst_title("Example$nb_display:", '-') . "\n";
my $has_desc = 0;
my $sql;
# Parse the example lines
foreach my $line (@lines) {
chomp($line);
# Pick up the SQL query if it exists
if ($line =~ /(.*)\s*\@sql\s*(.+)/) {
$html .= $1;
$sql = $2;
} elsif (!defined($sql)){
$html .= $line;
$has_desc = 1;
}
else {
$sql .= $line;
}
}
$html .= "\n\n";
# Search if there are some @link tags in the example description.
$html = add_internal_link($html,$data);
# Add a table of examples
if (defined($sql)) {
my $sql_table = '';
if (!defined($skip_conn) && defined($url)) {
$sql_table = get_example_table($sql,$table,$nb);
}
$html .= ".. code-block:: sql\n\n" . rst_add_indent_to_block($sql, " ") . "\n\n" . $sql_table . "\n";
}
$nb ++;
}
return $html;
}
# Method generating the HTML code to display the content of the tags @see
sub add_see {
my $sees = shift;
my $html = '';
if (scalar @$sees) {
$html .= qq{ <td class="sql_schema_extra_left">\ <p style="font-weight:bold">See also:</p>\n <ul>\n};
foreach my $see (@$sees) {
$html .= qq{ <li><a href="#$see">$see</a></li>\n};
}
$html .= qq{ </ul>\n </td>\n};
}
return $html;
}
# Method searching the tag @link into the string given as argument and replace it by an internal HTML link
sub add_internal_link {
my $desc = shift;
my $data = shift;
while ($desc =~ /\@link\s?(\w+)/) {
my $link = $1;
if ((!grep {$link eq $_} @{$data->{see}}) and defined($link)) {
push @{$data->{see}}, $link;
}
my $table_to_link = $link;
$desc =~ s/\@link\s?\w+/$table_to_link/;
}
return $desc;
}
# Method parsing the index information from the SQL table description in order to display it in the
# HTML table listing the columns of the corresponding SQL table.
sub add_column_index {
my $idx_type = shift;
my $idx_col = shift;
my $idx_name = shift;
my $index = $idx_type;
if (!defined($idx_name)) {
$idx_name = $idx_col;
}
if ($idx_type !~ /primary/i) {
$index .= ": *$idx_name*";
}
my @idx_cols = split(',',$idx_col); # The index can involve several columns
my %is_found = ();
foreach my $i_col (@idx_cols) {
$i_col =~ s/\s//g; # Remove white spaces
# In case of index using a number characters for a column
if ($i_col =~ /(.+)\(\d+\)/) {
$i_col = $1;
}
$is_found{$i_col} = 0;
foreach my $col (@{$documentation->{$header}{tables}{$table}{column}}) {
if ($col->{name} eq $i_col) {
if ($col->{index} ne '') {
$col->{index} .= "\n";
}
$col->{index} .= lc($index);
$is_found{$i_col} = 1;
last;
}
}
}
# Description missing
while (my ($k,$v) = each(%is_found)) {
if ($v==0) {
print STDERR "INDEX: The description of the column '$k' is missing in the table $table!\n";
}
}
}
# Method parsing the column type and default value from the SQL table description, in order to display them in the
# HTML table listing the columns of the corresponding SQL table.
sub add_column_type_and_default_value {
my $c_name = shift;
my $c_type = shift;
my $c_default = shift;
$count_sql_col ++;
my $is_found = 0;
foreach my $col (@{$documentation->{$header}{'tables'}{$table}{column}}) {
if ($col->{name} eq $c_name) {
$col->{type} = $c_type;
$col->{default} = $c_default if ($c_default ne '');
$is_found = 1;
last;
}
}
# Description missing
if ($is_found==0) {
print STDERR "COLUMN: The description of the column '$c_name' is missing in the table $table!\n";
}
}
# Display the types "enum" and "set" as an HTML list (<ul><li>)
sub parse_column_type {
my $type = shift;
$type =~ /^\s*(enum|set)\s*\((.*)\)/i;
my $c_type = uc($1);
my $c_data = $2;
return $type unless ($c_data);
$c_data =~ s/'//g;
$c_data =~ s/"//g;
$c_data =~ s/\s//g;
$c_data =~ s/<br \/>//g;
my @items_list = split(',',$c_data);
return $type unless (scalar(@items_list) > 1);
return $c_type . ":\n\n" . rst_bullet_list(\@items_list);
}