-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathfunction.go
More file actions
599 lines (527 loc) · 19 KB
/
function.go
File metadata and controls
599 lines (527 loc) · 19 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
package diff
import (
"fmt"
"strings"
"github.com/pgplex/pgschema/ir"
)
// generateCreateFunctionsSQL generates CREATE FUNCTION statements
func generateCreateFunctionsSQL(functions []*ir.Function, targetSchema string, collector *diffCollector) {
// Build dependencies from function bodies (supplements pg_depend, which doesn't track SQL function body references)
buildFunctionBodyDependencies(functions)
// Sort functions by dependency order (topological sort)
sortedFunctions := topologicallySortFunctions(functions)
for _, function := range sortedFunctions {
sql := generateFunctionSQL(function, targetSchema)
// Create context for this statement
context := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationCreate,
Path: fmt.Sprintf("%s.%s", function.Schema, function.Name),
Source: function,
CanRunInTransaction: true,
}
collector.collect(context, sql)
// Generate COMMENT ON FUNCTION if the function has a comment
if function.Comment != "" {
generateFunctionComment(function, targetSchema, DiffTypeFunction, DiffOperationCreate, collector)
}
}
}
// generateModifyFunctionsSQL generates ALTER FUNCTION statements
func generateModifyFunctionsSQL(diffs []*functionDiff, targetSchema string, collector *diffCollector) {
for _, diff := range diffs {
oldFunc := diff.Old
newFunc := diff.New
// Check if only comment changed (no body/attribute changes)
onlyCommentChanged := functionsEqualExceptComment(oldFunc, newFunc) && oldFunc.Comment != newFunc.Comment
if onlyCommentChanged {
// Only the comment changed - generate just COMMENT ON FUNCTION
generateFunctionComment(newFunc, targetSchema, DiffTypeFunction, DiffOperationAlter, collector)
continue
}
// Check if only LEAKPROOF or PARALLEL attributes changed (not the function body/definition)
onlyAttributesChanged := functionsEqualExceptAttributes(oldFunc, newFunc)
if onlyAttributesChanged {
// Generate ALTER FUNCTION statements for attribute-only changes
// Check PARALLEL changes
if oldFunc.Parallel != newFunc.Parallel {
stmt := fmt.Sprintf("ALTER FUNCTION %s(%s) PARALLEL %s;",
qualifyEntityName(newFunc.Schema, newFunc.Name, targetSchema),
newFunc.GetArguments(),
newFunc.Parallel)
context := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationAlter,
Path: fmt.Sprintf("%s.%s", newFunc.Schema, newFunc.Name),
Source: diff,
CanRunInTransaction: true,
}
collector.collect(context, stmt)
}
// Check LEAKPROOF changes
if oldFunc.IsLeakproof != newFunc.IsLeakproof {
var stmt string
if newFunc.IsLeakproof {
stmt = fmt.Sprintf("ALTER FUNCTION %s(%s) LEAKPROOF;",
qualifyEntityName(newFunc.Schema, newFunc.Name, targetSchema),
newFunc.GetArguments())
} else {
stmt = fmt.Sprintf("ALTER FUNCTION %s(%s) NOT LEAKPROOF;",
qualifyEntityName(newFunc.Schema, newFunc.Name, targetSchema),
newFunc.GetArguments())
}
context := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationAlter,
Path: fmt.Sprintf("%s.%s", newFunc.Schema, newFunc.Name),
Source: diff,
CanRunInTransaction: true,
}
collector.collect(context, stmt)
}
// Check if comment also changed alongside attributes
if oldFunc.Comment != newFunc.Comment {
generateFunctionComment(newFunc, targetSchema, DiffTypeFunction, DiffOperationAlter, collector)
}
} else if functionRequiresRecreate(oldFunc, newFunc) {
// Return type, OUT parameters, or parameter names changed - must DROP then CREATE
// PostgreSQL does not allow CREATE OR REPLACE to change these.
// See https://github.com/pgplex/pgschema/issues/326
dropSQL := generateDropFunctionSQL(oldFunc, targetSchema)
createSQL := generateFunctionSQL(newFunc, targetSchema)
alterContext := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationAlter,
Path: fmt.Sprintf("%s.%s", newFunc.Schema, newFunc.Name),
Source: diff,
CanRunInTransaction: true,
}
statements := []SQLStatement{
{SQL: dropSQL, CanRunInTransaction: true},
{SQL: createSQL, CanRunInTransaction: true},
}
collector.collectStatements(alterContext, statements)
// Check if comment also changed alongside body changes
if oldFunc.Comment != newFunc.Comment {
generateFunctionComment(newFunc, targetSchema, DiffTypeFunction, DiffOperationAlter, collector)
}
} else {
// Function body or other attributes changed - use CREATE OR REPLACE
sql := generateFunctionSQL(newFunc, targetSchema)
// Create context for this statement
context := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationAlter,
Path: fmt.Sprintf("%s.%s", newFunc.Schema, newFunc.Name),
Source: diff,
CanRunInTransaction: true,
}
collector.collect(context, sql)
// Check if comment also changed alongside body changes
if oldFunc.Comment != newFunc.Comment {
generateFunctionComment(newFunc, targetSchema, DiffTypeFunction, DiffOperationAlter, collector)
}
}
}
}
// generateDropFunctionsSQL generates DROP FUNCTION statements
func generateDropFunctionsSQL(functions []*ir.Function, targetSchema string, collector *diffCollector) {
// Sort functions by reverse dependency order (drop dependents before dependencies)
sortedFunctions := reverseSlice(topologicallySortFunctions(functions))
for _, function := range sortedFunctions {
sql := generateDropFunctionSQL(function, targetSchema)
// Create context for this statement
context := &diffContext{
Type: DiffTypeFunction,
Operation: DiffOperationDrop,
Path: fmt.Sprintf("%s.%s", function.Schema, function.Name),
Source: function,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}
}
// generateDropFunctionSQL generates a DROP FUNCTION IF EXISTS statement
func generateDropFunctionSQL(function *ir.Function, targetSchema string) string {
functionName := qualifyEntityName(function.Schema, function.Name, targetSchema)
argsList := function.GetArguments()
if argsList != "" {
return fmt.Sprintf("DROP FUNCTION IF EXISTS %s(%s);", functionName, argsList)
}
return fmt.Sprintf("DROP FUNCTION IF EXISTS %s();", functionName)
}
// generateFunctionSQL generates CREATE OR REPLACE FUNCTION SQL for a function
func generateFunctionSQL(function *ir.Function, targetSchema string) string {
var stmt strings.Builder
// Build the CREATE OR REPLACE FUNCTION header with schema qualification
functionName := qualifyEntityName(function.Schema, function.Name, targetSchema)
stmt.WriteString(fmt.Sprintf("CREATE OR REPLACE FUNCTION %s", functionName))
// Add parameters from structured Parameters array
// Exclude TABLE mode parameters as they're part of RETURNS clause
var paramParts []string
for _, param := range function.Parameters {
if param.Mode != "TABLE" {
paramParts = append(paramParts, formatFunctionParameter(param, true, targetSchema))
}
}
if len(paramParts) > 0 {
stmt.WriteString(fmt.Sprintf("(\n %s\n)", strings.Join(paramParts, ",\n ")))
} else {
stmt.WriteString("()")
}
// Add return type
if function.ReturnType != "" {
// Strip schema prefix from return type if it matches the target schema
returnType := stripSchemaPrefix(function.ReturnType, targetSchema)
stmt.WriteString(fmt.Sprintf("\nRETURNS %s", returnType))
}
// Add language
if function.Language != "" {
stmt.WriteString(fmt.Sprintf("\nLANGUAGE %s", function.Language))
}
// Add volatility if not default
if function.Volatility != "" {
stmt.WriteString(fmt.Sprintf("\n%s", function.Volatility))
}
// Add STRICT if specified
if function.IsStrict {
stmt.WriteString("\nSTRICT")
}
// Add SECURITY DEFINER if true (INVOKER is default and not output)
if function.IsSecurityDefiner {
stmt.WriteString("\nSECURITY DEFINER")
}
// Add LEAKPROOF if true
if function.IsLeakproof {
stmt.WriteString("\nLEAKPROOF")
}
// Note: Don't output NOT LEAKPROOF (it's the default)
// Add PARALLEL if not default (UNSAFE)
if function.Parallel == "SAFE" {
stmt.WriteString("\nPARALLEL SAFE")
} else if function.Parallel == "RESTRICTED" {
stmt.WriteString("\nPARALLEL RESTRICTED")
}
// Note: Don't output PARALLEL UNSAFE (it's the default)
// Add SET search_path if specified
// Note: Output without outer quotes to handle multi-schema paths correctly
// e.g., "SET search_path = pg_catalog, public" not "SET search_path = 'pg_catalog, public'"
if function.SearchPath != "" {
stmt.WriteString(fmt.Sprintf("\nSET search_path = %s", function.SearchPath))
}
// Add the function body
if function.Definition != "" {
// Check if this uses SQL-standard body syntax (PG14+)
// pg_get_function_sqlbody returns:
// - "RETURN expression" for simple SQL-standard bodies
// - "BEGIN ATOMIC ... END" for multi-statement SQL-standard bodies
// These should not be wrapped with AS $$ ... $$
trimmedDef := strings.TrimSpace(function.Definition)
isSQLStandardBody := (len(trimmedDef) >= 7 && strings.EqualFold(trimmedDef[:7], "RETURN ")) ||
(len(trimmedDef) >= 12 && strings.EqualFold(trimmedDef[:12], "BEGIN ATOMIC"))
if isSQLStandardBody {
stmt.WriteString(fmt.Sprintf("\n%s;", trimmedDef))
} else {
// Traditional AS $$ ... $$ syntax
tag := generateDollarQuoteTag(function.Definition)
stmt.WriteString(fmt.Sprintf("\nAS %s%s%s;", tag, function.Definition, tag))
}
} else {
stmt.WriteString("\nAS $$$$;")
}
return stmt.String()
}
// generateDollarQuoteTag creates a safe dollar quote tag that doesn't conflict with the function body content.
// This implements the same algorithm used by pg_dump to avoid conflicts.
func generateDollarQuoteTag(body string) string {
// Check if the body contains potential conflicts with $$ quoting:
// 1. Direct $$ sequences
// 2. Parameter references like $1, $2, etc. that could be ambiguous
needsTagged := strings.Contains(body, "$$") || containsParameterReferences(body)
if !needsTagged {
return "$$"
}
// Start with the pg_dump preferred tag
candidates := []string{"$_$", "$function$", "$body$", "$pgdump$"}
// Try each candidate tag
for _, tag := range candidates {
if !strings.Contains(body, tag) {
return tag
}
}
// If all predefined tags conflict, generate a unique one
// Use a simple incrementing number approach like pg_dump does
for i := 1; i < 1000; i++ {
tag := fmt.Sprintf("$tag%d$", i)
if !strings.Contains(body, tag) {
return tag
}
}
// Fallback - this should rarely happen
return "$fallback$"
}
// containsParameterReferences checks if the body contains PostgreSQL parameter references ($1, $2, etc.)
// that could be confused with dollar quoting delimiters
func containsParameterReferences(body string) bool {
// Simple check for $digit patterns which are PostgreSQL parameter references
for i := 0; i < len(body)-1; i++ {
if body[i] == '$' && i+1 < len(body) && body[i+1] >= '0' && body[i+1] <= '9' {
return true
}
}
return false
}
// formatFunctionParameter formats a single function parameter with name, type, and optional default value
// For functions, mode is typically omitted (unlike procedures) unless it's OUT/INOUT
// includeDefault controls whether DEFAULT clauses are included in the output
func formatFunctionParameter(param *ir.Parameter, includeDefault bool, targetSchema string) string {
var part string
// For functions, only include mode if it's OUT or INOUT (IN is implicit)
if param.Mode == "OUT" || param.Mode == "INOUT" || param.Mode == "VARIADIC" {
part = param.Mode + " "
}
// Add parameter name and type
// Strip schema prefix from data type if it matches the target schema
dataType := stripSchemaPrefix(param.DataType, targetSchema)
if param.Name != "" {
part += param.Name + " " + dataType
} else {
part += dataType
}
// Add DEFAULT value if present and requested
// Strip schema prefix from default value type casts
// We strip both the target schema prefix and any temporary schema prefix (pgschema_tmp_*)
if includeDefault && param.DefaultValue != nil {
defaultVal := *param.DefaultValue
// Strip target schema prefix
defaultVal = stripSchemaPrefix(defaultVal, targetSchema)
// Also strip temporary embedded postgres schema prefixes (pgschema_tmp_*)
defaultVal = stripTempSchemaPrefix(defaultVal)
part += " DEFAULT " + defaultVal
}
return part
}
// functionsEqualExceptAttributes compares two functions ignoring LEAKPROOF and PARALLEL attributes
// Used to determine if ALTER FUNCTION can be used instead of CREATE OR REPLACE
func functionsEqualExceptAttributes(old, new *ir.Function) bool {
if old.Schema != new.Schema {
return false
}
if old.Name != new.Name {
return false
}
if old.Definition != new.Definition {
return false
}
if old.ReturnType != new.ReturnType {
return false
}
if old.Language != new.Language {
return false
}
if old.Volatility != new.Volatility {
return false
}
if old.IsStrict != new.IsStrict {
return false
}
if old.IsSecurityDefiner != new.IsSecurityDefiner {
return false
}
if old.SearchPath != new.SearchPath {
return false
}
// Note: We intentionally do NOT compare IsLeakproof or Parallel here
// That's the whole point - we want to detect when only those attributes changed
// Compare using normalized Parameters array
oldInputParams := filterNonTableParameters(old.Parameters)
newInputParams := filterNonTableParameters(new.Parameters)
return parametersEqual(oldInputParams, newInputParams)
}
// functionsEqual compares two functions for equality
func functionsEqual(old, new *ir.Function) bool {
if old.Schema != new.Schema {
return false
}
if old.Name != new.Name {
return false
}
if old.Definition != new.Definition {
return false
}
if old.ReturnType != new.ReturnType {
return false
}
if old.Language != new.Language {
return false
}
if old.Volatility != new.Volatility {
return false
}
if old.IsStrict != new.IsStrict {
return false
}
if old.IsSecurityDefiner != new.IsSecurityDefiner {
return false
}
if old.IsLeakproof != new.IsLeakproof {
return false
}
if old.Parallel != new.Parallel {
return false
}
if old.SearchPath != new.SearchPath {
return false
}
if old.Comment != new.Comment {
return false
}
// Compare using normalized Parameters array
// This ensures type aliases like "character varying" vs "varchar" are treated as equal
// For RETURNS TABLE functions, exclude TABLE mode parameters (they're in ReturnType)
// Only compare input parameters (IN, INOUT, VARIADIC, OUT)
oldInputParams := filterNonTableParameters(old.Parameters)
newInputParams := filterNonTableParameters(new.Parameters)
return parametersEqual(oldInputParams, newInputParams)
}
// functionsEqualExceptComment compares two functions ignoring comment differences
// Used to determine if only the comment changed (no body/attribute changes needed)
func functionsEqualExceptComment(old, new *ir.Function) bool {
if old.Schema != new.Schema {
return false
}
if old.Name != new.Name {
return false
}
if old.Definition != new.Definition {
return false
}
if old.ReturnType != new.ReturnType {
return false
}
if old.Language != new.Language {
return false
}
if old.Volatility != new.Volatility {
return false
}
if old.IsStrict != new.IsStrict {
return false
}
if old.IsSecurityDefiner != new.IsSecurityDefiner {
return false
}
if old.IsLeakproof != new.IsLeakproof {
return false
}
if old.Parallel != new.Parallel {
return false
}
if old.SearchPath != new.SearchPath {
return false
}
// Note: We intentionally do NOT compare Comment here
oldInputParams := filterNonTableParameters(old.Parameters)
newInputParams := filterNonTableParameters(new.Parameters)
return parametersEqual(oldInputParams, newInputParams)
}
// functionRequiresRecreate checks if a function modification requires DROP+CREATE
// instead of CREATE OR REPLACE. PostgreSQL does not allow CREATE OR REPLACE to change
// the return type or parameter names of an existing function.
func functionRequiresRecreate(old, new *ir.Function) bool {
if old.ReturnType != new.ReturnType {
return true
}
// Check parameter changes that CREATE OR REPLACE cannot handle.
// Input parameter types are the same (same map key), but names, OUT/INOUT
// parameter types/modes, or parameter count differences require DROP+CREATE.
oldParams := filterNonTableParameters(old.Parameters)
newParams := filterNonTableParameters(new.Parameters)
if len(oldParams) != len(newParams) {
return true
}
for i := range oldParams {
if oldParams[i].Name != newParams[i].Name {
return true
}
// OUT/INOUT parameter type or mode changes also require DROP+CREATE
if oldParams[i].Mode == "OUT" || oldParams[i].Mode == "INOUT" ||
newParams[i].Mode == "OUT" || newParams[i].Mode == "INOUT" {
if !parameterEqual(oldParams[i], newParams[i]) {
return true
}
}
}
return false
}
// filterNonTableParameters filters out TABLE mode parameters
// TABLE parameters are output columns in RETURNS TABLE() and shouldn't be compared as input parameters
func filterNonTableParameters(params []*ir.Parameter) []*ir.Parameter {
var filtered []*ir.Parameter
for _, param := range params {
if param.Mode != "TABLE" {
filtered = append(filtered, param)
}
}
return filtered
}
// parametersEqual compares two parameter arrays for equality
func parametersEqual(oldParams, newParams []*ir.Parameter) bool {
if len(oldParams) != len(newParams) {
return false
}
for i := range oldParams {
if !parameterEqual(oldParams[i], newParams[i]) {
return false
}
}
return true
}
// parameterEqual compares two parameters for equality
func parameterEqual(old, new *ir.Parameter) bool {
if old.Name != new.Name {
return false
}
// Compare data types (already normalized by ir.normalizeFunction)
if old.DataType != new.DataType {
return false
}
if old.Mode != new.Mode {
return false
}
// Compare default values
if (old.DefaultValue == nil) != (new.DefaultValue == nil) {
return false
}
if old.DefaultValue != nil && new.DefaultValue != nil {
if *old.DefaultValue != *new.DefaultValue {
return false
}
}
return true
}
// generateFunctionComment generates COMMENT ON FUNCTION statement
func generateFunctionComment(
function *ir.Function,
targetSchema string,
diffType DiffType,
operation DiffOperation,
collector *diffCollector,
) {
functionName := qualifyEntityName(function.Schema, function.Name, targetSchema)
argsList := function.GetArguments()
var sql string
if function.Comment == "" {
sql = fmt.Sprintf("COMMENT ON FUNCTION %s(%s) IS NULL;", functionName, argsList)
} else {
sql = fmt.Sprintf("COMMENT ON FUNCTION %s(%s) IS %s;", functionName, argsList, quoteString(function.Comment))
}
context := &diffContext{
Type: diffType,
Operation: operation,
Path: fmt.Sprintf("%s.%s", function.Schema, function.Name),
Source: function,
CanRunInTransaction: true,
}
collector.collect(context, sql)
}