-
Notifications
You must be signed in to change notification settings - Fork 25
/
db2topg.pl
executable file
·1813 lines (1690 loc) · 58.1 KB
/
db2topg.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
#===============================================================================
#
# FILE: db2topg.pl
#
# USAGE: ./db2topg.pl
#
# DESCRIPTION: Convert a DB2 SQL schema dump to a PostgreSQL dump
#
#===============================================================================
use strict;
use warnings;
use utf8;
use Carp;
my $schema_db2;
use Data::Dumper;
use Getopt::Long;
use Encode::Guess; # No idea what encoding DB2 will use for its dump (for objects with diacritic characters)
# Migrate DB2 to PostgreSQL
# Global variables (command line arguments)
my $filename;
my $help;
my $do_tablespaces=0;
my $data_directory;
my $data_script_type;
my $db2dbname;
my $db2username;
my $db2password;
sub read_and_cleanup_line
{
my $line = <IN>;
return undef if (not defined $line);
$line =~ s/--.*//; # Remove comments, if any
return $line;
}
sub read_statement
{
my @statement;
my $read;
while (my $line = read_and_cleanup_line)
{
$line =~ s/\r//; # We sometimes have windows input
next if ($line =~ /^\s*$/);
$read = 1;
push @statement,($line);
# We have an exception for create functions: there will be semi-columns inside…
if ($statement[0] !~ /CREATE.*(FUNCTION|PROCEDURE|TRIGGER)/i)
{
if ($line =~ /;\s*$/)
{
# Cleanup trailing semi-colon (and spaces after it) on last line
$statement[-1] =~ s/;\s*$//;
# Remove \n at the end of each line
chomp @statement;
last;
}
}
else
{ # Specific statement identification for functions, procedures or triggers
my $stmt = read_function_code();
push @statement,($stmt);
last;
}
}
if ($read)
{
return \@statement;
}
return undef; # Behave like read: return undef if reads nothing
}
sub read_function_code
{
# There are functions containing SQL, others containing a sort of plpgsql
# Get the source code and copy as is (keeping blank lines and comments)
# The detection of the statement end is based on the END; statements. But possible nested BEGIN END obliged to count blocks
# And take into account the labels, comments, literals or identifiers...
my $line;
my $statement = '';
my $end_loop = 0;
my $remaining = '';
my $block_count = 0;
my $in_block_comment = 0;
my $in_literal = 0;
my $in_identifier = 0;
my $begin_found = 0;
my $end_found = 0;
my $labels = '';
my $found_kw;
while (! $end_loop)
{
if ($remaining eq '')
{ # The line is fully analyzed, get another one
$line = <IN>;
return undef if (not defined $line);
chomp $line;
$statement .= "\n" if ($statement ne '');
$remaining = $line;
}
elsif ($in_block_comment)
{ # We are in a block comment, search for the comment end
if ($remaining =~ /^(.*?)(\*\/)(.*)/)
{ # We have reached the comment end
$statement .= $1 . $2;
$remaining = $3;
$in_block_comment = 0;
}
else
{
$statement .= $remaining;
$remaining = '';
}
}
elsif ($in_literal)
{ # We are in a literal, search for the literal end (a ' not followed by another ')
if ($remaining =~ /^(.*?)('(?!'))(.*)/)
{ # We have reached the literal end
$statement .= $1 . $2;
$remaining = $3;
$in_literal = 0;
}
else
{
$statement .= $remaining;
$remaining = '';
}
}
elsif ($in_identifier)
{ # We are in an identifier, search for the identifier end
if ($remaining =~ /^(.*?)(")(.*)/)
{ # We have reached the identifier end
$statement .= $1 . $2;
$remaining = $3;
$in_identifier = 0;
}
else
{
die "Identifier end not found on line $line\n";
}
}
elsif ($begin_found)
{ # The previous word was a BEGIN, check if it was really a block start
if ($remaining =~ /^\s*(TRANSACTION|WORK|;)/i)
{ # In fact not a block start, but a transaction start, so keep the remaining as is
$block_count--;
}
$begin_found = 0;
}
elsif ($end_found)
{ # The previous word was an END, check if it was really a block end
if ($remaining =~ /^\s*($labels)?\s*;/)
{ # The block end is confirmed
$block_count--;
$end_loop = ($block_count == 0);
$end_found = 0;
}
$end_found = 0;
}
# We are in regular code, search for interesting keywords
elsif ($remaining !~ /^(.*?)(--|\/\*|'|"|BEGIN|END|(?:\S+):)(.*)$/i)
{ # No interested keyword found
$statement .= $remaining;
$remaining = '';
}
else
{ # A keyword is found, analyze it and keep the rigth part for the next search
$statement .= $1 . $2;
$remaining = $3;
$found_kw = $2;
if ($found_kw eq '--')
{ # A line comment start is detected
$statement .= $remaining;
$remaining = '';
}
elsif ($found_kw eq '/*')
{ # A block comment start is detected
$in_block_comment = 1;
}
elsif ($found_kw eq "'")
{ # A literal start is detected
$in_literal = 1;
}
elsif ($found_kw eq '"')
{ # An identifier start is detected
$in_identifier = 1;
}
elsif (uc($found_kw) eq 'END')
{
$end_found = 1;
}
elsif (uc($found_kw) eq 'BEGIN')
{
$begin_found = 1;
$block_count++;
}
elsif ($found_kw =~ /(.*):$/i)
{ # A label is detected
$labels .= "|$1";
}
}
}
$statement .= $remaining;
return $statement;
}
# Reads all remaining lines in a statement
sub slurp_statement
{
my ($refstatement)=@_;
my $statement='';
while(my $line=shift(@$refstatement))
{
$statement.="\n".$line;
}
$statement=~ s/;$//s;
return $statement;
}
# Slurp the rest of a comment, and remove trailing quote
sub slurp_comment
{
my ($refstatement)=@_;
my $comment=slurp_statement($refstatement);
$comment =~ s/'$//si;
return $comment;
}
# With DB2, one can specify «with default», with no default value. If that's the case, there is a «default» default value.
# This function should be called when you need to find the default value to a type. It is returned as the SQL litteral to be used.
sub find_default_default
{
my ($type)=@_;
if ($type =~ /^(SMALLINT|INT|BIGINT|DECIMAL|NUMERIC|REAL|DOUBLE|DECFLOAT|FLOAT)/i)
{
return 0;
}
if ($type =~ /^(CHAR|GRAPHIC)/i)
{
return "''";
}
if ($type =~ /^(VARCHAR|CLOB|VARGRAPHIC|DBCLOB|VARBINARY|BLOB)/i)
{
return "''";
}
if ($type =~ /^DATE/i)
{
return 'current_date';
}
if ($type =~ /^TIME\b/i)
{
return 'current_time';
}
if ($type =~ /^TIMESTAMP\b/i)
{
return 'current_timestamp';
}
if ($type =~ /^bytea/i)
{
return "''";
}
croak "Unknown type $type when trying to find 'default' default value for a type\n";
}
# Convert DB2's peculiar types to PostgreSQL
sub convert_type
{
my ($in_type)=@_;
my $out_type=$in_type; # Most of the time, this is enough
# CLOB and BLOB can have more specifications (logged, compact, etc…). We ignore them completely
if ($in_type =~ /^BLOB\((\d+)\)/)
{
$out_type="bytea"; # Could add a check constraint to verify size, but most of the time, the size is here
}
elsif ($in_type =~ /^CLOB\((\d+)\)/)
{
if ($1 < 10485760)
{
$out_type="varchar($1)"; # That's just a varchar to us, as these can store up to 1GB
}
else
{
$out_type="varchar";
}
}
elsif ($in_type eq 'DOUBLE')
{
$out_type='double precision';
}
elsif ($in_type eq 'LONG VARCHAR')
{
$out_type='text';
}
elsif ($in_type =~ /FOR BIT DATA/)
{
# No meaning in PG
$in_type =~ s/FOR BIT DATA//;
$out_type=$in_type;
}
elsif ($in_type =~ /VARCHAR\s*\((\d+)\s+(?:OCTETS|CODEUNITS16|CODEUNITS32)\s*\)/)
{
# PostgreSQL always calculates strings in characters semantics, never bytes
$out_type = "VARCHAR($1)";
}
return $out_type;
}
# Some keywords are reserved in PostgreSQL, such as //TABLE//. We'll need to protect them with double quotes
my %reserved_keywords=('TABLE' => 1,
'UNIQUE' => 1,
'DISTINCT' =>1,
);
# The one arg version. Called by the main function for each element of the array
sub _protect_reserved_keywords
{
my ($kw)=@_;
croak unless (defined $kw);
# First store the ASC/DESC somewhere if there is one
my $ascdesc='';
if ($kw =~ s/(\s+(?:ASC|DESC))//)
{
$ascdesc=$1;
}
# Also remove minus in object name… they are not supported in PostgreSQl (and in the SQL standard either i think)
if ($kw =~ /-/)
{
print STDERR "I had to rename $kw as it contained a '-' sign. Removing it\n";
$kw=~ s/-//g;
}
# Is this a reserved keyword ? Quote it if yes
if (exists($reserved_keywords{$kw}))
{
$kw = '"' . $kw . '"';
}
# Put back the ascdesc at the end
$kw .= $ascdesc;
return lc($kw); # FIXME: change this if we want to do a case sensitive schema
}
sub protect_reserved_keywords
{
my @result=map{_protect_reserved_keywords($_)} @_;
if ($#result==0)
{
# Called with only one value. Expects a scalar
return $result[0];
}
return @result;
}
# Try to fix some expressions (for default values for example)
# Only does brutal regexp corrections
# Try to be subtle when type is known (for default values for types)
sub try_fix_expression
{
my ($data,$type)=@_;
# get rid of newlines, anyway we just want to import the objects (views), they will be reformatted by PG anyway
$data =~ s/\r?\n/ /g;
# Date retrieval
$data =~ s/\bcurrent\s+date/current_date/gi;
$data =~ s/\bcurrent\s+timestamp/current_timestamp/gi;
# Time conversions
$data =~ s/\byear\(/extract (YEAR FROM /gi;
# Case conversions
$data =~ s/\bUCASE\(/upper(/gi;
$data =~ s/\bLCASE\(/lower(/gi;
# Type conversions
$data =~ s/\bCHAR\(/to_char(/gi;
$data =~ s/(\d{4}-\d{2}-\d{2})-(\d{2}).(\d{2}).(\d{2}).(\d{6})/$1 $2:$3:$4.$5/;
if ( defined $type ) {
if ($type =~ /\bTIME\b/)
{
# This is time. In postgresql, time values are separated by :, not .
$data =~ s/\b(\d{2})\.(\d{2})\.(\d{2})\b/$1:$2:$3/;
}
}
# for an empty blob:
if ($data =~ /"SYSIBM"."BLOB"/)
{
$data="''"; # Automatically casted in PostgreSQL, no need!
}
# The rest
$data =~ s/WITH ROW MOVEMENT|WITH NO ROW MOVEMENT//i; # No meaning anyway in PG
return $data;
}
# Checks there is no object with the same name (sequence, table, index…). And warns and renames if these is a problem.
# In DB2, objects are namespaced by table (you can have the same index or constraint name for instance, on two different tables)
# Names will be protected as necessary
my %renames; # Contains all the object names (sequences, tables, indexes…) I had to create to avoid conflicts
sub check_and_rename
{
my ($schema,$name,$type)=@_;;
# First, populate %renames if this is the first call, with the table names (these wont move)
unless (%renames)
{
foreach my $schema(keys %{$schema_db2->{SCHEMAS}})
{
foreach my $table(keys %{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}})
{
$renames{protect_reserved_keywords($schema)}->{protect_reserved_keywords($table)}='TABLE';
}
}
}
$schema=protect_reserved_keywords($schema);
$name=protect_reserved_keywords($name);
# Ok, we got called,
# We first try the name without modification
# Then we try to add the object_type at the end of the name
# Then we add a number at the end of its name in a loop until it does not conflict (start with an empty string)
# print STDERR Dumper(\%renames);
# print STDERR "NEW OBJECT : $schema , $name , $type\n";
unless (exists $renames{$schema}->{$name})
{
$renames{$schema}->{$name}=$type;
return $name;
}
# We have a conflict. Give a try to the name plus type
unless (exists $renames{$schema}->{$name.'_'.$type})
{
$renames{$schema}->{$name.'_'.$type}=$type;
print STDERR "I had to rename the $type $schema.$name to $schema.${name}_${type} to avoid conflict\n";
return $name.'_'.$type;
}
my $id=1;
while (exists $renames{$schema}->{$name.$id})
{
$id++;
}
$renames{$schema}->{$name.$id}=$type;
print STDERR "I had to rename the $type $schema.$name to $schema.${name}${id} to avoid conflict\n";
return $name.$id;
}
# In the main structure, indexes are attached to a table. We don't have a direct access to them
# It's a problem in one case: when parsing comment on index
# This function returns the tablename owning this index
sub find_index_in_schema
{
my ($schema,$searched_index)=@_;
foreach my $table (keys %{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}})
{
foreach my $index(keys %{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{INDEXES}})
{
return $table if ($index eq $searched_index);
}
}
}
my $current_schema=''; # Global as this will be set on a per view afterwards
my $current_path=''; # Global as this will be set on a per view afterwards
sub parse_dump
{
my ($filename)=@_;
# First guess encoding
open IN, '<',$filename or die "Cannot open $filename, $!";
my $data_guess;
while (my $line = <IN>)
{
$data_guess .= $line;
}
close IN;
# We now ask guess...
my $decoder = guess_encoding($data_guess, qw/iso8859-15 utf8 utf16-le utf16-be/);
die $decoder unless ref($decoder);
# print "encoding: " . $decoder->name . "\n";
open IN, "<:encoding(".$decoder->name.")",$filename or die "Cannot open $filename, $!";
MAIN:
while (my $refstatement=read_statement)
{
# New statement to parse
# Determine the statement type
my $line=shift(@$refstatement);
next if ($line =~ /^CREATE BUFFERPOOL/);
next if ($line =~ /^CONNECT (TO|RESET)/);
next if ($line =~ /^ALTER TABLESPACE/);
next if ($line =~ /^COMMIT WORK/);
next if ($line =~ /^TERMINATE/);
next if ($line =~ /^(CREATE|ALTER) STOGROUP/);
next if ($line =~ /^SET (SYSIBM\.)?NLS_STRING_UNITS/);
next if ($line =~ /^ALTER TABLE.*VOLATILE CARDINALITY/);
# Special cases for some versions that split create indexes in two lines:
if ($line =~ /^CREATE (UNIQUE )?INDEX/ and not $line =~ /^CREATE (UNIQUE )?INDEX.*ON "/)
{
$line.=shift(@$refstatement);
}
if ($line =~ /^CREATE (?:REGULAR|LARGE|(?:USER )?TEMPORARY) TABLESPACE "?(.*?)\s?"?($|\s)/)
{
# Parse tablespace
my $name=$1;
TABLESPACE:
while (my $line=shift(@$refstatement))
{
# Read the rest of create tablespace
if ($line =~ /^\s*USING \((?:\s?FILE )?'(.*)'(?:\s?\d+)?\s?(\)|,)/)
{
push @{$schema_db2->{TABLESPACE}->{$name}->{PATH}},($1);
if ($2 eq ',')
{
# There are other files in this tablespace
while (my $line=shift(@$refstatement))
{
$line =~ /^\s+(?:FILE )?'(.*)'(?: \d+)?(,|\))/ or die "I don't understand the list of files in this tablespace";
push @{$schema_db2->{TABLESPACE}->{$name}->{PATH}},($1);
if (defined $2)
{
# no more files
next TABLESPACE;
}
}
}
else
{
next;
}
}
next if ($line =~ /EXTENTSIZE|PAGESIZE|INITIALSIZE|PREFETCHSIZE|BUFFERPOOL|OVERHEAD|TRANSFERRATE|AUTORESIZE|INCREASESIZE|MAXSIZE|FILE SYSTEM CACHING|DROPPED TABLE|USING STOGROUP|DATA TAG/);
die "I don't understand $line in a CREATE TABLESPACE section";
}
} #CREATE TABLESPACE
elsif ($line =~ /^CREATE ROLE "(.*?)\s*"$/)
{
my %empty_hash=();
$schema_db2->{ROLES}->{$1}=\%empty_hash;
die ("Overflow in create role: " . join('',@$refstatement)) unless ($#$refstatement == -1);
}
elsif ($line =~ /^COMMENT ON ROLE "(.*?)\s*" IS '(.*?)'?$/)
{
die "This role $1 hasn't been seen before" unless (exists $schema_db2->{ROLES}->{$1});
$schema_db2->{ROLES}->{$1}->{COMMENT}=$2 . "\n" . slurp_comment($refstatement);
chomp $schema_db2->{ROLES}->{$1}->{COMMENT};
}
elsif ($line =~ /^CREATE SCHEMA "\s*(\S*)\s*"\s*(AUTHORIZATION\s+"\s*(\S*)\s*")?\s*$/)
{
if (defined ($2) and defined($3)) {
$schema_db2->{SCHEMAS}->{$1}->{AUTHORIZATION}=$3;
# Some roles may be there, and not have been created. I don't know why db2 would do this, but take care of it…
unless (exists $schema_db2->{ROLES}->{$3})
{
my %empty_hash=();
$schema_db2->{ROLES}->{$3}=\%empty_hash;
}
}
die ("Overflow in create schema: " . join('',@$refstatement)) unless ($#$refstatement == -1);
}
elsif ($line =~ /^CREATE SEQUENCE "(.*?)\s*"\."(.*?)\s*" AS (INTEGER|BIGINT)/)
{
# CREATE SEQUENCE are sometimes multi-line. weird. Anyway, put everything in a single line and salvage what we can :)
# We don't care about integer/bigint. All sequences are bigint in PG
my $schema=$1;
my $sequence=$2;
while (my $tmpline=shift(@$refstatement))
{
$line.=$tmpline;
}
# Extract what we can from the sequence
if ($line =~ /MINVALUE (\d+) MAXVALUE (\d+)/)
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{MINVALUE}=$1;
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{MAXVALUE}=$2;
}
if ($line =~ /START WITH (\d+) INCREMENT BY (\d+)/)
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{STARTWITH}=$1;
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{INCREMENTBY}=$2;
}
if ($line =~ /(NO )?\s*CACHE\s*(\d+)?/ )
{
if ( defined($1) )
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{CACHE}=1;
}
else
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{CACHE}=$2;
}
}
if ($line =~ /NO CYCLE/ )
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{CYCLE}=0;
}
else
{
$schema_db2->{SCHEMAS}->{$schema}->{SEQUENCES}->{$sequence}->{CYCLE}=1;
}
} #CREATE SEQUENCE
elsif ($line =~ /^ALTER SEQUENCE "(.*?)\s*"\."(.*?)\s*" RESTART WITH (\d+)\s*$/)
{
$schema_db2->{SCHEMAS}->{$1}->{SEQUENCES}->{$2}->{RESTARTWITH}=$3;
die ("Overflow in alter sequence: " . join('',@$refstatement)) unless ($#$refstatement == -1);
}
elsif ($line =~ /^CREATE TABLE "(.*?)\s*"\."(.*?)\s*"\s+\(\s*$/)
{
# Create table, multi-line of course
my $schema=$1;
my $table=$2;
my $incols=1;
my $colnum=0;
while (my $line=shift(@$refstatement))
{
$colnum++;
if ($line =~ /^\s+"(.*?)\s*"\s+(.+?)( NOT NULL)?(?: (?:WITH )?DEFAULT (.*?)| GENERATED (BY DEFAULT|ALWAYS) AS IDENTITY \(| GENERATED (BY DEFAULT|ALWAYS) AS \((.*?)\))?(\s?,| \))?\s*$/)
{
my ($colname,$coltype,$colnotnull,$coldefault,$colgeneratedbydefaultidentity,$colgeneratedbydefaultexpression,$colgeneratedbydefaultexpressionAS,$endofline)=($1,$2,$3,$4,$5,$6,$7,$8);
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{TYPE}=convert_type($coltype);
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{ORIGTYPE}=$coltype;
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{COLNUM}=$colnum;
if (defined ($colnotnull))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{NOTNULL}=1;
}
else
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{NOTNULL}=0;
}
if (defined ($coldefault))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{DEFAULT}=$4;
}
if (defined ($endofline) and $endofline eq ')')
{
# End of the columns definition
$incols=0;
}
if (defined ($colgeneratedbydefaultidentity) and not (defined ($colgeneratedbydefaultexpression))) # Seems there is a bug in certain versions of perl, capturing the GENERATED two times
{
if ($colgeneratedbydefaultidentity eq 'BY DEFAULT')
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{ALWAYS}=0;
}
else
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{ALWAYS}=1;
}
# We have an identity (it's like a record with a sequence with PostgreSQL)
# It's multi-line. Let's read the rest. There is always the exact same records
while (my $line=shift(@$refstatement))
{
$line =~ /START WITH \+(\d+)|INCREMENT BY \+(\d+)|MINVALUE \+(\d+)|MAXVALUE \+(\d+)|(NO CYCLE)|(NO )?CACHE (\d+)?|(NO ORDER \) ,)/ or die "Cannot understand $line in an IDENTITY definition";
if (defined ($1))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{STARTWITH}=$1;
}
if (defined ($2))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{INCREMENTBY}=$2;
}
if (defined ($3))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{MINVALUE}=$3;
}
if (defined ($4))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{MAXVALUE}=$4;
}
if (defined ($5))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{CYCLE}=0;
}
if (defined ($6) or not defined ($7))
{
# No cache… means cache=1 under PostgreSQL
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{CACHE}=1;
}
elsif (defined ($7))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{CACHE}=$7;
}
if (defined ($8))
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{ORDER}=0;
last; # Finished reading the identity definition
}
}
}
elsif (defined ($colgeneratedbydefaultexpression))
{
# This is a generated column with a function. We'll put a default value instead
# There is no way to emulate the GENERATED ALWAYS. Only warn.
if ($colgeneratedbydefaultexpression ne 'BY DEFAULT')
{
print STDERR "==>Warning: column $colname of table $schema.$table has a default value using GENERATE ALWAYS. This can't be done with PostgreSQL. It will be a default value<==\n";
}
else
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{IDENTITY}->{ALWAYS}=1;
}
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{COLS}->{$colname}->{DEFAULT}=$colgeneratedbydefaultexpressionAS;
print STDERR "==>Warning: column $colname of table $schema.$table has a default value using an expression. This may not work... you may have to correct this manually, and write a trigger<==\n";
}
}
elsif ($incols and $line =~ /^\s*\)\s*$/)
{
$incols=0;
}
elsif ($line =~ /^\s*(?:IN "(.*?)\s*")? *(?:INDEX IN "(.*?)\s*")? *(?:LONG IN "(.*?)\s*")?\s*;?\s*$/)
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{TBSTABLE}=$1 if (defined $1);
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{TBSINDEX}=$2 if (defined $2);
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{TBSLONG}=$3 if (defined $3);
}
elsif ($line =~ /^\s*ORGANIZE BY ROW/)
{
if ($line =~ /BY ROW USING \(/)
{
# This ORGANIZE has a list of columns on potentialy on several lines
# Look for the double closing parenthesis that ends the clause
while ($line !~ /\) \)/)
{
$line=shift(@$refstatement);
}
}
}
elsif ($line =~ /^\s*DISTRIBUTE BY/)
{
if ($line =~ /\(/)
{
# This distribute has a list of arguments (distribute by hash probably)
if ($line !~ /\(.*\)/)
{
# The closing parenthesis isn't here. Ignore entries until we get to it
while ($line !~ /\)/)
{
$line=shift(@$refstatement);
}
}
}
next;
}
elsif ($line =~ /^\s*ORGANIZE BY/)
{
# These end with double parenthesis with space...
while ($line !~ /\)\s*\)\s*$/)
{
$line=shift(@$refstatement);
}
next;
}
elsif ($line =~ /^\s*COMPRESS (NO|YES)/)
{
next;
}
elsif ($line =~ /^\s*DATA CAPTURE NONE\s*$/)
{
next;
}
else
{
die "I don't understand $line in a CREATE TABLE section";
}
}
} # CREATE TABLE
elsif ($line =~ /^ALTER TABLE .* PCTFREE \d+/)
{
# No point in keeping this. It exists in PG too, but the reasoning in setting it is entirely different.
next;
}
elsif ($line =~ /^ALTER TABLE "(.*?)\s*"\."(.*?)\s*" ALTER COLUMN "(.*?)\s*" RESTART WITH (\d+)\s*$/)
{
$schema_db2->{SCHEMAS}->{$1}->{TABLES}->{$2}->{COLS}->{$3}->{IDENTITY}->{STARTWITH}=$4;
}
elsif ($line =~ /^ALTER TABLE "(.*?)\s*"\."(.*?)\s*"\s* DEACTIVATE ROW ACCESS CONTROL$/)
{
next;# Just ignore
}
elsif ($line =~ /^ALTER TABLE "(.*?)\s*"\."(.*?)\s*"\s*(\bADD\b.*)?/)
{
my $schema=$1;
my $table=$2;
unless ($3) # Usually it is multiline. Sometimes not
{
$line.=shift(@$refstatement);
}
if ($line=~/\bADD(?: CONSTRAINT "(.*?)\s*"\s*)? (PRIMARY KEY|UNIQUE)\s*$/)
{
my %object;
my $type=$2;
if (defined $1)
{
$object{NAME}=$1;
}
# Read the column list
while (my $line=shift(@$refstatement))
{
if ( $line =~ /^\s+\(?(\S+)(,|\))/)
{
push @{$object{COLS}},($1);
}
elsif ( $line =~ /^\s+(NOT\s+)?ENFORCED/)
{
next;# Just ignore the [NOT] ENFORCED clause
}
else
{
die "I don't understand $line in an ALTER TABLE section";
}
}
if ($type eq 'PRIMARY KEY')
{
$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{PK}=\%object;
}
else
{
$object{TYPE}='UNIQUE';
push @{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{CONSTRAINTS}},(\%object);
}
} # Primary/Unique
elsif ($line=~/\bADD(?: CONSTRAINT "(.*?)\s*"\s*)? FOREIGN KEY\s*$/)
{
my %object;
$object{TYPE}='FK';
if (defined $1)
{
$object{NAME}=$1;
}
# Read the local column list
while (my $line=shift(@$refstatement))
{
if ( $line =~ /^\s+\(?(\S+)(,|\))/)
{
push @{$object{LOCALCOLS}},($1);
}
else
{
# End of this part. Now to the REFERENCES part of the constraint
unshift @$refstatement,($line);
last;
}
}
# Read the foreign table name
$line=shift(@$refstatement);
$line=~ /^\s+REFERENCES "(.*?)\s*"\."(.*?)\s*"\s*$/ or die "I don't understand $line in an ALTER TABLE section";
$object{FKTABLE}=$2;
$object{FKSCHEMA}=$1;
# Read the remote column list
while (my $line=shift(@$refstatement))
{
if ( $line =~ /^\s+\(?(\S+)(,|\))/)
{
push @{$object{REMOTECOLS}},($1);
}
else
{
# End of this part. Now to the rest of the constraint
unshift @$refstatement,($line);
last;
}
}
while (my $line=shift(@$refstatement))
{
if ($line =~/^\s+(?:ON (DELETE|UPDATE) (RESTRICT|NO ACTION|CASCADE|SET NULL)|(ENFORCED)|(ENABLE QUERY OPTIMIZATION))\s*$/)
{
if (defined $3)
{
$object{ENFORCED}=1
}
elsif (defined $4)
{
next;
}
else
{
# It's an on delete/on update
$object{"ON".$1}=$2;
}
}
elsif ($line =~ /\s*DISABLE QUERY OPTIMIZATION/)
{
next;
}
else
{
die "I don't understand $line in an ALTER TABLE FOREIGN KEY SECTION"
}
}
# We got there, the whole FK is parsed. Store it
push @{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{CONSTRAINTS}},(\%object);
} # FK
elsif ($line=~/\bADD(?: CONSTRAINT (\S+))? CHECK\s+$/)
{
# Next lines is the declaration of the constraint, until we reach ENFORCED
my %object;
$object{TYPE}='CHECK';
if (defined $1)
{
$object{NAME}=$1;
}
my @check_code;
while (my $line=shift(@$refstatement))
{
if ($line =~/^\s+ENFORCED\s*$/)
{
unshift @$refstatement,($line);
last; # We have read this definition
}
# Remove tabs and spaces from input
$line =~ s/^\s*//;
$line =~ s/\s*$//;
push @check_code,($line);
# FIXME: maybe the code should check there is nothing but ENFORCED and ENABLE QUERY OPTIMIZATION ?
}
$object{CODE}.=join(' ',@check_code);
chomp $object{CODE}; # Remove the trailing \n
push @{$schema_db2->{SCHEMAS}->{$schema}->{TABLES}->{$table}->{CONSTRAINTS}},(\%object);
} # CHECK
else
{
die "I don't understand $line in an ALTER TABLE section";
}
} # ALTER TABLE
elsif ($line =~ /^CREATE (UNIQUE )?INDEX "(.*?)\s*"\."(.*?)\s*"\s+ON "(.*?)\s*"\."(.*?)\s*"\s*$/)
{
my ($indexschema,$indexname,$tableschema,$tablename)=($2,$3,$4,$5);
# We ignore indexschema… it doesn't exist in PostgreSQl anyway
if (defined $1 and $1 eq 'UNIQUE ')
{
$schema_db2->{SCHEMAS}->{$tableschema}->{TABLES}->{$tablename}->{INDEXES}->{$indexname}->{UNIQUE}=1;
}
else
{
$schema_db2->{SCHEMAS}->{$tableschema}->{TABLES}->{$tablename}->{INDEXES}->{$indexname}->{UNIQUE}=0;
}
# Read the column list
while (my $line=shift(@$refstatement))
{
# column list. there may be asc/desc
if ( $line =~ /^\s+\(?(\S+(?:\s+\S+))(,|\);?)/)
{
push @{$schema_db2->{SCHEMAS}->{$tableschema}->{TABLES}->{$tablename}->{INDEXES}->{$indexname}->{COLS}},($1);
last if ($2 eq ')');# End of the list of columns
}
else
{
die "I don't understand $line in a create index. I expected a list of columns"
}
}
# We may have an include definition
$line=shift(@$refstatement);
if ($line=~/INCLUDE \((\S+) (,|\))?\s*$/)
{
push @{$schema_db2->{SCHEMAS}->{$tableschema}->{TABLES}->{$tablename}->{INDEXES}->{$indexname}->{INCLUDECOLS}},($1);
if ($2 eq ',') # There are more columns
{
while (my $line=shift(@$refstatement))
{
if ( $line =~ /^\s+(\S+)\s*(,|\);?)/)
{
push @{$schema_db2->{SCHEMAS}->{$tableschema}->{TABLES}->{$tablename}->{INDEXES}->{$indexname}->{INCLUDECOLS}},($1);
last if ($2 eq ')');# End of the list of columns of the include
}
else
{
die "I don't understand $line in create index. I expected a list of columns for an include section"
}
}
}
# We have finished the INCLUDE. Read another line in case there is something else
next unless ($line=shift(@$refstatement));
}
if ($line =~ /(?:DIS)?ALLOW REVERSE SCANS/)