|
| 1 | +package database |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/dipdup-net/go-lib/hasura" |
| 6 | + "github.com/go-pg/pg/v10" |
| 7 | + "github.com/pkg/errors" |
| 8 | + "reflect" |
| 9 | + "strings" |
| 10 | +) |
| 11 | + |
| 12 | +func makeComments(ctx context.Context, conn *PgGo, model interface{}) error { |
| 13 | + typ := reflect.TypeOf(model) |
| 14 | + |
| 15 | + // 1. go through fields |
| 16 | + // 2. if tableName field - |
| 17 | + // 2.1 read value from pg tab, if not exist from model type name with snake case convertion - remember as tableName |
| 18 | + // 2.2 read value from pg-comment tag, if not exist continue |
| 19 | + // 2.3 set comment with SQL statement |
| 20 | + // 3. other |
| 21 | + // 3.1 read comment from pg-comment, it not exist continue |
| 22 | + // 3.2 read pg tag first value if it exist, if not - then snake case name of field and set as columnName |
| 23 | + // 3.3 set comment with SQL statement |
| 24 | + for i := 0; i < typ.NumField(); i++ { |
| 25 | + fieldType := typ.Field(i) |
| 26 | + pgTag, ok := fieldType.Tag.Lookup("pg") |
| 27 | + if !ok { |
| 28 | + continue |
| 29 | + } |
| 30 | + |
| 31 | + tags := strings.Split(pgTag, ",") |
| 32 | + |
| 33 | + var name string |
| 34 | + for i := range tags { |
| 35 | + if i == 0 { |
| 36 | + if name == "" { |
| 37 | + name = hasura.ToSnakeCase(fieldType.Name) |
| 38 | + } else { |
| 39 | + name = tags[i] |
| 40 | + } |
| 41 | + continue |
| 42 | + } |
| 43 | + |
| 44 | + parts := strings.Split(tags[i], ":") |
| 45 | + if parts[0] == "comment" { |
| 46 | + if len(parts) != 2 { |
| 47 | + return errors.Errorf("invalid comments format: %s", pgTag) |
| 48 | + } |
| 49 | + if fieldType.Name == "tableName" { |
| 50 | + // typ.Name() to |
| 51 | + if _, err := conn.DB().ExecContext(ctx, `COMMENT ON TABLE ? IS ?`, pg.Safe(typ.Name()), parts[1]); err != nil { |
| 52 | + return err |
| 53 | + } |
| 54 | + } else { |
| 55 | + if _, err := conn.DB().ExecContext(ctx, `COMMENT ON COLUMN ?.? IS ?`, pg.Safe(typ.Name()), pg.Safe(name), parts[1]); err != nil { |
| 56 | + return err |
| 57 | + } |
| 58 | + } |
| 59 | + continue |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return nil |
| 65 | +} |
0 commit comments