Skip to content

Commit e1acfab

Browse files
committed
Added PgGoConnection interface. Added basic pgComment and test.
1 parent 53a6788 commit e1acfab

File tree

3 files changed

+74
-0
lines changed

3 files changed

+74
-0
lines changed

database/pg.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,14 @@ import (
99
"github.com/pkg/errors"
1010
)
1111

12+
type PgGoConnection interface {
13+
DB() PgDB
14+
}
15+
16+
type PgDB interface {
17+
ExecContext(c context.Context, query interface{}, params ...interface{}) (pg.Result, error)
18+
}
19+
1220
// PgGo -
1321
type PgGo struct {
1422
conn *pg.DB

database/pgComment.go

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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+
}

database/pgComment_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package database

0 commit comments

Comments
 (0)