fix: fix and improve primary keys on projections (#3708)

* fix: org_domain projection

* fix: projection reset

* fix test

* improve foreign keys on suffixed tables
This commit is contained in:
Livio Amstutz
2022-05-25 14:15:13 +02:00
committed by GitHub
parent 79452da7d6
commit 737e01bfd2
20 changed files with 403 additions and 156 deletions

View File

@@ -19,6 +19,7 @@ type Table struct {
primaryKey PrimaryKey
indices []*Index
constraints []*Constraint
foreignKeys []*ForeignKey
}
func NewTable(columns []*Column, key PrimaryKey, opts ...TableOption) *Table {
@@ -58,6 +59,12 @@ func WithConstraint(constraint *Constraint) TableOption {
}
}
func WithForeignKey(key *ForeignKey) TableOption {
return func(table *Table) {
table.foreignKeys = append(table.foreignKeys, key)
}
}
type Column struct {
Name string
Type ColumnType
@@ -158,6 +165,27 @@ type Constraint struct {
Columns []string
}
func NewForeignKey(name string, columns []string, refColumns []string) *ForeignKey {
i := &ForeignKey{
Name: name,
Columns: columns,
RefColumns: refColumns,
}
return i
}
func NewForeignKeyOfPublicKeys(name string) *ForeignKey {
return &ForeignKey{
Name: name,
}
}
type ForeignKey struct {
Name string
Columns []string
RefColumns []string
}
//Init implements handler.Init
func (h *StatementHandler) Init(ctx context.Context, checks ...*handler.Check) error {
for _, check := range checks {
@@ -268,6 +296,16 @@ func createTableStatement(table *Table, tableName string, suffix string) string
for _, index := range table.indices {
stmt += fmt.Sprintf(", INDEX %s (%s)", index.Name, strings.Join(index.Columns, ","))
}
for _, key := range table.foreignKeys {
ref := tableName
if len(key.RefColumns) > 0 {
ref += fmt.Sprintf("(%s)", strings.Join(key.RefColumns, ","))
}
if len(key.Columns) == 0 {
key.Columns = table.primaryKey
}
stmt += fmt.Sprintf(", CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s ON DELETE CASCADE", key.Name, strings.Join(key.Columns, ","), ref)
}
for _, constraint := range table.constraints {
stmt += fmt.Sprintf(", CONSTRAINT %s UNIQUE (%s)", constraint.Name, strings.Join(constraint.Columns, ","))
}