Skip to content

Commit

Permalink
Added ability to handle multiple queries (#159)
Browse files Browse the repository at this point in the history
  • Loading branch information
remade authored Oct 17, 2024
1 parent 8d77d50 commit 08ad39f
Show file tree
Hide file tree
Showing 7 changed files with 107 additions and 36 deletions.
31 changes: 31 additions & 0 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import (
"os"
"strings"

"github.com/fxamacker/cbor/v2"

"github.com/surrealdb/surrealdb.go/pkg/connection"
"github.com/surrealdb/surrealdb.go/pkg/constants"
"github.com/surrealdb/surrealdb.go/pkg/logger"
Expand Down Expand Up @@ -293,3 +295,32 @@ func InsertRelation(db *DB, relationship *Relationship) error {
relationship.ID = (*res.Result)[0].ID
return nil
}

func QueryRaw(db *DB, queries *[]QueryStmt) error {
preparedQuery := ""
parameters := map[string]interface{}{}
for i := 0; i < len(*queries); i++ {
// append query
preparedQuery += fmt.Sprintf("%s;", (*queries)[i].SQL)
for k, v := range (*queries)[i].Vars {
parameters[k] = v
}
}

if preparedQuery == "" {
return fmt.Errorf("no query to run")
}

var res connection.RPCResponse[[]QueryResult[cbor.RawMessage]]
if err := db.con.Send(&res, "query", preparedQuery, parameters); err != nil {
return err
}

for i := 0; i < len(*queries); i++ {
// assign results
(*queries)[i].Result = (*res.Result)[i]
(*queries)[i].unmarshaler = db.con.GetUnmarshaler()
}

return nil
}
70 changes: 43 additions & 27 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,6 @@ func (s *SurrealDBTestSuite) TestLiveViaMethod() {
s.Require().NoError(e)

notification := <-notifications
fmt.Println(notification)
s.Require().Equal(connection.CreateAction, notification.Action)
s.Require().Equal(live, notification.ID)
}
Expand Down Expand Up @@ -409,42 +408,59 @@ func (s *SurrealDBTestSuite) TestMerge() {
s.Equal("456", user.Password)
}

func (s *SurrealDBTestSuite) TestInsertRelation() {
func (s *SurrealDBTestSuite) TestRelateAndInsertRelation() {
persons, err := surrealdb.Insert[testPerson](s.db, "person", []testPerson{
{FirstName: "Mary", LastName: "Doe"},
{FirstName: "John", LastName: "Doe"},
})
s.Require().NoError(err)

relationship := surrealdb.Relationship{
In: *(*persons)[0].ID,
Out: *(*persons)[1].ID,
Relation: "knows",
Data: map[string]any{
"since": time.Now(),
},
s.Run("Test 'insert_relation' method", func() {
relationship := surrealdb.Relationship{
In: *(*persons)[0].ID,
Out: *(*persons)[1].ID,
Relation: "knows",
Data: map[string]any{
"since": time.Now(),
},
}
err = surrealdb.InsertRelation(s.db, &relationship)
s.Require().NoError(err)
s.Assert().NotNil(relationship.ID)
})

s.Run("Test 'relate' method", func() {
relationship := surrealdb.Relationship{
In: *(*persons)[0].ID,
Out: *(*persons)[1].ID,
Relation: "knows",
Data: map[string]any{
"since": time.Now(),
},
}
err = surrealdb.Relate(s.db, &relationship)
s.Require().NoError(err)
s.Assert().NotNil(relationship.ID)
})
}

func (s *SurrealDBTestSuite) TestQueryRaw() {
queries := []surrealdb.QueryStmt{
{SQL: "CREATE person SET name = 'John'"},
{SQL: "SELECT * FROM type::table($tb)", Vars: map[string]interface{}{"tb": "person"}},
}
err = surrealdb.InsertRelation(s.db, &relationship)

err := surrealdb.QueryRaw(s.db, &queries)
s.Require().NoError(err)
s.Assert().NotNil(relationship.ID)
}

func (s *SurrealDBTestSuite) TestRelate() {
persons, err := surrealdb.Insert[testPerson](s.db, "person", []testPerson{
{FirstName: "Mary", LastName: "Doe"},
{FirstName: "John", LastName: "Doe"},
})
var created []testPerson
err = queries[0].GetResult(&created)
s.Require().NoError(err)

relationship := surrealdb.Relationship{
In: *(*persons)[0].ID,
Out: *(*persons)[1].ID,
Relation: "knows",
Data: map[string]any{
"since": time.Now(),
},
}
err = surrealdb.Relate(s.db, &relationship)
var selected []testPerson
err = queries[1].GetResult(&selected)
s.Require().NoError(err)
s.Assert().NotNil(relationship.ID)

fmt.Println(created)
fmt.Println(selected)
}
1 change: 1 addition & 0 deletions pkg/connection/connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Connection interface {
Let(key string, value interface{}) error
Unset(key string) error
LiveNotifications(id string) (chan Notification, error)
GetUnmarshaler() codec.Unmarshaler
}

type NewConnectionParams struct {
Expand Down
6 changes: 6 additions & 0 deletions pkg/connection/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import (
"sync"
"time"

"github.com/surrealdb/surrealdb.go/internal/codec"

"github.com/surrealdb/surrealdb.go/internal/rand"
"github.com/surrealdb/surrealdb.go/pkg/constants"
)
Expand Down Expand Up @@ -70,6 +72,10 @@ func (h *HTTPConnection) SetHTTPClient(client *http.Client) *HTTPConnection {
return h
}

func (h *HTTPConnection) GetUnmarshaler() codec.Unmarshaler {
return h.unmarshaler
}

func (h *HTTPConnection) Send(dest any, method string, params ...interface{}) error {
if h.baseURL == "" {
return constants.ErrNoBaseURL
Expand Down
7 changes: 7 additions & 0 deletions pkg/connection/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ package connection
import (
"errors"
"fmt"

"github.com/surrealdb/surrealdb.go/internal/codec"

"io"
"log/slog"
"net"
Expand Down Expand Up @@ -134,6 +137,10 @@ func (ws *WebSocketConnection) Unset(key string) error {
return ws.Send(nil, "unset", key)
}

func (ws *WebSocketConnection) GetUnmarshaler() codec.Unmarshaler {
return ws.unmarshaler
}

func (ws *WebSocketConnection) Send(dest interface{}, method string, params ...interface{}) error {
select {
case <-ws.closeChan:
Expand Down
8 changes: 4 additions & 4 deletions pkg/models/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,16 +43,16 @@ func (d *CustomDateTime) MarshalCBOR() ([]byte, error) {
func (d *CustomDateTime) UnmarshalCBOR(data []byte) error {
dec := getCborDecoder()

var temp [2]interface{}
var temp [2]int64
err := dec.Unmarshal(data, &temp)
if err != nil {
return err
}

s := temp[0].(uint64)
ns := temp[1].(uint64)
s := temp[0]
ns := temp[1]

*d = CustomDateTime(time.Unix(int64(s), int64(ns)))
*d = CustomDateTime(time.Unix(s, ns))

return nil
}
Expand Down
20 changes: 15 additions & 5 deletions types.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package surrealdb

import (
"github.com/surrealdb/surrealdb.go/pkg/connection"
"github.com/fxamacker/cbor/v2"
"github.com/surrealdb/surrealdb.go/internal/codec"
"github.com/surrealdb/surrealdb.go/pkg/constants"
"github.com/surrealdb/surrealdb.go/pkg/models"
)

Expand All @@ -18,10 +20,18 @@ type QueryResult[T any] struct {
Result T `json:"result"`
}

type QueryStmt[TResult any] struct {
SQL string
Vars map[string]interface{}
Result *connection.RPCResponse[TResult]
type QueryStmt struct {
unmarshaler codec.Unmarshaler
SQL string
Vars map[string]interface{}
Result QueryResult[cbor.RawMessage]
}

func (q *QueryStmt) GetResult(dest interface{}) error {
if q.unmarshaler == nil {
return constants.ErrNoUnmarshaler
}
return q.unmarshaler.Unmarshal(q.Result.Result, dest)
}

type Relationship struct {
Expand Down

0 comments on commit 08ad39f

Please sign in to comment.