Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/xgfone/go-op
Provide a common condition and setter operation.
https://github.com/xgfone/go-op
condition conditions go golang operation operations operator operators set setter setters
Last synced: 18 days ago
JSON representation
Provide a common condition and setter operation.
- Host: GitHub
- URL: https://github.com/xgfone/go-op
- Owner: xgfone
- License: apache-2.0
- Created: 2023-04-27T16:29:32.000Z (over 1 year ago)
- Default Branch: master
- Last Pushed: 2024-11-22T09:21:44.000Z (about 1 month ago)
- Last Synced: 2024-11-22T10:25:34.324Z (about 1 month ago)
- Topics: condition, conditions, go, golang, operation, operations, operator, operators, set, setter, setters
- Language: Go
- Homepage:
- Size: 65.4 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# Go Operation [![Build Status](https://github.com/xgfone/go-op/actions/workflows/go.yml/badge.svg)](https://github.com/xgfone/go-op/actions/workflows/go.yml) [![GoDoc](https://pkg.go.dev/badge/github.com/xgfone/go-op)](https://pkg.go.dev/github.com/xgfone/go-op) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg?style=flat-square)](https://raw.githubusercontent.com/xgfone/go-op/master/LICENSE)
Provide a common operation, such as `Condition` and `Updater`, supporting Go `1.18+`.
## Install
```shell
$ go get -u github.com/xgfone/go-op
```## Example
```go
package mainimport (
"fmt"
"strings""github.com/xgfone/go-op"
)func main() {
// Manage the global op builders.
builders := make(map[string]func(op.Op) string, 4)
buildOper := func(op op.Oper) string { return builders[op.Op().Op](op.Op()) }
register := func(op string, f func(op.Op) string) { builders[op] = f }// Register the Op builders.
buildSignEq := func(op op.Op) string {
if s, ok := op.Val.(string); ok {
return fmt.Sprintf("`%s`='%s'", op.Key, s)
}
return fmt.Sprintf("`%s`=%v", op.Key, op.Val)
}
register(op.CondOpNotEqual, buildSignEq)
register(op.CondOpEqual, buildSignEq)
register(op.UpdateOpAdd, buildSignEq)
register(op.UpdateOpSet, buildSignEq)// Define a UPDATE sql builder.
buildUpdateSQL := func(table string, updaters []op.Updater, conds []op.Condition) string {
sets := make([]string, len(updaters))
for i, up := range updaters {
sets[i] = buildOper(up)
}wheres := make([]string, len(conds))
for i, cond := range conds {
wheres[i] = buildOper(cond)
}return fmt.Sprintf("UPDATE `%s` SET %s WHERE %s",
table, strings.Join(sets, ", "),
strings.Join(wheres, " AND "))
}// build the UPDATE sql.
ColumnID := op.Key("id")
ColumnAge := op.Key("age")
sql := buildUpdateSQL("user",
[]op.Updater{ColumnAge.Add(1), op.Set("name", "Aaron")},
[]op.Condition{ColumnID.Eq(123), op.NotEq("is_deleted", false)},
)fmt.Println(sql)
// Output:
// UPDATE `user` SET `age`=1, `name`='Aaron' WHERE `id`=123 AND `is_deleted`=false
}
```