// Lag calls the stored procedure 'pg_catalog.lag(anyelement, anyelement, integer, anyelement, integer, anyelement) anyelement' on db.
424882
func Lag(db XODB, v0 pgtypes.Anyelement, v1 pgtypes.Anyelement, v2 int, v3 pgtypes.Anyelement, v4 int, v5 pgtypes.Anyelement) (pgtypes.Anyelement, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.lag($1, $2, $3, $4, $5, $6)`

	// run query
	var ret pgtypes.Anyelement
	XOLog(sqlstr, v0, v1, v2, v3, v4, v5)
	err = db.QueryRow(sqlstr, v0, v1, v2, v3, v4, v5).Scan(&ret)
	if err != nil {
		return pgtypes.Anyelement{}, err
	}

	return ret, nil
}
835393
func (s *server) httpEtag(pdoc *doc.Package, pkgs []database.Package, importerCount int, flashMessages []flashMessage) string {
	b := make([]byte, 0, 128)
	b = strconv.AppendInt(b, pdoc.Updated.Unix(), 16)
	b = append(b, 0)
	b = append(b, pdoc.Etag...)
	if importerCount >= 8 {
		importerCount = 8
	}
	b = append(b, 0)
	b = strconv.AppendInt(b, int64(importerCount), 16)
	for _, pkg := range pkgs {
		b = append(b, 0)
		b = append(b, pkg.Path...)
		b = append(b, 0)
		b = append(b, pkg.Synopsis...)
	}
	if s.v.GetBool(ConfigSidebar) {
		b = append(b, "\000xsb"...)
	}
	for _, m := range flashMessages {
		b = append(b, 0)
		b = append(b, m.ID...)
		for _, a := range m.Args {
			b = append(b, 1)
			b = append(b, a...)
		}
	}
	h := md5.New()
	h.Write(b)
	b = h.Sum(b[:0])
	return fmt.Sprintf("\"%x\"", b)
}
202022
func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) {
	b.logger.Debug("postgres/db: enter")
	defer b.logger.Debug("postgres/db: exit")

	b.lock.Lock()
	defer b.lock.Unlock()

	// If we already have a DB, we got it!
	if b.db != nil {
		if err := b.db.Ping(); err == nil {
			return b.db, nil
		}
		// If the ping was unsuccessful, close it and ignore errors as we'll be
		// reestablishing anyways
		b.db.Close()
	}

	// Otherwise, attempt to make connection
	entry, err := s.Get(ctx, "config/connection")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil,
			fmt.Errorf("configure the DB connection with config/connection first")
	}

	var connConfig connectionConfig
	if err := entry.DecodeJSON(&connConfig); err != nil {
		return nil, err
	}

	conn := connConfig.ConnectionURL
	if len(conn) == 0 {
		conn = connConfig.ConnectionString
	}

	// Ensure timezone is set to UTC for all the connections
	if strings.HasPrefix(conn, "postgres://") || strings.HasPrefix(conn, "postgresql://") {
		if strings.Contains(conn, "?") {
			conn += "&timezone=utc"
		} else {
			conn += "?timezone=utc"
		}
	} else {
		conn += " timezone=utc"
	}

	b.db, err = sql.Open("postgres", conn)
	if err != nil {
		return nil, err
	}

	// Set some connection pool settings. We don't need much of this,
	// since the request rate shouldn't be high.
	b.db.SetMaxOpenConns(connConfig.MaxOpenConnections)
	b.db.SetMaxIdleConns(connConfig.MaxIdleConnections)

	return b.db, nil
}
227644
func (db *DB) Use(name string) *Col {
	db.schemaLock.RLock()
	defer db.schemaLock.RUnlock()
	if col, exists := db.cols[name]; exists {
		return col
	}
	return nil
}
663508
func ClockTimestamp(db XODB) (time.Time, error) {
	var err error

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

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

	return ret, nil
}
1248058
func (lag *lag) OrdinalPluralRule(num float64, v uint64) locales.PluralRule {
	return locales.PluralRuleUnknown
}
1306265
func Tidge(db XODB, v0 pgtypes.Tid, v1 pgtypes.Tid) (bool, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.tidge($1, $2)`

	// run query
	var ret bool
	XOLog(sqlstr, v0, v1)
	err = db.QueryRow(sqlstr, v0, v1).Scan(&ret)
	if err != nil {
		return false, err
	}

	return ret, nil
}
128168
func Reltimesend(db XODB, v0 pgtypes.Reltime) ([]byte, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.reltimesend($1)`

	// run query
	var ret []byte
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return nil, err
	}

	return ret, nil
}
1258772
func (db *Database) Visit(sid string, cb func(key string, value interface{})) {
	prefix := makePrefix(sid)

	txn := db.Service.NewTransaction(false)
	defer txn.Discard()

	iter := txn.NewIterator(badger.DefaultIteratorOptions)
	defer iter.Close()

	for iter.Rewind(); iter.ValidForPrefix(prefix); iter.Next() {
		item := iter.Item()
		var value interface{}

		// err := item.Value(func(valueBytes []byte) {
		// 	if err := sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil {
		// 		golog.Error(err)
		// 	}
		// })

		// if err != nil {
		// 	golog.Error(err)
		// 	continue
		// }

		valueBytes, err := item.Value()
		if err != nil {
			continue
		}

		if err = sessions.DefaultTranscoder.Unmarshal(valueBytes, &value); err != nil {
			continue
		}

		cb(string(bytes.TrimPrefix(item.Key(), prefix)), value)
	}
}
896588
func (db *PGStore) load(session *sessions.Session) error {
	var s PGSession

	err := db.selectOne(&s, session.ID)
	if err != nil {
		return err
	}

	return securecookie.DecodeMulti(session.Name(), string(s.Data), &session.Values, db.Codecs...)
}
439896
func (db *database) Update(ctx context.Context, api api) (time.Duration, bool) {
	db.mu.Lock()
	defer db.mu.Unlock()

	// Construct the request.
	var numTypes int
	var s []*pb.FetchThreatListUpdatesRequest_ListUpdateRequest
	for _, td := range db.config.ThreatLists {
		var state []byte
		if row, ok := db.tfu[td]; ok {
			state = row.State
		}

		s = append(s, &pb.FetchThreatListUpdatesRequest_ListUpdateRequest{
			ThreatType:      pb.ThreatType(td.ThreatType),
			PlatformType:    pb.PlatformType(td.PlatformType),
			ThreatEntryType: pb.ThreatEntryType(td.ThreatEntryType),
			Constraints: &pb.FetchThreatListUpdatesRequest_ListUpdateRequest_Constraints{
				SupportedCompressions: db.config.compressionTypes},
			State: state,
		})
		numTypes++
	}
	req := &pb.FetchThreatListUpdatesRequest{
		Client: &pb.ClientInfo{
			ClientId:      db.config.ID,
			ClientVersion: db.config.Version,
		},
		ListUpdateRequests: s,
	}

	// Query the API for the threat list and update the database.
	last := db.config.now()
	resp, err := api.ListUpdate(ctx, req)
	if err != nil {
		db.log.Printf("ListUpdate failure (%d): %v", db.updateAPIErrors+1, err)
		db.setError(err)
		// backoff strategy: MIN((2**N-1 * 15 minutes) * (RAND + 1), 24 hours)
		n := 1 << db.updateAPIErrors
		delay := time.Duration(float64(n) * (rand.Float64() + 1) * float64(baseRetryDelay))
		if delay > maxRetryDelay {
			delay = maxRetryDelay
		}
		db.updateAPIErrors++
		return delay, false
	}
	db.updateAPIErrors = 0

	// add jitter to wait time to avoid all servers lining up
	nextUpdateWait := db.config.UpdatePeriod + time.Duration(rand.Int31n(60)-30)*time.Second
	if resp.MinimumWaitDuration != nil {
		serverMinWait := time.Duration(resp.MinimumWaitDuration.Seconds)*time.Second + time.Duration(resp.MinimumWaitDuration.Nanos)
		if serverMinWait > nextUpdateWait {
			nextUpdateWait = serverMinWait
			db.log.Printf("Server requested next update in %v", nextUpdateWait)
		}
	}
	if len(resp.ListUpdateResponses) != numTypes {
		db.setError(errors.New("safebrowsing: threat list count mismatch"))
		db.log.Printf("invalid server response: got %d, want %d threat lists",
			len(resp.ListUpdateResponses), numTypes)
		return nextUpdateWait, false
	}

	// Update the threat database with the response.
	db.generateThreatsForUpdate()
	if err := db.tfu.update(resp); err != nil {
		db.setError(err)
		db.log.Printf("update failure: %v", err)
		db.tfu = nil
		return nextUpdateWait, false
	}
	dbf := databaseFormat{make(threatsForUpdate), last}
	for td, phs := range db.tfu {
		// Copy of partialHashes before generateThreatsForLookups clobbers it.
		dbf.Table[td] = phs
	}
	db.generateThreatsForLookups(last)

	// Regenerate the database and store it.
	if db.config.DBPath != "" {
		// Semantically, we ignore save errors, but we do log them.
		if err := saveDatabase(db.config.DBPath, dbf); err != nil {
			db.log.Printf("save failure: %v", err)
		}
	}

	return nextUpdateWait, true
}
1248351
func TsLexize(db XODB, v0 pgtypes.Regdictionary, v1 string) (StringSlice, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.ts_lexize($1, $2)`

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

	return ret, nil
}
682212
func (db *SQLDB) Ping() error {
	if err := db.DB.Ping(); err != nil {
		db.Log.Info("msg", "Error database not available", "err", err)
		return err
	}

	return nil
}
105295
func (db *Database) Scan(dest ...interface{}) error {
	defer db.clear()
	ld := len(dest)
	if ld == 0 {
		return errors.New("Required at least one parameter to Scan method")
	}

	var err error
	var rows *sql.Rows
	destIndirect := reflect.Indirect(reflect.ValueOf(dest[0]))
	if db.rawRows == nil {
		// Compile query
		var stmt *sql.Stmt
		// If the destionation is a struct (or a slice of struct)
		// select should select only exported sql fields in the order declared in the struct
		// This thing should go only if the user does not selected with .Select the fields to export
		// Thus only if db.selectFields == ""
		if db.selectFields == "" {
			if ld == 1 { // if is a struct or a slice of struct
				switch destIndirect.Kind() {
				case reflect.Struct:
					db.selectFields = strings.Join(getSQLFields(destIndirect.Interface().(DBModel)), ",")
				case reflect.Slice:
					// hanlde slice of structs and slice of pointers to struct
					sliceType := destIndirect.Type().Elem()
					if sliceType.Kind() == reflect.Ptr {
						return errors.New("Do not use a slice of pointers. Use a slice of real values. E.g. use []int instead of []*int")
					}
					if sliceType.Kind() == reflect.Struct {
						db.selectFields = strings.Join(getSQLFields(reflect.Indirect(reflect.New(sliceType)).Interface().(DBModel)), ",")
					} else {
						panic(sliceType)
					}
				case reflect.Invalid:
					fallthrough
				default:
					panic("Remember to initialize the scan arguments with make() when using pointers")
				}
			}
		}

		if stmt, err = db.db.Prepare(db.buildSelect()); err != nil {
			return err
		}

		// Pass query parameters and execute it
		if rows, err = stmt.Query(append(db.cteSelectValues, db.whereValues...)...); err != nil {
			return err
		}

	} else {
		// Raw has already executed the Query
		rows = db.rawRows
	}

	defer rows.Close()

	if ld == 1 {
		// if is a slice, find first element to decide how to use scan
		// oterwhise use destIndirect
		var defaultElem reflect.Value
		var slicePtr reflect.Value
		switch destIndirect.Kind() {
		// slice
		case reflect.Slice:
			// create a new element, because slice usually is empty. Thus we have to dinamically create it
			defaultElem = reflect.Indirect(reflect.New(destIndirect.Type().Elem()))
			// Create a pointer to a slice value and set it to the slice
			realSlice := reflect.ValueOf(dest[0])
			slicePtr = reflect.New(realSlice.Type())
		default:
			defaultElem = destIndirect
		}

		// if defaultElem is a struct, extract its fields, pass it to scan (extracts the address)
		var interfaces []interface{}
		if defaultElem.Kind() == reflect.Struct {
			fields := getFields(defaultElem.Interface())
			for _, field := range fields {
				interfaces = append(interfaces, reflect.Indirect(defaultElem.FieldByName(field.Name)).Addr().Interface())
			}
		} else {
			// else convert defaultElem into interfaces, use the address
			interfaces = append(interfaces, defaultElem.Addr().Interface())
		}

		for rows.Next() {
			// defaultElem fields are filled by Scan (scan result into fields as variadic arguments)
			if err = rows.Scan(interfaces...); err != nil {
				return err
			}
			// append result to dest (if the destination is a slice)
			if slicePtr.IsValid() {
				destIndirect.Set(reflect.Append(destIndirect, reflect.Indirect(defaultElem)))
				//x := reflect.Indirect(slicePtr.Elem())
				//x.Set(reflect.Append(x, reflect.ValueOf(defaultElem.Interface())))
				//defaultElem = reflect.Zero(destIndirect.Type().Elem())
			}
		}
	} else {
		// Scan(field1, field2, ...)
		for rows.Next() {
			if err = rows.Scan(dest...); err != nil {
				return err
			}
		}
	}
	return nil
}
578702
func (db *database) UpdateLag() time.Duration {
	lag := db.SinceLastUpdate()
	if lag < db.config.UpdatePeriod {
		return 0
	}
	return lag - db.config.UpdatePeriod
}
749214
func (mysqld *Mysqld) OnTerm(f func()) {
	mysqld.mutex.Lock()
	defer mysqld.mutex.Unlock()
	mysqld.onTermFuncs = append(mysqld.onTermFuncs, f)
}
436986
func IntervalEq(db XODB, v0 *time.Duration, v1 *time.Duration) (bool, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.interval_eq($1, $2)`

	// run query
	var ret bool
	XOLog(sqlstr, v0, v1)
	err = db.QueryRow(sqlstr, v0, v1).Scan(&ret)
	if err != nil {
		return false, err
	}

	return ret, nil
}