-
Notifications
You must be signed in to change notification settings - Fork 0
/
table.go
63 lines (52 loc) · 1.3 KB
/
table.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package condition
import (
"gorm.io/gorm"
"github.com/FrancoLiberali/cql/model"
)
type Table struct {
Name string
Alias string
Initial bool
}
// SQLName returns the name that must be used in a sql query to use this table:
// the alias if not empty or the table name
func (t Table) SQLName() string {
if t.Alias != "" {
return t.Alias
}
return t.Name
}
// Returns true if the Table is the initial table in a query
func (t Table) IsInitial() bool {
return t.Initial
}
// Returns the related Table corresponding to the model
func (t Table) DeliverTable(query *GormQuery, model model.Model, relationName string) (Table, error) {
// get the name of the table for the model
tableName, err := getTableName(query.GormDB, model)
if err != nil {
return Table{}, err
}
// add a suffix to avoid tables with the same name when joining
// the same table more than once
tableAlias := relationName
if !t.IsInitial() {
tableAlias = t.Alias + "__" + relationName
}
return Table{
Name: tableName,
Alias: tableAlias,
Initial: false,
}, nil
}
func NewTable(db *gorm.DB, model model.Model) (Table, error) {
initialTableName, err := getTableName(db, model)
if err != nil {
return Table{}, err
}
return Table{
Name: initialTableName,
Alias: initialTableName,
Initial: true,
}, nil
}