-
Notifications
You must be signed in to change notification settings - Fork 73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add constraints
option to create_table
and unique
constraint support
#585
Merged
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
5908c19
mi folyik itt gyongyoson?
kvch c9ef10d
update generated file
kvch 03b3952
first batch
kvch f84b9a7
more updates
kvch 296731e
validation
kvch 766ddbc
add table constraint
kvch 965f28f
minor fixes
kvch abd6aed
add missing fixes
kvch b1dba4a
moreeee
kvch a0e918c
add default values
kvch 1ef47fd
uppercase
kvch 253e436
add validation test
kvch fd54808
rm messages
kvch b088ffd
deparse storage params
kvch File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
{ | ||
"name": "50_create_table_with_table_constraint", | ||
"operations": [ | ||
{ | ||
"create_table": { | ||
"name": "phonebook", | ||
"columns": [ | ||
{ | ||
"name": "id", | ||
"type": "serial", | ||
"pk": true | ||
}, | ||
{ | ||
"name": "name", | ||
"type": "varchar(255)" | ||
}, | ||
{ | ||
"name": "city", | ||
"type": "varchar(255)" | ||
}, | ||
{ | ||
"name": "phone", | ||
"type": "varchar(255)" | ||
} | ||
], | ||
"constraints": [ | ||
{ | ||
"name": "unique_numbers", | ||
"type": "unique", | ||
"columns": [ | ||
"phone" | ||
], | ||
"index_parameters": { | ||
"include_columns": [ | ||
"name" | ||
] | ||
} | ||
} | ||
] | ||
} | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,10 +22,16 @@ func (o *OpCreateTable) Start(ctx context.Context, conn db.DB, latestSchema stri | |
return nil, fmt.Errorf("failed to create columns SQL: %w", err) | ||
} | ||
|
||
constraintsSQL, err := constraintsToSQL(o.Constraints) | ||
if err != nil { | ||
return nil, fmt.Errorf("failed to create constraints SQL: %w", err) | ||
} | ||
|
||
// Create the table | ||
_, err = conn.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (%s)", | ||
_, err = conn.ExecContext(ctx, fmt.Sprintf("CREATE TABLE %s (%s %s)", | ||
pq.QuoteIdentifier(o.Name), | ||
columnsSQL)) | ||
columnsSQL, | ||
constraintsSQL)) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
@@ -102,6 +108,22 @@ func (o *OpCreateTable) Validate(ctx context.Context, s *schema.Schema) error { | |
} | ||
} | ||
|
||
for _, c := range o.Constraints { | ||
if c.Name == "" { | ||
return FieldRequiredError{Name: "name"} | ||
} | ||
if err := ValidateIdentifierLength(c.Name); err != nil { | ||
return fmt.Errorf("invalid constraint: %w", err) | ||
} | ||
|
||
switch c.Type { //nolint:gocritic // more cases are coming soon | ||
case ConstraintTypeUnique: | ||
if len(c.Columns) == 0 { | ||
return FieldRequiredError{Name: "columns"} | ||
} | ||
} | ||
} | ||
andrew-farries marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Update the schema to ensure that the new table is visible to validation of | ||
// subsequent operations. | ||
o.updateSchema(s) | ||
|
@@ -118,9 +140,23 @@ func (o *OpCreateTable) updateSchema(s *schema.Schema) *schema.Schema { | |
Name: col.Name, | ||
} | ||
} | ||
var uniqueConstraints map[string]*schema.UniqueConstraint | ||
for _, c := range o.Constraints { | ||
switch c.Type { //nolint:gocritic // more cases are coming soon | ||
case ConstraintTypeUnique: | ||
if uniqueConstraints == nil { | ||
uniqueConstraints = make(map[string]*schema.UniqueConstraint) | ||
} | ||
uniqueConstraints[c.Name] = &schema.UniqueConstraint{ | ||
Name: c.Name, | ||
Columns: c.Columns, | ||
} | ||
} | ||
} | ||
s.AddTable(o.Name, &schema.Table{ | ||
Name: o.Name, | ||
Columns: columns, | ||
Name: o.Name, | ||
Columns: columns, | ||
UniqueConstraints: uniqueConstraints, | ||
}) | ||
|
||
return s | ||
|
@@ -150,3 +186,88 @@ func columnsToSQL(cols []Column, tr SQLTransformer) (string, error) { | |
} | ||
return sql, nil | ||
} | ||
|
||
func constraintsToSQL(constraints []Constraint) (string, error) { | ||
constraintsSQL := make([]string, len(constraints)) | ||
for i, c := range constraints { | ||
writer := &ConstraintSQLWriter{ | ||
Name: c.Name, | ||
Columns: c.Columns, | ||
InitiallyDeferred: c.InitiallyDeferred, | ||
Deferrable: c.Deferrable, | ||
} | ||
if c.IndexParameters != nil { | ||
writer.IncludeColumns = c.IndexParameters.IncludeColumns | ||
writer.StorageParameters = c.IndexParameters.StorageParameters | ||
writer.Tablespace = c.IndexParameters.Tablespace | ||
} | ||
|
||
switch c.Type { //nolint:gocritic // more cases are coming soon | ||
case ConstraintTypeUnique: | ||
constraintsSQL[i] = writer.WriteUnique(c.NullsNotDistinct) | ||
} | ||
} | ||
if len(constraintsSQL) == 0 { | ||
return "", nil | ||
} | ||
return ", " + strings.Join(constraintsSQL, ", "), nil | ||
} | ||
|
||
type ConstraintSQLWriter struct { | ||
Name string | ||
Columns []string | ||
InitiallyDeferred bool | ||
Deferrable bool | ||
|
||
// unique, exclude, primary key constraints support the following options | ||
IncludeColumns []string | ||
StorageParameters string | ||
Tablespace string | ||
} | ||
|
||
func (w *ConstraintSQLWriter) WriteUnique(nullsNotDistinct bool) string { | ||
var constraint string | ||
if w.Name != "" { | ||
constraint = fmt.Sprintf("CONSTRAINT %s ", pq.QuoteIdentifier(w.Name)) | ||
} | ||
nullsDistinct := "" | ||
if nullsNotDistinct { | ||
nullsDistinct = "NULLS NOT DISTINCT" | ||
} | ||
constraint += fmt.Sprintf("UNIQUE %s (%s)", nullsDistinct, strings.Join(quoteColumnNames(w.Columns), ", ")) | ||
constraint += w.addIndexParameters() | ||
constraint += w.addDeferrable() | ||
Comment on lines
+237
to
+239
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. optional: we could use |
||
return constraint | ||
} | ||
|
||
func (w *ConstraintSQLWriter) addIndexParameters() string { | ||
constraint := "" | ||
if len(w.IncludeColumns) != 0 { | ||
constraint += fmt.Sprintf(" INCLUDE (%s)", strings.Join(quoteColumnNames(w.IncludeColumns), ", ")) | ||
} | ||
if w.StorageParameters != "" { | ||
constraint += fmt.Sprintf(" WITH (%s)", w.StorageParameters) | ||
} | ||
if w.Tablespace != "" { | ||
constraint += fmt.Sprintf(" USING INDEX TABLESPACE %s", w.Tablespace) | ||
} | ||
return constraint | ||
} | ||
|
||
func (w *ConstraintSQLWriter) addDeferrable() string { | ||
if !w.InitiallyDeferred && !w.Deferrable { | ||
return "" | ||
} | ||
deferrable := "" | ||
if w.Deferrable { | ||
deferrable += " DEFERRABLE" | ||
} else { | ||
deferrable += " NOT DEFERRABLE" | ||
} | ||
if w.InitiallyDeferred { | ||
deferrable += " INITIALLY DEFERRED" | ||
} else { | ||
deferrable += " INITIALLY IMMEDIATE" | ||
} | ||
return deferrable | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This might be updated because I have another example in a PR....