forked from Guy-Incognito/ora2pg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOra2Pg.pm
21480 lines (19250 loc) · 685 KB
/
Ora2Pg.pm
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
package Ora2Pg;
#------------------------------------------------------------------------------
# Project : Oracle to PostgreSQL database schema converter
# Name : Ora2Pg.pm
# Language : Perl
# Authors : Gilles Darold, gilles _AT_ darold _DOT_ net
# Copyright: Copyright (c) 2000-2023 : Gilles Darold - All rights reserved -
# Function : Main module used to export Oracle database schema to PostgreSQL
# Usage : See documentation in this file with perldoc.
#------------------------------------------------------------------------------
#
# This program 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 3 of the License, or
# 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. If not, see < http://www.gnu.org/licenses/ >.
#
#------------------------------------------------------------------------------
use vars qw($VERSION $PSQL %AConfig);
use Carp qw(confess);
use DBI;
use POSIX qw(locale_h _exit :sys_wait_h strftime);
use IO::File;
use Config;
use Time::HiRes qw/usleep/;
use Fcntl qw/ :flock /;
use IO::Handle;
use IO::Pipe;
use File::Basename;
use File::Spec qw/ tmpdir /;
use File::Temp qw/ tempfile /;
use Benchmark;
use Encode;
#set locale to LC_NUMERIC C
setlocale(LC_NUMERIC,"C");
$VERSION = '24.0';
$PSQL = $ENV{PLSQL} || 'psql';
$| = 1;
our %RUNNING_PIDS = ();
# Multiprocess communication pipe
our $pipe = undef;
our $TMP_DIR = File::Spec->tmpdir() || '/tmp';
our %ordered_views = ();
# Character that must be escaped in COPY statement
my $ESCAPE_COPY = { "\0" => "", "\\" => "\\\\", "\r" => "\\r", "\n" => "\\n", "\t" => "\\t"};
# Oracle internal timestamp month equivalent
our %ORACLE_MONTHS = ('JAN'=>'01', 'FEB'=>'02','MAR'=>'03','APR'=>'04','MAY'=>'05','JUN'=>'06','JUL'=>'07','AUG'=>'08','SEP'=>'09','OCT'=>10,'NOV'=>11,'DEC'=>12);
# Exclude table generated by partition logging, materialized view logs, statistis on spatial index,
# spatial index tables, sequence index tables, interMedia Text index tables and Unified Audit tables.
# LogMiner, Oracle Advanced Replication, hash table used by loadjava.
our @EXCLUDED_TABLES = ('USLOG\$_.*', 'MLOG\$_.*', 'RUPD\$_.*', 'MDXT_.*', 'MDRT_.*', 'MDRS_.*', 'DR\$.*', 'CLI_SWP\$.*', 'LOGMNR\$.*', 'REPCAT\$.*', 'JAVA\$.*', 'AQ\$.*', 'BIN\$.*', 'SDO_GR_.*', '.*\$JAVA\$.*', 'PROF\$.*', 'TOAD_PLAN_.*', 'SYS_.*\$', 'QUEST_SL_.*');
our @EXCLUDED_TABLES_8I = ('USLOG$_%', 'MLOG$_%', 'RUPD$_%', 'MDXT_%', 'MDRT_%', 'MDRS_%', 'DR$%', 'CLI_SWP$%', 'LOGMNR$%', 'REPCAT$%', 'JAVA$%', 'AQ$%', 'BIN$%', '%$JAVA$%', 'PROF$%', 'TOAD_PLAN_%', 'SYS_%$', 'QUEST_SL_%');
our @Oracle_tables = qw(
EVT_CARRIER_CONFIGURATION
EVT_DEST_PROFILE
EVT_HISTORY
EVT_INSTANCE
EVT_MAIL_CONFIGURATION
EVT_MONITOR_NODE
EVT_NOTIFY_STATUS
EVT_OPERATORS
EVT_OPERATORS_ADDITIONAL
EVT_OPERATORS_SYSTEMS
EVT_OUTSTANDING
EVT_PROFILE
EVT_PROFILE_EVENTS
EVT_REGISTRY
EVT_REGISTRY_BACKLOG
OLS_DIR_BUSINESSE
OLS_DIR_BUSINESSES
SDO_COORD_REF_SYS
SDO_CS_SRS
SDO_INDEX_METADATA_TABLE
SDO_INDEX_METADATA_TABLES
SDO_PC_BLK_TABLE
SDO_STYLES_TABLE
SDO_TIN_BLK_TABLE
SMACTUALPARAMETER_S
SMGLOBALCONFIGURATION_S
SMFORMALPARAMETER_S
SMFOLDER_S
SMDISTRIBUTIONSET_S
SMDEPENDENTLINKS
SMDEPENDENTINDEX
SMDEPENDEEINDEX
SMDEFAUTH_S
SMDBAUTH_S
SMPARALLELJOB_S
SMPACKAGE_S
SMOWNERLINKS
SMOWNERINDEX
SMOWNEEINDEX
SMOSNAMES_X
SMOMSTRING_S
SMMOWNERLINKS
SMMOWNERINDEX
SMPACKAGE_S
SMPARALLELJOB_S
SMPARALLELOPERATION_S
SMPARALLELSTATEMENT_S
SMPRODUCT_S
SMP_AD_ADDRESSES_
SMP_AD_DISCOVERED_NODES_
SMP_AD_NODES_
SMP_AD_PARMS_
SMP_AUTO_DISCOVERY_ITEM_
SMP_AUTO_DISCOVERY_PARMS_
SMP_BLOB_
SMP_CREDENTIALS\$
SMP_JOB_
SMP_JOB_EVENTLIST_
SMP_JOB_HISTORY_
SMP_JOB_INSTANCE_
SMP_JOB_LIBRARY_
SMP_JOB_TASK_INSTANCE_
SMP_LONG_TEXT_
SMP_REP_VERSION
SMP_SERVICES
SMP_SERVICE_GROUP_DEFN_
SMP_SERVICE_GROUP_ITEM_
SMP_SERVICE_ITEM_
SMP_UPDATESERVICES_CALLED_
SMAGENTJOB_S
SMARCHIVE_S
SMBREAKABLELINKS
SMCLIQUE
SMCONFIGURATION
SMCONSOLESOSETTING_S
SMDATABASE_S
SMHOSTAUTH_S
SMHOST_S
SMINSTALLATION_S
SMLOGMESSAGE_S
SMMONTHLYENTRY_S
SMMONTHWEEKENTRY_S
SMP_USER_DETAILS
SMRELEASE_S
SMRUN_S
SMSCHEDULE_S
SMSHAREDORACLECLIENT_S
SMSHAREDORACLECONFIGURATION_S
SMTABLESPACE_S
SMVCENDPOINT_S
SMWEEKLYENTRY_S
);
push(@EXCLUDED_TABLES, @Oracle_tables);
# Some function might be excluded from export and assessment.
our @EXCLUDED_FUNCTION = ('SQUIRREL_GET_ERROR_OFFSET');
our @FKEY_OPTIONS = ('NEVER', 'DELETE', 'ALWAYS');
# Minimized the footprint on disc, so that more rows fit on a data page,
# which is the most important factor for speed.
our %TYPALIGN = (
# Types and size, 1000 = variable
'boolean' => 1,
'smallint' => 2,
'smallserial' => 2,
'integer' => 4,
'real' => 4,
'serial' => 4,
'date' => 4,
'oid' => 4,
'macaddr' => 6,
'bigint' => 8,
'bigserial' => 8,
'double precision' => 8,
'macaddr8' => 8,
'money' => 8,
'time' => 8,
'timestamp' => 8,
'timestamp without time zone' => 8,
'timestamp with time zone' => 8,
'interval' => 16,
'point' => 16,
'tinterval' => 16,
'uuid' => 16,
'circle' => 24,
'box' => 32,
'line' => 32,
'lseg' => 32,
'bit' => 1000,
'bytea' => 1000,
'character varying' => 1000,
'cidr' => 19,
'json' => 1000,
'jsonb' => 1000,
'numeric' => 1000,
'path' => 1000,
'polygon' => 1000,
'text' => 1000,
'xml' => 1000,
# aliases
'bool' => 1,
'timetz' => 12,
'char' => 1000,
'decimal' => 1000,
# deprecated
'int2' => 2,
'abstime' => 4,
'bpchar' => 4,
'int4' => 4,
'reltime' => 4,
'float4' => 4,
'timestamptz' => 8,
'float8' => 8,
'int8' => 8,
'name' => 64,
'inet' => 19,
'varbit' => 1000,
'varchar' => 1000
);
our %INDEX_TYPE = (
'NORMAL' => 'b-tree',
'NORMAL/REV' => 'reversed b-tree',
'FUNCTION-BASED NORMAL' => 'function based b-tree',
'FUNCTION-BASED NORMAL/REV' => 'function based reversed b-tree',
'BITMAP' => 'bitmap',
'BITMAP JOIN' => 'bitmap join',
'FUNCTION-BASED BITMAP' => 'function based bitmap',
'FUNCTION-BASED BITMAP JOIN' => 'function based bitmap join',
'CLUSTER' => 'cluster',
'DOMAIN' => 'domain',
'IOT - TOP' => 'IOT',
'SPATIAL INDEX' => 'spatial index',
);
# Reserved keywords in PostgreSQL
our @KEYWORDS = qw(
ALL ANALYSE ANALYZE AND ANY ARRAY AS ASC ASYMMETRIC AUTHORIZATION BINARY
BOTH CASE CAST CHECK CMAX CMIN COLLATE COLLATION COLUMN CONCURRENTLY CONSTRAINT CREATE
CROSS CTID CURRENT_CATALOG CURRENT_DATE CURRENT_ROLE CURRENT_SCHEMA CURRENT_TIME
CURRENT_TIMESTAMP CURRENT_USER DEFAULT DEFERRABLE DESC DISTINCT DO ELSE END
EXCEPT FALSE FETCH FOR FOREIGN FREEZE FROM FULL GRANT GROUP HAVING ILIKE IN
INITIALLY INNER INTERSECT INTO IS ISNULL JOIN KEY LATERAL LEADING LEFT LIKE LIMIT
LOCALTIME LOCALTIMESTAMP NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER
OVERLAPS PARTITION PASSWORD PLACING PRIMARY REFERENCES REF RETURNING RIGHT SELECT SESSION_USER
SIMILAR SOME SYMMETRIC TABLE TABLESAMPLE THEN TO TRAILING TRUE UNION UNIQUE USER
USING VARIADIC VERBOSE WHEN WHERE WINDOW WITH
);
# Reserved keywords that can be used in PostgreSQL as function or type name
our @FCT_TYPE_KEYWORDS = qw(
AUTHORIZATION BINARY COLLATION CONCURRENTLY CROSS CURRENT_SCHEMA FREEZE
FULL ILIKE INNER IS ISNULL JOIN LEFT LIKE NATURAL NOTNULL OUTER OVERLAPS
RIGHT SIMILAR TABLESAMPLE VERBOSE
);
our @SYSTEM_FIELDS = qw(oid tableoid xmin xmin cmin xmax cmax ctid);
our %BOOLEAN_MAP = (
'yes' => 't',
'no' => 'f',
'y' => 't',
'n' => 'f',
'1' => 't',
'0' => 'f',
'true' => 't',
'false' => 'f',
'enabled'=> 't',
'disabled'=> 'f',
't' => 't',
'f' => 'f',
);
our @GRANTS = (
'SELECT', 'INSERT', 'UPDATE', 'DELETE', 'TRUNCATE',
'REFERENCES', 'TRIGGER', 'USAGE', 'CREATE', 'CONNECT',
'TEMPORARY', 'TEMP', 'USAGE', 'ALL', 'ALL PRIVILEGES',
'EXECUTE'
);
$SIG{'CHLD'} = 'DEFAULT';
####
# method used to fork as many child as wanted
##
sub spawn
{
my $coderef = shift;
unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
print "usage: spawn CODEREF";
exit 0;
}
my $pid;
if (!defined($pid = fork)) {
print STDERR "Error: cannot fork: $!\n";
return;
} elsif ($pid) {
$RUNNING_PIDS{$pid} = $pid;
return; # the parent
}
# the child -- go spawn
$< = $>;
$( = $); # suid progs only
exit &$coderef();
}
# With multiprocess we need to wait all childs
sub wait_child
{
my $sig = shift;
print STDERR "Received terminating signal ($sig).\n";
if ($^O !~ /MSWin32|dos/i) {
1 while wait != -1;
$SIG{INT} = \&wait_child;
$SIG{TERM} = \&wait_child;
}
print STDERR "Aborting.\n";
_exit(0);
}
$SIG{INT} = \&wait_child;
$SIG{TERM} = \&wait_child;
=head1 PUBLIC METHODS
=head2 new HASH_OPTIONS
Creates a new Ora2Pg object.
The only required option is:
- config : Path to the configuration file (required).
All directives found in the configuration file can be overwritten in the
instance call by passing them in lowercase as arguments.
=cut
sub new
{
my ($class, %options) = @_;
# This create an OO perl object
my $self = {};
bless ($self, $class);
# Initialize this object
$self->_init(%options);
# Return the instance
return($self);
}
=head2 export_schema FILENAME
Print SQL data output to a file name or
to STDOUT if no file name is specified.
=cut
sub export_schema
{
my $self = shift;
# Create default export file where things will be written with the dump() method
# First remove it if the output file already exists
foreach my $t (@{$self->{export_type}})
{
next if ($t =~ /^(?:SHOW_|TEST)/i); # SHOW_* commands are not concerned here
# Set current export type
$self->{type} = $t;
if ($self->{type} ne 'LOAD')
{
# Close open main output file
if (defined $self->{fhout}) {
$self->close_export_file($self->{fhout});
}
# Remove old export file if it already exists
$self->remove_export_file();
# then create a new one
$self->create_export_file();
}
# Dump exported statement to output
$self->_get_sql_statements();
if ($self->{type} ne 'LOAD')
{
# Close output export file create above
$self->close_export_file($self->{fhout}) if (defined $self->{fhout});
}
}
# Disconnect from the database
$self->{dbh}->disconnect() if ($self->{dbh});
$self->{dbhdest}->disconnect() if ($self->{dbhdest});
# Try to requalify package function call
if (!$self->{package_as_schema}) {
$self->fix_function_call();
}
my $dirprefix = '';
$dirprefix = "$self->{output_dir}/" if ($self->{output_dir});
unlink($dirprefix . 'temp_pass2_file.dat');
}
=head2 open_export_file FILENAME
Open a file handle to a given filename.
=cut
sub open_export_file
{
my ($self, $outfile, $noprefix) = @_;
my $filehdl = undef;
if ($outfile && $outfile ne '-') {
if ($outfile ne '-') {
if ($self->{output_dir} && !$noprefix) {
$outfile = $self->{output_dir} . '/' . $outfile;
}
if ($self->{input_file} && ($outfile eq $self->{input_file})) {
$self->logit("FATAL: input file is the same as output file: $outfile, can not overwrite it.\n",0,1);
}
}
# If user request data compression
if ($outfile =~ /\.gz$/i) {
eval("use Compress::Zlib;");
$self->{compress} = 'Zlib';
$filehdl = gzopen("$outfile", "wb") or $self->logit("FATAL: Can't create deflation file $outfile\n",0,1);
} elsif ($outfile =~ /\.bz2$/i) {
$self->logit("Error: can't run bzip2\n",0,1) if (!-x $self->{bzip2});
$self->{compress} = 'Bzip2';
$filehdl = new IO::File;
$filehdl->open("|$self->{bzip2} --stdout >$outfile") or $self->logit("FATAL: Can't open pipe to $self->{bzip2} --stdout >$outfile: $!\n", 0,1);
} else {
$filehdl = new IO::File;
$filehdl->open(">$outfile") or $self->logit("FATAL: Can't open $outfile: $!\n", 0, 1);
}
$filehdl->autoflush(1) if (defined $filehdl && !$self->{compress});
}
return $filehdl;
}
=head2 create_export_file FILENAME
Set output file and open a file handle on it,
will use STDOUT if no file name is specified.
=cut
sub create_export_file
{
my ($self, $outfile) = @_;
# Do not create the default export file with direct data export
if (($self->{type} eq 'INSERT') || ($self->{type} eq 'COPY')) {
return if ($self->{pg_dsn});
}
# Init with configuration OUTPUT filename
$outfile ||= $self->{output};
if ($outfile)
{
if ($outfile ne '-')
{
# Prefix out file with export type in multiple export type call
$outfile = $self->{type} . "_$outfile" if ($#{$self->{export_type}} > 0);
if ($self->{output_dir} && $outfile) {
$outfile = $self->{output_dir} . "/" . $outfile;
}
if ($self->{input_file} && ($outfile eq $self->{input_file})) {
$self->logit("FATAL: input file is the same as output file: $outfile, can not overwrite it.\n",0,1);
}
}
# Send output to the specified file
if ($outfile =~ /\.gz$/)
{
eval("use Compress::Zlib;");
$self->{compress} = 'Zlib';
$self->{fhout} = gzopen($outfile, "wb") or $self->logit("FATAL: Can't create deflation file $outfile\n", 0, 1);
}
elsif ($outfile =~ /\.bz2$/)
{
$self->logit("FATAL: can't run bzip2\n",0,1) if (!-x $self->{bzip2});
$self->{compress} = 'Bzip2';
$self->{fhout} = new IO::File;
$self->{fhout}->open("|$self->{bzip2} --stdout >$outfile") or $self->logit("FATAL: Can't open pipe to $self->{bzip2} --stdout >$outfile: $!\n", 0, 1);
}
else
{
$self->{fhout} = new IO::File;
$self->{fhout}->open(">>$outfile") or $self->logit("FATAL: Can't open $outfile: $!\n", 0, 1);
$self->set_binmode($self->{fhout});
}
if ( $self->{compress} && (($self->{jobs} > 1) || ($self->{oracle_copies} > 1)) )
{
die "FATAL: you can't use compressed output with parallel dump\n";
}
}
}
sub remove_export_file
{
my ($self, $outfile) = @_;
# Init with configuration OUTPUT filename
$outfile ||= $self->{output};
if ($outfile && $outfile ne '-')
{
# Prefix out file with export type in multiple export type call
$outfile = $self->{type} . "_$outfile" if ($#{$self->{export_type}} > 0);
if ($self->{output_dir} && $outfile)
{
$outfile = $self->{output_dir} . "/" . $outfile;
}
if ($self->{input_file} && ($outfile eq $self->{input_file}))
{
$self->logit("FATAL: input file is the same as output file: $outfile, can not overwrite it.\n",0,1);
}
unlink($outfile);
}
}
=head2 append_export_file FILENAME
Open a file handle to a given filename to append data.
=cut
sub append_export_file
{
my ($self, $outfile, $noprefix) = @_;
my $filehdl = undef;
if ($outfile)
{
if ($self->{output_dir} && !$noprefix) {
$outfile = $self->{output_dir} . '/' . $outfile;
}
# If user request data compression
if ($self->{compress} && (($self->{jobs} > 1) || ($self->{oracle_copies} > 1))) {
die "FATAL: you can't use compressed output with parallel dump\n";
} else {
$filehdl = new IO::File;
$filehdl->open(">>$outfile") or $self->logit("FATAL: Can't open $outfile: $!\n", 0, 1);
$filehdl->autoflush(1);
}
}
return $filehdl;
}
=head2 append_lo_import_file FILENAME
Open a file handle to lo_import-$table.sh file to append data.
=cut
sub append_lo_import_file
{
my ($self, $table, $noprefix) = @_;
my $filehdl = undef;
my $new = 0;
my $outfile = "lo_import-$table.sh";
if ($self->{output_dir} && !$noprefix) {
$outfile = $self->{output_dir} . '/' . $outfile;
}
$filehdl = new IO::File;
$new = 1 if (!-e $outfile);
$filehdl->open(">>$outfile") or $self->logit("FATAL: Can't open $outfile: $!\n", 0, 1);
$filehdl->autoflush(1);
$self->set_binmode($filehdl);
flock($filehdl, 2) || die "FATAL: can't lock file $outfile\n";
# At file creation append the verification of the required environment variable
if ($new)
{
$self->{post_lo_script} = qq{#!/bin/sh
if [ "\${PGDATABASE}a" = "a" ]; then
echo "You must set the environment variable PGDATABASE to defined the database where the commands"
echo "will be executed. And optionally PGHOST, PGUSER, etc. if they don't correspond to the default."
exit 1
fi
$self->{post_lo_script}
};
}
$filehdl->print($self->{post_lo_script});
$filehdl->close();
}
=head2 read_export_file FILENAME
Open a file handle to a given filename to read data.
=cut
sub read_export_file
{
my ($self, $infile) = @_;
my $filehdl = new IO::File;
$filehdl->open("<$infile") or $self->logit("FATAL: Can't read $infile: $!\n", 0, 1);
return $filehdl;
}
=head2 close_export_file FILEHANDLE
Close a file handle.
=cut
sub close_export_file
{
my ($self, $filehdl, $not_compressed) = @_;
return if (!defined $filehdl);
if (!$not_compressed && $self->{output} =~ /\.gz$/) {
if ($filehdl =~ /IO::File=/) {
$filehdl->close();
} else {
$filehdl->gzclose();
}
} else {
$filehdl->close();
}
}
=head2 modify_struct TABLE_NAME ARRAYOF_FIELDNAME
Modify the table structure during the export. Only the specified columns
will be exported.
=cut
sub modify_struct
{
my ($self, $table, @fields) = @_;
if (!$self->{preserve_case}) {
map { $_ = lc($_) } @fields;
$table = lc($table);
}
push(@{$self->{modify}{$table}}, @fields);
}
=head2 exclude_columns TABLE_NAME ARRAYOF_FIELDNAME
Modify the table structure during the export. The specified columns
will NOT be exported.
=cut
sub exclude_columns
{
my ($self, $table, @fields) = @_;
if (!$self->{preserve_case}) {
delete $self->{exclude_columns}{$table};
map { $_ = lc($_) } @fields;
$table = lc($table);
push(@{$self->{exclude_columns}{$table}}, @fields);
}
}
=head2 is_reserved_words
Returns 1 if the given object name is a PostgreSQL reserved word
Returns 2 if the object name is only numeric
Returns 3 if the object name is a system column
=cut
sub is_reserved_words
{
my ($self, $obj_name) = @_;
if ($obj_name && grep(/^\Q$obj_name\E$/i, @KEYWORDS)) {
return 1 if (!grep(/^$self->{type}/, 'FUNCTION', 'PACKAGE', 'PROCEDURE') || grep(/^\Q$obj_name\E$/i, @FCT_TYPE_KEYWORDS));
}
# columns starting by numbers need to be quoted unless it is an operation
if ($obj_name =~ /^\d+/ && $obj_name !~ /[\+\-\/\*]/) {
return 2;
}
if ($obj_name && grep(/^\Q$obj_name\E$/i, @SYSTEM_FIELDS)) {
return 3;
}
return 0;
}
=head2 quote_object_name
Return a quoted object named when needed:
- PostgreSQL reserved word
- unsupported character
- start with a digit or digit only
=cut
sub quote_object_name
{
my ($self, @obj_list) = @_;
my @ret = ();
foreach my $obj_name (@obj_list)
{
next if ($obj_name =~ /^SYS_NC\d+/);
# Start by removing any double quote and extra space
$obj_name =~ s/"//g;
$obj_name =~ s/^\s+//;
$obj_name =~ s/\s+$//;
# When PRESERVE_CASE is not enabled set object name to lower case
if (!$self->{preserve_case})
{
$obj_name = lc($obj_name);
# then if there is non alphanumeric or the object name is a reserved word
if ($obj_name =~ /[^a-z0-9\_\.\$]/ || ($self->{use_reserved_words} && $self->is_reserved_words($obj_name)) || $obj_name =~ /^\d+/)
{
# Add double quote to [schema.] object name
if ($obj_name !~ /^[^\.]+\.[^\.]+$/ && $obj_name !~ /^[^\.]+\.[^\.]+\.[^\.]+$/) {
$obj_name = '"' . $obj_name . '"';
} elsif ($obj_name =~ /^[^\.]+\.[^\.]+$/) {
$obj_name =~ s/^([^\.]+)\.([^\.]+)$/"$1"\."$2"/;
} else {
$obj_name =~ s/^([^\.]+)\.([^\.]+)\.([^\.]+)$/"$1"\."$2"\."$3"/;
}
$obj_name = '"' . $obj_name . '"' if ($obj_name =~ /^\d+/);
}
}
# Add double quote to [schema.] object name
elsif ($obj_name !~ /^[^\.]+\.[^\.]+$/ && $obj_name !~ /^[^\.]+\.[^\.]+\.[^\.]+$/) {
$obj_name = "\"$obj_name\"";
} elsif ($obj_name =~ /^[^\.]+\.[^\.]+$/) {
$obj_name =~ s/^([^\.]+)\.([^\.]+)$/"$1"\."$2"/;
} else {
$obj_name =~ s/^([^\.]+)\.([^\.]+)\.([^\.]+)$/"$1"\."$2"\."$3"/;
}
push(@ret, $obj_name);
}
return join(',', @ret);
}
=head2 replace_tables HASH
Modify table names during the export.
=cut
sub replace_tables
{
my ($self, %tables) = @_;
foreach my $t (keys %tables) {
$self->{replaced_tables}{"\L$t\E"} = $tables{$t};
}
}
=head2 replace_cols HASH
Modify column names during the export.
=cut
sub replace_cols
{
my ($self, %cols) = @_;
foreach my $t (keys %cols) {
foreach my $c (keys %{$cols{$t}}) {
$self->{replaced_cols}{"\L$t\E"}{"\L$c\E"} = $cols{$t}{$c};
}
}
}
=head2 set_where_clause HASH
Add a WHERE clause during data export on specific tables or on all tables
=cut
sub set_where_clause
{
my ($self, $global, %table_clause) = @_;
$self->{global_where} = $global;
foreach my $t (keys %table_clause) {
$self->{where}{"\L$t\E"} = $table_clause{$t};
}
}
=head2 set_delete_clause HASH
Add a DELETE clause before data export on specific tables or on all tables
=cut
sub set_delete_clause
{
my ($self, $global, %table_clause) = @_;
$self->{global_delete} = $global;
foreach my $t (keys %table_clause) {
$self->{delete}{"\L$t\E"} = $table_clause{$t};
}
}
#### Private subroutines ####
=head1 PRIVATE METHODS
=head2 _db_connection
Initialize a connexion to the Oracle database.
=cut
sub _db_connection
{
my $self = shift;
if ($self->{is_mysql})
{
use Ora2Pg::MySQL;
return Ora2Pg::MySQL::_db_connection($self);
}
elsif ($self->{is_mssql})
{
use Ora2Pg::MSSQL;
return Ora2Pg::MSSQL::_db_connection($self);
}
else
{
use Ora2Pg::Oracle;
return Ora2Pg::Oracle::_db_connection($self);
}
}
=head2 _init HASH_OPTIONS
Initialize an Ora2Pg object instance with a connexion to the
Oracle database.
=cut
sub _init
{
my ($self, %options) = @_;
# Use custom temp directory if specified
$TMP_DIR = $options{temp_dir} || $TMP_DIR;
# Read configuration file
$self->read_config($options{config}) if ($options{config});
# Those are needed by DBI
$ENV{ORACLE_HOME} = $AConfig{'ORACLE_HOME'} if ($AConfig{'ORACLE_HOME'});
$ENV{NLS_LANG} = $AConfig{'NLS_LANG'} if ($AConfig{'NLS_LANG'});
# Init arrays
$self->{default_tablespaces} = ();
$self->{limited} = ();
$self->{excluded} = ();
$self->{view_as_table} = ();
$self->{mview_as_table} = ();
$self->{modify} = ();
$self->{replaced_tables} = ();
$self->{replaced_cols} = ();
$self->{replace_as_boolean} = ();
$self->{ora_boolean_values} = ();
$self->{null_equal_empty} = 1;
$self->{estimate_cost} = 0;
$self->{where} = ();
$self->{replace_query} = ();
$self->{ora_reserved_words} = ();
$self->{defined_pk} = ();
$self->{allow_partition} = ();
$self->{empty_lob_null} = 0;
$self->{look_forward_function} = ();
$self->{no_function_metadata} = 0;
$self->{transform_value} = ();
$self->{all_objects} = ();
# Initial command to execute at Oracle and PostgreSQL connexion
$self->{ora_initial_command} = ();
$self->{pg_initial_command} = ();
# To register user defined exception
$self->{custom_exception} = ();
$self->{exception_id} = 50001;
# Init PostgreSQL DB handle
$self->{dbhdest} = undef;
$self->{standard_conforming_strings} = 1;
$self->{create_schema} = 1;
# Init some arrays
$self->{external_table} = ();
$self->{function_metadata} = ();
$self->{grant_object} = '';
# Used to precise if we need to rename the partitions
$self->{rename_partition} = 0;
# Use to preserve the data export type with geometry objects
$self->{local_type} = '';
# Shall we log on error during data import or abort.
$self->{log_on_error} = 0;
# Initialize some variable related to export of mysql database
$self->{is_mysql} = 0;
$self->{mysql_mode} = '';
$self->{mysql_internal_extract_format} = 0;
$self->{mysql_pipes_as_concat} = 0;
# Initialize some variable related to export of mssql database
$self->{is_mssql} = 0;
$self->{drop_rowversion} = 0;
$self->{case_insensitive_search} = 'citext';
# List of users for audit trail
$self->{audit_user} = '';
# Disable copy freeze by default
$self->{copy_freeze} = '';
# Use FTS index to convert CONTEXT Oracle's indexes by default
$self->{context_as_trgm} = 0;
$self->{fts_index_only} = 1;
$self->{fts_config} = '';
$self->{use_unaccent} = 1;
$self->{use_lower_unaccent} = 1;
# Enable rewrite of outer join by default.
$self->{rewrite_outer_join} = 1;
# Init comment and text constant storage variables
$self->{idxcomment} = 0;
$self->{comment_values} = ();
$self->{text_values} = ();
$self->{text_values_pos} = 0;
# Keep commit/rollback in converted pl/sql code by default
$self->{comment_commit_rollback} = 0;
# Keep savepoint in converted pl/sql code by default
$self->{comment_savepoint} = 0;
# Storage of string constant placeholder regexp
$self->{string_constant_regexp} = ();
$self->{alternative_quoting_regexp} = ();
# Number of row for data validation
$self->{data_validation_rows} = 10000;
$self->{data_validation_error} = 10;
$self->{data_validation_ordering} = 1;
# Global file handle
$self->{cfhout} = undef;
# oracle_fdw foreign server