Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 12 additions & 19 deletions benchmarks/kallax.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,12 +122,12 @@ func (s *PersonStore) DebugWith(logger kallax.LoggerFunc) *PersonStore {
func (s *PersonStore) relationshipRecords(record *Person) []kallax.RecordWithSchema {
var records []kallax.RecordWithSchema

for _, rec := range record.Pets {
rec.ClearVirtualColumns()
rec.AddVirtualColumn("person_id", record.GetID())
for i := range record.Pets {
record.Pets[i].ClearVirtualColumns()
record.Pets[i].AddVirtualColumn("person_id", record.GetID())
records = append(records, kallax.RecordWithSchema{
Schema: Schema.Pet.BaseSchema,
Record: rec,
Record: record.Pets[i],
})
}

Expand All @@ -137,12 +137,10 @@ func (s *PersonStore) relationshipRecords(record *Person) []kallax.RecordWithSch
// Insert inserts a Person in the database. A non-persisted object is
// required for this operation.
func (s *PersonStore) Insert(record *Person) error {

records := s.relationshipRecords(record)

if len(records) > 0 {
return s.Store.Transaction(func(s *kallax.Store) error {

if err := s.Insert(Schema.Person.BaseSchema, record); err != nil {
return err
}
Expand All @@ -167,7 +165,6 @@ func (s *PersonStore) Insert(record *Person) error {
}

return s.Store.Insert(Schema.Person.BaseSchema, record)

}

// Update updates the given record on the database. If the columns are given,
Expand All @@ -177,12 +174,10 @@ func (s *PersonStore) Insert(record *Person) error {
// Only writable records can be updated. Writable objects are those that have
// been just inserted or retrieved using a query with no custom select fields.
func (s *PersonStore) Update(record *Person, cols ...kallax.SchemaField) (updated int64, err error) {

records := s.relationshipRecords(record)

if len(records) > 0 {
err = s.Store.Transaction(func(s *kallax.Store) error {

updated, err = s.Update(Schema.Person.BaseSchema, record, cols...)
if err != nil {
return err
Expand Down Expand Up @@ -213,7 +208,6 @@ func (s *PersonStore) Update(record *Person, cols ...kallax.SchemaField) (update
}

return s.Store.Update(Schema.Person.BaseSchema, record, cols...)

}

// Save inserts the object if the record is not persisted, otherwise it updates
Expand All @@ -233,9 +227,7 @@ func (s *PersonStore) Save(record *Person) (updated bool, err error) {

// Delete removes the given record from the database.
func (s *PersonStore) Delete(record *Person) error {

return s.Store.Delete(Schema.Person.BaseSchema, record)

}

// Find returns the set of results for the given query.
Expand Down Expand Up @@ -641,6 +633,8 @@ func (r *Pet) ColumnAddress(col string) (interface{}, error) {
return &r.Name, nil
case "kind":
return (*string)(&r.Kind), nil
case "person_id":
return types.Nullable(kallax.VirtualColumn("person_id", r, new(kallax.NumericID))), nil

default:
return nil, fmt.Errorf("kallax: invalid column in Pet: %s", col)
Expand All @@ -656,6 +650,8 @@ func (r *Pet) Value(col string) (interface{}, error) {
return r.Name, nil
case "kind":
return (string)(r.Kind), nil
case "person_id":
return r.Model.VirtualColumn(col), nil

default:
return nil, fmt.Errorf("kallax: invalid column in Pet: %s", col)
Expand Down Expand Up @@ -710,9 +706,7 @@ func (s *PetStore) DebugWith(logger kallax.LoggerFunc) *PetStore {
// Insert inserts a Pet in the database. A non-persisted object is
// required for this operation.
func (s *PetStore) Insert(record *Pet) error {

return s.Store.Insert(Schema.Pet.BaseSchema, record)

}

// Update updates the given record on the database. If the columns are given,
Expand All @@ -722,9 +716,7 @@ func (s *PetStore) Insert(record *Pet) error {
// Only writable records can be updated. Writable objects are those that have
// been just inserted or retrieved using a query with no custom select fields.
func (s *PetStore) Update(record *Pet, cols ...kallax.SchemaField) (updated int64, err error) {

return s.Store.Update(Schema.Pet.BaseSchema, record, cols...)

}

// Save inserts the object if the record is not persisted, otherwise it updates
Expand All @@ -744,9 +736,7 @@ func (s *PetStore) Save(record *Pet) (updated bool, err error) {

// Delete removes the given record from the database.
func (s *PetStore) Delete(record *Pet) error {

return s.Store.Delete(Schema.Pet.BaseSchema, record)

}

// Find returns the set of results for the given query.
Expand Down Expand Up @@ -1070,7 +1060,9 @@ var Schema = &schema{
"__person",
kallax.NewSchemaField("id"),
kallax.ForeignKeys{
"Pets": kallax.NewForeignKey("person_id", false),
"Pets": []*kallax.ForeignKey{
kallax.NewForeignKey("person_id", false),
},
},
func() kallax.Record {
return new(Person)
Expand All @@ -1095,6 +1087,7 @@ var Schema = &schema{
kallax.NewSchemaField("id"),
kallax.NewSchemaField("name"),
kallax.NewSchemaField("kind"),
kallax.NewSchemaField("person_id"),
),
ID: kallax.NewSchemaField("id"),
Name: kallax.NewSchemaField("name"),
Expand Down
2 changes: 2 additions & 0 deletions benchmarks/models_kallax.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package benchmark

import kallax "gopkg.in/src-d/go-kallax.v1"

//go:generate kallax gen

type Person struct {
kallax.Model `table:"people"`
ID int64 `pk:"autoincr"`
Expand Down
25 changes: 23 additions & 2 deletions generator/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,27 @@ func (td *TemplateData) findJSONSchemas(parent string, f *Field) {
}
}

const fkTpl = `kallax.NewForeignKey("%s", %s)`

func (td *TemplateData) GenForeignKeys(f *Field) string {
var fks []string
if f.IsManyToManyRelationship() {
fks = append(
fks,
fmt.Sprintf(fkTpl, f.LeftForeignKey(), "true"),
fmt.Sprintf(fkTpl, f.RightForeignKey(), "true"),
)
} else {
fks = append(fks, fmt.Sprintf(
fkTpl,
f.ForeignKey(),
fmt.Sprint(f.IsInverse()),
))
}

return strings.Join(fks, ", ")
}

// GenTypeName generates the name of the type in the field.
func (td *TemplateData) GenTypeName(f *Field) string {
if name, ok := findNamed(f.Node.Type(), td.pkg); ok {
Expand Down Expand Up @@ -529,7 +550,7 @@ const (
// The passed values to the FindBy will be used in an kallax.ArrayContains
tplFindByCollection = `
// FindBy%[1]s adds a new filter to the query that will require that
// the %[1]s property contains all the passed values; if no passed values,
// the %[1]s property contains all the passed values; if no passed values,
// it will do nothing.
func (q *%[2]s) FindBy%[1]s(v ...%[3]s) *%[2]s {
if len(v) == 0 {return q}
Expand Down Expand Up @@ -557,7 +578,7 @@ const (
// The passed values to the FindBy will be used in an kallax.In condition.
tplFindByID = `
// FindBy%[1]s adds a new filter to the query that will require that
// the %[1]s property is equal to one of the passed values; if no passed values,
// the %[1]s property is equal to one of the passed values; if no passed values,
// it will do nothing.
func (q *%[2]s) FindBy%[1]s(v ...%[3]s) *%[2]s {
if len(v) == 0 {return q}
Expand Down
55 changes: 55 additions & 0 deletions generator/template_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,61 @@ func (s *TemplateSuite) TestGenTimeTruncations() {
s.Equal(expectedTimeTruncations, s.td.GenTimeTruncations(m))
}

func (s *TemplateSuite) TestGenForeignKeys() {
s.processSource(`
package foo

import "gopkg.in/src-d/go-kallax.v1"

type Foo struct {
kallax.Model
ID int64 ` + "`pk:\"autoincr\"`" + `
Multiple *Bar ` + "`through:\"baz\"`" + `
Rel *Qux
RelInverse *Mux ` + "`fk:\",inverse\"`" + `
}

type Baz struct {
kallax.Model
ID int64 ` + "`pk:\"autoincr\"`" + `
Foo *Foo ` + "`fk:\",inverse\"`" + `
Bar *Bar ` + "`fk:\",inverse\"`" + `
}

type Bar struct {
kallax.Model
ID int64 ` + "`pk:\"autoincr\"`" + `
}

type Qux struct {
kallax.Model
ID int64 ` + "`pk:\"autoincr\"`" + `
}

type Mux struct {
kallax.Model
ID int64 ` + "`pk:\"autoincr\"`" + `
Foo *Foo
}
`)

m := findModel(s.td.Package, "Foo")
f := findField(m, "Multiple")
s.Equal(expectedMultipleFKs, s.td.GenForeignKeys(f))

f = findField(m, "Rel")
s.Equal(expectedSingleFKNoInverse, s.td.GenForeignKeys(f))

f = findField(m, "RelInverse")
s.Equal(expectedSingleFKInverse, s.td.GenForeignKeys(f))
}

const (
expectedMultipleFKs = `kallax.NewForeignKey("foo_id", true), kallax.NewForeignKey("bar_id", true)`
expectedSingleFKNoInverse = `kallax.NewForeignKey("foo_id", false)`
expectedSingleFKInverse = `kallax.NewForeignKey("mux_id", true)`
)

func (s *TemplateSuite) TestExecute() {
s.processSource(baseTpl)
var buf bytes.Buffer
Expand Down
5 changes: 4 additions & 1 deletion generator/templates/schema.tgo
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ var Schema = &schema{
"{{.Alias}}",
kallax.NewSchemaField("{{.ID.ColumnName}}"),
kallax.ForeignKeys{
{{range .Relationships}}"{{.Name}}": kallax.NewForeignKey("{{.ForeignKey}}", {{if .IsInverse}}true{{else}}false{{end}}),
{{range .Relationships}}
"{{.Name}}": []*kallax.ForeignKey{
{{$.GenForeignKeys .}},
},
{{end}}
},
func() kallax.Record {
Expand Down
8 changes: 4 additions & 4 deletions generator/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ func (s *FieldSuite) TestIsInverse() {
}

for _, tt := range cases {
f := withTag(mkField("", ""), tt.tag)
f := mkField("", "", tt.tag)
f.Kind = Relationship
s.Equal(tt.expected, f.IsInverse(), tt.tag)
}
Expand All @@ -227,7 +227,7 @@ func (s *FieldSuite) TestThroughTable() {
}

for _, tt := range cases {
s.Equal(tt.expected, withTag(mkField("", ""), tt.tag).ThroughTable(), tt.tag)
s.Equal(tt.expected, mkField("", "", tt.tag).ThroughTable(), tt.tag)
}
}

Expand All @@ -243,7 +243,7 @@ func (s *FieldSuite) TestLeftForeignKey() {
}

for _, tt := range cases {
f := withTag(mkField("", ""), tt.tag)
f := mkField("", "", tt.tag)
f.Model = &Model{Name: "Bar"}
s.Equal(tt.expected, f.LeftForeignKey(), tt.tag)
}
Expand All @@ -261,7 +261,7 @@ func (s *FieldSuite) TestRightForeignKey() {
}

for _, tt := range cases {
f := withTag(mkField("", ""), tt.tag)
f := mkField("", "", tt.tag)
f.Type = "Foo"
s.Equal(tt.expected, f.RightForeignKey(), tt.tag)
}
Expand Down
Loading