Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: Added support for inserting multiple entries #131

Closed
Closed
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
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ func main() {
panic(err)
}

// Insert multiple entries
userList := []User{
{
Name: "John",
Surname: "Doe",
},
{
Name: "Jane",
Surname: "Doe",
},
}

createdUsers, err := s.db.CreateMany("users", userList)

if err != nil {
panic(err)
}

// Get user by ID
data, err = db.Select(createdUser[0].ID)
if err != nil {
Expand Down
7 changes: 7 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,13 @@ func (db *DB) Create(thing string, data interface{}) (interface{}, error) {
return db.send("create", thing, data)
}

// Creates multiple records in table
func (db *DB) CreateMany(thing string, records interface{}) (interface{}, error) {
return db.send("query", fmt.Sprintf("INSERT INTO %s ($records)", thing), map[string]interface{}{
"records": records,
})
}

// Update a table or record in the database like a PUT request.
func (db *DB) Update(what string, data interface{}) (interface{}, error) {
return db.send("update", what, data)
Expand Down
34 changes: 34 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,40 @@ func (s *SurrealDBTestSuite) TestCreate() {
})
}

func (s *SurrealDBTestSuite) TestCreateMany() {

userList := []testUser{
{
Username: "dwight",
Password: "123",
},
{
Username: "michael",
Password: "456",
},
}

createdUsers, err := s.db.CreateMany("users", userList)

s.Require().NoError(err)
s.NotEmpty(createdUsers)

var userSlice []marshal.RawQuery[testUser]
err = marshal.UnmarshalRaw(createdUsers, &userSlice)
s.Require().NoError(err)
s.Len(userSlice, 1)
s.Equal(userSlice[0].Status, marshal.StatusOK)

s.Len(userSlice[0].Result, 2)

s.NotEmpty(userSlice[0].Result[0].ID, "The ID should have been set by the database for record 1")
s.Equal("dwight", userSlice[0].Result[0].Username)

s.NotEmpty(userSlice[0].Result[1].ID, "The ID should have been set by the database for record 1")
s.Equal("michael", userSlice[0].Result[1].Username)

}

func (s *SurrealDBTestSuite) TestSelect() {
createdUsers, err := s.db.Create("users", testUser{
Username: "johnnyjohn",
Expand Down