connect to our chainstate db
964893
def db_connect(cls, path):
        
        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)
        con.row_factory = StateEngine.db_row_factory
        return con
1099265
function connectToRedis(db, opts) {

    // get the redis client
    var client = redis.createClient(opts.port, opts.host);

    // log any errors
    client.on('error', function (err) {
        redisOffline = true;
        console.log('connectToRedis error: ' + err);
    });

    client.on('ready', function () {
        redisOffline = false;
    });

    // if there is a password, do auth
    var deferred = Q.defer();
    if (opts.password) {
        client.auth(opts.password, function (authErr) {
            if (authErr) {
                deferred.reject(authErr);
                return;
            }

            client.select(db, function (err) {
                err ? deferred.reject(err) : deferred.resolve(client);
            });
        });
    }
    else {
        client.select(db, function (err) {
            err ? deferred.reject(err) : deferred.resolve(client);
        });
    }

    return deferred.promise;
}
220992
def get_or_instantiate_db_state(working_dir):
    

    # instantiates
    new_db = BlockstackDB.borrow_readwrite_instance(working_dir, -1)
    BlockstackDB.release_readwrite_instance(new_db, -1)

    return get_db_state(working_dir)
1055251
async def connect(self):
        
        self.pool = await aiomysql.create_pool(
            loop=self.loop,
            db=self.database,
            connect_timeout=self.timeout,
            **self.connect_params)
875261
def connect(self):
        
        self.log.debug('starting the ``get`` method')

        dbSettings = self.dbSettings

        port = False
        if "tunnel" in dbSettings and dbSettings["tunnel"]:
            port = self._setup_tunnel(
                tunnelParameters=dbSettings["tunnel"]
            )

        # SETUP A DATABASE CONNECTION
        host = dbSettings["host"]
        user = dbSettings["user"]
        passwd = dbSettings["password"]
        dbName = dbSettings["db"]
        dbConn = ms.connect(
            host=host,
            user=user,
            passwd=passwd,
            db=dbName,
            port=port,
            use_unicode=True,
            charset='utf8',
            local_infile=1,
            client_flag=ms.constants.CLIENT.MULTI_STATEMENTS,
            connect_timeout=36000,
            max_allowed_packet=51200000
        )
        if self.autocommit:
            dbConn.autocommit(True)

        self.log.debug('completed the ``get`` method')
        return dbConn
1166996
function connect(uri, callback) {
  console.log('connecting to database (' + uri + ')');
  mongo.MongoClient.connect(uri, {safe: true}, function (err, client) {
    if (err) return callback(err);

    db = client;
    db.addListener("error", function (error) {
      console.log("mongo client error: " + error);
    });

    callback(null, db);
  });
}
819363
@Override
    public synchronized void chainStarted(ChainData chainData) {
        chainState.set(ChainState.STARTED.val);

        final ActiveConfiguration cfg = currentConfig;
        final int port = cfg.getActivePort();

        if (port > 0) {
            // HOORAY! we have a bound listener.
            // Notify listeners that the chain was started.
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "New configuration started " + cfg);
            }

            VirtualHostMap.notifyStarted(owner, cfg.resolvedHost, port, isHttps);

            // Post an endpoint started event to anyone listening
            String topic = owner.getEventTopic() + HttpServiceConstants.ENDPOINT_STARTED;
            postEvent(topic, cfg, null);
        }
    }
1151151
function connect() {
    if (!redis) {
      debug('createClient ' + key + ' at ' + host + ':' + port);
      redis = redisLib.createClient(port, host, redisOpts); }
  }
859316
def connect(
        database: str,
        loop: asyncio.BaseEventLoop = None,
        executor: concurrent.futures.Executor = None,
        timeout: int = 5,
        echo: bool = False,
        isolation_level: str = '',
        check_same_thread: bool = False,
        **kwargs: dict
):
    
    coro = _connect(
        database,
        loop=loop,
        executor=executor,
        timeout=timeout,
        echo=echo,
        isolation_level=isolation_level,
        check_same_thread=check_same_thread,
        **kwargs
    )
    return _ContextManager(coro)
292094
function(callback) {

  log('Connecting...');
  MongoClient.connect(dbUrl, dbOptions, function(err, dbConn) {
    
    if(err) {
      log('Cannot connect: ' + err);
      callback(err);
      return;
    } 
    
    log('Connected!');
    isConnected = true;
    db = dbConn;

    // http://stackoverflow.com/a/18715857/446681
    db.on('close', function() {
      log('Connection was closed!!!');
      isConnected = false;
    });

    log('Executing...');
    callback(null, db);
  
  });

}
380476
def connect(self):
        '''
        
        '''
        self._connect()

        try:
            self._listen()
        except (KeyboardInterrupt, SystemExit):
            pass
        finally:
            self.close()
522555
def init(self, db=RDB_DB, host=RDB_HOST, port=RDB_PORT):
        """"""
        self.RDB_HOST = host
        self.RDB_PORT = port
        self.RDB_DB = db

        from .connection import RethinkDB
        self.rdb = RethinkDB()
        self.rdb.init()
96505
def _connect(self):
        
        self._close()
        self.conn = MySQLdb.Connect(host=self.hostname,
                                    port=self.port,
                                    user=self.username,
                                    passwd=self.password,
                                    db=self.database)
1361716
def db_create(cls, impl, working_dir):
        

        global VIRTUALCHAIN_DB_SCRIPT
       
        log.debug("Setup chain state in {}".format(working_dir))

        path = config.get_snapshots_filename(impl, working_dir)
        if os.path.exists( path ):
            raise Exception("Database {} already exists")

        lines = [l + ";" for l in VIRTUALCHAIN_DB_SCRIPT.split(";")]
        con = sqlite3.connect(path, isolation_level=None, timeout=2**30)

        for line in lines:
            con.execute(line)

        con.row_factory = StateEngine.db_row_factory
        return con
1117490
def connect(self):
        
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', '.*deprecated.*')
            self._conn = client.connect(
                init_command=self.init_fun,
                sql_mode="NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO,"
                         "STRICT_ALL_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION",
                charset=config['connection.charset'],
                **self.conn_info)
        self._conn.autocommit(True)
280490
private void initFromDatabase() throws SQLException, BlockStoreException {
        PreparedStatement ps = conn.get().prepareStatement(getSelectSettingsSQL());
        ResultSet rs;
        ps.setString(1, CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no chain head pointer");
        }
        Sha256Hash hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        this.chainHeadBlock = get(hash);
        this.chainHeadHash = hash;
        if (this.chainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - head block not found");
        }
        ps.setString(1, VERIFIED_CHAIN_HEAD_SETTING);
        rs = ps.executeQuery();
        if (!rs.next()) {
            throw new BlockStoreException("corrupt database block store - no verified chain head pointer");
        }
        hash = Sha256Hash.wrap(rs.getBytes(1));
        rs.close();
        ps.close();
        this.verifiedChainHeadBlock = get(hash);
        this.verifiedChainHeadHash = hash;
        if (this.verifiedChainHeadBlock == null) {
            throw new BlockStoreException("corrupt database block store - verified head block not found");
        }
    }
16931
def db_chainstate_get_block(cls, cur, block_height):
        
        query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;'
        args = (block_height,)

        rows = cls.db_query_execute(cur, query, args, verbose=False)
        ret = []

        for r in rows:
            rowdata = {
                'txid': str(r['txid']),
                'block_id': r['block_id'],
                'txindex': r['txindex'],
                'vtxindex': r['vtxindex'],
                'opcode': str(r['opcode']),
                'data_hex': str(r['data_hex']),
                'senders': simplejson.loads(r['senders']),
                'tx_hex': str(r['tx_hex']),
                'tx_merkle_path': str(r['tx_merkle_path']),
                'fee': r['fee']
            }

            ret.append(rowdata)

        return ret