Skip to content

Commit

Permalink
feat: corroclient
Browse files Browse the repository at this point in the history
  • Loading branch information
lucas-jacques committed Aug 19, 2024
0 parents commit ad3bf68
Show file tree
Hide file tree
Showing 10 changed files with 700 additions and 0 deletions.
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2024 SAS Valyent

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# corroclient
A go client for the [https://github.com/superfly/corrosion](Corrosion) API.

# License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
30 changes: 30 additions & 0 deletions corroclient.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// This package is used to interact with the corrosion API.
package corroclient

import "net/http"

type Config struct {
URL string
Bearer string
}

type CorroClient struct {
c *http.Client
url string
bearer string
}

func (c *CorroClient) getURL(path string) string {
return c.url + path
}

func NewCorroClient(config Config) *CorroClient {
client := &http.Client{}
corroClient := &CorroClient{
c: client,
url: config.URL,
bearer: config.Bearer,
}

return corroClient
}
70 changes: 70 additions & 0 deletions exec.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package corroclient

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)

func (c *CorroClient) Exec(ctx context.Context, stmts []Statement) (*ExecResult, error) {
payload, err := json.Marshal(stmts)
if err != nil {
return nil, err
}

buffer := bytes.NewBuffer(payload)

request, err := http.NewRequest("POST", c.getURL("/v1/transactions"), buffer)
if err != nil {
return nil, err
}

resp, err := c.request(request)
if err != nil {
return nil, err

}

if resp.StatusCode != http.StatusOK {
bodyErr, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("corroclient: invalid status code: %d, body: %s", resp.StatusCode, string(bodyErr))
}

var execResult ExecResult
err = json.NewDecoder(resp.Body).Decode(&execResult)
if err != nil {
return nil, err
}

return &execResult, nil
}

type ExecResult struct {
Results []Result `json:"results"`
}

func (e *ExecResult) Errors() []error {
var errs []error
for _, res := range e.Results {
err := res.Err()
errs = append(errs, err)
}
return errs
}

type Result struct {
Error string `json:"error"`
RowAffected int `json:"rows_affected"`
Time float64 `json:"time"`
}

func (r *Result) Err() error {
if r.Error != "" {
return errors.New(r.Error)
}
return nil
}
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/valyentdev/corroclient

go 1.22.5
104 changes: 104 additions & 0 deletions queries.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
package corroclient

import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"sync"
)

var ErrNoRows = errors.New("corroclient: no rows")

func (c *CorroClient) Query(ctx context.Context, stmt Statement) (*Rows, error) {
payload, err := json.Marshal(stmt)
if err != nil {
return nil, err
}

buffer := bytes.NewBuffer(payload)

request, err := http.NewRequest("POST", c.getURL("/v1/queries"), buffer)
if err != nil {
return nil, err
}

resp, err := c.request(request)
if err != nil {
return nil, err
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
bodyBytes, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("corroclient: invalid status code: %d, body: %s", resp.StatusCode, string(bodyBytes))
}

reader := bufio.NewReader(resp.Body)

var columns Columns

rows := []*Row{}

for {
data, err := reader.ReadBytes('\n')
if err != nil {
return nil, err
}

var e event
if err := json.Unmarshal(data, &e); err != nil {
return nil, err
}

if e.Columns != nil {
columns = e.Columns
continue
}

if e.Row != nil {
row, err := readRow(e.Row)
if err != nil {
return nil, err
}

rows = append(rows, row)
}

if e.EOQ != nil {
break
}

}

if len(rows) == 0 {
return nil, ErrNoRows
}

return &Rows{
columns: columns,
rows: rows,
mutex: sync.RWMutex{},
currentIndex: -1,
}, nil
}

func (c *CorroClient) QueryRow(ctx context.Context, stmt Statement) (*Row, error) {
rows, err := c.Query(ctx, stmt)
if err != nil {
return nil, err
}

if !rows.Next() {
return nil, ErrNoRows // should never append but just in case...
}

row := rows.rows[rows.currentIndex]
row.columns = rows.columns

return row, nil
}
75 changes: 75 additions & 0 deletions rows.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package corroclient

import (
"errors"
"fmt"
"sync"
)

var ErrScan = errors.New("corroclient: scan error")

// Warning: Scan does not handle time.Time because of the various ways time can be stored
// in SQLite and JSON. You're responsible for converting time.Time yourself from numbers types or
// strings.
func (r *Row) Scan(dest ...any) error {
for i, value := range r.values {
if value == nil {
continue
}
switch v := value.(type) {
case float64:
if err := scanJSONNumber(v, dest[i]); err != nil {
return fmt.Errorf("%w, failed to scan JSON float64 %s", err, value)
}
continue
case string:
if err := scanJSONString(v, dest[i]); err != nil {
return fmt.Errorf("%w, failed to scan JSON string %s", err, value)
}
continue
case bool:
if err := scanJSONBool(v, dest[i]); err != nil {
return fmt.Errorf("%w, failed to scan JSON bool %s", err, value)
}
continue
}
}
return nil
}

type Rows struct {
columns []string
rows []*Row
currentIndex int
mutex sync.RWMutex
}

func (r *Rows) Columns() []string {
return r.columns
}

func (r *Rows) Next() bool {
r.mutex.Lock()
defer r.mutex.Unlock()
if r.currentIndex == len(r.rows)-1 {
return false
}

r.currentIndex++
return true
}

// Warning: Scan does not handle time.Time because of the various ways time can be stored
// in SQLite and JSON. You're responsible for converting time.Time yourself from numbers types or
// strings.
func (r *Rows) Scan(dest ...any) error {
r.mutex.RLock()
defer r.mutex.RUnlock()
if r.currentIndex == -1 {
return fmt.Errorf("you must call Next at least once before calling Scan")
}

row := r.rows[r.currentIndex]

return row.Scan(dest...)
}
74 changes: 74 additions & 0 deletions scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package corroclient

func scanJSONNumber(number float64, d interface{}) error {
switch dest := d.(type) {
case *int:
*dest = int(number)
return nil
case *int8:
*dest = int8(number)
return nil
case *int16:
*dest = int16(number)
return nil
case *int32:
*dest = int32(number)
return nil
case *int64:
*dest = int64(number)
return nil
case *uint:
*dest = uint(number)
return nil
case *uint8:
*dest = uint8(number)
return nil
case *uint16:
*dest = uint16(number)
return nil
case *uint32:
*dest = uint32(number)
return nil
case *uint64:
*dest = uint64(number)
return nil
case *float32:
*dest = float32(number)
return nil
case *float64:
*dest = float64(number)
return nil
case *bool:
*dest = number != 0
return nil
}

return ErrScan
}

func scanJSONString(s string, dest any) error {
if dest == nil {
return ErrScan
}

switch d := dest.(type) {
case *string:
*d = s
return nil
case *[]byte:
*d = []byte(s)
return nil
}

return ErrScan
}

func scanJSONBool(b any, dest interface{}) error {

switch d := dest.(type) {
case *bool:
*d = b.(bool)
return nil
}
return ErrScan
}
Loading

0 comments on commit ad3bf68

Please sign in to comment.