'Opens a connection to the database. If the database doesn\'t exist, we create a new one and run the
initialization SQL scripts. If the database doesn\'t exist, we simply connect to it.
And finally, we read the database version.'

def _open_connection(self):

    is_in_memory = (self.sqlite_db_path == u':memory:')
    is_new_db = is_in_memory
    if (not is_in_memory):
        if (not os.path.exists(self.sqlite_db_path)):
            is_new_db = True
        elif (not os.path.isfile(self.sqlite_db_path)):
            msg = (u'Not    a    file:    %s' % self.sqlite_db_path)
            raise OSError(msg)
    try:
        self._connection = apsw.Connection(self.sqlite_db_path)
        self._connection.setbusytimeout(self._busytimeout)
    except CantOpenError as e:
        msg = (u'Failed    to    open    connection    to    %s:    %s' % (self.sqlite_db_path, e))
        raise CantOpenError(msg)
    cursor = self.get_cursor()
    (page_size,) = next(cursor.execute(u'PRAGMA    page_size'))
    if (page_size < 8192):
        self._logger.info(u'begin    page_size    upgrade...')
        cursor.execute(u'PRAGMA    journal_mode    =    DELETE;')
        cursor.execute(u'PRAGMA    page_size    =    8192;')
        cursor.execute(u'VACUUM;')
        self._logger.info(u'...end    page_size    upgrade')
    cursor.execute(u'PRAGMA    synchronous    =    NORMAL;')
    cursor.execute(u'PRAGMA    cache_size    =    10000;')
    cursor.execute(u'PRAGMA    journal_mode    =    WAL;')
    if (is_new_db and (self.db_script_path is not None)):
        self._logger.info(u'Initializing    new    database...')
        if (not os.path.exists(self.db_script_path)):
            msg = (u"SQL    script    doesn't    exist:    %s" % self.db_script_path)
            raise OSError(msg)
        if (not os.path.isfile(self.db_script_path)):
            msg = (u'SQL    script    is    not    a    file:    %s' % self.db_script_path)
            raise OSError(msg)
        try:
            f = open(self.db_script_path, 'r')
            sql_script = f.read()
            f.close()
        except IOError as e:
            msg = (u'Failed    to    load    SQL    script    %s:    %s' % (self.db_script_path, e))
            raise IOError(msg)
        cursor.execute(sql_script)
    if (self.db_script_path is not None):
        self._logger.info(u'Reading    database    version...')
        try:
            (version_str,) = cursor.execute(u"SELECT    value    FROM    MyInfo    WHERE    entry    ==    'version'").next()
            self._version = int(version_str)
            self._logger.info(u'Current    database    version    is    %s', self._version)
        except (StopIteration, SQLError) as e:
            msg = (u'Failed    to    load    database    version:    %s' % e)
            raise CorruptedDatabaseError(msg)
    else:
        self._version = 1
