// Open connects to a PostgreSQL database, opens it & create default schema if provided
977002
func (adapter *PostgresAdapter) Open(dbURL string) (*sql.DB, error) {
	db, err := sql.Open("postgres", dbURL)
	if err != nil {
		adapter.Log.Info("msg", "Error creating database connection", "err", err)
		return nil, err
	}

	// if there is a supplied Schema
	if adapter.Schema != "" {
		if err = db.Ping(); err != nil {
			adapter.Log.Info("msg", "Error opening database connection", "err", err)
			return nil, err
		}

		var found bool

		query := Cleanf(`SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace n WHERE n.nspname = '%s');`, adapter.Schema)
		adapter.Log.Info("msg", "FIND SCHEMA", "query", query)

		if err := db.QueryRow(query).Scan(&found); err == nil {
			if !found {
				adapter.Log.Warn("msg", "Schema not found")
			}
			adapter.Log.Info("msg", "Creating schema")

			query = Cleanf("CREATE SCHEMA %s;", adapter.Schema)
			adapter.Log.Info("msg", "CREATE SCHEMA", "query", query)

			if _, err = db.Exec(query); err != nil {
				if adapter.ErrorEquals(err, types.SQLErrorTypeDuplicatedSchema) {
					adapter.Log.Warn("msg", "Duplicated schema")
					return db, nil
				}
			}
		} else {
			adapter.Log.Info("msg", "Error searching schema", "err", err)
			return nil, err
		}
	} else {
		return nil, fmt.Errorf("no schema supplied")
	}

	return db, err
}
1354039
func (e *TableScanExec) Open(ctx context.Context) error {
	e.iter = nil
	e.virtualTableChunkList = nil
	return nil
}
1357041
func (m *Schema) OpenConn(tableName string) (Conn, error) {
	tableName = strings.ToLower(tableName)
	m.mu.RLock()
	defer m.mu.RUnlock()
	sch, ok := m.tableSchemas[tableName]
	if !ok || sch == nil || sch.DS == nil {
		return nil, fmt.Errorf("Could not find a DataSource for that table %q", tableName)
	}

	conn, err := sch.DS.Open(tableName)
	if err != nil {
		return nil, err
	}
	if conn == nil {
		return nil, fmt.Errorf("Could not establish a connection for %v", tableName)
	}
	return conn, nil
}
163403
func Open(paths ...string) gkv.KV {
	var path string
	if len(paths) != 0 {
		path = paths[0]
	} else {
		path = filepath.Join(gkv.ProjectDir(), "data", "data.db")
	}
	db, err := bolt.Open(path, 0600, nil)
	if err != nil {
		panic(err)
	}
	return &KV{
		db:    db,
		table: []byte(gkv.DefaultTableName),
	}
}
491417
func Open(driver, config string) shimmie.Store {
	db := openDB(driver, config)
	return &datastore{db}
}
111716
func (rc *RedisConnector) open(socketPath, host, password string, db int, cnf *config.RedisConfig, tlsConfig *tls.Config) (redis.Conn, error) {
	var opts = []redis.DialOption{
		redis.DialDatabase(db),
		redis.DialReadTimeout(time.Duration(cnf.ReadTimeout) * time.Second),
		redis.DialWriteTimeout(time.Duration(cnf.WriteTimeout) * time.Second),
		redis.DialConnectTimeout(time.Duration(cnf.ConnectTimeout) * time.Second),
	}

	if tlsConfig != nil {
		opts = append(opts, redis.DialTLSConfig(tlsConfig), redis.DialUseTLS(true))
	}

	if password != "" {
		opts = append(opts, redis.DialPassword(password))
	}

	if socketPath != "" {
		return redis.Dial("unix", socketPath, opts...)
	}

	return redis.Dial("tcp", host, opts...)
}
1044704
func (fs MapFS) Open(p string) (vfs.ReadSeekCloser, error) {
	e, ok := fs[fixpath(p)]
	if !ok {
		return nil, os.ErrNotExist
	}
	return nopCloser{bytes.NewReader(e.data)}, nil
}
243805
func Open(dirname string, opts *db.Options) (*DB, error) {
	d := &DB{
		dirname:        dirname,
		opts:           opts,
		icmp:           internalKeyComparer{opts.GetComparer()},
		pendingOutputs: make(map[uint64]struct{}),
	}
	if opts != nil {
		d.icmpOpts = *opts
	}
	d.icmpOpts.Comparer = d.icmp
	tableCacheSize := opts.GetMaxOpenFiles() - numNonTableCacheFiles
	if tableCacheSize < minTableCacheSize {
		tableCacheSize = minTableCacheSize
	}
	d.tableCache.init(dirname, opts.GetFileSystem(), &d.icmpOpts, tableCacheSize)
	d.mem = memdb.New(&d.icmpOpts)
	d.compactionCond = sync.Cond{L: &d.mu}
	fs := opts.GetFileSystem()

	d.mu.Lock()
	defer d.mu.Unlock()

	// Lock the database directory.
	err := fs.MkdirAll(dirname, 0755)
	if err != nil {
		return nil, err
	}
	fileLock, err := fs.Lock(dbFilename(dirname, fileTypeLock, 0))
	if err != nil {
		return nil, err
	}
	defer func() {
		if fileLock != nil {
			fileLock.Close()
		}
	}()

	if _, err := fs.Stat(dbFilename(dirname, fileTypeCurrent, 0)); os.IsNotExist(err) {
		// Create the DB if it did not already exist.
		if err := createDB(dirname, opts); err != nil {
			return nil, err
		}
	} else if err != nil {
		return nil, fmt.Errorf("leveldb: database %q: %v", dirname, err)
	} else if opts.GetErrorIfDBExists() {
		return nil, fmt.Errorf("leveldb: database %q already exists", dirname)
	}

	// Load the version set.
	err = d.versions.load(dirname, opts)
	if err != nil {
		return nil, err
	}

	// Replay any newer log files than the ones named in the manifest.
	var ve versionEdit
	ls, err := fs.List(dirname)
	if err != nil {
		return nil, err
	}
	var logFiles fileNumAndNameSlice
	for _, filename := range ls {
		ft, fn, ok := parseDBFilename(filename)
		if ok && ft == fileTypeLog && (fn >= d.versions.logNumber || fn == d.versions.prevLogNumber) {
			logFiles = append(logFiles, fileNumAndName{fn, filename})
		}
	}
	sort.Sort(logFiles)
	for _, lf := range logFiles {
		maxSeqNum, err := d.replayLogFile(&ve, fs, filepath.Join(dirname, lf.name))
		if err != nil {
			return nil, err
		}
		d.versions.markFileNumUsed(lf.num)
		if d.versions.lastSequence < maxSeqNum {
			d.versions.lastSequence = maxSeqNum
		}
	}

	// Create an empty .log file.
	ve.logNumber = d.versions.nextFileNum()
	d.logNumber = ve.logNumber
	logFile, err := fs.Create(dbFilename(dirname, fileTypeLog, ve.logNumber))
	if err != nil {
		return nil, err
	}
	defer func() {
		if logFile != nil {
			logFile.Close()
		}
	}()
	d.log = record.NewWriter(logFile)

	// Write a new manifest to disk.
	if err := d.versions.logAndApply(dirname, &ve); err != nil {
		return nil, err
	}

	d.deleteObsoleteFiles()
	d.maybeScheduleCompaction()

	d.logFile, logFile = logFile, nil
	d.fileLock, fileLock = fileLock, nil
	return d, nil
}
1055452
func (p *Postgres) Open(logger log.Logger) (storage.Storage, error) {
	conn, err := p.open(logger, p.createDataSourceName())
	if err != nil {
		return nil, err
	}
	return conn, nil
}
493761
func (d *ThriftTransport) Open() error {
	if d.currentTransport == nil || !d.currentTransport.IsOpen() {
		return errors.Annotate(d.NextConnection(), "cannot open next connection")
	}
	return nil
}
631510
func (dbGorp *DbGorp) OpenDb() (err error) {
	db, err := sql.Open(dbGorp.Info.DbDriver, dbGorp.Info.DbConnection)
	if err != nil {
		moduleLogger.Fatal("Open Database Error", "error", err)
	}

	// Create the database map
	dbGorp.Map = &gorp.DbMap{Db: db, Dialect: dbGorp.Info.Dialect}

	revel.OnAppStop(func() {
		revel.RevelLog.Info("Closing the database (from module)")
		if err := dbGorp.Close(); err != nil {
			revel.AppLog.Error("Failed to close the database", "error", err)
		}
	})

	return dbGorp.dbInit()
}
87690
func (cp *Pool) Open(appParams, dbaParams, appDebugParams *mysql.ConnParams) {
	cp.mu.Lock()
	defer cp.mu.Unlock()

	f := func() (pools.Resource, error) {
		return NewDBConn(cp, appParams)
	}
	cp.connections = pools.NewResourcePool(f, cp.capacity, cp.capacity, cp.idleTimeout)
	cp.appDebugParams = appDebugParams

	cp.dbaPool.Open(dbaParams, tabletenv.MySQLStats)
}
785615
func (e *LoadDataExec) Open(ctx context.Context) error {
	if e.loadDataInfo.insertColumns != nil {
		e.loadDataInfo.initEvalBuffer()
	}
	return nil
}
580686
func Open(dbFile string, opts *kv.Options) (*kv.DB, error) {
	createOpen := kv.Open
	verb := "opening"
	if _, err := os.Stat(dbFile); os.IsNotExist(err) {
		createOpen = kv.Create
		verb = "creating"
	}
	if opts == nil {
		opts = &kv.Options{}
	}
	if opts.Locker == nil {
		opts.Locker = func(dbFile string) (io.Closer, error) {
			lkfile := dbFile + ".lock"
			cl, err := lock.Lock(lkfile)
			if err != nil {
				return nil, fmt.Errorf("failed to acquire lock on %s: %v", lkfile, err)
			}
			return cl, nil
		}
	}
	if v, _ := strconv.ParseBool(os.Getenv("CAMLI_KV_VERIFY")); v {
		opts.VerifyDbBeforeOpen = true
		opts.VerifyDbAfterOpen = true
		opts.VerifyDbBeforeClose = true
		opts.VerifyDbAfterClose = true
	}
	db, err := createOpen(dbFile, opts)
	if err != nil {
		return nil, fmt.Errorf("error %s %s: %v", verb, dbFile, err)
	}
	return db, nil
}
553466
func (c *CodebaseController) Open(ctx *app.OpenCodebaseContext) error {
	_, err := login.ContextIdentity(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrUnauthorized(err.Error()))
	}
	var cb *codebase.Codebase
	err = application.Transactional(c.db, func(appl application.Application) error {
		cb, err = appl.Codebases().Load(ctx, ctx.CodebaseID)
		return err
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	ns, err := c.getCheNamespace(ctx)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}
	cheClient, err := c.NewCheClient(ctx, ns)
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}
	workspaceResp, err := cheClient.StartExistingWorkspace(ctx, ctx.WorkspaceID)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"codebase_id": cb.ID,
			"stack_id":    cb.StackID,
			"err":         err,
		}, "unable to open workspaces")
		if werr, ok := err.(*che.StarterError); ok {
			log.Error(ctx, map[string]interface{}{
				"codebase_id": cb.ID,
				"stack_id":    cb.StackID,
				"err":         err,
			}, "unable to open workspaces: %s", werr.String())
		}
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}

	err = application.Transactional(c.db, func(appl application.Application) error {
		cb.LastUsedWorkspace = ctx.WorkspaceID
		_, err := appl.Codebases().Save(ctx, cb)
		return err
	})
	if err != nil {
		return jsonapi.JSONErrorResponse(ctx, goa.ErrInternal(err.Error()))
	}

	ideURL := workspaceResp.GetHrefByRelOfWorkspaceLink(che.IdeUrlRel)
	resp := &app.WorkspaceOpen{
		Links: &app.WorkspaceOpenLinks{
			Open: &ideURL,
		},
	}
	return ctx.OK(resp)
}
1216370
func (e *TableDualExec) Open(ctx context.Context) error {
	e.numReturned = 0
	return nil
}
951078
func (e *CheckIndexExec) Open(ctx context.Context) error {
	if err := e.baseExecutor.Open(ctx); err != nil {
		return err
	}
	if err := e.src.Open(ctx); err != nil {
		return err
	}
	e.done = false
	return nil
}