Skip to content

Commit

Permalink
refactor: Copy-paste connor fork into repo (sourcenetwork#567)
Browse files Browse the repository at this point in the history
Copy-paste connor fork into repo, ensuring that the original authors "github.com/SierraSoftworks/connor" get credit
  • Loading branch information
AndrewSisley authored Jun 27, 2022
1 parent c3e6c70 commit e828cef
Show file tree
Hide file tree
Showing 41 changed files with 2,720 additions and 7 deletions.
7 changes: 7 additions & 0 deletions connor/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
The MIT License (MIT)

Copyright © 2016 Sierra Softworks

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.
155 changes: 155 additions & 0 deletions connor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
# Connor
**Flexible condition DSL for Go**

Connor is a simple condition DSL and evaluator for Go inspired by MongoDB's
query language. It aims to provide a simple and straightforward means to
express conditions against `map[string]interface{}` objects for everything
from rules engines to query tools.

Connor only implements a subset of MongoDB's query language, the most commonly
used methods, however it has been designed to make adding new operators simple
and straightforward should you require them.

## Example

```go
package main

import (
"github.com/SierraSoftworks/connor"
)

func parse(d string) map[string]interface{} {
var v map[string]interface{}
if err := json.NewDecoder(bytes.NewBufferString(d)).Decode(&v); err != nil {
fmt.Fatal(err)
}

return v
}

func main() {
conds := parse(`{
"x": 1,
"y": { "$in": [1, 2, 3] },
"z": { "$ne": 5 }
}`)

data := parse(`{
"x": 1,
"y": 2,
"z": 3
}`)

if match, err := connor.Match(conds, data); err != nil {
fmt.Fatal("failed to run match:", err)
} else if match {
fmt.Println("Matched")
} else {
fmt.Println("No Match")
}
}
```

## Operators
Connor has a number of built in operators which enable you to quickly compare a number
of common data structures to one another. The following are supported operators for use
in your conditions.

### Equality `$eq`
```json
{ "$eq": "value" }
```

### Inequality `$ne`
```json
{ "$ne": "value" }
```

### Greater Than `$gt`
```json
{ "$gt": 5.3 }
```

### Greater Than or Equal `$ge`
```json
{ "$ge": 5 }
```

### Less Than `$lt`
```json
{ "$lt": 42 }
```

### Less Than or Equal `$le`
```json
{ "$le": 42 }
```

### Set Contains `$in`
```json
{ "$in": [1, 2, 3] }
```

### Set Excludes `$nin`
```json
{ "$nin": [1, 2, 3] }
```

### String Contains `$contains`
```json
{ "$contains": "test" }
```

### Logical And `$and`
```json
{ "$and": [{ "$gt": 5 }, { "$lt": 10 }]}
```

### Logical Or `$or`
```json
{ "$or": [{ "$gt": 10 }, { "$eq": 0 }]}
```

## Custom Operators
Connor supports registering your own custom operators for any additional condition
evaluation you wish to perform. These operators are registered using the `Register()`
method and are expected to match the following interface:

```go
type Operator interface {
Name() string
Evaluate(condition, data interface{}) (bool, error)
}
```

The following is an example of an operator which determines whether the data is nil.

```go
func init() {
connor.Register(&NilOperator{})
}

type NilOperator struct {}

func (o *NilOperator) Name() string {
return "nil"
}

func (o *NilOperator) Evaluate(condition, data interface{}) (bool, error) {
if c, ok := condition.(bool); ok {
return data != nil ^ c, nil
} else {
return data == nil, nil
}
}
```

You can then use this operator as the following example shows, or specify `false`
to check for non-nil values.

```json
{
"x": { "$nil": true }
}
```
33 changes: 33 additions & 0 deletions connor/and.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package connor

import "fmt"

func init() {
Register(&AndOperator{})
}

// AndOperator is an operator which allows the evaluation of
// of a number of conditions, matching if all of them match.
type AndOperator struct {
}

func (o *AndOperator) Name() string {
return "and"
}

func (o *AndOperator) Evaluate(condition, data interface{}) (bool, error) {
switch cn := condition.(type) {
case []interface{}:
for _, c := range cn {
if m, err := MatchWith("$eq", c, data); err != nil {
return false, err
} else if !m {
return false, nil
}
}

return true, nil
default:
return false, fmt.Errorf("unknown or condition type '%#v'", cn)
}
}
31 changes: 31 additions & 0 deletions connor/and_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package connor_test

import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

. "github.com/sourcenetwork/defradb/connor"
)

var _ = Describe("$and", func() {
It("should be registered as an operator", func() {
Expect(Operators()).To(ContainElement("and"))
})

cases := TestCases{
`{ "x": 1, "y": 2 }`: []TestCase{
{"match with a single value", `{ "x": { "$and": [1] } }`, true, false},
{"not match with a single value", `{ "x": { "$and": [2] } }`, false, false},
{"match with a single operation", `{ "x": { "$and": [{ "$eq": 1 }] } }`, true, false},
{"not match with a single operation", `{ "x": { "$and": [{ "$eq": 2 }] } }`, false, false},
{"not match with multiple values", `{ "x": { "$and": [1, 2] } }`, false, false},
{"error without an array of values", `{ "x": { "$and": 1 } }`, false, true},
},
`{ "a": { "x": 1 }, "y": 2 }`: []TestCase{
{"not match when a nested operator doesn't match", `{ "x": { "$and": [{ "$eq": 1 }] } }`, false, false},
{"match when nested operators all match", `{ "a.x": { "$and": [{ "$in": [1, 3] }, { "$in": [1, 2] }] } }`, true, false},
},
}

cases.Generate(nil)
})
28 changes: 28 additions & 0 deletions connor/connor.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package connor

import (
"fmt"
"strings"
)

// Match is the default method used in Connor to match some data to a
// set of conditions.
func Match(conditions, data map[string]interface{}) (bool, error) {
return MatchWith("$eq", conditions, data)
}

// MatchWith can be used to specify the exact operator to use when performing
// a match operation. This is primarily used when building custom operators or
// if you wish to override the behavior of another operator.
func MatchWith(op string, conditions, data interface{}) (bool, error) {
if !strings.HasPrefix(op, "$") {
return false, fmt.Errorf("operator should have '$' prefix")
}

o, ok := opMap[op[1:]]
if !ok {
return false, fmt.Errorf("unknown operator '%s'", op[1:])
}

return o.Evaluate(conditions, data)
}
42 changes: 42 additions & 0 deletions connor/connor_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package connor_test

import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

. "github.com/sourcenetwork/defradb/connor"
)

var _ = Describe("Connor", func() {
Describe("with a malformed operator", func() {
_, err := MatchWith("malformed", nil, nil)

It("should return an error", func() {
Expect(err).ToNot(BeNil())
})

It("should provide a descriptive error", func() {
Expect(err.Error()).To(Equal("operator should have '$' prefix"))
})

It("should return a short error", func() {
Expect(len(err.Error()) < 80).To(BeTrue(), "error message should be less than 80 characters long")
})
})

Describe("with an invalid/unknown operator", func() {
_, err := MatchWith("$invalid", nil, nil)

It("should return an error", func() {
Expect(err).ToNot(BeNil())
})

It("should provide a descriptive error", func() {
Expect(err.Error()).To(Equal("unknown operator 'invalid'"))
})

It("should return a short error", func() {
Expect(len(err.Error()) < 80).To(BeTrue(), "error message should be less than 80 characters long")
})
})
})
30 changes: 30 additions & 0 deletions connor/contains.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package connor

import (
"fmt"
"strings"
)

func init() {
Register(&ContainsOperator{})
}

// The ContainsOperator determines whether a string contains
// the provided substring.
type ContainsOperator struct{}

func (o *ContainsOperator) Name() string {
return "contains"
}

func (o *ContainsOperator) Evaluate(conditions, data interface{}) (bool, error) {
if c, ok := conditions.(string); ok {
if d, ok := data.(string); ok {
return strings.Contains(d, c), nil
} else if data == nil {
return false, nil
}
}

return false, fmt.Errorf("contains operator only works with strings")
}
59 changes: 59 additions & 0 deletions connor/contains_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package connor_test

import (
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"

. "github.com/sourcenetwork/defradb/connor"
)

var _ = Describe("$contains", func() {
It("should be registered as an operator", func() {
Expect(Operators()).To(ContainElement("contains"))
})

cases := TestCases{
`{"x":1}`: []TestCase{
{
"error if a non-string value is provided",
`{"x":{"$contains":"abc"}}`,
false,
true,
},
},
`{"x":"abc"}`: []TestCase{
{
"match a complete string",
`{"x":{"$contains":"abc"}}`,
true,
false,
},
{
"match a partial suffix",
`{"x":{"$contains":"bc"}}`,
true,
false,
},
{
"match a partial prefix",
`{"x":{"$contains":"ab"}}`,
true,
false,
},
{
"not match a different string",
`{"x":{"$contains":"xyz"}}`,
false,
false,
},
{
"not match a missing field",
`{"y":{"$contains":"xyz"}}`,
false,
false,
},
},
}

cases.Generate(nil)
})
Loading

0 comments on commit e828cef

Please sign in to comment.