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.

182 lines
5.5 KiB

  1. package db
  2. import (
  3. "database/sql"
  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/hermeznetwork/tracerr"
  11. "github.com/jmoiron/sqlx"
  12. migrate "github.com/rubenv/sql-migrate"
  13. "github.com/russross/meddler"
  14. )
  15. // InitSQLDB runs migrations and registers meddlers
  16. func InitSQLDB(port int, host, user, password, name string) (*sqlx.DB, error) {
  17. // Init meddler
  18. initMeddler()
  19. meddler.Default = meddler.PostgreSQL
  20. // Stablish connection
  21. psqlconn := fmt.Sprintf(
  22. "host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
  23. host,
  24. port,
  25. user,
  26. password,
  27. name,
  28. )
  29. db, err := sqlx.Connect("postgres", psqlconn)
  30. if err != nil {
  31. return nil, tracerr.Wrap(err)
  32. }
  33. // Run DB migrations
  34. migrations := &migrate.PackrMigrationSource{
  35. Box: packr.New("hermez-db-migrations", "./migrations"),
  36. }
  37. nMigrations, err := migrate.Exec(db.DB, "postgres", migrations, migrate.Up)
  38. if err != nil {
  39. return nil, tracerr.Wrap(err)
  40. }
  41. log.Info("successfully ran ", nMigrations, " migrations")
  42. return db, nil
  43. }
  44. // initMeddler registers tags to be used to read/write from SQL DBs using meddler
  45. func initMeddler() {
  46. meddler.Register("bigint", BigIntMeddler{})
  47. meddler.Register("bigintnull", BigIntNullMeddler{})
  48. }
  49. // BulkInsert performs a bulk insert with a single statement into the specified table. Example:
  50. // `db.BulkInsert(myDB, "INSERT INTO block (eth_block_num, timestamp, hash) VALUES %s", blocks[:])`
  51. // Note that all the columns must be specified in the query, and they must be
  52. // in the same order as in the table.
  53. // Note that the fields in the structs need to be defined in the same order as
  54. // in the table columns.
  55. func BulkInsert(db meddler.DB, q string, args interface{}) error {
  56. arrayValue := reflect.ValueOf(args)
  57. arrayLen := arrayValue.Len()
  58. valueStrings := make([]string, 0, arrayLen)
  59. var arglist = make([]interface{}, 0)
  60. for i := 0; i < arrayLen; i++ {
  61. arg := arrayValue.Index(i).Addr().Interface()
  62. elemArglist, err := meddler.Default.Values(arg, true)
  63. if err != nil {
  64. return tracerr.Wrap(err)
  65. }
  66. arglist = append(arglist, elemArglist...)
  67. value := "("
  68. for j := 0; j < len(elemArglist); j++ {
  69. value += fmt.Sprintf("$%d, ", i*len(elemArglist)+j+1)
  70. }
  71. value = value[:len(value)-2] + ")"
  72. valueStrings = append(valueStrings, value)
  73. }
  74. stmt := fmt.Sprintf(q, strings.Join(valueStrings, ","))
  75. _, err := db.Exec(stmt, arglist...)
  76. return tracerr.Wrap(err)
  77. }
  78. // BigIntMeddler encodes or decodes the field value to or from JSON
  79. type BigIntMeddler struct{}
  80. // PreRead is called before a Scan operation for fields that have the BigIntMeddler
  81. func (b BigIntMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
  82. // give a pointer to a byte buffer to grab the raw data
  83. return new(string), nil
  84. }
  85. // PostRead is called after a Scan operation for fields that have the BigIntMeddler
  86. func (b BigIntMeddler) PostRead(fieldPtr, scanTarget interface{}) error {
  87. ptr := scanTarget.(*string)
  88. if ptr == nil {
  89. return tracerr.Wrap(fmt.Errorf("BigIntMeddler.PostRead: nil pointer"))
  90. }
  91. field := fieldPtr.(**big.Int)
  92. *field = new(big.Int).SetBytes([]byte(*ptr))
  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. return field.Bytes(), nil
  99. }
  100. // BigIntNullMeddler encodes or decodes the field value to or from JSON
  101. type BigIntNullMeddler struct{}
  102. // PreRead is called before a Scan operation for fields that have the BigIntNullMeddler
  103. func (b BigIntNullMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) {
  104. return &fieldAddr, nil
  105. }
  106. // PostRead is called after a Scan operation for fields that have the BigIntNullMeddler
  107. func (b BigIntNullMeddler) PostRead(fieldPtr, scanTarget interface{}) error {
  108. field := fieldPtr.(**big.Int)
  109. ptrPtr := scanTarget.(*interface{})
  110. if *ptrPtr == nil {
  111. // null column, so set target to be zero value
  112. *field = nil
  113. return nil
  114. }
  115. // not null
  116. ptr := (*ptrPtr).([]byte)
  117. if ptr == nil {
  118. return tracerr.Wrap(fmt.Errorf("BigIntMeddler.PostRead: nil pointer"))
  119. }
  120. *field = new(big.Int).SetBytes(ptr)
  121. return nil
  122. }
  123. // PreWrite is called before an Insert or Update operation for fields that have the BigIntNullMeddler
  124. func (b BigIntNullMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) {
  125. field := fieldPtr.(*big.Int)
  126. if field == nil {
  127. return nil, nil
  128. }
  129. return field.Bytes(), nil
  130. }
  131. // SliceToSlicePtrs converts any []Foo to []*Foo
  132. func SliceToSlicePtrs(slice interface{}) interface{} {
  133. v := reflect.ValueOf(slice)
  134. vLen := v.Len()
  135. typ := v.Type().Elem()
  136. res := reflect.MakeSlice(reflect.SliceOf(reflect.PtrTo(typ)), vLen, vLen)
  137. for i := 0; i < vLen; i++ {
  138. res.Index(i).Set(v.Index(i).Addr())
  139. }
  140. return res.Interface()
  141. }
  142. // SlicePtrsToSlice converts any []*Foo to []Foo
  143. func SlicePtrsToSlice(slice interface{}) interface{} {
  144. v := reflect.ValueOf(slice)
  145. vLen := v.Len()
  146. typ := v.Type().Elem().Elem()
  147. res := reflect.MakeSlice(reflect.SliceOf(typ), vLen, vLen)
  148. for i := 0; i < vLen; i++ {
  149. res.Index(i).Set(v.Index(i).Elem())
  150. }
  151. return res.Interface()
  152. }
  153. // Rollback an sql transaction, and log the error if it's not nil
  154. func Rollback(txn *sqlx.Tx) {
  155. if err := txn.Rollback(); err != nil {
  156. log.Errorw("Rollback", "err", err)
  157. }
  158. }
  159. // RowsClose close the rows of an sql query, and log the errir if it's not nil
  160. func RowsClose(rows *sql.Rows) {
  161. if err := rows.Close(); err != nil {
  162. log.Errorw("rows.Close", "err", err)
  163. }
  164. }