-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathignore_integration_test.go
More file actions
1363 lines (1168 loc) · 38.6 KB
/
ignore_integration_test.go
File metadata and controls
1363 lines (1168 loc) · 38.6 KB
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 cmd
// Ignore Integration Tests
// These comprehensive integration tests verify the .pgschemaignore functionality
// across dump, plan, and apply commands by testing the complete workflow with
// various database object types and ignore patterns including wildcards and negation.
import (
"database/sql"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/pgplex/pgschema/cmd/apply"
"github.com/pgplex/pgschema/cmd/dump"
planCmd "github.com/pgplex/pgschema/cmd/plan"
"github.com/pgplex/pgschema/testutil"
"github.com/spf13/cobra"
)
// Note: This file shares the TestMain and sharedEmbeddedPG from migrate_integration_test.go
// since they're in the same package (cmd)
func TestIgnoreIntegration(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
// Setup PostgreSQL container
embeddedPG := testutil.SetupPostgres(t)
defer embeddedPG.Stop()
conn, host, port, dbname, user, password := testutil.ConnectToPostgres(t, embeddedPG)
defer conn.Close()
// Create containerInfo struct to match old API for minimal changes
containerInfo := &struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}{
Conn: conn,
Host: host,
Port: port,
DBName: dbname,
User: user,
Password: password,
}
// Create the test schema with various object types
createTestSchema(t, containerInfo.Conn)
// Save current working directory and restore it at the end
originalWd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current working directory: %v", err)
}
defer func() {
os.Chdir(originalWd)
}()
// Create a temporary directory for our tests
tmpDir := t.TempDir()
err = os.Chdir(tmpDir)
if err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
// Run sub-tests in isolated environments
t.Run("dump", func(t *testing.T) {
testIgnoreDump(t, containerInfo)
})
t.Run("plan", func(t *testing.T) {
testIgnorePlan(t, containerInfo)
})
t.Run("dependencies_on_ignored_tables", func(t *testing.T) {
testDependenciesOnIgnoredTables(t, containerInfo)
})
t.Run("apply", func(t *testing.T) {
// Create a fresh container for apply test to avoid fingerprint conflicts
applyEmbeddedPG := testutil.SetupPostgres(t)
defer applyEmbeddedPG.Stop()
applyConn, applyHost, applyPort, applyDbname, applyUser, applyPassword := testutil.ConnectToPostgres(t, applyEmbeddedPG)
defer applyConn.Close()
// Create applyContainerInfo struct to match old API
applyContainerInfo := &struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}{
Conn: applyConn,
Host: applyHost,
Port: applyPort,
DBName: applyDbname,
User: applyUser,
Password: applyPassword,
}
// Create the test schema in the fresh container
createTestSchema(t, applyContainerInfo.Conn)
testIgnoreApply(t, applyContainerInfo)
})
}
// createTestSchema creates all test objects in the database
func createTestSchema(t *testing.T, conn *sql.DB) {
testSQL := `
-- Create user status enum type
CREATE TYPE user_status AS ENUM ('active', 'inactive', 'suspended');
-- Create test enum type (to be ignored)
CREATE TYPE type_test_enum AS ENUM ('test1', 'test2');
-- Create regular tables
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
status user_status DEFAULT 'active'
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total_amount DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price DECIMAL(10,2) NOT NULL
);
-- Create temporary tables (to be ignored)
CREATE TABLE temp_backup (
id SERIAL PRIMARY KEY,
data TEXT,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE temp_cache (
key TEXT PRIMARY KEY,
value TEXT,
expires_at TIMESTAMP
);
CREATE TABLE temp_session (
session_id TEXT PRIMARY KEY,
user_id INTEGER,
created_at TIMESTAMP DEFAULT NOW()
);
-- Create test tables (to be ignored, except core)
CREATE TABLE test_data (
id SERIAL PRIMARY KEY,
test_value TEXT
);
CREATE TABLE test_results (
id SERIAL PRIMARY KEY,
result TEXT
);
-- Create test core table (NOT ignored due to negation pattern)
CREATE TABLE test_core_config (
id SERIAL PRIMARY KEY,
config_key TEXT NOT NULL,
config_value TEXT NOT NULL
);
-- Create regular sequences
CREATE SEQUENCE user_id_seq;
-- Create temp sequence (to be ignored)
CREATE SEQUENCE seq_temp_counter;
-- Create regular views
CREATE VIEW user_orders_view AS
SELECT u.name, u.email, o.total_amount, o.created_at
FROM users u
JOIN orders o ON u.id = o.user_id;
CREATE VIEW product_summary AS
SELECT COUNT(*) as total_products, AVG(price) as avg_price
FROM products;
-- Create debug views (to be ignored)
CREATE VIEW debug_performance AS
SELECT 'debug_data' as info;
CREATE VIEW debug_stats AS
SELECT 'debug_stats' as stats;
-- Create temp view (to be ignored)
CREATE VIEW orders_view_tmp AS
SELECT * FROM orders WHERE created_at > NOW() - INTERVAL '1 hour';
-- Create regular functions
CREATE OR REPLACE FUNCTION get_user_count() RETURNS INTEGER AS $$
BEGIN
RETURN (SELECT COUNT(*) FROM users);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION calculate_total(p_user_id INTEGER) RETURNS DECIMAL AS $$
BEGIN
RETURN (SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE user_id = p_user_id);
END;
$$ LANGUAGE plpgsql;
-- Create test functions (to be ignored)
CREATE OR REPLACE FUNCTION fn_test_helper() RETURNS TEXT AS $$
BEGIN
RETURN 'test helper';
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION fn_debug_log(p_message TEXT) RETURNS VOID AS $$
BEGIN
-- Debug function
RETURN;
END;
$$ LANGUAGE plpgsql;
-- Create regular procedure
CREATE OR REPLACE PROCEDURE process_orders()
LANGUAGE plpgsql
AS $$
BEGIN
-- Process orders logic
UPDATE orders SET total_amount = total_amount * 1.1 WHERE total_amount > 100;
END;
$$;
-- Create temp procedure (to be ignored)
CREATE OR REPLACE PROCEDURE sp_temp_cleanup()
LANGUAGE plpgsql
AS $$
BEGIN
DELETE FROM temp_cache WHERE expires_at < NOW();
END;
$$;
-- Create external table (to be ignored)
CREATE TABLE temp_external_users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
`
_, err := conn.Exec(testSQL)
if err != nil {
t.Fatalf("Failed to create test schema: %v", err)
}
}
// createIgnoreFile creates a .pgschemaignore file in the current directory
func createIgnoreFile(t *testing.T) func() {
ignoreContent := `[tables]
patterns = ["temp_*", "test_*", "!test_core_*"]
[views]
patterns = ["debug_*", "*_view_tmp"]
[functions]
patterns = ["fn_test_*", "fn_debug_*"]
[procedures]
patterns = ["sp_temp_*"]
[types]
patterns = ["type_test_*"]
[sequences]
patterns = ["seq_temp_*"]
`
err := os.WriteFile(".pgschemaignore", []byte(ignoreContent), 0644)
if err != nil {
t.Fatalf("Failed to create .pgschemaignore file: %v", err)
}
// Return cleanup function
return func() {
os.Remove(".pgschemaignore")
}
}
// testIgnoreDump tests the dump command with ignore functionality
func testIgnoreDump(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}) {
// Create .pgschemaignore file
cleanup := createIgnoreFile(t)
defer cleanup()
// Execute dump command
output := executeIgnoreDumpCommand(t, containerInfo)
// Verify output contains expected objects and excludes ignored ones
verifyDumpOutput(t, output)
}
// testDependenciesOnIgnoredTables tests that dependencies (FK, triggers, views) on ignored tables are preserved
// This consolidated test covers:
// - Triggers on ignored tables (issue #56)
// - Foreign keys to ignored tables (issue #167)
// - Views referencing ignored tables
// Tests both single-file and multi-file dump modes, plus plan command
func testDependenciesOnIgnoredTables(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}) {
// Create additional test objects (reuse existing temp_external_users, users, user_status from createTestSchema)
createSQL := `
-- External/ignored table for FK test (temp_* pattern)
CREATE TABLE temp_external_suppliers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
contact_email TEXT
);
-- Managed table with FK to ignored table
CREATE TABLE supplier_contracts (
id SERIAL PRIMARY KEY,
supplier_id INTEGER NOT NULL,
contract_value DECIMAL(10,2) NOT NULL,
CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES temp_external_suppliers(id)
);
-- Trigger function for syncing from ignored table (reuses existing temp_external_users and users)
CREATE OR REPLACE FUNCTION sync_external_user_profile()
RETURNS trigger AS $$
BEGIN
INSERT INTO users (name, email, status)
VALUES ('External User', NEW.email, 'active');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger on ignored external table (reuses temp_external_users from createTestSchema)
CREATE TRIGGER on_external_user_created
AFTER INSERT ON temp_external_users
FOR EACH ROW
EXECUTE FUNCTION sync_external_user_profile();
-- View that references ignored table
CREATE VIEW supplier_contract_summary AS
SELECT s.name, s.contact_email, c.contract_value
FROM temp_external_suppliers s
JOIN supplier_contracts c ON s.id = c.supplier_id;
`
_, err := containerInfo.Conn.Exec(createSQL)
if err != nil {
t.Fatalf("Failed to create test schema: %v", err)
}
// Clean up after test (don't drop shared objects from createTestSchema)
defer func() {
containerInfo.Conn.Exec("DROP VIEW IF EXISTS supplier_contract_summary CASCADE")
containerInfo.Conn.Exec("DROP TRIGGER IF EXISTS on_external_user_created ON temp_external_users CASCADE")
containerInfo.Conn.Exec("DROP FUNCTION IF EXISTS sync_external_user_profile() CASCADE")
containerInfo.Conn.Exec("DROP TABLE IF EXISTS supplier_contracts CASCADE")
containerInfo.Conn.Exec("DROP TABLE IF EXISTS temp_external_suppliers CASCADE")
}()
// Create .pgschemaignore file
cleanup := createIgnoreFile(t)
defer cleanup()
// Test 1: Single-file dump
t.Run("single_file_dump", func(t *testing.T) {
output := executeIgnoreDumpCommand(t, containerInfo)
// Verify ignored tables are NOT in dump
if strings.Contains(output, "CREATE TABLE IF NOT EXISTS temp_external_suppliers") {
t.Error("Dump should not include ignored table temp_external_suppliers")
}
if strings.Contains(output, "CREATE TABLE IF NOT EXISTS temp_external_users") {
t.Error("Dump should not include ignored table temp_external_users")
}
// Verify FK constraint to ignored table IS preserved
if !strings.Contains(output, "fk_supplier") {
t.Error("Dump should include FK constraint fk_supplier")
}
if !strings.Contains(output, "temp_external_suppliers") {
t.Error("FK constraint should reference temp_external_suppliers")
}
// Verify trigger on ignored table IS preserved
if !strings.Contains(output, "on_external_user_created") {
t.Error("Dump should include trigger on_external_user_created")
}
// Verify view referencing ignored table IS preserved
if !strings.Contains(output, "supplier_contract_summary") {
t.Error("Dump should include view supplier_contract_summary")
}
})
// Test 2: Multi-file dump (issue #167 bug was here)
t.Run("multi_file_dump", func(t *testing.T) {
tmpDir := t.TempDir()
outputFile := filepath.Join(tmpDir, "schema.sql")
config := &dump.DumpConfig{
Host: containerInfo.Host,
Port: containerInfo.Port,
DB: containerInfo.DBName,
User: containerInfo.User,
Password: containerInfo.Password,
Schema: "public",
MultiFile: true,
File: outputFile,
}
_, err := dump.ExecuteDump(config)
if err != nil {
t.Fatalf("Failed to execute multi-file dump: %v", err)
}
// Read supplier_contracts table file (should have FK)
tablesDir := filepath.Join(tmpDir, "tables")
contractsFile := filepath.Join(tablesDir, "supplier_contracts.sql")
contractsContent, err := os.ReadFile(contractsFile)
if err != nil {
t.Fatalf("Failed to read supplier_contracts.sql: %v", err)
}
contractsOutput := string(contractsContent)
// Verify FK constraint is in the table file
if !strings.Contains(contractsOutput, "fk_supplier") {
t.Error("Multi-file dump should include FK constraint fk_supplier in supplier_contracts.sql")
}
if !strings.Contains(contractsOutput, "temp_external_suppliers") {
t.Error("FK constraint should reference temp_external_suppliers in multi-file dump")
}
// Verify view file exists and references ignored table
viewsDir := filepath.Join(tmpDir, "views")
viewFile := filepath.Join(viewsDir, "supplier_contract_summary.sql")
viewContent, err := os.ReadFile(viewFile)
if err != nil {
t.Fatalf("Failed to read supplier_contract_summary.sql: %v", err)
}
if !strings.Contains(string(viewContent), "temp_external_suppliers") {
t.Error("View should reference temp_external_suppliers in multi-file dump")
}
})
// Test 3: Plan command
t.Run("plan", func(t *testing.T) {
// The dump and multi-file tests already verify that dependencies are preserved in output.
// Plan test verifies that when given a desired state schema file with dependencies on
// ignored tables, the plan doesn't try to DROP or CREATE those ignored tables.
// Create schema file with modified version (add a column) to generate a plan
schemaWithDeps := `
-- Reuse existing objects but with a modification to generate a diff
CREATE TYPE user_status AS ENUM ('active', 'inactive', 'suspended');
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
status user_status DEFAULT 'active'
);
-- External tables (ignored)
CREATE TABLE temp_external_suppliers (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
contact_email TEXT
);
CREATE TABLE temp_external_users (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
email TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
-- Modified table with FK to ignored table (add new column to generate diff)
CREATE TABLE supplier_contracts (
id SERIAL PRIMARY KEY,
supplier_id INTEGER NOT NULL,
contract_value DECIMAL(10,2) NOT NULL,
notes TEXT, -- NEW COLUMN
CONSTRAINT fk_supplier FOREIGN KEY (supplier_id) REFERENCES temp_external_suppliers(id)
);
-- Trigger function
CREATE OR REPLACE FUNCTION sync_external_user_profile()
RETURNS trigger AS $$
BEGIN
INSERT INTO users (name, email, status)
VALUES ('External User', NEW.email, 'active');
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- Trigger on ignored table
CREATE TRIGGER on_external_user_created
AFTER INSERT ON temp_external_users
FOR EACH ROW
EXECUTE FUNCTION sync_external_user_profile();
-- View referencing ignored table
CREATE VIEW supplier_contract_summary AS
SELECT s.name, s.contact_email, c.contract_value
FROM temp_external_suppliers s
JOIN supplier_contracts c ON s.id = c.supplier_id;
`
schemaFile := "schema_with_deps.sql"
err := os.WriteFile(schemaFile, []byte(schemaWithDeps), 0644)
if err != nil {
t.Fatalf("Failed to create schema file: %v", err)
}
defer os.Remove(schemaFile)
output := executeIgnorePlanCommand(t, containerInfo, schemaFile)
// Verify ignored tables are NOT in plan (no CREATE/DROP for them)
if strings.Contains(output, "CREATE TABLE IF NOT EXISTS temp_external_suppliers") ||
strings.Contains(output, "DROP TABLE IF EXISTS temp_external_suppliers") {
t.Error("Plan should not create or drop ignored table temp_external_suppliers")
}
if strings.Contains(output, "CREATE TABLE IF NOT EXISTS temp_external_users") ||
strings.Contains(output, "DROP TABLE IF EXISTS temp_external_users") {
t.Error("Plan should not create or drop ignored table temp_external_users")
}
// Verify the plan includes operations on managed objects that reference ignored tables
// (The FK, trigger, and view should all be present in the desired state and not cause errors)
if !strings.Contains(output, "supplier_contracts") {
t.Error("Plan should include operations on supplier_contracts (table with FK to ignored table)")
}
})
}
// testIgnorePlan tests the plan command with ignore functionality
func testIgnorePlan(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}) {
// Create .pgschemaignore file
cleanup := createIgnoreFile(t)
defer cleanup()
// Create a modified schema file with changes to both regular and ignored objects
modifiedSchema := `
-- User status enum type (needed for users table)
CREATE TYPE user_status AS ENUM ('active', 'inactive', 'suspended');
-- Modified regular table (should appear in plan)
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
status user_status DEFAULT 'active',
phone TEXT -- NEW COLUMN
);
-- Modified ignored table (should NOT appear in plan)
CREATE TABLE temp_backup (
id SERIAL PRIMARY KEY,
data TEXT,
created_at TIMESTAMP DEFAULT NOW(),
backup_type TEXT -- NEW COLUMN - should be ignored
);
-- Keep test_core_config (should appear due to negation)
CREATE TABLE test_core_config (
id SERIAL PRIMARY KEY,
config_key TEXT NOT NULL,
config_value TEXT NOT NULL,
updated_at TIMESTAMP DEFAULT NOW() -- NEW COLUMN
);
`
schemaFile := "modified_schema.sql"
err := os.WriteFile(schemaFile, []byte(modifiedSchema), 0644)
if err != nil {
t.Fatalf("Failed to create modified schema file: %v", err)
}
defer os.Remove(schemaFile)
// Execute plan command
output := executeIgnorePlanCommand(t, containerInfo, schemaFile)
// Verify plan output excludes ignored objects
verifyPlanOutput(t, output)
}
// testIgnoreApply tests the apply command with ignore functionality
// This test verifies that ignored objects are excluded from fingerprint calculation
func testIgnoreApply(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}) {
// Create .pgschemaignore file
cleanup := createIgnoreFile(t)
defer cleanup()
// Verify that ignored objects exist before apply
verifyIgnoredObjectsExist(t, containerInfo.Conn, "before apply")
// Create a schema file with ONLY regular (non-ignored) objects
// This schema does NOT include ignored objects like sp_temp_cleanup, temp_*, fn_test_*, etc.
regularObjectsSchema := `
-- Regular enum type (not ignored)
CREATE TYPE user_status AS ENUM ('active', 'inactive', 'suspended');
-- Regular tables (not ignored)
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
status user_status DEFAULT 'active'
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total_amount DECIMAL(10,2) NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
CREATE TABLE products (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
price DECIMAL(10,2) NOT NULL
);
-- Keep test_core_config (not ignored due to negation pattern !test_core_*)
CREATE TABLE test_core_config (
id SERIAL PRIMARY KEY,
config_key TEXT NOT NULL,
config_value TEXT NOT NULL
);
-- Regular sequence (not ignored)
CREATE SEQUENCE IF NOT EXISTS user_id_seq;
-- Regular views (not ignored)
CREATE VIEW user_orders_view AS
SELECT u.name, u.email, o.total_amount, o.created_at
FROM users u
JOIN orders o ON u.id = o.user_id;
CREATE VIEW product_summary AS
SELECT COUNT(*) as total_products, AVG(price) as avg_price
FROM products;
-- Regular functions (not ignored)
CREATE OR REPLACE FUNCTION get_user_count() RETURNS INTEGER AS $$
BEGIN
RETURN (SELECT COUNT(*) FROM users);
END;
$$ LANGUAGE plpgsql;
CREATE OR REPLACE FUNCTION calculate_total(p_user_id INTEGER) RETURNS DECIMAL AS $$
BEGIN
RETURN (SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE user_id = p_user_id);
END;
$$ LANGUAGE plpgsql;
-- Regular procedure (not ignored)
CREATE OR REPLACE PROCEDURE process_orders()
LANGUAGE plpgsql
AS $$
BEGIN
-- Process orders logic
UPDATE orders SET total_amount = total_amount * 1.1 WHERE total_amount > 100;
END;
$$;
`
schemaFile := "regular_objects_schema.sql"
err := os.WriteFile(schemaFile, []byte(regularObjectsSchema), 0644)
if err != nil {
t.Fatalf("Failed to create schema file: %v", err)
}
defer os.Remove(schemaFile)
// Execute apply command - should succeed because ignored objects are excluded from fingerprint
err = executeIgnoreApplyCommandWithError(containerInfo, schemaFile)
if err != nil {
t.Fatalf("Apply command should succeed when ignored objects are excluded from fingerprint, but got error: %v", err)
}
// Verify that ignored objects still exist after apply (they should remain untouched)
verifyIgnoredObjectsExist(t, containerInfo.Conn, "after apply")
// Verify that the ignored procedure sp_temp_cleanup still exists
verifyIgnoredProcedureExists(t, containerInfo.Conn, "after apply")
}
// executeIgnoreDumpCommand runs the dump command and returns the output
func executeIgnoreDumpCommand(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}) string {
// Create a new root command with dump as subcommand
rootCmd := &cobra.Command{
Use: "pgschema",
}
rootCmd.AddCommand(dump.DumpCmd)
// Capture stdout
oldStdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
var output string
done := make(chan bool)
go func() {
defer close(done)
buf := make([]byte, 1024*1024) // 1MB buffer
n, _ := r.Read(buf)
output = string(buf[:n])
}()
// Set command arguments
args := []string{
"dump",
"--host", containerInfo.Host,
"--port", fmt.Sprintf("%d", containerInfo.Port),
"--db", containerInfo.DBName,
"--user", containerInfo.User,
"--password", containerInfo.Password,
"--schema", "public",
}
rootCmd.SetArgs(args)
// Execute the command
err := rootCmd.Execute()
w.Close()
os.Stdout = oldStdout
<-done
if err != nil {
t.Fatalf("Failed to execute dump command: %v", err)
}
return output
}
// executeIgnorePlanCommand runs the plan command and returns the output
func executeIgnorePlanCommand(t *testing.T, containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}, schemaFile string) string {
// Create plan configuration with shared embedded postgres for performance
config := &planCmd.PlanConfig{
Host: containerInfo.Host,
Port: containerInfo.Port,
DB: containerInfo.DBName,
User: containerInfo.User,
Password: containerInfo.Password,
Schema: "public",
File: schemaFile,
ApplicationName: "pgschema",
}
// Generate the plan (reuse shared embedded postgres from migrate_integration_test.go)
migrationPlan, err := planCmd.GeneratePlan(config, sharedEmbeddedPG)
if err != nil {
t.Fatalf("Failed to execute plan command: %v", err)
}
// Return human-readable output (no color, like stdout)
return migrationPlan.HumanColored(false)
}
// executeIgnoreApplyCommandWithError runs the apply command and returns any error
func executeIgnoreApplyCommandWithError(containerInfo *struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}, schemaFile string) error {
rootCmd := &cobra.Command{
Use: "pgschema",
}
rootCmd.AddCommand(apply.ApplyCmd)
args := []string{
"apply",
"--host", containerInfo.Host,
"--port", fmt.Sprintf("%d", containerInfo.Port),
"--db", containerInfo.DBName,
"--user", containerInfo.User,
"--password", containerInfo.Password,
"--schema", "public",
"--file", schemaFile,
"--auto-approve",
}
rootCmd.SetArgs(args)
return rootCmd.Execute()
}
// verifyIgnoredObjectsExist checks that ignored objects still exist in the database
func verifyIgnoredObjectsExist(t *testing.T, conn *sql.DB, phase string) {
// Check that temp_backup table still exists (should be ignored)
var tempTableExists bool
err := conn.QueryRow(`
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'temp_backup'
AND table_schema = 'public'
)
`).Scan(&tempTableExists)
if err != nil {
t.Fatalf("Failed to check temp_backup table existence %s: %v", phase, err)
}
if !tempTableExists {
t.Errorf("temp_backup table should exist %s (ignored tables should remain unchanged)", phase)
}
// Check that test_data table still exists (should be ignored)
var testTableExists bool
err = conn.QueryRow(`
SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_name = 'test_data'
AND table_schema = 'public'
)
`).Scan(&testTableExists)
if err != nil {
t.Fatalf("Failed to check test_data table existence %s: %v", phase, err)
}
if !testTableExists {
t.Errorf("test_data table should exist %s (ignored tables should remain unchanged)", phase)
}
}
// verifyIgnoredProcedureExists checks that the ignored procedure sp_temp_cleanup still exists
func verifyIgnoredProcedureExists(t *testing.T, conn *sql.DB, phase string) {
var procedureExists bool
err := conn.QueryRow(`
SELECT EXISTS (
SELECT 1 FROM information_schema.routines
WHERE routine_name = 'sp_temp_cleanup'
AND routine_schema = 'public'
AND routine_type = 'PROCEDURE'
)
`).Scan(&procedureExists)
if err != nil {
t.Fatalf("Failed to check sp_temp_cleanup procedure existence %s: %v", phase, err)
}
if !procedureExists {
t.Errorf("sp_temp_cleanup procedure should exist %s (ignored procedures should remain unchanged)", phase)
}
}
// verifyDumpOutput checks that dump output contains expected objects and excludes ignored ones
func verifyDumpOutput(t *testing.T, output string) {
// Objects that should be present (not ignored)
expectedPresent := []string{
"CREATE TABLE IF NOT EXISTS users",
"CREATE TABLE IF NOT EXISTS orders",
"CREATE TABLE IF NOT EXISTS products",
"CREATE TABLE IF NOT EXISTS test_core_config", // Not ignored due to negation
"CREATE OR REPLACE VIEW user_orders_view",
"CREATE OR REPLACE VIEW product_summary",
"CREATE OR REPLACE FUNCTION get_user_count",
"CREATE OR REPLACE FUNCTION calculate_total",
"CREATE OR REPLACE PROCEDURE process_orders",
"CREATE TYPE user_status",
"CREATE SEQUENCE IF NOT EXISTS user_id_seq",
}
// Objects that should be absent (ignored)
expectedAbsent := []string{
"temp_backup",
"temp_cache",
"temp_session",
"test_data",
"test_results",
"debug_performance",
"debug_stats",
"orders_view_tmp",
"fn_test_helper",
"fn_debug_log",
"sp_temp_cleanup",
"type_test_enum",
"seq_temp_counter",
}
// Check for expected present objects
for _, expected := range expectedPresent {
if !strings.Contains(output, expected) {
t.Errorf("Expected object not found in dump output: %s", expected)
}
}
// Check for expected absent objects
for _, unexpected := range expectedAbsent {
if strings.Contains(output, unexpected) {
t.Errorf("Ignored object found in dump output (should be excluded): %s", unexpected)
}
}
}
func TestIgnorePrivileges(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test in short mode")
}
embeddedPG := testutil.SetupPostgres(t)
defer embeddedPG.Stop()
conn, host, port, dbname, user, password := testutil.ConnectToPostgres(t, embeddedPG)
defer conn.Close()
containerInfo := &struct {
Conn *sql.DB
Host string
Port int
DBName string
User string
Password string
}{
Conn: conn,
Host: host,
Port: port,
DBName: dbname,
User: user,
Password: password,
}
// Create schema with roles and privileges
setupSQL := `
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL
);
CREATE TABLE orders (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id),
total_amount DECIMAL(10,2) NOT NULL
);
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app_reader') THEN
CREATE ROLE app_reader;
END IF;
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'deploy_bot') THEN
CREATE ROLE deploy_bot;