SHARE
TWEET

Untitled

a guest Sep 17th, 2019 101 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // creates the string to send to the database and execute it returning an error
  2. func bulkCreateRecordsV2(d []map[string]interface{}) error {
  3.     if len(d) <= 0 {
  4.         return errors.New("no data to process")
  5.     }
  6.     var keyStrings []string
  7.     valueStrings := make([]string, 0, len(d)) //allocate space
  8.     var valueArgs []interface{}
  9.     //get keys
  10.     for key, _ := range d[0] {
  11.         keyStrings = append(keyStrings, key)
  12.     }
  13.     // for each map
  14.     for _, v := range d {
  15.         nofk := len(v)                          // get the len of keys in the map
  16.         tmpQstnMrk := make([]string, 0, len(v)) // tmp variable to store the question marks for every key
  17.         for n := 0; n < nofk; n++ { // for each key
  18.             tmpQstnMrk = append(tmpQstnMrk, "?") // add a "?" to the temp variable
  19.         }
  20.         tmpToAppend := strings.Join(tmpQstnMrk, ",")                          // join all the ? with a , in between ?,?,?,?...
  21.         valueStrings = append(valueStrings, fmt.Sprintf("(%s)", tmpToAppend)) // append the (?,?,?,?) to the valueStrings slice
  22.         for _, strKey := range keyStrings {
  23.             valueArgs = append(valueArgs, v[strKey])
  24.         }
  25.  
  26.     }
  27.     smt := `INSERT INTO mytable(%s) VALUES %s`
  28.     smt = fmt.Sprintf(smt, strings.Join(keyStrings, ","), strings.Join(valueStrings, ","))
  29.     fmt.Println(smt)
  30.     tx := db.GetDB().Begin()
  31.     if err := tx.Exec(smt, valueArgs...).Error; err != nil {
  32.         tx.Rollback()
  33.         return err
  34.     }
  35.  
  36.     tx.Commit()
  37.     return nil
  38. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top