// PgCurrentXlogInsertLocation calls the stored procedure 'pg_catalog.pg_current_xlog_insert_location() pg_lsn' on db.
190698
func PgCurrentXlogInsertLocation(db XODB) (pgtypes.PgLsn, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.pg_current_xlog_insert_location()`

	// run query
	var ret pgtypes.PgLsn
	XOLog(sqlstr)
	err = db.QueryRow(sqlstr).Scan(&ret)
	if err != nil {
		return pgtypes.PgLsn{}, err
	}

	return ret, nil
}
62460
func (xft *XFastTrie) insert(entry Entry) {
	key := entry.Key() // so we aren't calling this interface method over and over, fucking Go
	n := xft.layers[xft.bits-1][key]
	if n != nil {
		n.entry = entry
		return
	}

	// we need to find a predecessor or successor if it exists
	// to help us set threads later in this method.
	var predecessor, successor *node
	if xft.min != nil && key < xft.min.entry.Key() {
		successor = xft.min
	} else {
		successor = xft.successor(key)
	}

	// only need to find predecessor if successor is nil as otherwise
	// the successor will provide us is the predecessor if it exists.
	if successor == nil {
		if xft.max != nil && key > xft.max.entry.Key() {
			predecessor = xft.max
		} else {
			predecessor = xft.predecessor(key)
		}
	}

	// find the deepest root with a matching prefix, this should
	// save us some time, assuming the hashmap has perfect hashing.
	layer, root := binarySearchHashMaps(xft.layers, key)
	if root == nil {
		n = xft.root
		layer = 0
	} else {
		n = root
	}

	var leftOrRight uint64

	// from the existing node, create new nodes.
	for i := uint8(layer); i < xft.bits; i++ {
		// on 0th, this will be root
		// find out if we need to go left or right
		leftOrRight = (key & positions[xft.diff+i]) >> (xft.bits - 1 - i)
		if n.children[leftOrRight] == nil || isLeaf(n.children[leftOrRight]) {
			var nn *node
			if i < xft.bits-1 {
				nn = newNode(n, nil)
			} else {
				nn = newNode(n, entry)
				xft.num++
			}

			n.children[leftOrRight] = nn
			xft.layers[i][key&masks[xft.diff+i]] = nn // prefix for this layer
		}

		n = n.children[leftOrRight]
	}

	// we need to put the new node where it belongs in the doubly-linked
	// list comprised of all the leaves.
	if successor != nil { // we have to walk predecessor and successor threads
		predecessor = successor.children[0]
		if predecessor != nil {
			predecessor.children[1] = n
			n.children[0] = predecessor
		}
		n.children[1] = successor
		successor.children[0] = n
	} else if predecessor != nil {
		n.children[0] = predecessor
		predecessor.children[1] = n
	}

	// walk up the successor if it exists to set that branch's new
	// predecessor.
	if successor != nil {
		xft.walkUpSuccessor(root, n, successor)
	}

	// walk up the predecessor if it exists to set that branch's
	// new successor.
	if predecessor != nil {
		xft.walkUpPredecessor(root, n, predecessor)
	}

	// finally, walk up our own branch to set both successors
	// and predecessors.
	xft.walkUpNode(root, n, predecessor, successor)

	// and then do a final check against the min/max indicies.
	if xft.max == nil || key > xft.max.entry.Key() {
		xft.max = n
	}

	if xft.min == nil || key < xft.min.entry.Key() {
		xft.min = n
	}
}
1114100
func CurrentDatabase(db XODB) (pgtypes.Name, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.current_database()`

	// run query
	var ret pgtypes.Name
	XOLog(sqlstr)
	err = db.QueryRow(sqlstr).Scan(&ret)
	if err != nil {
		return pgtypes.Name{}, err
	}

	return ret, nil
}
67480
func InsertLogger(h httpx.Handler, g loggerGenerator) httpx.Handler {
	return httpx.HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {
		l := g(ctx, r)

		ctx = logger.WithLogger(ctx, l)
		r = r.WithContext(ctx)

		return h.ServeHTTPContext(ctx, w, r)
	})
}
544509
func TxidCurrent(db XODB) (int64, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.txid_current()`

	// run query
	var ret int64
	XOLog(sqlstr)
	err = db.QueryRow(sqlstr).Scan(&ret)
	if err != nil {
		return 0, err
	}

	return ret, nil
}
1162047
func (sess *Session) InsertBySql(query string, value ...interface{}) *InsertStmt {
	b := InsertBySql(query, value...)
	b.runner = sess
	b.EventReceiver = sess.EventReceiver
	b.Dialect = sess.Dialect
	return b
}
732828
func insertIntoTableExecutor(e *Engine, insertDecl *parser.Decl, conn protocol.EngineConn) error {

	// Get table and concerned attributes and write lock it
	r, attributes, err := getRelation(e, insertDecl.Decl[0])
	if err != nil {
		return err
	}
	r.Lock()
	defer r.Unlock()

	// Check for RETURNING clause
	var returnedID string
	if len(insertDecl.Decl) > 2 {
		for i := range insertDecl.Decl {
			if insertDecl.Decl[i].Token == parser.ReturningToken {
				returnedID = insertDecl.Decl[i].Lexeme
				break
			}
		}
	}

	// Create a new tuple with values
	id, err := insert(r, attributes, insertDecl.Decl[1].Decl, returnedID)
	if err != nil {
		return err
	}

	// if RETURNING decl is not present
	if returnedID != "" {
		conn.WriteRowHeader([]string{returnedID})
		conn.WriteRow([]string{fmt.Sprintf("%v", id)})
		conn.WriteRowEnd()
	} else {
		conn.WriteResult(id, 1)
	}
	return nil
}
954119
func initDBPrivEntry(ctx sessionctx.Context, user string, host string, db string) error {
	sql := fmt.Sprintf(`INSERT INTO %s.%s (Host, User, DB) VALUES ('%s', '%s', '%s')`, mysql.SystemDB, mysql.DBTable, host, user, db)
	_, _, err := ctx.(sqlexec.RestrictedSQLExecutor).ExecRestrictedSQL(ctx, sql)
	return err
}
880153
func (pgb *ChainDB) AddressTxIoCsv(address string) ([][]string, error) {
	rows, err := pgb.AddressRowsCompact(address)
	if err != nil {
		return nil, err
	}

	return MakeCsvAddressRowsCompact(rows), nil

	// ALT implementation, without cache update:

	// Try the address rows cache.
	// hash := pgb.BestBlockHash()
	// rows, validBlock := pgb.AddressCache.Rows(address)
	// cacheCurrent := validBlock != nil && validBlock.Hash == *hash
	// if cacheCurrent && rows != nil {
	// 	log.Debugf("AddressTxIoCsv: Merged address rows cache HIT for %s.", address)

	// 	csvRows := make([][]string, 0, len(rows)+1)
	// 	csvRows = append(csvRows, []string{"tx_hash", "direction", "io_index",
	// 		"valid_mainchain", "value", "time_stamp", "tx_type", "matching_tx_hash"})

	// 	for _, r := range rows {
	// 		var strValidMainchain string
	// 		if r.ValidMainChain {
	// 			strValidMainchain = "1"
	// 		} else {
	// 			strValidMainchain = "0"
	// 		}

	// 		var strDirection string
	// 		if r.IsFunding {
	// 			strDirection = "1"
	// 		} else {
	// 			strDirection = "-1"
	// 		}

	// 		csvRows = append(csvRows, []string{
	// 			r.TxHash,
	// 			strDirection,
	// 			strconv.Itoa(int(r.TxVinVoutIndex)),
	// 			strValidMainchain,
	// 			strconv.FormatFloat(dcrutil.Amount(r.Value).ToCoin(), 'f', -1, 64),
	// 			strconv.FormatInt(r.TxBlockTime.UNIX(), 10),
	// 			txhelpers.TxTypeToString(int(r.TxType)),
	// 			r.MatchingTxHash,
	// 		})
	// 	}

	// 	return csvRows, nil
	// }

	// log.Debugf("AddressTxIoCsv: Merged address rows cache MISS for %s.", address)

	// ctx, cancel := context.WithTimeout(pgb.ctx, pgb.queryTimeout)
	// defer cancel()

	// csvRows, err := retrieveAddressIoCsv(ctx, pgb.db, address)
	// if err != nil {
	// 	return nil, fmt.Errorf("retrieveAddressIoCsv: %v", err)
	// }
	// return csvRows, nil
}
1128064
func (ap *AuthPermission) Insert(db XODB) error {
	var err error

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

	// sql insert query, primary key provided by autoincrement
	const sqlstr = `INSERT INTO auth_permission (` +
		`content_type_id, codename, name` +
		`) VALUES (` +
		`?, ?, ?` +
		`)`

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

	// retrieve id
	id, err := res.LastInsertId()
	if err != nil {
		return err
	}

	// set primary key and existence
	ap.ID = int(id)
	ap._exists = true

	return nil
}
10812
func (s *Section) getInsertLocation(idx int) int {
	for i := idx; i >= 0; i-- {
		if s.file.lines[i].item != nil {
			return i + 1
		}
	}

	return -1
}
588830
func (ag *AuthGroup) Insert(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 django.auth_group (` +
		`name` +
		`) VALUES (` +
		`:1` +
		`) RETURNING id /*lastInsertId*/ INTO :pk`

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

	// retrieve id
	id, err := res.LastInsertId()
	if err != nil {
		return err
	}

	// set primary key and existence
	ag.ID = float64(id)
	ag._exists = true

	return nil
}
778652
func (rt *routingTable) Insert(nd *node) bool {
	rt.Lock()
	defer rt.Unlock()

	if rt.dht.blackList.in(nd.addr.IP.String(), nd.addr.Port) ||
		rt.cachedNodes.Len() >= rt.dht.MaxNodes {
		return false
	}

	var (
		next   *routingTableNode
		bucket *kbucket
	)
	root := rt.root

	for prefixLen := 1; prefixLen <= maxPrefixLength; prefixLen++ {
		next = root.Child(nd.id.Bit(prefixLen - 1))

		if next != nil {
			// If next is not the leaf.
			root = next
		} else if root.KBucket().nodes.Len() < rt.k ||
			root.KBucket().nodes.HasKey(nd.id.RawString()) {

			bucket = root.KBucket()
			isNew := bucket.Insert(nd)

			rt.cachedNodes.Set(nd.addr.String(), nd)
			rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)

			return isNew
		} else if root.KBucket().prefix.Compare(nd.id, prefixLen-1) == 0 {
			// If node has the same prefix with bucket, split it.

			root.Split()

			rt.cachedKBuckets.Delete(root.KBucket().prefix.String())
			root.SetKBucket(nil)

			for i := 0; i < 2; i++ {
				bucket = root.Child(i).KBucket()
				rt.cachedKBuckets.Push(bucket.prefix.String(), bucket)
			}

			root = root.Child(nd.id.Bit(prefixLen - 1))
		} else {
			// Finally, store node as a candidate and fresh the bucket.
			root.KBucket().candidates.PushBack(nd)
			if root.KBucket().candidates.Len() > rt.k {
				root.KBucket().candidates.Remove(
					root.KBucket().candidates.Front())
			}

			go root.KBucket().Fresh(rt.dht)
			return false
		}
	}
	return false
}
166915
func (p Insert) Init(ctx sessionctx.Context) *Insert {
	p.basePlan = newBasePlan(ctx, TypeInsert)
	return &p
}
730792
func (ds *DjangoSession) Insert(db XODB) error {
	var err error

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

	// sql insert query, primary key must be provided
	const sqlstr = `INSERT INTO public.django_session (` +
		`session_key, session_data, expire_date` +
		`) VALUES (` +
		`$1, $2, $3` +
		`)`

	// run query
	XOLog(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate)
	err = db.QueryRow(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate).Scan(&ds.SessionKey)
	if err != nil {
		return err
	}

	// set existence
	ds._exists = true

	return nil
}
924280
func (env *environ) MaybeWriteLXDProfile(pName string, put *charm.LXDProfile) error {
	return nil
}
970993
func (h *sqlHelper) Insert(
	logger lager.Logger,
	q Queryable,
	table string,
	attributes SQLAttributes,
) (sql.Result, error) {
	attributeCount := len(attributes)
	if attributeCount == 0 {
		return nil, nil
	}

	query := fmt.Sprintf("INSERT INTO %s\n", table)
	attributeNames := make([]string, 0, attributeCount)
	attributeBindings := make([]string, 0, attributeCount)
	bindings := make([]interface{}, 0, attributeCount)

	for column, value := range attributes {
		attributeNames = append(attributeNames, column)
		attributeBindings = append(attributeBindings, "?")
		bindings = append(bindings, value)
	}
	query += fmt.Sprintf("(%s)", strings.Join(attributeNames, ", "))
	query += fmt.Sprintf("VALUES (%s)", strings.Join(attributeBindings, ", "))

	return q.Exec(h.Rebind(query), bindings...)
}