/
test_ddl_printers.py
1508 lines (1060 loc) · 35.1 KB
/
test_ddl_printers.py
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
# -*- coding: utf-8 -*-
# :Project: pglast -- Test for the printers/ddl.py module
# :Created: gio 09 nov 2017 10:57:55 CET
# :Author: Lele Gaifax <lele@metapensiero.it>
# :License: GNU General Public License version 3 or later
# :Copyright: © 2017, 2018, 2019 Lele Gaifax
#
from ast import literal_eval
import pytest
from pglast.printer import IndentedStream
import pglast.printers
from test_dml_printers import roundtrip
# Make pyflakes happy
pglast.printers
ALTER_DEFAULT_PRIVILEGES = """
ALTER DEFAULT PRIVILEGES FOR ROLE role1, role2 IN SCHEMA s1, s2
GRANT ALL PRIVILEGES ON TABLES TO grantee1, grantee2
ALTER DEFAULT PRIVILEGES FOR ROLE role1, role2 IN SCHEMA s1, s2
REVOKE INSERT, UPDATE ON TABLES FROM grantee1, grantee2
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in
ALTER_DEFAULT_PRIVILEGES.split('\n\n')))
def test_alter_default_privileges(sql):
roundtrip(sql)
ALTER_OWNERS = """
ALTER FUNCTION fonction1() OWNER TO rol1
ALTER VIEW v1 OWNER TO rol2
ALTER TABLE t1 OWNER TO rol3
ALTER SCHEMA schema1 OWNER TO rol4
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in ALTER_OWNERS.split('\n\n')))
def test_alter_owners(sql):
roundtrip(sql)
ALTER_ROLES = """
ALTER ROLE r1 LOGIN
ALTER ROLE r1 NOLOGIN
ALTER ROLE r2 CONNECTION LIMIT 10
ALTER ROLE r2 VALID UNTIL '1900-01-01' SUPERUSER
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in ALTER_ROLES.split('\n\n')))
def test_alter_roles(sql):
roundtrip(sql)
ALTER_TABLES = """
ALTER TABLE t1 ALTER c1 TYPE varchar(20)
ALTER TABLE t1 ALTER c1 TYPE montype USING mafonction(c1)
ALTER TABLE t1 OWNER TO role1
ALTER TABLE t1 ALTER c1 SET STATISTICS 1000
ALTER TABLE t1 ALTER C1 SET DEFAULT 'default'
ALTER TABLE IF EXISTS t1 ALTER C1 DROP DEFAULT
ALTER TABLE t1 ADD COLUMN IF NOT EXISTS c1 int
ALTER TABLE t2 DROP COLUMN IF EXISTS c1
ALTER TABLE t2 DROP COLUMN IF EXISTS c1 CASCADE
ALTER TABLE t2 ENABLE TRIGGER trig1
ALTER TABLE t2 DISABLE TRIGGER trig1
ALTER TABLE t1 ALTER COLUMN c1 DROP NOT NULL
ALTER TABLE t1 ALTER COLUMN c2 SET NOT NULL
ALTER TABLE t1 ADD FOREIGN KEY (c1) REFERENCES t2(c1) DEFERRABLE INITIALLY DEFERRED NOT VALID
ALTER TABLE t1 DROP CONSTRAINT IF EXISTS c1_check
ALTER TABLE t1 CLUSTER ON c1_idx
ALTER TABLE t1 ENABLE ROW LEVEL SECURITY
ALTER TABLE t1 VALIDATE CONSTRAINT c1_check
ALTER TABLE t1 ADD PRIMARY KEY USING INDEX t1_idx
ALTER FOREIGN TABLE c1 ADD COLUMN c1 int
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in ALTER_TABLES.split('\n\n')))
def test_alter_tables(sql):
roundtrip(sql)
CLUSTERS = """
CLUSTER t1 USING idx1
CLUSTER VERBOSE t1 USING idx1
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CLUSTERS.split('\n\n')))
def test_clusters(sql):
roundtrip(sql)
TYPES = """
CREATE TYPE t1 AS ENUM ('value1', 'value2')
ALTER TYPE t1 ADD VALUE 'value3'
ALTER TYPE t1 ADD VALUE 'value2.5' BEFORE 'value3'
ALTER TYPE t1 ADD VALUE 'value3.5' AFTER 'value3'
ALTER TYPE t1 ADD VALUE IF NOT EXISTS 'value3'
CREATE TYPE tcomposite AS (c1 int, c2 text)
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in TYPES.split('\n\n')))
def test_types(sql):
roundtrip(sql)
DISCARDS = """
DISCARD ALL
DISCARD PLANS
DISCARD SEQUENCES
DISCARD TEMP
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in DISCARDS.split('\n\n')))
def test_discards(sql):
roundtrip(sql)
COMMENTS = """\
COMMENT ON ACCESS METHOD rtree IS 'R-Tree access method'
COMMENT ON AGGREGATE my_aggregate (double precision) IS 'Computes sample variance'
COMMENT ON CAST (text AS int4) IS 'Allow casts from text to int4'
COMMENT ON COLLATION "fr_CA" IS 'Canadian French'
COMMENT ON COLUMN my_table.my_column IS 'Employee ID number'
COMMENT ON CONVERSION my_conv IS 'Conversion to UTF8'
COMMENT ON CONSTRAINT bar_col_cons ON bar IS 'Constrains column col'
COMMENT ON CONSTRAINT dom_col_constr ON DOMAIN dom IS 'Constrains col of domain'
COMMENT ON DATABASE my_database IS 'Development Database'
COMMENT ON DOMAIN my_domain IS 'Email Address Domain'
COMMENT ON EXTENSION hstore IS 'implements the hstore data type'
COMMENT ON FOREIGN DATA WRAPPER mywrapper IS 'my foreign data wrapper'
COMMENT ON FOREIGN TABLE my_foreign_table IS 'Employee Information in other database'
COMMENT ON FUNCTION my_function (timestamp) IS 'Returns Roman Numeral'
COMMENT ON INDEX my_index IS 'Enforces uniqueness on employee ID'
COMMENT ON LANGUAGE plpython IS 'Python support for stored procedures'
COMMENT ON LARGE OBJECT 346344 IS 'Planning document'
COMMENT ON MATERIALIZED VIEW my_matview IS 'Summary of order history'
COMMENT ON OPERATOR ^ (text, text) IS 'Performs intersection of two texts'
COMMENT ON OPERATOR - (NONE, integer) IS 'Unary minus'
COMMENT ON OPERATOR CLASS int4ops USING btree IS '4 byte integer operators for btrees'
COMMENT ON OPERATOR FAMILY integer_ops USING btree IS 'all integer operators for btrees'
COMMENT ON POLICY my_policy ON mytable IS 'Filter rows by users'
COMMENT ON ROLE my_role IS 'Administration group for finance tables'
COMMENT ON RULE my_rule ON my_table IS 'Logs updates of employee records'
COMMENT ON SCHEMA my_schema IS 'Departmental data'
COMMENT ON SEQUENCE my_sequence IS 'Used to generate primary keys'
COMMENT ON SERVER myserver IS 'my foreign server'
COMMENT ON STATISTICS my_statistics IS 'Improves planner row estimations'
COMMENT ON TABLE my_schema.my_table IS 'Employee Information'
COMMENT ON TABLESPACE my_tablespace IS 'Tablespace for indexes'
COMMENT ON TEXT SEARCH CONFIGURATION my_config IS 'Special word filtering'
COMMENT ON TEXT SEARCH DICTIONARY swedish IS 'Snowball stemmer for Swedish language'
COMMENT ON TEXT SEARCH PARSER my_parser IS 'Splits text into words'
COMMENT ON TEXT SEARCH TEMPLATE snowball IS 'Snowball stemmer'
COMMENT ON TRANSFORM FOR hstore LANGUAGE plpythonu
IS 'Transform between hstore and Python dict'
COMMENT ON TRIGGER my_trigger ON my_table IS 'Used for RI'
COMMENT ON TYPE complex IS 'Complex number data type'
COMMENT ON VIEW my_view IS
'Lorem ipsum dolor sit amet, consectetur adipisicing elit,'
' sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.'
' Ut enimad minim veniam, quis nostrud exercitation ullamco laboris.'
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in COMMENTS.split('\n\n')))
def test_comments(sql):
roundtrip(sql)
CREATE_ACCESS_METHODS = """\
CREATE ACCESS METHOD heptree TYPE INDEX HANDLER heptree_handler
CREATE ACCESS METHOD "Heptree" TYPE INDEX HANDLER "MySchema"."MyHandler"
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_ACCESS_METHODS.split('\n\n')))
def test_create_access_methods(sql):
roundtrip(sql)
CREATE_AGGREGATES = """\
CREATE AGGREGATE sum (complex)
(
sfunc = complex_add,
stype = complex,
initcond = '(0,0)'
)
CREATE AGGREGATE sum (complex)
(
sfunc = complex_add,
stype = complex,
initcond = '(0,0)',
parallel = safe
)
CREATE AGGREGATE avg (float8)
(
sfunc = float8_accum,
stype = float8[],
finalfunc = float8_avg,
initcond = '{0,0,0}'
)
CREATE AGGREGATE sum (complex)
(
sfunc = complex_add,
stype = complex,
initcond = '(0,0)',
msfunc = complex_add,
minvfunc = complex_sub,
mstype = complex,
minitcond = '(0,0)'
)
CREATE AGGREGATE array_accum (anyelement)
(
sfunc = array_append,
stype = anyarray,
initcond = '{}'
)
CREATE AGGREGATE array_agg (anynonarray)
(
sfunc = array_agg_transfn,
stype = internal,
finalfunc = array_agg_finalfn,
finalfunc_extra
)
CREATE AGGREGATE percentile_disc (float8 ORDER BY anyelement)
(
sfunc = ordered_set_transition,
stype = internal,
finalfunc = percentile_disc_final,
finalfunc_extra
)
CREATE AGGREGATE percentile_disc (float8 ORDER BY anyelement)
(
sfunc = ordered_set_transition,
stype = internal,
finalfunc = percentile_disc_final,
finalfunc_extra,
hypotetical
)
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_AGGREGATES.split('\n\n')))
def test_create_aggregates(sql):
roundtrip(sql)
CREATE_CASTS = """\
CREATE CAST (bigint AS int4) WITH FUNCTION int4(bigint) AS ASSIGNMENT
CREATE CAST (varchar AS citext) WITHOUT FUNCTION AS ASSIGNMENT
CREATE CAST (citext AS varchar) WITHOUT FUNCTION AS IMPLICIT
CREATE CAST (text AS casttesttype) WITHOUT FUNCTION
CREATE CAST (text AS casttesttype) WITHOUT FUNCTION AS IMPLICIT
CREATE CAST (int4 AS casttesttype) WITH INOUT
CREATE CAST (int4 AS casttesttype) WITH FUNCTION int4_casttesttype(int4) AS IMPLICIT
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_CASTS.split('\n\n')))
def test_create_casts(sql):
roundtrip(sql)
CREATE_COLLATIONS = """\
CREATE COLLATION french (locale = 'fr_FR.utf8')
CREATE COLLATION IF NOT EXISTS french (locale = 'fr_FR.utf8')
CREATE COLLATION german_phonebook (provider = icu, locale = 'de-u-co-phonebk')
CREATE COLLATION german FROM "de_DE"
CREATE COLLATION IF NOT EXISTS german FROM "de_DE"
CREATE COLLATION mycoll2 ( LC_COLLATE = "POSIX", LC_CTYPE = "POSIX" )
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_COLLATIONS.split('\n\n')))
def test_create_collations(sql):
roundtrip(sql)
CREATE_CONVERSIONS = """\
CREATE CONVERSION myconv FOR 'UTF8' TO 'LATIN1' FROM myfunc
CREATE DEFAULT CONVERSION myconv FOR 'UTF8' TO 'LATIN1' FROM myfunc
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_CONVERSIONS.split('\n\n')))
def test_create_conversions(sql):
roundtrip(sql)
CREATE_DATABASES = """\
CREATE DATABASE sales OWNER salesapp TABLESPACE salesspace
CREATE DATABASE music LC_COLLATE 'sv_SE.utf8' LC_CTYPE 'sv_SE.utf8' TEMPLATE template0
CREATE DATABASE music2
LC_COLLATE 'sv_SE.iso885915' LC_CTYPE 'sv_SE.iso885915'
ENCODING LATIN9
TEMPLATE template0
ALTER DATABASE db1 ALLOW_CONNECTIONS true
ALTER DATABASE db1 CONNECTION LIMIT 10
ALTER DATABASE db1 SET work_mem = '2GB'
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_DATABASES.split('\n\n')))
def test_create_databases(sql):
roundtrip(sql)
CREATE_FOREIGN_DATA_WRAPPERS = """\
CREATE FOREIGN DATA WRAPPER dummy
CREATE FOREIGN DATA WRAPPER file HANDLER file_fdw_handler
CREATE FOREIGN DATA WRAPPER mywrapper OPTIONS (debug 'true')
"""
@pytest.mark.parametrize('sql', (sql.strip()
for sql in CREATE_FOREIGN_DATA_WRAPPERS.split('\n\n')))
def test_create_foreign_data_wrappers(sql):
roundtrip(sql)
CREATE_INDEXES = """\
create index aidx on atbl (value)
create index aidx on atbl using gin (value)
create unique index if not exists aidx on atbl (value)
create index aidx on atbl (value) where value is not null
create index aidx on atbl (value1 asc nulls first, value2 desc nulls last)
create index concurrently aidx on atbl using gin (value)
with (fastupdate = ON, gin_pending_list_limit = 100)
create index aidx on atbl (value) tablespace foo
create index aidx on atbl (value collate "it_IT")
CREATE INDEX test_index ON test_table (col varchar_pattern_ops)
CREATE INDEX aidx ON atbl USING gin(value public.trgm_pattern_ops)
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_INDEXES.split('\n\n')))
def test_create_indexes(sql):
roundtrip(sql)
CREATE_OPERATORS = """\
CREATE OPERATOR "MySchema".+ (
LEFTARG = box,
RIGHTARG = box,
PROCEDURE = area_sum_procedure
)
CREATE OPERATOR === (
LEFTARG = box,
RIGHTARG = box,
PROCEDURE = area_equal_procedure,
COMMUTATOR = ===,
NEGATOR = !==,
RESTRICT = area_restriction_procedure,
JOIN = area_join_procedure,
HASHES, MERGES
)
CREATE OPERATOR === (
LEFTARG = box,
RIGHTARG = box,
PROCEDURE = area_equal_procedure,
COMMUTATOR = OPERATOR("MySchema".===),
NEGATOR = !==,
RESTRICT = area_restriction_procedure,
JOIN = area_join_procedure,
HASHES, MERGES
)
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_OPERATORS.split('\n\n')))
def test_create_operators(sql):
roundtrip(sql)
CREATE_POLICIES = """
CREATE POLICY test_policy ON some_table AS PERMISSIVE
FOR ALL
TO some_role
USING ( current_user = c1 )
WITH CHECK ( current_user = c2)
CREATE POLICY test_policy ON some_table AS RESTRICTIVE
FOR UPDATE
TO CURRENT_USER
USING ( current_user = c1 )
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_POLICIES.split('\n\n')))
def test_create_policies(sql):
roundtrip(sql)
CREATE_SEQUENCES = """\
CREATE SEQUENCE serial START 101
CREATE TEMP SEQUENCE serial
CREATE TEMP SEQUENCE serial NO CYCLE
CREATE SEQUENCE IF NOT EXISTS "SomeSchema"."SomeSerial" as smallint
CREATE TEMP SEQUENCE serial INCREMENT 2 MINVALUE 5 NO MAXVALUE
CREATE TEMP SEQUENCE serial INCREMENT 2 MINVALUE 5 MAXVALUE 15 START WITH 7 CYCLE
CREATE SEQUENCE serial OWNED BY "SomeSchema"."SomeTable"."SomeColumn"
ALTER SEQUENCE serial MINVALUE 2
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_SEQUENCES.split('\n\n')))
def test_create_sequences(sql):
roundtrip(sql)
CREATE_SCHEMAS = """\
create schema myschema
create schema authorization joe
create schema if not exists test authorization joe
create schema test authorization public
create schema test authorization current_user
create schema test authorization session_user
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_SCHEMAS.split('\n\n')))
def test_create_schemas(sql):
roundtrip(sql)
CREATE_TABLES = """\
create table a (id serial primary key, value integer)
create table a (id serial, value integer null unique)
create table a (id serial, value integer not null)
create table a (id serial, value integer not null default 1)
create table if not exists a (id serial)
create temporary table if not exists a (id serial)
create temporary table a (id serial) on commit drop
create temporary table a (id serial) on commit delete rows
create temporary table a (id serial) on commit preserve rows
create temporary table a (id serial) inherits ("BaseTable") on commit preserve rows
create unlogged table if not exists a (id serial)
create table a (value integer) inherits (b, c)
create table a (name text not null check (position('@' in name) = 0))
create table a (value integer not null check (value < 10) no inherit)
create table "Someschema"."Sometable" (a integer primary key)
create table a (id serial primary key, value integer) with oids
create table a (id serial primary key, value integer) without oids
create table a (
id serial primary key,
v integer references b(id) on delete cascade on update cascade
)
create table a (
id serial primary key,
v integer references b(id) on delete set default on update restrict
)
create table a (
id serial primary key,
v integer references b(id) on delete restrict on update set default
)
create table a (
id serial primary key,
v integer references b(id) on delete restrict on update set null
)
CREATE TABLE a(t text collate "C")
CREATE TABLE ages (
id integer primary key,
age1 interval year,
age2 interval month,
age3 interval day,
age4 interval hour,
age5 interval minute,
age6a interval second,
age6b interval second (5),
age7 interval year to month,
age8 interval day to hour,
age9 interval day to minute,
age10a interval day to second,
age10b interval day to second (5),
age11 interval hour to minute,
age11 interval hour to second,
age11a interval minute to second,
age11b interval minute to second (5)
)
CREATE TABLE films (
code char(5) CONSTRAINT firstkey PRIMARY KEY,
title varchar(40) NOT NULL,
did integer NOT NULL,
date_prod date,
kind varchar(10),
len interval hour to minute
)
CREATE TABLE distributors (
did integer PRIMARY KEY DEFAULT nextval('serial'),
name varchar(40) NOT NULL CHECK (name <> '')
)
CREATE TABLE array_int (
vector int[][]
)
CREATE TABLE films (
code char(5),
title varchar(40),
did integer,
date_prod date,
kind varchar(10),
len interval hour to minute,
CONSTRAINT production UNIQUE(date_prod)
)
CREATE TABLE distributors (
did integer,
name varchar(40)
CONSTRAINT con1 CHECK (did > 100 AND name <> '')
)
CREATE TABLE films (
code char(5),
title varchar(40),
did integer,
date_prod date,
kind varchar(10),
len interval hour to second(3),
CONSTRAINT code_title PRIMARY KEY(code,title)
)
CREATE TABLE distributors (
did integer,
name varchar(40),
UNIQUE(name) USING INDEX TABLESPACE indexes
)
CREATE TABLE distributors (
did integer,
name varchar(40),
UNIQUE(name) WITH (fillfactor=70) USING INDEX TABLESPACE indexes
)
WITH (fillfactor=70)
CREATE TABLE distributors (
did integer,
name varchar(40)
) INHERITS ("BaseTable") WITH (fillfactor=70)
CREATE TABLE circles (
c circle,
EXCLUDE USING gist (c WITH &&)
)
CREATE TABLE contracts (
id id_t NOT NULL,
company_id id_t NOT NULL,
company_contract_kind_id id_t NULL
REFERENCES company_contract_kinds (id) ON DELETE SET NULL ON UPDATE CASCADE,
validity period_t NOT NULL,
PRIMARY KEY (id),
EXCLUDE USING gist (cast(company_id AS text) WITH =, validity WITH &&)
)
CREATE TABLE contracts (
company_id id_t NOT NULL,
validity period_t NOT NULL,
EXCLUDE USING gist ((company_id::text) WITH =, validity WITH &&)
)
CREATE TABLE cities (
id id_t NOT NULL,
name text NOT NULL,
region_id id_t NOT NULL,
country_id id_t NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (region_id, country_id) REFERENCES regions (id, country_id) MATCH FULL
)
CREATE TABLE cities (
id id_t NOT NULL,
name text NOT NULL,
region_id id_t NOT NULL,
country_id id_t NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (region_id, country_id)
REFERENCES regions (id, country_id) MATCH SIMPLE ON DELETE RESTRICT ON UPDATE CASCADE
DEFERRABLE INITIALLY DEFERRED
)
CREATE TABLE test (
id int NOT NULL REFERENCES t2 DEFERRABLE INITIALLY DEFERRED
)
CREATE TABLE cinemas (
id serial,
name text,
location text
) TABLESPACE diskvol1
CREATE TABLE employees OF employee_type (
PRIMARY KEY (name),
salary WITH OPTIONS DEFAULT 1000
)
CREATE TABLE measurement (
logdate date not null,
peaktemp int,
unitsales int
) PARTITION BY RANGE (logdate)
CREATE TABLE measurement_year_month (
logdate date not null,
peaktemp int,
unitsales int
) PARTITION BY RANGE (EXTRACT(YEAR FROM logdate), EXTRACT(MONTH FROM logdate))
CREATE TABLE cities (
city_id bigserial not null,
name text not null,
population bigint
) PARTITION BY LIST (left(lower(name), 1))
CREATE TABLE measurement_y2016m07
PARTITION OF measurement (
unitsales DEFAULT 0
) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01')
CREATE TABLE measurement_y2016m07
PARTITION OF measurement (
unitsales DEFAULT 0
) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01')
CREATE TABLE measurement_y2016m07
PARTITION OF measurement (
unitsales DEFAULT 0
) FOR VALUES FROM ('2016-07-01') TO ('2016-08-01')
CREATE TABLE measurement_ym_older
PARTITION OF measurement_year_month
FOR VALUES FROM (MINVALUE, MINVALUE) TO (2016, MAXVALUE)
CREATE TABLE cities_ab
PARTITION OF cities (
CONSTRAINT city_id_nonzero CHECK (city_id != 0)
) FOR VALUES IN ('a', 'b')
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_TABLES.split('\n\n')))
def test_create_tables(sql):
roundtrip(sql)
CREATE_TABLES_AS = """\
CREATE TABLE films2 AS TABLE films
CREATE TABLE films2 AS TABLE films WITH NO DATA
CREATE TABLE films2 WITH OIDS AS TABLE films
CREATE TABLE films2 WITHOUT OIDS AS TABLE films
CREATE TABLE films2 AS VALUES (1,2)
CREATE TEMPORARY TABLE films2 AS VALUES (1,2)
CREATE TABLE films2 WITH (fillfactor=70) ON COMMIT PRESERVE ROWS AS VALUES (1,2)
CREATE TABLE films2 ON COMMIT DELETE ROWS TABLESPACE "Foo" AS TABLE films
CREATE TABLE films2 ON COMMIT DROP AS TABLE films
CREATE UNLOGGED TABLE IF NOT EXISTS "SomeSchema".films2 (id, title) AS
SELECT id, title FROM films
CREATE TABLE films_recent AS
SELECT * FROM films WHERE date_prod >= '2002-01-01'
CREATE TABLE test AS SELECT * FROM t1 LIMIT 1;
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in CREATE_TABLES_AS.split('\n\n')))
def test_create_tables_as(sql):
roundtrip(sql)
DROPS = """\
drop access method some_name cascade
DROP AGGREGATE myrank(VARIADIC "any" ORDER BY VARIADIC "any")
DROP AGGREGATE myavg(integer), myavg(bigint)
DROP CAST (text AS int)
DROP COLLATION german
DROP CONVERSION myname
drop database if exists mydb
DROP DOMAIN "NameSpace"."Domain"
DROP EVENT TRIGGER snitch
DROP EXTENSION hstore
DROP FOREIGN DATA WRAPPER dbi
DROP FOREIGN TABLE films, distributors
drop function slower_one(int, int)
drop function if exists "Mine".generic_function
DROP INDEX title_idx
DROP INDEX CONCURRENTLY title_idx
DROP LANGUAGE plsample
DROP MATERIALIZED VIEW order_summary
DROP OPERATOR ^ (integer, integer)
DROP OPERATOR ~ (none, bit), ! (bigint, none)
DROP OPERATOR CLASS widget_ops USING btree
DROP OPERATOR FAMILY "My".float_ops USING btree
drop owned by "White"
drop owned by current_user cascade
DROP POLICY p1 ON my_table
DROP PUBLICATION mypublication
DROP ROLE myrole
DROP RULE newrule ON mytable
DROP SEQUENCE serial
DROP SCHEMA a,"B" CASCADE
DROP SERVER IF EXISTS foo CASCADE
DROP STATISTICS IF EXISTS
accounting.users_uid_creation,
public.grants_user_role
DROP SUBSCRIPTION mysub
DROP SUBSCRIPTION IF EXISTS mysub CASCADE
drop table foo.bar
DROP TABLESPACE IF EXISTS mystuff
DROP TEXT SEARCH CONFIGURATION my_english
DROP TEXT SEARCH CONFIGURATION IF EXISTS my_english CASCADE
DROP TEXT SEARCH DICTIONARY english
DROP TEXT SEARCH DICTIONARY IF EXISTS english CASCADE
DROP TEXT SEARCH TEMPLATE thesaurus
DROP TEXT SEARCH TEMPLATE IF EXISTS "Thesaurus" CASCADE
DROP TRANSFORM FOR hstore LANGUAGE plpythonu
DROP TRIGGER "If_dist_exists" ON "Films"
DROP TRIGGER trig1 ON public."Films"
DROP USER IF EXISTS barry, "White"
DROP USER MAPPING IF EXISTS FOR bob SERVER foo
DROP USER MAPPING FOR user SERVER "Foo"
DROP USER MAPPING FOR current_user SERVER foo
DROP TYPE "Foo", bar RESTRICT
DROP VIEW x.y
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in DROPS.split('\n\n')))
def test_drops(sql):
roundtrip(sql)
FUNCS = r"""
CREATE OR REPLACE FUNCTION funca(somearg text, someotherarg text) RETURNS void
AS $$
BEGIN
PERFORM $function$<some_string_literal>$function$;
RETURN;
END;
$$ language plpgsql IMMUTABLE PARALLEL SAFE STRICT
CREATE FUNCTION funcb(somearg text) RETURNS TABLE(c1 int, c2 text)
AS $$
SELECT 1, 'Label 1'
$$ language sql SECURITY INVOKER
CREATE FUNCTION funcb() RETURNS TABLE(c1 int, c2 text)
AS $$
SELECT 1, 'Label 1'
$$ language sql SECURITY DEFINER
CREATE FUNCTION func_in_c(arg text) RETURNS text AS 'function_name', 'lib.so'
LANGUAGE C
CREATE FUNCTION funcc(arg text = 'default_val', OUT arg2 text, INOUT arg3 text, VARIADIC
arglist text[]) RETURNS SETOF integer AS $$
$$ language sql
ALTER FUNCTION funca(somearg text) COST 100
ALTER FUNCTION func_without_args() IMMUTABLE
ALTER FUNCTION func() SET search_path TO public,schema2
DO $$
some_code
$$ language somelanguage
"""
@pytest.mark.parametrize('sql', (sql.strip() for sql in FUNCS.split('\n\n')))
def test_functions(sql):
roundtrip(sql)
GRANTS = """
GRANT SELECT ON ALL TABLES IN SCHEMA public TO role1, role2
GRANT EXECUTE ON FUNCTION func1() TO role1