// When passed as an option to NewDB(), determines whether to allow string queries.
322667
func AllowStringQueries(allow bool) DBOption {
	return func(db *DB) error {
		db.AllowStringQueries = allow
		return nil
	}
}
1076404
func (scope *Scope) NewDB() *DB {
	if scope.db != nil {
		db := scope.db.clone()
		db.search = nil
		db.Value = nil
		return db
	}
	return nil
}
777969
func Open(driverName, dsn string) (*DB, error) {
	sqlDB, err := sql.Open(driverName, dsn)
	if err != nil {
		return nil, err
	}

	return NewFromDB(sqlDB, driverName), nil
}
570475
func Open(dbPath string, modifiers ...OptionModifier) (*DB, error) {
	path := filepath.Join(dbPath, dbName)

	if !fileExists(path) {
		if err := createChannelDB(dbPath); err != nil {
			return nil, err
		}
	}

	opts := DefaultOptions()
	for _, modifier := range modifiers {
		modifier(&opts)
	}

	bdb, err := bbolt.Open(path, dbFilePermission, nil)
	if err != nil {
		return nil, err
	}

	chanDB := &DB{
		DB:     bdb,
		dbPath: dbPath,
	}
	chanDB.graph = newChannelGraph(
		chanDB, opts.RejectCacheSize, opts.ChannelCacheSize,
	)

	// Synchronize the version of database and apply migrations if needed.
	if err := chanDB.syncVersions(dbVersions); err != nil {
		bdb.Close()
		return nil, err
	}

	return chanDB, nil
}
722693
func (db *RedisDB) stringGet(k string) string {
	if t, ok := db.keys[k]; !ok || t != "string" {
		return ""
	}
	return db.stringKeys[k]
}
1310289
func (b *backend) DB(ctx context.Context, s logical.Storage) (*sql.DB, error) {
	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
	}
	connString := connConfig.ConnectionString

	db, err := sql.Open("sqlserver", connString)
	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.
	db.SetMaxOpenConns(connConfig.MaxOpenConnections)

	stmt, err := db.Prepare("SELECT db_name();")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	err = stmt.QueryRow().Scan(&b.defaultDb)
	if err != nil {
		return nil, err
	}

	b.db = db
	return b.db, nil
}
1178440
func (db *DB) HandleQuery(c *mysql.Conn, query string, callback func(*sqltypes.Result) error) error {
	if db.AllowAll {
		return callback(&sqltypes.Result{})
	}

	if db.t != nil {
		db.t.Logf("ComQuery(%v): client %v: %v", db.name, c.ConnectionID, query)
	}
	if db.orderMatters {
		result, err := db.comQueryOrdered(query)
		if err != nil {
			return err
		}
		return callback(result)
	}

	key := strings.ToLower(query)
	db.mu.Lock()
	defer db.mu.Unlock()
	db.queryCalled[key]++

	// Check if we should close the connection and provoke errno 2013.
	if db.shouldClose {
		c.Close()
		callback(&sqltypes.Result{})
		return nil
	}

	// Using special handling for 'SET NAMES utf8'.  The driver
	// may send this at connection time, and we don't want it to
	// interfere.
	if key == "set names utf8" {
		callback(&sqltypes.Result{})
		return nil
	}

	// check if we should reject it.
	if err, ok := db.rejectedData[key]; ok {
		return err
	}

	// Check explicit queries from AddQuery().
	result, ok := db.data[key]
	if ok {
		if f := result.BeforeFunc; f != nil {
			f()
		}
		return callback(result.Result)
	}

	// Check query patterns from AddQueryPattern().
	for _, pat := range db.patternData {
		if pat.expr.MatchString(query) {
			return callback(pat.result)
		}
	}

	// Nothing matched.
	return fmt.Errorf("query: '%s' is not supported on %v", query, db.name)
}
846662
func InitDB(path string) error {
	db, err := sql.Open("sqlite3", path)
	if err != nil {
		return err
	}
	defer db.Close()
	for _, tableSQL := range SQLCreateTables() {
		if _, err := db.Exec(tableSQL); err != nil {
			return err
		}
	}

	// Use Write Ahead Logging which improves SQLite concurrency.
	// Requires SQLite >= 3.7.0
	if _, err := db.Exec("PRAGMA journal_mode = WAL"); err != nil {
		return err
	}

	// Check if the WAL mode was set correctly
	var journalMode string
	if err = db.QueryRow("PRAGMA journal_mode").Scan(&journalMode); err != nil {
		log.Fatalf("Unable to determine sqlite3 journal_mode: %v", err)
	}
	if journalMode != "wal" {
		log.Fatal("SQLite Write Ahead Logging (introducted in v3.7.0) is required. See http://perkeep.org/issue/114")
	}

	_, err = db.Exec(fmt.Sprintf(`REPLACE INTO meta VALUES ('version', '%d')`, SchemaVersion()))
	return err
}
249476
func (db *Database) Select(fields string, args ...interface{}) *Database {
	db = db.clone()
	db.selectFields += db.replaceMarks(fields)
	db.cteSelectValues = append(db.cteSelectValues, args...)
	return db
}
995219
func NewPrefixDB(db DB, prefix []byte) *prefixDB {
	return &prefixDB{
		prefix: prefix,
		db:     db,
	}
}
164582
func InitDB(path string, params *chaincfg.Params) (*PublicRecord, error) {
	path = filepath.Clean(path)
	// Check if the file exists and remove it if it does.
	if _, err := os.Stat(path); err == nil {
		if err := os.Remove(path); err != nil {
			return nil, err
		}
	}

	conn, err := sql.Open("sqlite3", path)
	if err != nil {
		return nil, err
	}

	// Execute the Create Table sql
	_, err = conn.Exec(createSql())
	if err != nil {
		return nil, err
	}
	conn.Close()

	db, err := createPubRec(path)
	if err != nil {
		return nil, err
	}

	// Prepare the DB to do one insert (for the pegBlk)
	if err := prepareInserts(db); err != nil {
		return nil, err
	}

	err = db.InsertGenesisBlk(params.Net)
	if err != nil {
		return nil, err
	}
	return prepareDB(db)
}
59151
func (dbInst *DB) Open() {
	dbInst.mux.Lock()
	defer dbInst.mux.Unlock()
	if dbInst.dbState == opened {
		return
	}
	dbOpts := &opt.Options{}
	dbPath := dbInst.conf.DBPath
	var err error
	var dirEmpty bool
	if dirEmpty, err = util.CreateDirIfMissing(dbPath); err != nil {
		panic(fmt.Sprintf("Error creating dir if missing: %s", err))
	}
	dbOpts.ErrorIfMissing = !dirEmpty
	if dbInst.db, err = leveldb.OpenFile(dbPath, dbOpts); err != nil {
		panic(fmt.Sprintf("Error opening leveldb: %s", err))
	}
	dbInst.dbState = opened
}
104431
func NewQueryString(field, query string) QueryString {
	return QueryString{"", field, query, "", "", nil, false}
}
676465
func RepairDatabase(dbname string, o *Options) error {
	var errStr *C.char
	ldbname := C.CString(dbname)
	defer C.free(unsafe.Pointer(ldbname))

	C.leveldb_repair_db(o.Opt, ldbname, &errStr)
	if errStr != nil {
		gs := C.GoString(errStr)
		C.leveldb_free(unsafe.Pointer(errStr))
		return DatabaseError(gs)
	}
	return nil
}
2547
func addOptions(s string, opt interface{}) (string, error) {
	v := reflect.ValueOf(opt)
	if v.Kind() == reflect.Ptr && v.IsNil() {
		return s, nil
	}

	u, err := url.Parse(s)
	if err != nil {
		return s, err
	}

	qs, err := query.Values(opt)
	if err != nil {
		return s, err
	}

	u.RawQuery = qs.Encode()
	return u.String(), nil
}
953811
func (r *Request) QueryOption(key string, value string) *Request {
	if r.err != nil {
		return r
	}
	if r.params == nil {
		r.params = make(url.Values)
	}
	r.params.Add(string(key), value)
	return r
}
539229
func PredicateToSql(predicate Predicate, allowedFields []Field) (sql string, values []interface{}) {
	b := newQueryBuilder(allowedFields)

	predicate.Accept(b)

	return b.Sql(), b.Values()
}