forked from mla/pg_sample
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pg_sample.t
executable file
·280 lines (233 loc) · 7.01 KB
/
pg_sample.t
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
#!/usr/bin/env perl
# NOTE: THIS SCRIPT IS DESTRUCTIVE! It will drop and recreate the table
#
# Uses TAP testing protocol. See "perldoc prove".
#
# To run this test program with prove, you should be able to just run 'prove'
# or 'prove -v' from the top-level directory.
#
# Or, to supply options (such as database connection info), you can also
# run it directly:
#
# t/pg_sample.t --db_user=foo
#
# The --cover option will generate code coverage statistics (see Devel::Cover)
#
# t/pg_sample.t --cover
our $DB_NAME = '_pg_sample_test';
$ENV{PATH} = ".:..:$ENV{PATH}";
$ENV{VERBOSITY} = 'terse';
use strict;
use warnings;
use Carp;
use DBI;
use Getopt::Long qw/ GetOptions :config no_ignore_case /;
use Test::More tests => 14;
$| = 1;
my %opt;
sub connect_db {
my $dsn = join ';',
"dbi:Pg:dbname=$opt{db_name}",
$opt{db_host} ? "host=$opt{db_host}" : (),
$opt{db_port} ? "port=$opt{db_port}" : (),
;
my $dbh = DBI->connect(
$dsn,
$opt{db_user},
$opt{db_pass},
{
RaiseError => 1,
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
PrintError => 0,
HandleError => sub { confess( shift ) },
},
) or croak "db connection failed!";
return $dbh;
}
sub connect_template1 {
local $opt{db_name} = 'template1';
return connect_db();
}
%opt = (
db_name => $DB_NAME,
db_host => '',
db_port => '',
);
GetOptions(\%opt,
'db_name|db-name=s',
'db_user|db_username|db-user|db-username|username|U=s',
'db_pass|db_password|db-pass|db-password|password|W=s',
'db_host|db-host|host=s',
'db_port|db-port|port=i',
'force',
'verbose',
'cover|coverage|testcover',
);
$opt{db_user} ||= $ENV{PGUSER} || scalar getpwuid($<);
$opt{db_name} ||= shift() || $ENV{PGDATABASE} || $opt{db_user};
$opt{db_host} ||= $ENV{PGHOST} if defined $ENV{PGHOST};
$opt{db_port} ||= $ENV{PGPORT} if defined $ENV{PGPORT};
$ENV{PGUSER} = $opt{db_user};
$ENV{PGDATABASE} = $opt{db_name};
$ENV{PGHOST} = $opt{db_host};
$ENV{PGPORT} = $opt{db_port};
my $template1_dbh = connect_template1();
unless ($opt{force}) {
my ($db_exists) = $template1_dbh->selectrow_array(qq{
SELECT TRUE
FROM pg_database
WHERE datname = ?
}, undef, $opt{db_name});
if ($db_exists) {
print STDERR "Warning: database $opt{db_name} will be dropped.\n";
my $ans = '';
do {
print STDERR "Are you sure you want to continue? [Y/n]: ";
my $i = lc <STDIN>;
chomp $i;
$i =~ s/\s+//g;
$ans = substr($i, 0, 1);
$ans = 'y' unless defined $ans and length $ans;
} until ($ans =~ /^[yn]$/);
if ($ans eq 'n') { exit 0 }
}
}
eval { $template1_dbh->do("DROP DATABASE $opt{db_name}") };
$template1_dbh->do("CREATE DATABASE $opt{db_name}");
my $dbh = connect_db();
$dbh->do(qq{ SET client_min_messages = warning });
$dbh->do(qq{
CREATE TABLE parent (
parent_id integer PRIMARY KEY
,name text NOT NULL UNIQUE
,favorite_child_id integer
)
});
# now create 10 child tables, each with 100 rows pointing to parent
foreach (1..10) {
$dbh->do(qq{
CREATE TABLE child$_ (
child_id integer PRIMARY KEY
,name text NOT NULL UNIQUE
,parent_id integer REFERENCES parent ON UPDATE CASCADE
)
});
}
$dbh->do(qq{
ALTER TABLE parent ADD FOREIGN KEY (favorite_child_id) REFERENCES child1
});
# create parent
for (1..1000) {
$dbh->do(
qq{ INSERT INTO parent (parent_id, name) VALUES (?, ?) },
undef,
$_, "p$_"
);
}
my $parent_id = 1;
for (1..10) {
for my $row (1..100) {
$dbh->do(
qq{ INSERT INTO child$_ (child_id, name, parent_id) VALUES (?, ?, ?) },
undef,
$row, "c$row", $parent_id++,
);
}
}
# create circular reference between tables
$dbh->do(qq{
UPDATE parent
SET favorite_child_id = (SELECT max(child_id) FROM child1)
WHERE parent_id = (SELECT min(parent_id) FROM parent)
});
# make sure COPY escaping works
$dbh->do(qq{
UPDATE parent
SET name = E'\\\\.'
WHERE parent_id = 1
});
# create schema/table/column with key words and embedded quotes
# to test quoting logic
$dbh->do(qq{ CREATE SCHEMA "S'""chema" });
$dbh->do(qq{
CREATE TABLE "S'""chema"."table" (
"table" text PRIMARY KEY
)
});
$dbh->do(qq{
CREATE TABLE "S'""chema".table_details (
table_detail_id serial PRIMARY KEY
,"table" text NOT NULL REFERENCES "S'""chema"."table"
ON UPDATE CASCADE ON DELETE CASCADE
)
});
### Partitioning
eval {
$dbh->do(qq{
CREATE TABLE partition_parent (
id int PRIMARY KEY
) PARTITION BY RANGE(id)
});
};
if ($@) {
diag "Skipping declarative partition tests";
} else {
$dbh->do(qq{
CREATE TABLE partition_child PARTITION OF partition_parent
FOR VALUES FROM (0) TO (100)
});
$dbh->do(qq{
INSERT INTO partition_parent VALUES (10)
});
}
### End Parititions
# Create unordered table to test --ordered
$dbh->do(qq{CREATE TABLE "test_ordered" (id SERIAL PRIMARY KEY, name TEXT);});
$dbh->do(qq{CREATE INDEX "my_index" ON "test_ordered" (name);});
$dbh->do(qq{INSERT INTO "test_ordered" VALUES (1, 'b'), (2, 'a');});
$dbh->do(qq{CLUSTER "test_ordered" USING "my_index"; -- with this, default SELECT will return 2,1;});
# Perform code coverage analysis? Requires Devel::Cover module.
if ($opt{cover}) {
$ENV{PERL5OPT} .= ' -MDevel::Cover=+select,pg_sample,+ignore,.*';
}
my @opts = ('--limit=100');
push @opts, '--verbose' if $opt{verbose};
my $cmd = "pg_sample @opts $opt{db_name} > sample.sql";
system($cmd) == 0 or die "pg_sample failed: $?";
$dbh->disconnect;
$template1_dbh->do("DROP DATABASE $opt{db_name}");
$template1_dbh->do("CREATE DATABASE $opt{db_name}");
$dbh = connect_db();
# Load the sample DB
$cmd = "psql -q -X -v ON_ERROR_STOP=1 $opt{db_name} < sample.sql";
system($cmd) == 0 or die "pg_sample failed: $?";
foreach (1..10) {
my($cnt) = $dbh->selectrow_array(qq{ SELECT count(*) FROM child$_ });
is($cnt, 100, "child$_ should have 100 rows");
}
my($cnt) = $dbh->selectrow_array(qq{ SELECT count(*) FROM parent });
is($cnt, 1000, "all parent rows should be fetched due to FKs");
my $row = $dbh->selectrow_hashref(qq{
SELECT * FROM parent WHERE parent_id = 1
});
is($row->{name}, "\\.", "escaping");
# without --ordered, test_ordered returns as per clustered order
my($ord) = $dbh->selectrow_array(qq{ SELECT STRING_AGG(id::text, ',') FROM "test_ordered" GROUP BY TRUE });
is($ord, '2,1', "ordered test case broken, this should return by clustered order");
@opts = ('--ordered');
push @opts, '--verbose' if $opt{verbose};
$cmd = "pg_sample @opts $opt{db_name} > sample_ordered.sql";
system($cmd) == 0 or die "pg_sample failed: $?";
$dbh->disconnect;
$template1_dbh->do("DROP DATABASE $opt{db_name}");
$template1_dbh->do("CREATE DATABASE $opt{db_name}");
$dbh = connect_db();
# Load the sample DB
$cmd = "psql -q -X -v ON_ERROR_STOP=1 $opt{db_name} < sample_ordered.sql";
system($cmd) == 0 or die "pg_sample failed: $?";
$ord = $dbh->selectrow_array(qq{ SELECT STRING_AGG(id::text, ',') FROM "test_ordered" GROUP BY TRUE });
is($ord, '1,2', "results should be ordered");
$dbh->disconnect;
$template1_dbh->do("DROP DATABASE $opt{db_name}");
exit 0;