Skip to content
Open
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
70 changes: 58 additions & 12 deletions backend/plugins/org/api/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import (
"github.com/apache/devlake/core/context"
"github.com/apache/devlake/core/dal"
"github.com/apache/devlake/core/errors"
"github.com/apache/devlake/core/log"
"github.com/apache/devlake/core/models/domainlayer/crossdomain"
"github.com/apache/devlake/helpers/dbhelper"
helper "github.com/apache/devlake/helpers/pluginhelper/api"
"reflect"
)
Expand All @@ -32,18 +34,46 @@ type store interface {
findAllAccounts() ([]account, errors.Error)
findAllUserAccounts() ([]userAccount, errors.Error)
findAllProjectMapping() ([]projectMapping, errors.Error)
deleteAll(i interface{}) errors.Error
replace(deletions []deletion, items []interface{}) errors.Error
save(items []interface{}) errors.Error
}

// deletion selects the rows of one table that replace deletes.
type deletion struct {
table interface{}
where dal.Clause
}

// allRows selects every row of table.
func allRows(table interface{}) deletion {
return deletion{table: table, where: dal.Where("1=1")}
}

type dbStore struct {
db dal.Dal
driver *helper.BatchSaveDivider
db dal.Dal
basicRes context.BasicRes
}

func NewDbStore(db dal.Dal, basicRes context.BasicRes) *dbStore {
driver := helper.NewBatchSaveDivider(basicRes, 1000, "", "")
return &dbStore{db: db, driver: driver}
return &dbStore{db: db, basicRes: basicRes}
}

// txBasicRes gives a BatchSaveDivider the transaction as its Dal.
type txBasicRes struct {
context.BasicRes
tx dal.Dal
}

func (r txBasicRes) GetDal() dal.Dal {
return r.tx
}

func (r txBasicRes) NestedLogger(name string) context.BasicRes {
return txBasicRes{BasicRes: r.BasicRes.NestedLogger(name), tx: r.tx}
}

func (r txBasicRes) ReplaceLogger(logger log.Logger) context.BasicRes {
return txBasicRes{BasicRes: r.BasicRes.ReplaceLogger(logger), tx: r.tx}
}

func (d *dbStore) findAllUsers() ([]user, errors.Error) {
Expand Down Expand Up @@ -104,13 +134,24 @@ func (d *dbStore) findAllProjectMapping() ([]projectMapping, errors.Error) {
var pm *projectMapping
return pm.fromDomainLayer(mapping), nil
}
func (d *dbStore) deleteAll(i interface{}) errors.Error {
return d.db.Delete(i, dal.Where("1=1"))
}

func (d *dbStore) save(items []interface{}) errors.Error {
// replace deletes the rows that deletions select, then saves items, in one transaction.
// If any step fails, nothing changes. Each call uses a new BatchSaveDivider, because a
// BatchSave keeps its first error and rejects every later row.
func (d *dbStore) replace(deletions []deletion, items []interface{}) (err errors.Error) {
txHelper := dbhelper.NewTxHelper(d.basicRes, &err)
defer txHelper.End()
tx := txHelper.Begin()
for _, del := range deletions {
err = tx.Delete(del.table, del.where)
if err != nil {
return err
}
}
divider := helper.NewBatchSaveDivider(txBasicRes{BasicRes: d.basicRes, tx: tx}, 1000, "", "")
var batch *helper.BatchSave
for _, item := range items {
batch, err := d.driver.ForType(reflect.TypeOf(item))
batch, err = divider.ForType(reflect.TypeOf(item))
if err != nil {
return err
}
Expand All @@ -119,6 +160,11 @@ func (d *dbStore) save(items []interface{}) errors.Error {
return err
}
}
d.driver.Close()
return nil
err = divider.Close()
return err
}

// save saves items without deleting any rows, in one transaction.
func (d *dbStore) save(items []interface{}) errors.Error {
return d.replace(nil, items)
}
36 changes: 36 additions & 0 deletions backend/plugins/org/api/store_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package api

import (
"testing"

contextimpl "github.com/apache/devlake/impls/context"
"github.com/apache/devlake/impls/logruslog"
mockdal "github.com/apache/devlake/mocks/core/dal"
"github.com/stretchr/testify/assert"
)

func TestTxBasicResKeepsTransaction(t *testing.T) {
tx := new(mockdal.Dal)
basicRes := txBasicRes{BasicRes: contextimpl.NewDefaultBasicRes(nil, logruslog.Global, nil), tx: tx}

assert.Same(t, tx, basicRes.GetDal())
assert.Same(t, tx, basicRes.NestedLogger("nested").GetDal())
assert.Same(t, tx, basicRes.ReplaceLogger(logruslog.Global).GetDal())
}
6 changes: 1 addition & 5 deletions backend/plugins/org/api/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,7 @@ func (h *Handlers) CreateTeam(input *plugin.ApiResourceInput) (*plugin.ApiResour
for _, tm := range (&team{}).toDomainLayer(tt) {
items = append(items, tm)
}
err = h.store.deleteAll(&crossdomain.Team{})
if err != nil {
return nil, err
}
err = h.store.save(items)
err = h.store.replace([]deletion{allRows(&crossdomain.Team{})}, items)
if err != nil {
return nil, err
}
Expand Down
10 changes: 1 addition & 9 deletions backend/plugins/org/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,15 +87,7 @@ func (h *Handlers) CreateUser(input *plugin.ApiResourceInput) (*plugin.ApiResour
for _, teamUser := range teamUsers {
items = append(items, teamUser)
}
err = h.store.deleteAll(&crossdomain.User{})
if err != nil {
return nil, err
}
err = h.store.deleteAll(&crossdomain.TeamUser{})
if err != nil {
return nil, err
}
err = h.store.save(items)
err = h.store.replace([]deletion{allRows(&crossdomain.User{}), allRows(&crossdomain.TeamUser{})}, items)
if err != nil {
return nil, err
}
Expand Down
6 changes: 1 addition & 5 deletions backend/plugins/org/api/user_account_mapping.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,11 +77,7 @@ func (h *Handlers) CreateUserAccountMapping(input *plugin.ApiResourceInput) (*pl
for _, userAccount := range userAccounts {
items = append(items, userAccount)
}
err = h.store.deleteAll(&crossdomain.UserAccount{})
if err != nil {
return nil, err
}
err = h.store.save(items)
err = h.store.replace([]deletion{allRows(&crossdomain.UserAccount{})}, items)
if err != nil {
return nil, err
}
Expand Down
104 changes: 104 additions & 0 deletions backend/plugins/org/e2e/csv_upload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/*
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package e2e

import (
"testing"

"github.com/apache/devlake/core/errors"
"github.com/apache/devlake/core/models/domainlayer/crossdomain"
"github.com/apache/devlake/core/plugin"
"github.com/apache/devlake/plugins/org/api"
"gorm.io/gorm/schema"
)

type uploadSnapshot struct {
table schema.Tabler
csvRelPath string
targetFields []string
}

// A failed upload must keep the existing rows, and a later upload must still work.
// Each too_long file ends with a row whose value has 300 characters. The column is
// varchar(255), so MySQL in strict mode (the default) and PostgreSQL reject the row.
func TestCsvUploadFailureChangesNothing(t *testing.T) {
tests := []struct {
name string
upload func(h *api.Handlers, input *plugin.ApiResourceInput) (*plugin.ApiResourceOutput, errors.Error)
validFile string
tooLongFile string
snapshots []uploadSnapshot
}{
{
name: "teams",
upload: (*api.Handlers).CreateTeam,
validFile: "./raw_tables/upload_teams.csv",
tooLongFile: "./raw_tables/upload_teams_too_long.csv",
snapshots: []uploadSnapshot{
{crossdomain.Team{}, "./snapshot_tables/upload_teams.csv", []string{"id", "name", "alias", "parent_id", "sorting_index"}},
},
},
{
name: "users",
upload: (*api.Handlers).CreateUser,
validFile: "./raw_tables/upload_users.csv",
tooLongFile: "./raw_tables/upload_users_too_long.csv",
snapshots: []uploadSnapshot{
{crossdomain.User{}, "./snapshot_tables/upload_users.csv", []string{"id", "name", "email"}},
{crossdomain.TeamUser{}, "./snapshot_tables/upload_team_users.csv", []string{"team_id", "user_id"}},
},
},
{
name: "user account mapping",
upload: (*api.Handlers).CreateUserAccountMapping,
validFile: "./raw_tables/upload_user_account_mapping.csv",
tooLongFile: "./raw_tables/upload_user_account_mapping_too_long.csv",
snapshots: []uploadSnapshot{
{crossdomain.UserAccount{}, "./snapshot_tables/upload_user_accounts.csv", []string{"account_id", "user_id"}},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
dataflowTester, handlers := newUploadHandlers(t)
verify := func() {
for _, s := range tt.snapshots {
dataflowTester.VerifyTable(s.table, s.csvRelPath, s.targetFields)
}
}
for _, s := range tt.snapshots {
dataflowTester.FlushTabler(s.table)
}

if _, err := tt.upload(handlers, uploadInput(t, tt.validFile)); err != nil {
t.Fatal(err)
}
verify()

if _, err := tt.upload(handlers, uploadInput(t, tt.tooLongFile)); err == nil {
t.Error("the upload with a value that is too long must return an error")
}
verify()

if _, err := tt.upload(handlers, uploadInput(t, tt.validFile)); err != nil {
t.Fatalf("an upload after a failed upload must work: %v", err)
}
verify()
})
}
}
4 changes: 4 additions & 0 deletions backend/plugins/org/e2e/raw_tables/upload_teams.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Id,Name,Alias,ParentId,SortingIndex
1,Team One,one,,1
2,Team Two,two,1,2
3,Team Three,three,1,3
5 changes: 5 additions & 0 deletions backend/plugins/org/e2e/raw_tables/upload_teams_too_long.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Id,Name,Alias,ParentId,SortingIndex
1,Team One,one,,1
2,Team Two,two,1,2
3,Team Three,three,1,3
4,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,four,,4
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Id,Email,FullName,UserName,AvatarUrl,Organization,CreatedDate,Status,UserId
github:GithubAccount:1:101,,,one,,,,0,1
github:GithubAccount:1:102,,,two,,,,0,2
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Id,Email,FullName,UserName,AvatarUrl,Organization,CreatedDate,Status,UserId
github:GithubAccount:1:101,,,one,,,,0,1
github:GithubAccount:1:102,,,two,,,,0,2
github:GithubAccount:1:103,,,three,,,,0,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
3 changes: 3 additions & 0 deletions backend/plugins/org/e2e/raw_tables/upload_users.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Id,Name,Email,TeamIds
1,User One,one@example.com,1
2,User Two,two@example.com,1;2
4 changes: 4 additions & 0 deletions backend/plugins/org/e2e/raw_tables/upload_users_too_long.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Id,Name,Email,TeamIds
1,User One,one@example.com,1
2,User Two,two@example.com,1;2
3,xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx,three@example.com,2
4 changes: 4 additions & 0 deletions backend/plugins/org/e2e/snapshot_tables/upload_team_users.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
team_id,user_id
1,1
1,2
2,2
4 changes: 4 additions & 0 deletions backend/plugins/org/e2e/snapshot_tables/upload_teams.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
id,name,alias,parent_id,sorting_index
1,Team One,one,,1
2,Team Two,two,1,2
3,Team Three,three,1,3
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
account_id,user_id
github:GithubAccount:1:101,1
github:GithubAccount:1:102,2
3 changes: 3 additions & 0 deletions backend/plugins/org/e2e/snapshot_tables/upload_users.csv
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
id,name,email
1,User One,one@example.com
2,User Two,two@example.com
Loading
Loading
⌂ Proxy