|
| 1 | +{{/* Generate indexes for the trailing column of every m2m join table */}} |
| 2 | +{{/* gotype: entgo.io/ent/entc/gen.Graph */}} |
| 3 | + |
| 4 | +{{ define "join_table_indexes" }} |
| 5 | + |
| 6 | +{{/* Add the base header for the generated file */}} |
| 7 | +{{ $pkg := base $.Config.Package }} |
| 8 | +{{ template "header" $ }} |
| 9 | + |
| 10 | +import ( |
| 11 | + "entgo.io/ent/dialect/sql/schema" |
| 12 | + |
| 13 | + "{{ $.Config.Package }}/migrate" |
| 14 | +) |
| 15 | + |
| 16 | +// maxJoinIndexNameLen is the maximum length of an identifier in postgres, longer names are |
| 17 | +// silently truncated by the server which would make the generated migration diff unstable |
| 18 | +const maxJoinIndexNameLen = 63 |
| 19 | + |
| 20 | +// joinTables are the m2m join tables ent generates from the edges in the schema |
| 21 | +// ent has no schema level api for indexing them, so they are amended below instead |
| 22 | +var joinTables = map[string]bool{ |
| 23 | +{{- range $t := $.Tables }} |
| 24 | +{{- if and (eq (len $t.Columns) 2) (eq (len $t.PrimaryKey) 2) }} |
| 25 | + "{{ $t.Name }}": true, |
| 26 | +{{- end }} |
| 27 | +{{- end }} |
| 28 | +} |
| 29 | + |
| 30 | +// init adds an index on the trailing column of every m2m join table |
| 31 | +// the leading column is already covered by the composite primary key, but the trailing one is |
| 32 | +// not, so enforcing its foreign key requires a sequential scan of the join table whenever a |
| 33 | +// referenced row is deleted, and traversing the edge in reverse scans it as well |
| 34 | +// |
| 35 | +// this runs for every consumer of the tables, both the auto migration and the versioned |
| 36 | +// migration diff, because they share this package |
| 37 | +func init() { |
| 38 | + for _, t := range migrate.Tables { |
| 39 | + if !joinTables[t.Name] { |
| 40 | + continue |
| 41 | + } |
| 42 | + |
| 43 | + col := t.PrimaryKey[1] |
| 44 | + |
| 45 | + name := t.Name + "_" + col.Name + "_idx" |
| 46 | + if len(name) > maxJoinIndexNameLen { |
| 47 | + name = name[:maxJoinIndexNameLen] |
| 48 | + } |
| 49 | + |
| 50 | + t.Indexes = append(t.Indexes, &schema.Index{ |
| 51 | + Name: name, |
| 52 | + Columns: []*schema.Column{col}, |
| 53 | + }) |
| 54 | + } |
| 55 | +} |
| 56 | +{{ end }} |
0 commit comments