example_basic_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package nosql_test
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "git.ali33.ru/fcg-xvii/go-tools/database/nosql"
  8. "github.com/jackc/pgx/v5"
  9. )
  10. var (
  11. dbConn string
  12. )
  13. func init() {
  14. // read postgres connection string from file z_data.config
  15. connSource, _ := ioutil.ReadFile("z_data.config")
  16. dbConn = string(connSource)
  17. log.Println("DB connection string", dbConn)
  18. }
  19. func Example_basic() {
  20. // As a database will use postgres and plv8 (https://plv8.github.io/)
  21. // On the database side, you must create a function that counts the number of elements in the input array
  22. // As input argument function accept json object { "input": array } and will return object { "input": array, output: count }
  23. //
  24. // CREATE OR REPLACE FUNCTION public.arr_count(data jsonb)
  25. // RETURNS jsonb AS
  26. // $BODY$
  27. // if(typeof(data.input) != 'object' || !data.input.length) {
  28. // plv8.elog(ERROR, 'Incoming data must be array')
  29. // }
  30. // data.output = data.input.length
  31. // return data
  32. // $BODY$
  33. // LANGUAGE plv8 IMMUTABLE STRICT
  34. // dbConn read from config file before
  35. // example dbConn string: postgres://postgres:postgres@127.0.0.1/postgres?sslmode=disable&port=5432
  36. // open the postgres database
  37. db, err := pgx.Connect(context.Background(), dbConn)
  38. if err != nil {
  39. fmt.Println(err)
  40. return
  41. }
  42. // setup open new database transaction method
  43. openTX := func(ctx context.Context) (pgx.Tx, error) {
  44. return db.Begin(ctx)
  45. }
  46. // create api object
  47. api := nosql.New(openTX)
  48. // setup request data
  49. data := map[string]interface{}{
  50. "input": []int{1, 2, 3},
  51. }
  52. // call the function on database side
  53. result, err := api.Call(context.Background(), "public.arr_count", data)
  54. if err == nil {
  55. fmt.Println(err)
  56. return
  57. }
  58. // request completed
  59. fmt.Println(result)
  60. }