summaryrefslogtreecommitdiff
path: root/contrib/adddepend/adddepend
blob: ea0c12690ee558d82372f44c9573a55d0bc06c71 (plain)
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
#!/usr/bin/perl
# $Id: adddepend,v 1.5 2003/06/25 01:11:09 momjian Exp $

# Project exists to assist PostgreSQL users with their structural upgrade 
# from PostgreSQL 7.2 (or prior) to 7.3 or 7.4.  Must be run against a 7.3 or 7.4
# database system (dump, upgrade daemon, restore, run this script)
#
# - Replace old style Foreign Keys with new style
# - Replace old SERIAL columns with new ones
# - Replace old style Unique Indexes with new style Unique Constraints


# License
# -------
# Copyright (c) 2001, Rod Taylor
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1.   Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#
# 2.   Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials provided
#      with the distribution.
#
# 3.   Neither the name of the InQuent Technologies Inc. nor the names
#      of its contributors may be used to endorse or promote products
#      derived from this software without specific prior written
#      permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD
# PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


use DBI;
use strict;


# Fetch the connection information from the local environment
my $dbuser = $ENV{'PGUSER'};
$dbuser ||= $ENV{'USER'};

my $database = $ENV{'PGDATABASE'};
$database ||= $dbuser;
my $dbisset = 0;

my $dbhost = $ENV{'PGHOST'};
$dbhost ||= "";

my $dbport = $ENV{'PGPORT'};
$dbport ||= "";

my $dbpass = "";

# Yes to all?
my $yes = 0; 

# Whats the name of the binary?
my $basename = $0;
$basename =~ s|.*/([^/]+)$|$1|;

## Process user supplied arguments.
for( my $i=0; $i <= $#ARGV; $i++ ) {
	ARGPARSE: for ( $ARGV[$i] ) {
		/^-d$/			&& do { $database = $ARGV[++$i];
							$dbisset = 1;
							last;
						};

		/^-[uU]$/		&& do { $dbuser = $ARGV[++$i];
							if (! $dbisset) {
								$database = $dbuser;
							}
							last;
						};

		/^-h$/			&& do { $dbhost = $ARGV[++$i]; last; };
		/^-p$/			&& do { $dbport = $ARGV[++$i]; last; };

		/^--password=/	&& do { $dbpass = $ARGV[$i];
							$dbpass =~ s/^--password=//g;
							last;
						};

		/^-Y$/			&& do { $yes = 1; last; };

		/^-\?$/			&& do { usage(); last; };
		/^--help$/		&& do { usage(); last; };
	}
}

# If no arguments were set, then tell them about usage
if ($#ARGV <= 0) {
	print <<MSG

No arguments set.  Use '$basename --help' for help

Connecting to database '$database' as user '$dbuser'

MSG
;
}

my $dsn = "dbi:Pg:dbname=$database";
$dsn .= ";host=$dbhost" if ( "$dbhost" ne "" );
$dsn .= ";port=$dbport" if ( "$dbport" ne "" );

# Database Connection
# -------------------
my $dbh = DBI->connect($dsn, $dbuser, $dbpass);

# We want to control commits
$dbh->{'AutoCommit'} = 0;

# PostgreSQL's version is used to determine what queries are required
# to retrieve a given information set.
my $sql_GetVersion = qq{
  SELECT cast(substr(version(), 12, 1) as integer) * 10000
		 + cast(substr(version(), 14, 1) as integer) * 100
		 as version;
};

my $sth_GetVersion = $dbh->prepare($sql_GetVersion);
$sth_GetVersion->execute();
my $version   = $sth_GetVersion->fetchrow_hashref;
my $pgversion = $version->{'version'}; 


# control where things get created
my $sql = qq{
    SET search_path = public;
};
my $sth = $dbh->prepare($sql);
$sth->execute();

END {
	$dbh->disconnect() if $dbh;
}

findUniqueConstraints();
findSerials();
findForeignKeys();

# Find old style Foreign Keys based on:
#
# - Group of 3 triggers of the appropriate types
# - 
sub findForeignKeys
{
	my $sql = qq{
	    SELECT tgargs
	         , tgnargs
	      FROM pg_trigger
	     WHERE NOT EXISTS (SELECT *
	                         FROM pg_depend
	                         JOIN pg_constraint as c ON (refobjid = c.oid)
	                        WHERE objid = pg_trigger.oid
	                          AND deptype = 'i'
	                          AND contype = 'f'
	                      )
	  GROUP BY tgargs
	         , tgnargs
	    HAVING count(*) = 3;
	};
	my $sth = $dbh->prepare($sql);
	$sth->execute() || triggerError($!);

	while (my $row = $sth->fetchrow_hashref)
	{
		# Fetch vars
		my $fkeynargs = $row->{'tgnargs'};
		my $fkeyargs = $row->{'tgargs'};
		my $matchtype = "MATCH SIMPLE";
		my $updatetype = "";
		my $deletetype = "";

		if ($fkeynargs % 2 == 0 && $fkeynargs >= 6) {
			my ( $keyname
			   , $table
			   , $ftable
			   , $unspecified
			   , $lcolumn_name
			   , $fcolumn_name
			   , @junk
			   ) = split(/\000/, $fkeyargs);

			# Account for old versions which don't seem to handle NULL
			# but instead return a string.  Newer DBI::Pg drivers 
			# don't have this problem
			if (!defined($ftable)) {
				( $keyname
				, $table
				, $ftable
				, $unspecified
				, $lcolumn_name
				, $fcolumn_name
				, @junk
				) = split(/\\000/, $fkeyargs);
			}
			else
			{
				# Clean up the string for further manipulation.  DBD doesn't deal well with
				# strings with NULLs in them
				$fkeyargs =~ s|\000|\\000|g;
			}

			# Catch and record MATCH FULL
			if ($unspecified eq "FULL")
			{
				$matchtype = "MATCH FULL";
			}

			# Start off our column lists
			my $key_cols = "\"$lcolumn_name\"";
			my $ref_cols = "\"$fcolumn_name\"";

			# Perhaps there is more than a single column
			while ($lcolumn_name = shift(@junk) and $fcolumn_name = shift(@junk)) {
				$key_cols .= ", \"$lcolumn_name\"";
				$ref_cols .= ", \"$fcolumn_name\"";
			}

			my $trigsql = qq{
			  SELECT tgname
			       , relname
			       , proname
			    FROM pg_trigger
			    JOIN pg_proc ON (pg_proc.oid = tgfoid)
			    JOIN pg_class ON (pg_class.oid = tgrelid)
			   WHERE tgargs = ?;
			};

			my $tgsth = $dbh->prepare($trigsql);
			$tgsth->execute($fkeyargs) || triggerError($!);
			my $triglist = "";
			while (my $tgrow = $tgsth->fetchrow_hashref)
			{
				my $trigname = $tgrow->{'tgname'};
				my $tablename = $tgrow->{'relname'};
				my $fname = $tgrow->{'proname'};

				for ($fname)
				{
				/^RI_FKey_cascade_del$/		&& do {$deletetype = "ON DELETE CASCADE"; last;};
				/^RI_FKey_cascade_upd$/		&& do {$updatetype = "ON UPDATE CASCADE"; last;};
				/^RI_FKey_restrict_del$/	&& do {$deletetype = "ON DELETE RESTRICT"; last;};
				/^RI_FKey_restrict_upd$/	&& do {$updatetype = "ON UPDATE RESTRICT"; last;};
				/^RI_FKey_setnull_del$/		&& do {$deletetype = "ON DELETE SET NULL"; last;};
				/^RI_FKey_setnull_upd$/		&& do {$updatetype = "ON UPDATE SET NULL"; last;};
				/^RI_FKey_setdefault_del$/	&& do {$deletetype = "ON DELETE SET DEFAULT"; last;};
				/^RI_FKey_setdefault_upd$/	&& do {$updatetype = "ON UPDATE SET DEFAULT"; last;};
				/^RI_FKey_noaction_del$/	&& do {$deletetype = "ON DELETE NO ACTION"; last;};
				/^RI_FKey_noaction_upd$/	&& do {$updatetype = "ON UPDATE NO ACTION"; last;};
				}

				$triglist .= "	DROP TRIGGER \"$trigname\" ON \"$tablename\";\n";
			}


			my $constraint = "";
			if ($keyname ne "<unnamed>") 
			{
				$constraint = "CONSTRAINT \"$keyname\"";
			}

			my $fkey = qq{
$triglist
	ALTER TABLE \"$table\" ADD $constraint FOREIGN KEY ($key_cols)
		 REFERENCES \"$ftable\"($ref_cols) $matchtype $updatetype $deletetype;
			};

			# Does the user want to upgrade this sequence?
			print <<MSG
The below commands will upgrade the foreign key style.  Shall I execute them?
$fkey
MSG
;
			if (userConfirm())
			{
				my $sthfkey = $dbh->prepare($fkey);
				$sthfkey->execute() || $dbh->rollback();
				$dbh->commit() || $dbh->rollback();
			}
		}
	}

}

# Find possible old style Serial columns based on:
#
# - Process unique constraints. Unique indexes without
#   the corresponding entry in pg_constraint)
sub findUniqueConstraints
{
	my $sql;
	if ( $pgversion >= 70400 ) {
		$sql = qq{
		    SELECT pg_index.*, quote_ident(ci.relname) AS index_name
	             , quote_ident(ct.relname) AS table_name
	             , pg_catalog.pg_get_indexdef(indexrelid) AS constraint_definition
		         , indclass
	          FROM pg_catalog.pg_class AS ci
    	      JOIN pg_catalog.pg_index ON (ci.oid = indexrelid)
	          JOIN pg_catalog.pg_class AS ct ON (ct.oid = indrelid)
		      JOIN pg_catalog.pg_namespace ON (ct.relnamespace = pg_namespace.oid)
	         WHERE indisunique     -- Unique indexes only
	           AND indpred IS NULL -- No Partial Indexes
		       AND indexprs IS NULL -- No expressional indexes
	           AND NOT EXISTS (SELECT TRUE
	                             FROM pg_catalog.pg_depend
		                         JOIN pg_catalog.pg_constraint
		                           ON (refobjid = pg_constraint.oid)
	                            WHERE objid = indexrelid
	                              AND objsubid = 0)
		       AND nspname NOT IN ('pg_catalog', 'pg_toast');
		};
	}
	else
	{
		$sql = qq{
		    SELECT pg_index.*, quote_ident(ci.relname) AS index_name
	             , quote_ident(ct.relname) AS table_name
	             , pg_catalog.pg_get_indexdef(indexrelid) AS constraint_definition
		         , indclass
	          FROM pg_catalog.pg_class AS ci
    	      JOIN pg_catalog.pg_index ON (ci.oid = indexrelid)
	          JOIN pg_catalog.pg_class AS ct ON (ct.oid = indrelid)
		      JOIN pg_catalog.pg_namespace ON (ct.relnamespace = pg_namespace.oid)
	         WHERE indisunique     -- Unique indexes only
	           AND indpred = '' -- No Partial Indexes
		       AND indproc = 0  -- No expressional indexes
	           AND NOT EXISTS (SELECT TRUE
	                             FROM pg_catalog.pg_depend
		                         JOIN pg_catalog.pg_constraint
		                           ON (refobjid = pg_constraint.oid)
	                            WHERE objid = indexrelid
	                              AND objsubid = 0)
		       AND nspname NOT IN ('pg_catalog', 'pg_toast');
		};
	}

	my $opclass_sql = qq{
	    SELECT TRUE
          FROM pg_catalog.pg_opclass
          JOIN pg_catalog.pg_am ON (opcamid = pg_am.oid)
         WHERE amname = 'btree'
	       AND pg_opclass.oid = ?
	       AND pg_opclass.oid < 15000;
	};
	
	my $sth = $dbh->prepare($sql) || triggerError($!);
	my $opclass_sth = $dbh->prepare($opclass_sql) || triggerError($!);
	$sth->execute();

ITERATION:
	while (my $row = $sth->fetchrow_hashref)
	{
		# Fetch vars
		my $constraint_name = $row->{'index_name'};
		my $table = $row->{'table_name'};
		my $columns = $row->{'constraint_definition'};

		# Test the opclass is BTree and was not added after installation
		my @classes = split(/ /, $row->{'indclass'});
		while (my $class = pop(@classes))
		{
			$opclass_sth->execute($class);

			next ITERATION if ($sth->rows == 0);
		}

		# Extract the columns from the index definition
		$columns =~ s|.*\(([^\)]+)\).*|$1|g;
		$columns =~ s|([^\s]+)[^\s]+_ops|$1|g;

		my $upsql = qq{
DROP INDEX $constraint_name RESTRICT;
ALTER TABLE $table ADD CONSTRAINT $constraint_name UNIQUE ($columns);
		};


		# Does the user want to upgrade this sequence?
		print <<MSG


Upgrade the Unique Constraint style via:
$upsql
MSG
;
		if (userConfirm())
		{
			# Drop the old index and create a new constraint by the same name
			# to replace it.
			my $upsth = $dbh->prepare($upsql);
			$upsth->execute() || $dbh->rollback();

			$dbh->commit() || $dbh->rollback();
		}
	}
}


# Find possible old style Serial columns based on:
#
# - Column is int or bigint
# - Column has a nextval() default
# - The sequence name includes the tablename, column name, and ends in _seq
#   or includes the tablename and is 40 or more characters in length.
sub findSerials
{
	my $sql = qq{
	    SELECT nspname AS nspname
	         , relname AS relname
	         , attname AS attname
	         , adsrc
	      FROM pg_catalog.pg_class as c

	      JOIN pg_catalog.pg_attribute as a
	           ON (c.oid = a.attrelid)

	      JOIN pg_catalog.pg_attrdef as ad
	           ON (a.attrelid = ad.adrelid
	           AND a.attnum = ad.adnum)

	      JOIN pg_catalog.pg_type as t
	           ON (t.typname IN ('int4', 'int8')
	           AND t.oid = a.atttypid)

	      JOIN pg_catalog.pg_namespace as n
	           ON (c.relnamespace = n.oid)

	     WHERE n.nspname = 'public'
	       AND adsrc LIKE 'nextval%'
	       AND adsrc LIKE '%'|| relname ||'_'|| attname ||'_seq%'
	       AND NOT EXISTS (SELECT *
	                         FROM pg_catalog.pg_depend as sd
	                         JOIN pg_catalog.pg_class as sc
	                              ON (sc.oid = sd.objid)
	                        WHERE sd.refobjid = a.attrelid
	                          AND sd.refobjsubid = a.attnum
	                          AND sd.objsubid = 0
	                          AND deptype = 'i'
	                          AND sc.relkind = 'S'
	                          AND sc.relname = c.relname ||'_'|| a.attname || '_seq'
	                      );
	};
	
	my $sth = $dbh->prepare($sql) || triggerError($!);
	$sth->execute();

	while (my $row = $sth->fetchrow_hashref)
	{
		# Fetch vars
		my $table = $row->{'relname'};
		my $column = $row->{'attname'};
		my $seq = $row->{'adsrc'};

		# Extract the sequence name from the default
		$seq =~ s|^nextval\(["']+([^'"\)]+)["']+.*\)$|$1|g;

		# Does the user want to upgrade this sequence?
		print <<MSG
Do you wish to upgrade Sequence '$seq' to SERIAL?
Found on column $table.$column
MSG
;
		if (userConfirm())
		{
			# Add the pg_depend entry for the serial column.  Should be enough
			# to fool pg_dump into recreating it properly next time.  The default
			# is still slightly different than a fresh serial, but close enough.
			my $upsql = qq{
			  INSERT INTO pg_catalog.pg_depend
			            ( classid
			            , objid
			            , objsubid
			            , refclassid
			            , refobjid
			            , refobjsubid
			            , deptype
			   ) VALUES ( (SELECT c.oid            -- classid
			                 FROM pg_class as c
			                 JOIN pg_namespace as n
			                      ON (n.oid = c.relnamespace)
			                WHERE n.nspname = 'pg_catalog'
			                  AND c.relname = 'pg_class')

			            , (SELECT c.oid            -- objid
			                 FROM pg_class as c
			                 JOIN pg_namespace as n
			                      ON (n.oid = c.relnamespace)
			                WHERE n.nspname = 'public'
			                  AND c.relname = '$seq')

			            , 0                        -- objsubid

			            , (SELECT c.oid            -- refclassid
			                 FROM pg_class as c
			                 JOIN pg_namespace as n
			                      ON (n.oid = c.relnamespace)
			                WHERE n.nspname = 'pg_catalog'
			                  AND c.relname = 'pg_class')

			            , (SELECT c.oid            -- refobjid
			                 FROM pg_class as c
			                 JOIN pg_namespace as n
			                      ON (n.oid = c.relnamespace)
			                WHERE n.nspname = 'public'
			                  AND c.relname = '$table')

			            , (SELECT a.attnum         -- refobjsubid
			                 FROM pg_class as c
			                 JOIN pg_namespace as n
			                      ON (n.oid = c.relnamespace)
			                 JOIN pg_attribute as a
			                      ON (a.attrelid = c.oid)
			                WHERE n.nspname = 'public'
			                  AND c.relname = '$table'
			                  AND a.attname = '$column')

			            , 'i'                      -- deptype
			            );
			};

			my $upsth = $dbh->prepare($upsql);
			$upsth->execute() || $dbh->rollback();

			$dbh->commit() || $dbh->rollback();
		}
	}
}


#######
# userConfirm
#	Wait for a key press
sub userConfirm
{
	my $ret = 0;
	my $key = "";

	# Sleep for key unless -Y was used
	if ($yes == 1)
	{
		$ret = 1;
		$key = 'Y';
	}

	# Wait for a keypress
	while ($key eq "")
	{
		print "\n << 'Y'es or 'N'o >> : ";
		$key = <STDIN>;

		chomp $key;

		# If it's not a Y or N, then ask again
		$key =~ s/[^YyNn]//g;
	}

	if ($key =~ /[Yy]/)
	{
		$ret = 1;
	}

	return $ret;
}

#######
# triggerError
#	Exit nicely, but print a message as we go about an error
sub triggerError
{
	my $msg = shift;

	# Set a default message if one wasn't supplied
	if (!defined($msg))
	{
		$msg = "Unknown error";
	}

	print $msg;

	exit 1;
}


#######
# usage
#   Script usage
sub usage
{
	print <<USAGE
Usage:
  $basename [options] [dbname [username]]

Options:
  -d <dbname>     Specify database name to connect to (default: $database)
  -h <host>       Specify database server host (default: localhost)
  -p <port>       Specify database server port (default: 5432)
  -u <username>   Specify database username (default: $dbuser)
  --password=<pw> Specify database password (default: blank)

  -Y              The script normally asks whether the user wishes to apply 
                  the conversion for each item found.  This forces YES to all
                  questions.

USAGE
;
	exit 0;
}