// NewQbsStoreFromDSN creates a *QbsStore from a DSN; DSNs can be created
// directly with ParamsToDSN or from the environment with GetDSNOrDie, via
// the DATABASE_URL environment var.
7042
func NewQbsStoreFromDSN(dsn *qbs.DataSourceName) *QbsStore {
	qbs.RegisterWithDataSourceName(dsn)
	result := &QbsStore{
		Dsn:    dsn,
		Policy: NewQbsDefaultOrmTransactionPolicy(),
	}
	return result
}
1351978
func NewNodeStore(addr common.Address, store GlobalStorer) *NodeStore {
	return &NodeStore{
		store: store,
		addr:  addr,
	}
}
442562
func NewFromDB(service *bolt.DB, bucketName string) (*Database, error) {
	bucket := []byte(bucketName)

	service.Update(func(tx *bolt.Tx) (err error) {
		_, err = tx.CreateBucketIfNotExists(bucket)
		return
	})

	db := &Database{table: bucket, Service: service}

	runtime.SetFinalizer(db, closeDB)
	return db, db.cleanup()
}
385141
func NewPostgresStore(c *sql.DB, sid string, kv map[interface{}]interface{}) *PostgresStore {
	return &PostgresStore{
		c:    c,
		sid:  sid,
		data: kv,
	}
}
869148
func NewMySQLStoreFromConnection(db *sql.DB, tableName string, keyPairs ...[]byte) (*MySQLStore, error) {
	// Make sure table name is enclosed.
	tableName = "`" + strings.Trim(tableName, "`") + "`"

	cTableQ := fmt.Sprintf(DDL, tableName)
	if _, err := db.Exec(cTableQ); err != nil {
		switch err.(type) {
		case *mysql.MySQLError:
			// Error 1142 means permission denied for create command
			if err.(*mysql.MySQLError).Number == 1142 {
				break
			} else {
				return nil, errors.Wrap(err, cTableQ)
			}
		default:
			return nil, err
		}
	}

	insQ := "REPLACE INTO " + tableName +
		"(id, data, created, modified, expires) VALUES (?, ?, ?, ?, ?)"
	stmtInsert, stmtErr := db.Prepare(insQ)
	if stmtErr != nil {
		return nil, errors.Wrap(stmtErr, insQ)
	}

	delQ := "DELETE FROM " + tableName + " WHERE id = ?"
	stmtDelete, stmtErr := db.Prepare(delQ)
	if stmtErr != nil {
		return nil, errors.Wrap(stmtErr, delQ)
	}

	updQ := "UPDATE " + tableName + " SET data = ?, created = ?, expires = ? " +
		"WHERE id = ?"
	stmtUpdate, stmtErr := db.Prepare(updQ)
	if stmtErr != nil {
		return nil, errors.Wrap(stmtErr, updQ)
	}

	selQ := "SELECT id, data, created, modified, expires from " +
		tableName + " WHERE id = ?"
	stmtSelect, stmtErr := db.Prepare(selQ)
	if stmtErr != nil {
		return nil, errors.Wrap(stmtErr, selQ)
	}

	return &MySQLStore{
		db:         db,
		stmtInsert: stmtInsert,
		stmtDelete: stmtDelete,
		stmtUpdate: stmtUpdate,
		stmtSelect: stmtSelect,
		Codecs:     securecookie.CodecsFromPairs(keyPairs...),
		table:      tableName,
	}, nil
}
365495
func QbsWrapAllUdid(a QbsRestAllUdid, s *QbsStore) RestAllUdid {
	return &qbsWrappedUdid{store: s, index: a, find: a, del: a, put: a, post: a}
}
1001273
func (s *Service) FQSN() string {
	components := []string{""}
	if s.File.Package != nil {
		components = append(components, s.File.GetPackage())
	}
	components = append(components, s.GetName())
	return strings.Join(components, ".")
}
40855
func NewRethinkDBKeyStore(dbName, username, password string, passphraseRetriever notary.PassRetriever, defaultPassAlias string, rethinkSession *gorethink.Session) *RethinkDBKeyStore {
	return &RethinkDBKeyStore{
		sess:             rethinkSession,
		defaultPassAlias: defaultPassAlias,
		dbName:           dbName,
		retriever:        passphraseRetriever,
		user:             username,
		password:         password,
		nowFunc:          time.Now,
	}
}
1037816
func (store *QueueStore) listN(n int) []string {
	storeDir, _ := os.Open(store.directory)
	names, _ := storeDir.Readdirnames(n)
	_ = storeDir.Close()
	return names
}
388552
func NewFsStore(fs utilfs.Filesystem, dir string) Store {
	return &fsStore{
		fs:  fs,
		dir: dir,
	}
}
500971
func NewRedisQueueStore(client *redis.Client, prefix string) *RedisQueueStore {
	if !strings.HasSuffix(prefix, ":") {
		prefix += ":"
	}
	return &RedisQueueStore{
		RedisStore: NewRedisStore(client, prefix),
	}
}
432065
func (store *QueueStore) ListN(n int) []string {
	store.RLock()
	defer store.RUnlock()
	return store.listN(n)
}
773525
func (s *GlobalStore) NewNodeStore(addr common.Address) *mock.NodeStore {
	return mock.NewNodeStore(addr, s)
}
516260
func (s *ImageStoreService) GetSecondaryStagingStoreByName(name string, opts ...OptionFunc) (*SecondaryStagingStore, int, error) {
	id, count, err := s.GetSecondaryStagingStoreID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetSecondaryStagingStoreByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
563242
func (fs *FileStore) newFileMsgStore(channelDirName, channel string, limits *MsgStoreLimits, doRecover bool) (*FileMsgStore, error) {
	// Create an instance and initialize
	ms := &FileMsgStore{
		fm:           fs.fm,
		hasFDsLimit:  fs.opts.FileDescriptorsLimit > 0,
		fstore:       fs,
		wOffset:      int64(4), // The very first record starts after the file version record
		files:        make(map[int]*fileSlice),
		channelName:  channel,
		bkgTasksDone: make(chan bool, 1),
		bkgTasksWake: make(chan bool, 1),
	}
	ms.init(channel, fs.log, limits)

	ms.setSliceLimits()
	ms.initCache()

	maxBufSize := fs.opts.BufferSize
	if maxBufSize > 0 {
		ms.bw = newBufferWriter(msgBufMinShrinkSize, maxBufSize)
		ms.bufferedSeqs = make([]uint64, 0, 1)
		ms.bufferedMsgs = make(map[uint64]*bufferedMsg)
	}

	// Use this variable for all errors below so we can do the cleanup
	var err error

	// Recovery case
	if doRecover {
		var dirFiles []os.FileInfo
		var fseq int64
		var datFile, idxFile *file
		var useIdxFile bool

		dirFiles, err = ioutil.ReadDir(channelDirName)
		for _, file := range dirFiles {
			if file.IsDir() {
				continue
			}
			fileName := file.Name()
			if !strings.HasPrefix(fileName, msgFilesPrefix) || !strings.HasSuffix(fileName, datSuffix) {
				continue
			}
			// Remove suffix
			fileNameWithoutSuffix := strings.TrimSuffix(fileName, datSuffix)
			// Remove prefix
			fileNameWithoutPrefixAndSuffix := strings.TrimPrefix(fileNameWithoutSuffix, msgFilesPrefix)
			// Get the file sequence number
			fseq, err = strconv.ParseInt(fileNameWithoutPrefixAndSuffix, 10, 64)
			if err != nil {
				err = fmt.Errorf("message log has an invalid name: %v", fileName)
				break
			}
			idxFName := fmt.Sprintf("%s%v%s", msgFilesPrefix, fseq, idxSuffix)
			useIdxFile = false
			if s, statErr := os.Stat(filepath.Join(channelDirName, idxFName)); s != nil && statErr == nil {
				useIdxFile = true
			}
			datFile, err = ms.fm.createFile(filepath.Join(channel, fileName), defaultFileFlags, nil)
			if err != nil {
				break
			}
			idxFile, err = ms.fm.createFile(filepath.Join(channel, idxFName), defaultFileFlags, nil)
			if err != nil {
				ms.fm.unlockFile(datFile)
				break
			}
			// Create the slice
			fslice := &fileSlice{file: datFile, idxFile: idxFile, lastUsed: time.Now().UnixNano()}
			// Recover the file slice
			err = ms.recoverOneMsgFile(fslice, int(fseq), useIdxFile)
			if err != nil {
				break
			}
		}
		if err == nil && ms.lastFSlSeq > 0 {
			// Now that all file slices have been recovered, we know which
			// one is the last, so use it as the write slice.
			ms.writeSlice = ms.files[ms.lastFSlSeq]
			// Need to set the writer, etc..
			ms.fm.lockFile(ms.writeSlice.file)
			err = ms.setFile(ms.writeSlice, -1)
			ms.fm.unlockFile(ms.writeSlice.file)
			if err == nil {
				// Set the beforeFileClose callback to the slices now that
				// we are done recovering.
				for _, fslice := range ms.files {
					ms.fm.setBeforeCloseCb(fslice.file, ms.beforeDataFileCloseCb(fslice))
					ms.fm.setBeforeCloseCb(fslice.idxFile, ms.beforeIndexFileCloseCb(fslice))
				}
				ms.checkSlices = 1
			}
		}
		if err == nil {
			// Apply message limits (no need to check if there are limits
			// defined, the call won't do anything if they aren't).
			err = ms.enforceLimits(false, true)
		}
	}
	if err == nil {
		ms.Lock()
		ms.allDone.Add(1)
		// Capture the time here first, it will then be captured
		// in the go routine we are about to start.
		ms.timeTick = time.Now().UnixNano()
		// On recovery, if there is age limit set and at least one message...
		if doRecover {
			if ms.limits.MaxAge > 0 && ms.totalCount > 0 {
				// Force the execution of the expireMsgs method.
				// This will take care of expiring messages that should have
				// expired while the server was stopped.
				ms.expireMsgs(ms.timeTick, int64(ms.limits.MaxAge))
			}
			// Now that we are done with recovery, close the write slice
			if ms.writeSlice != nil {
				ms.fm.closeFileIfOpened(ms.writeSlice.file)
				ms.fm.closeFileIfOpened(ms.writeSlice.idxFile)
			}
		}
		// Start the background tasks go routine
		go ms.backgroundTasks()
		ms.Unlock()
	}
	// Cleanup on error
	if err != nil {
		// The buffer writer may not be fully set yet
		if ms.bw != nil && ms.bw.buf == nil {
			ms.bw = nil
		}
		ms.Close()
		ms = nil
		action := "create"
		if doRecover {
			action = "recover"
		}
		err = fmt.Errorf("unable to %s message store for [%s]: %v", action, channel, err)
		return nil, err
	}

	return ms, nil
}
131883
func New(path, dsnQuery string, memory bool) (*DB, error) {
	q, err := url.ParseQuery(dsnQuery)
	if err != nil {
		return nil, err
	}
	if memory {
		q.Set("mode", "memory")
		q.Set("cache", "shared")
	}

	if !strings.HasPrefix(path, "file:") {
		path = fmt.Sprintf("file:%s", path)
	}

	var fqdsn string
	if len(q) > 0 {
		fqdsn = fmt.Sprintf("%s?%s", path, q.Encode())
	} else {
		fqdsn = path
	}

	return &DB{
		path:     path,
		dsnQuery: dsnQuery,
		memory:   memory,
		fqdsn:    fqdsn,
	}, nil
}
63383
func NewCouchStore(res *resource.Definition, objModel caddyshack.StoreObject) (c *CouchStore) {
	objType := reflect.ValueOf(objModel).Elem().Type()
	client := couchdb.NewClient(res.Host, res.Port)
	c = &CouchStore{
		client:    &client,
		StoreName: "couchdb",
		ObjType:   objType,
		DesDoc:    make(map[string]*couchdb.DesignDoc),
		Res:       res,
	}

	dbObj := c.client.DB(res.Name)
	status, err := dbObj.Exists()
	if err == nil {
		if status == false {
			err = dbObj.Create()
			if err != nil {
				panic("Could not create a database " + err.Error())
			}
		}
	} else {
		panic("Could not connect with db " + res.Host + string(res.Port) + err.Error())
	}
	c.DbObj = &dbObj
	c.DefQuery = NewObjQuery(objModel, c)
	return
}