You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

152 lines
4.7 KiB

  1. package db
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "math/big"
  6. "reflect"
  7. "strings"
  8. "github.com/gobuffalo/packr/v2"
  9. "github.com/hermeznetwork/hermez-node/log"
  10. "github.com/jmoiron/sqlx"
  11. migrate "github.com/rubenv/sql-migrate"
  12. "github.com/russross/meddler"
  13. )
  14. // InitSQLDB runs migrations and registers meddlers
  15. func InitSQLDB(port int, host, user, password, name string) (*sqlx.DB, error) {
  16. // Init meddler
  17. initMeddler()
  18. meddler.Default = meddler.PostgreSQL
  19. // Stablish connection
  20. psqlconn := fmt.Sprintf(
  21. "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
  22. host,
  23. port,
  24. user,
  25. password,
  26. name,
  27. )
  28. db, err := sqlx.Connect("postgres", psqlconn)
  29. if err != nil {
  30. return nil, err
  31. }
  32. // Run DB migrations
  33. migrations := &migrate.PackrMigrationSource{
  34. Box: packr.New("hermez-db-migrations", "./migrations"),
  35. }
  36. nMigrations, err := migrate.Exec(db.DB, "postgres", migrations, migrate.Up)
  37. if err != nil {
  38. return nil, err
  39. }
  40. log.Info("successfully runt ", nMigrations, " migrations")
  41. return db, nil
  42. }
  43. // initMeddler registers tags to be used to read/write from SQL DBs using meddler
  44. func initMeddler() {
  45. meddler.Register("bigint", BigIntMeddler{})
  46. meddler.Register("bigintnull", BigIntNullMeddler{})
  47. }
  48. // BulkInsert performs a bulk insert with a single statement into the specified table. Example:
  49. // `db.BulkInsert(myDB, "INSERT INTO block (eth_block_num, timestamp, hash) VALUES %s", blocks[:])`
  50. // Note that all the columns must be specified in the query, and they must be in the same order as in the table.
  51. func BulkInsert(db meddler.DB, q string, args interface{}) error {
  52. arrayValue := reflect.ValueOf(args)
  53. arrayLen := arrayValue.Len()
  54. valueStrings := make([]string, 0, arrayLen)
  55. var arglist = make([]interface{}, 0)
  56. for i := 0; i < arrayLen; i++ {
  57. arg := arrayValue.Index(i).Addr().Interface()
  58. elemArglist, err := meddler.Default.Values(arg, true)
  59. if err != nil {
  60. return err
  61. }
  62. arglist = append(arglist, elemArglist...)
  63. value := "("
  64. for j := 0; j < len(elemArglist); j++ {
  65. value += fmt.Sprintf("$%d, ", i*len(elemArglist)+j+1)
  66. }
  67. value = value[:len(value)-2] + ")"
  68. valueStrings = append(valueStrings, value)
  69. }
  70. stmt := fmt.Sprintf(q, strings.Join(valueStrings, ","))
  71. _, err := db.Exec(stmt, arglist...)
  72. return err
  73. }
  74. // BigIntMeddler encodes or decodes the field value to or from JSON
  75. type BigIntMeddler struct{}
  76. // PreRead is called before a Scan operation for fields that have the BigIntMeddler
  77. func (b BigIntMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
  78. // give a pointer to a byte buffer to grab the raw data
  79. return new(string), nil
  80. }
  81. // PostRead is called after a Scan operation for fields that have the BigIntMeddler
  82. func (b BigIntMeddler) PostRead(fieldPtr, scanTarget interface{}) error {
  83. ptr := scanTarget.(*string)
  84. if ptr == nil {
  85. return fmt.Errorf("BigIntMeddler.PostRead: nil pointer")
  86. }
  87. data, err := base64.StdEncoding.DecodeString(*ptr)
  88. if err != nil {
  89. return fmt.Errorf("big.Int decode error: %v", err)
  90. }
  91. field := fieldPtr.(**big.Int)
  92. *field = new(big.Int).SetBytes(data)
  93. return nil
  94. }
  95. // PreWrite is called before an Insert or Update operation for fields that have the BigIntMeddler
  96. func (b BigIntMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) {
  97. field := fieldPtr.(*big.Int)
  98. str := base64.StdEncoding.EncodeToString(field.Bytes())
  99. return str, nil
  100. }
  101. // BigIntNullMeddler encodes or decodes the field value to or from JSON
  102. type BigIntNullMeddler struct{}
  103. // PreRead is called before a Scan operation for fields that have the BigIntNullMeddler
  104. func (b BigIntNullMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
  105. return &fieldAddr, nil
  106. }
  107. // PostRead is called after a Scan operation for fields that have the BigIntNullMeddler
  108. func (b BigIntNullMeddler) PostRead(fieldPtr, scanTarget interface{}) error {
  109. sv := reflect.ValueOf(scanTarget)
  110. if sv.Elem().IsNil() {
  111. // null column, so set target to be zero value
  112. fv := reflect.ValueOf(fieldPtr)
  113. fv.Elem().Set(reflect.Zero(fv.Elem().Type()))
  114. return nil
  115. }
  116. // not null
  117. encoded := new([]byte)
  118. refEnc := reflect.ValueOf(encoded)
  119. refEnc.Elem().Set(sv.Elem().Elem())
  120. data, err := base64.StdEncoding.DecodeString(string(*encoded))
  121. if err != nil {
  122. return fmt.Errorf("big.Int decode error: %v", err)
  123. }
  124. field := fieldPtr.(**big.Int)
  125. *field = new(big.Int).SetBytes(data)
  126. return nil
  127. }
  128. // PreWrite is called before an Insert or Update operation for fields that have the BigIntNullMeddler
  129. func (b BigIntNullMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) {
  130. field := fieldPtr.(*big.Int)
  131. if field == nil {
  132. return nil, nil
  133. }
  134. return base64.StdEncoding.EncodeToString(field.Bytes()), nil
  135. }