//Generates the INSERT sql with (ON CONFLICT/ON DUPLICATE KEY) clause, and returns an Exec struct with the sql set to the INSERT statement
//    db.From("test").InsertConflict(DoNothing(), Record{"name":"Bob"}).Exec()
//
//See Dataset#Upsert for arguments
556683
func (me *Dataset) InsertConflict(c ConflictExpression, i ...interface{}) *CrudExec {
	sql, args, err := me.ToInsertConflictSql(c, i...)
	return newCrudExec(me.database, err, sql, args...)
}
907255
func (t *Txn) Insert(k []byte, v interface{}) (interface{}, bool) {
	newRoot, oldVal, didUpdate := t.insert(t.root, k, k, v)
	if newRoot != nil {
		t.root = newRoot
	}
	if !didUpdate {
		t.size++
	}
	return oldVal, didUpdate
}
82023
func (ag *AuthGroup) Upsert(db XODB) error {
	var err error

	// if already exist, bail
	if ag._exists {
		return errors.New("insert failed: already exists")
	}

	// sql query
	const sqlstr = `INSERT INTO public.auth_group (` +
		`id, name` +
		`) VALUES (` +
		`$1, $2` +
		`) ON CONFLICT (id) DO UPDATE SET (` +
		`id, name` +
		`) = (` +
		`EXCLUDED.id, EXCLUDED.name` +
		`)`

	// run query
	XOLog(sqlstr, ag.ID, ag.Name)
	_, err = db.Exec(sqlstr, ag.ID, ag.Name)
	if err != nil {
		return err
	}

	// set existence
	ag._exists = true

	return nil
}
263086
func (rev *Revocation) Insert(tx *sql.Tx) error {
	_, err := tx.Exec(`INSERT INTO revocations (ski, revoked_at, mechanism, reason) VALUES (?, ?, ?, ?)`, rev.SKI, rev.RevokedAt, rev.Mechanism, rev.Reason)
	return err
}
358750
func (t *Txn) insert(n *Node, k, search []byte, v interface{}) (*Node, interface{}, bool) {
	// Handle key exhaustion
	if len(search) == 0 {
		var oldVal interface{}
		didUpdate := false
		if n.isLeaf() {
			oldVal = n.leaf.val
			didUpdate = true
		}

		nc := t.writeNode(n, true)
		nc.leaf = &leafNode{
			mutateCh: make(chan struct{}),
			key:      k,
			val:      v,
		}
		return nc, oldVal, didUpdate
	}

	// Look for the edge
	idx, child := n.getEdge(search[0])

	// No edge, create one
	if child == nil {
		e := edge{
			label: search[0],
			node: &Node{
				mutateCh: make(chan struct{}),
				leaf: &leafNode{
					mutateCh: make(chan struct{}),
					key:      k,
					val:      v,
				},
				prefix: search,
			},
		}
		nc := t.writeNode(n, false)
		nc.addEdge(e)
		return nc, nil, false
	}

	// Determine longest prefix of the search key on match
	commonPrefix := longestPrefix(search, child.prefix)
	if commonPrefix == len(child.prefix) {
		search = search[commonPrefix:]
		newChild, oldVal, didUpdate := t.insert(child, k, search, v)
		if newChild != nil {
			nc := t.writeNode(n, false)
			nc.edges[idx].node = newChild
			return nc, oldVal, didUpdate
		}
		return nil, oldVal, didUpdate
	}

	// Split the node
	nc := t.writeNode(n, false)
	splitNode := &Node{
		mutateCh: make(chan struct{}),
		prefix:   search[:commonPrefix],
	}
	nc.replaceEdge(edge{
		label: search[0],
		node:  splitNode,
	})

	// Restore the existing child node
	modChild := t.writeNode(child, false)
	splitNode.addEdge(edge{
		label: modChild.prefix[commonPrefix],
		node:  modChild,
	})
	modChild.prefix = modChild.prefix[commonPrefix:]

	// Create a new leaf node
	leaf := &leafNode{
		mutateCh: make(chan struct{}),
		key:      k,
		val:      v,
	}

	// If the new key is a subset, add to to this node
	search = search[commonPrefix:]
	if len(search) == 0 {
		splitNode.leaf = leaf
		return nc, nil, false
	}

	// Create a new edge for the node
	splitNode.addEdge(edge{
		label: search[0],
		node: &Node{
			mutateCh: make(chan struct{}),
			leaf:     leaf,
			prefix:   search,
		},
	})
	return nc, nil, false
}
314534
func InsertBySql(query string, value ...interface{}) *InsertStmt {
	return &InsertStmt{
		raw: raw{
			Query: query,
			Value: value,
		},
	}
}
238262
func (b *BaseBuilder) Insert(table string, cols Params) *Query {
	names := make([]string, 0, len(cols))
	for name := range cols {
		names = append(names, name)
	}
	sort.Strings(names)

	params := Params{}
	columns := make([]string, 0, len(names))
	values := make([]string, 0, len(names))
	for _, name := range names {
		columns = append(columns, b.db.QuoteColumnName(name))
		value := cols[name]
		if e, ok := value.(Expression); ok {
			values = append(values, e.Build(b.db, params))
		} else {
			values = append(values, fmt.Sprintf("{:p%v}", len(params)))
			params[fmt.Sprintf("p%v", len(params))] = value
		}
	}

	var sql string
	if len(names) == 0 {
		sql = fmt.Sprintf("INSERT INTO %v DEFAULT VALUES", b.db.QuoteTableName(table))
	} else {
		sql = fmt.Sprintf("INSERT INTO %v (%v) VALUES (%v)",
			b.db.QuoteTableName(table),
			strings.Join(columns, ", "),
			strings.Join(values, ", "),
		)
	}

	return b.NewQuery(sql).Bind(params)
}
287468
func (me *Dataset) Insert(i ...interface{}) *CrudExec {
	sql, args, err := me.ToInsertSql(i...)
	return newCrudExec(me.database, err, sql, args...)
}
906377
func (db *Storage) Insert(ctxt Context, val interface{}) error {
	ctxt = debugContext(ctxt)
	t, _, err := db.findType(val, "Insert")
	if err != nil {
		return err
	}

	var args []interface{}
	rval := reflect.ValueOf(val).Elem()
	var rowcol *field
	for _, col := range t.fields {
		rv := rval.FieldByIndex(col.index)
		if col.rowid && rv.Int() == 0 {
			rowcol = col
			args = append(args, nil)
		} else {
			args = append(args, rval.FieldByIndex(col.index).Interface())
		}
	}

	var buf bytes.Buffer
	if t.fts4 {
		fmt.Fprintf(&buf, "update %q", t.name)
		fmt.Fprintf(&buf, " set ")
		sep := ""
		var args1 []interface{}
		for i, col := range t.fields {
			if !col.key {
				fmt.Fprintf(&buf, "%s%q = ?", sep, col.name)
				sep = ", "
				args1 = append(args1, args[i])
			}
		}
		fmt.Fprintf(&buf, " where ")
		sep = ""
		for i, col := range t.fields {
			if col.key {
				fmt.Fprintf(&buf, "%s%q = ?", sep, col.name)
				sep = ", "
				args1 = append(args1, args[i])
			}
		}

		res, err := ctxt.Exec(buf.String(), args1...)
		if err != nil {
			return err
		}
		count, err := res.RowsAffected()
		if err != nil {
			return err
		}
		if count > 0 {
			return nil
		}
		// fall through to ordinary insert command
		buf.Reset()
	}

	fmt.Fprintf(&buf, "insert or replace into %q (", t.name)
	for i, col := range t.fields {
		if i > 0 {
			fmt.Fprintf(&buf, ", ")
		}
		fmt.Fprintf(&buf, "%q", col.name)
	}
	fmt.Fprintf(&buf, ") values (")
	for i := range t.fields {
		if i > 0 {
			fmt.Fprintf(&buf, ", ")
		}
		fmt.Fprintf(&buf, "?")
	}
	fmt.Fprintf(&buf, ")")

	res, err := ctxt.Exec(buf.String(), args...)
	if err != nil {
		return err
	}
	if rowcol != nil {
		id, err := res.LastInsertId()
		if err != nil {
			return err
		}
		rval.FieldByIndex(rowcol.index).SetInt(id)
	}
	return nil
}
259181
func (ap *AuthPermission) Upsert(db XODB) error {
	var err error

	// if already exist, bail
	if ap._exists {
		return errors.New("insert failed: already exists")
	}

	// sql query
	const sqlstr = `INSERT INTO public.auth_permission (` +
		`id, name, content_type_id, codename` +
		`) VALUES (` +
		`$1, $2, $3, $4` +
		`) ON CONFLICT (id) DO UPDATE SET (` +
		`id, name, content_type_id, codename` +
		`) = (` +
		`EXCLUDED.id, EXCLUDED.name, EXCLUDED.content_type_id, EXCLUDED.codename` +
		`)`

	// run query
	XOLog(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
	_, err = db.Exec(sqlstr, ap.ID, ap.Name, ap.ContentTypeID, ap.Codename)
	if err != nil {
		return err
	}

	// set existence
	ap._exists = true

	return nil
}
36483
func (iv InsertValues) EncodeSQL(buf *strings.Builder) {
	for i, rows := range iv {
		if i != 0 {
			buf.WriteString(", ")
		}
		buf.WriteByte('(')
		for j, bv := range rows {
			if j != 0 {
				buf.WriteString(", ")
			}
			bv.EncodeSQL(buf)
		}
		buf.WriteByte(')')
	}
}
881962
func (db *DB) Exec(query string, args ...interface{}) (Result, error) {
	var res Result
	var err error
	for i := 0; i < maxBadConnRetries; i++ {
		res, err = db.exec(query, args)
		if err != driver.ErrBadConn {
			break
		}
	}
	return res, err
}
383394
func (me *DefaultAdapter) InsertBeginSql(buf *SqlBuilder, o ConflictExpression) error {
	if me.SupportsInsertIgnoreSyntax() && o != nil {
		buf.Write(me.InsertIgnoreClause)
	} else {
		buf.Write(me.InsertClause)
	}
	return nil
}
513346
func (db *Database) Exec(query string, args ...interface{}) error {
	defer db.clear()
	stmt := db.commonRawQuery(query, args...)
	_, e := stmt.Exec(db.whereValues...)
	return e
}
119147
func (b *Builder) Insert(eq ...interface{}) *Builder {
	if len(eq) > 0 {
		var paramType = -1
		for _, e := range eq {
			switch t := e.(type) {
			case Eq:
				if paramType == -1 {
					paramType = 0
				}
				if paramType != 0 {
					break
				}
				for k, v := range t {
					b.insertCols = append(b.insertCols, k)
					b.insertVals = append(b.insertVals, v)
				}
			case string:
				if paramType == -1 {
					paramType = 1
				}
				if paramType != 1 {
					break
				}
				b.insertCols = append(b.insertCols, t)
			}
		}
	}

	if len(b.insertCols) == len(b.insertVals) {
		sort.Sort(insertColsSorter{
			cols: b.insertCols,
			vals: b.insertVals,
		})
	}
	b.optype = insertType
	return b
}
342267
func (r *Release) Insert(tx *sql.Tx) error {
	if !r.validBundle() {
		return r.errInvalidBundle()
	}

	query := fmt.Sprintf("INSERT INTO %s_releases (version, released_at) VALUES (?, ?)",
		r.table())
	_, err := tx.Exec(query, r.Version, r.ReleasedAt)
	return err
}
773047
func (q *Query) Exec() error {
	return q.Connection.timeFunc("Exec", func() error {
		sql, args := q.ToSQL(nil)
		log(logging.SQL, sql, args...)
		_, err := q.Connection.Store.Exec(sql, args...)
		return err
	})
}