// Loads a sqlite db, checks if its reachabale and prepares all the queries.
334377
func LoadDB(path string) (*PublicRecord, error) {
	db, err := createPubRec(path)
	if err != nil {
		return nil, err
	}
	return prepareDB(db)
}
725016
func Get(dbName string) (Db, error) {
	if db, ok := connectionMap[dbName]; ok {
		return db, nil
	}
	return Db{}, errors.New("Database connection not available. Perform 'Setup' first")
}
880868
func LoadFromFile(sqlFile string) (*DotSql, error) {
	f, err := os.Open(sqlFile)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return Load(f)
}
719280
func Init() {
	dbMutex.Lock()
	defer dbMutex.Unlock()

	if initialized {
		return
	}

	DBUrl = url.URL{
		Scheme:   "postgres",
		Host:     config.Constants.DbAddr,
		Path:     config.Constants.DbDatabase,
		RawQuery: "sslmode=disable",
	}

	logrus.Info("Connecting to DB on ", DBUrl.String())

	DBUrl.User = url.UserPassword(config.Constants.DbUsername, config.Constants.DbPassword)

	var err error
	DB, err = gorm.Open("postgres", DBUrl.String())
	//	DB, err := gorm.Open("sqlite3", "/tmp/gorm.db")
	if err != nil {
		logrus.Fatal(err.Error())
	}

	DB.SetLogger(logrus.StandardLogger())

	logrus.Info("Connected!")
	initialized = true
}
763585
func InitDB(dbInfo *DBInfo, shutdown func()) (*DB, error) {
	dbPath, err := filepath.Abs(dbInfo.FileName)
	if err != nil {
		return nil, err
	}

	// Ensures target DB-file has a parent folder
	parent := filepath.Dir(dbPath)
	err = os.MkdirAll(parent, 0755)
	if err != nil {
		return nil, err
	}

	// "shared-cache" mode has multiple connections share a single data and
	// schema cache. _busy_timeout helps prevent SQLITE_BUSY ("database is
	// locked") errors by sleeping for a certain amount of time when the
	// database is locked. See https://www.sqlite.org/c3ref/busy_timeout.html.
	dbPath = dbPath + "?cache=shared&_busy_timeout=" + DBBusyTimeout
	db, err := sql.Open("sqlite3", dbPath)
	if err != nil || db == nil {
		return nil, err
	}

	// Historically, SQLite did not handle concurrent writes internally,
	// necessitating a limitation of just 1 open connecton. With a busy_timeout
	// set, this is less important. With go-sqlite 1.10, this is not needed at
	// all since the library started compiling sqlite3 for
	// thread-safe/"serialized" operation (SQLITE_THREADSAFE=1). For details,
	// see https://sqlite.org/threadsafe.html and
	// https://sqlite.org/c3ref/c_config_covering_index_scan.html#sqliteconfigserialized.
	// The change to go-sqlite3 is
	// github.com/mattn/go-sqlite3@acfa60124032040b9f5a9406f5a772ee16fe845e
	//
	// db.SetMaxOpenConns(1)

	// These are db-wide settings that persist for the entire session.
	_, err = db.Exec(SetCacheSizeSQL)
	if err != nil {
		log.Error("Error setting SQLite Cache size")
		return nil, err
	}
	_, err = db.Exec(SetSynchrounousOffSQL)
	if err != nil {
		log.Error("Error setting SQLite synchrounous off")
		return nil, err
	}

	rawCreateBlockSummaryStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	size INTEGER,
      	diff FLOAT,
      	sdiff FLOAT,
      	time INTEGER,
      	poolsize INTEGER,
      	poolval FLOAT,
      	poolavg FLOAT,
      	winners TEXT,
      	is_mainchain BOOL,
      	is_valid BOOL
    	);`

	createBlockSummaryStmt := fmt.Sprintf(rawCreateBlockSummaryStmt, TableNameSummaries)

	_, err = db.Exec(createBlockSummaryStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createBlockSummaryStmt)
		return nil, err
	}

	rawCreateStakeInfoExtendedStmt := `
    	create table if not exists %s(
      	hash TEXT PRIMARY KEY,
      	height INTEGER,
      	num_tickets INTEGER,
      	fee_min FLOAT, fee_max FLOAT, fee_mean FLOAT,
      	fee_med FLOAT, fee_std FLOAT,
      	sdiff FLOAT, window_num INTEGER, window_ind INTEGER,
      	pool_size INTEGER, pool_val FLOAT, pool_valavg FLOAT,
      	winners TEXT
    	);`

	createStakeInfoExtendedStmt := fmt.Sprintf(rawCreateStakeInfoExtendedStmt, TableNameStakeInfo)

	_, err = db.Exec(createStakeInfoExtendedStmt)
	if err != nil {
		log.Errorf("%q: %s\n", err, createStakeInfoExtendedStmt)
		return nil, err
	}

	if err = db.Ping(); err != nil {
		return nil, err
	}

	dataBase, err := NewDB(db, shutdown)
	if err != nil {
		return nil, err
	}

	// Table creation string are used in JustifyTableStructures
	// Eventually won't be needed.
	dataBase.rawCreateBlockSummaryStmt = rawCreateBlockSummaryStmt
	dataBase.rawCreateStakeInfoExtendedStmt = rawCreateStakeInfoExtendedStmt
	if err = dataBase.JustifyTableStructures(dbInfo); err != nil {
		return nil, err
	}

	return dataBase, err
}
955614
func Open(name string) (*DB, error) {
	_, err := os.Stat(name)
	if err != nil {
		return nil, err
	}
	meta, err := sql.Open("sqlite3", name)
	if err != nil {
		return nil, err
	}
	store := new(dbstore.Storage)
	store.Register(new(Doc))
	store.Register(new(thumb))
	store.Register(new(text))
	return &DB{meta, store, name}, nil
}
455768
func (r *GormTrackerQueryRepository) Load(ctx context.Context, ID uuid.UUID) (*TrackerQuery, error) {
	defer goa.MeasureSince([]string{"goa", "db", "trackerquery", "load"}, time.Now())
	res := TrackerQuery{}
	tx := r.db.Where("id = ?", ID).Find(&res)
	if tx.RecordNotFound() {
		log.Error(ctx, map[string]interface{}{
			"tracker_id": ID.String(),
		}, "tracker resource not found")
		return nil, errors.NewNotFoundError("tracker query", ID.String())
	}
	if tx.Error != nil {
		log.Error(ctx, map[string]interface{}{
			"err":             tx.Error,
			"trackerquery_id": ID,
		}, "unable to load the trackerquery by ID")
		return nil, errors.NewInternalError(ctx, errs.Wrapf(tx.Error, "failed to load the trackerquery by ID: %s", ID))
	}
	return &res, nil
}
1181226
func LoadTable(conn *connpool.DBConn, tableName string, tableType string, comment string) (*Table, error) {
	ta := NewTable(tableName)
	sqlTableName := sqlparser.String(ta.Name)
	if err := fetchColumns(ta, conn, sqlTableName); err != nil {
		return nil, err
	}
	if err := fetchIndexes(ta, conn, sqlTableName); err != nil {
		return nil, err
	}
	switch {
	case strings.Contains(comment, "vitess_sequence"):
		ta.Type = Sequence
		ta.SequenceInfo = &SequenceInfo{}
	case strings.Contains(comment, "vitess_message"):
		if err := loadMessageInfo(ta, comment); err != nil {
			return nil, err
		}
		ta.Type = Message
	}
	return ta, nil
}
1218874
func (q *Query) Prepare() *Query {
	stmt, err := q.executor.Prepare(q.rawSQL)
	if err != nil {
		q.LastError = err
		return q
	}
	q.stmt = stmt
	return q
}
124504
func InitDB(db *bolt.DB) error {
	return db.Update(func(tx *bolt.Tx) error {
		_, err := createBucketIfNotExists(tx, bucketKeyStorageVersion, bucketKeyTasks)
		return err
	})
}
520746
func ExecuteDBQuery(ctx context.Context, db *sql.DB, params map[string]string, query string) error {

	parsedQuery := parseQuery(params, query)

	stmt, err := db.PrepareContext(ctx, parsedQuery)
	if err != nil {
		return err
	}
	defer stmt.Close()

	return execute(ctx, stmt)
}
773353
func (c *boltConn) Prepare(query string) (driver.Stmt, error) {
	return c.prepare(query)
}
1289367
func (d DotSql) Prepare(db Preparer, name string) (*sql.Stmt, error) {
	query, err := d.lookupQuery(name)
	if err != nil {
		return nil, err
	}

	return db.Prepare(query)
}
229608
func (p *MySQLPrivilege) LoadAll(ctx sessionctx.Context) error {
	err := p.LoadUserTable(ctx)
	if err != nil {
		return errors.Trace(err)
	}

	err = p.LoadDBTable(ctx)
	if err != nil {
		if !noSuchTable(err) {
			return errors.Trace(err)
		}
		log.Warn("mysql.db maybe missing")
	}

	err = p.LoadTablesPrivTable(ctx)
	if err != nil {
		if !noSuchTable(err) {
			return errors.Trace(err)
		}
		log.Warn("mysql.tables_priv missing")
	}

	err = p.LoadDefaultRoles(ctx)
	if err != nil {
		if !noSuchTable(err) {
			return errors.Trace(err)
		}
		log.Warn("mysql.default_roles missing")
	}

	err = p.LoadColumnsPrivTable(ctx)
	if err != nil {
		if !noSuchTable(err) {
			return errors.Trace(err)
		}
		log.Warn("mysql.columns_priv missing")
	}

	err = p.LoadRoleGraph(ctx)
	if err != nil {
		if !noSuchTable(err) {
			return errors.Trace(err)
		}
		log.Warn("mysql.role_edges missing")
	}
	return nil
}
1213440
func (spec *ConnectionSpec) Db(db int) *ConnectionSpec {
	spec.db = db
	return spec
}
828844
func Connect(file string) (*DB, error) {
	db := &DB{
		Driver: "sqlite3",
		DSN:    file,
	}

	connection, err := sqlx.Open(db.Driver, db.DSN)
	if err != nil {
		return nil, err
	}
	db.connection = connection

	if db.cache == nil {
		db.cache = make(map[string]*sql.Stmt)
	}

	return db, nil
}
1327946
func (db *DB) Preparex(query string) (*Stmt, error) {
	return Preparex(db, query)
}