123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- package nosql
- import (
- "context"
- "encoding/json"
- "fmt"
- "github.com/jackc/pgx/v5"
- )
- // OpenTXMethod is callback functon to open transaction in NoSQL object
- type OpenTXMethod func(context.Context) (pgx.Tx, error)
- // NoSQL object
- type NoSQL struct {
- openMethod OpenTXMethod
- }
- // New is NoSQL object constructor
- func New(openMethod OpenTXMethod) *NoSQL {
- return &NoSQL{openMethod}
- }
- // CallJSON accepts raw json bytes and returns result raw json bytes
- func (_self *NoSQL) CallJSON(ctx context.Context, function string, rawJSON []byte) (resRawJSON []byte, err error) {
- // open tx
- var tx pgx.Tx
- if tx, err = _self.openMethod(ctx); err == nil {
- // execute query and scan result
- row := tx.QueryRow(context.Background(), fmt.Sprintf("select * from %v($1)", function), rawJSON)
- if err = row.Scan(&resRawJSON); err != nil {
- tx.Rollback(context.Background())
- return
- }
- err = tx.Commit(context.Background())
- }
- return
- }
- // CallObjParam accepts interface{} object and returns result raw json bytes
- func (_self *NoSQL) CallObjParam(ctx context.Context, function string, data interface{}) (resRawJSON []byte, err error) {
- // convert incoming object to raw json
- var raw []byte
- if raw, err = json.Marshal(data); err != nil {
- return
- }
- return _self.CallJSON(ctx, function, raw)
- }
- // Call accepts interface{} object and returns result interface{}
- func (_self *NoSQL) Call(ctx context.Context, function string, data interface{}) (res interface{}, err error) {
- var resRawJSON []byte
- if resRawJSON, err = _self.CallObjParam(ctx, function, data); err == nil {
- // convert raw result data to obj
- if len(resRawJSON) > 0 {
- err = json.Unmarshal(resRawJSON, &res)
- }
- }
- return
- }
- func (_self *NoSQL) CallObject(ctx context.Context, function string, data interface{}, resultObject interface{}) (err error) {
- var resRawJSON []byte
- if resRawJSON, err = _self.CallObjParam(ctx, function, data); err == nil {
- // convert raw result data to result object
- err = json.Unmarshal(resRawJSON, resultObject)
- }
- return
- }
|