5.1. Opening a database

The steps to open a database are as follows. The algorithm in these steps takes four arguments: the origin which requested the database to be opened, a database name, a database version, and a request.

  1. Let queue be the connection queue for origin and name.

  2. Add request to queue.

  3. Wait until all previous requests in queue have been processed.

  4. Let db be the database named name in origin, or null otherwise.

  1. If version is undefined, let version be 1 if db is null, or db’s version otherwise.

  2. If db is null, let db be a new database with name name, version 0 (zero), and with no object stores. If this fails for any reason, return an appropriate error (e.g. a “[QuotaExceededError](https://www.w3.org/TR/WebIDL-1/#quotaexceedederror)“ or “[UnknownError](https://www.w3.org/TR/WebIDL-1/#unknownerror)[DOMException](https://www.w3.org/TR/WebIDL-1/#idl-DOMException)).

  3. If db’s version is greater than version, return a newly created[VersionError](https://www.w3.org/TR/WebIDL-1/#versionerror)[DOMException](https://www.w3.org/TR/WebIDL-1/#idl-DOMException) and abort these steps.

  4. Let connection be a new connection to db.

  5. Set connection’s version to version.

  6. If db’s version is less than version, then:

    1. Let openConnections be the set of all connections, except connection, associated with db.

    2. For each entry in openConnections that does not have its close pending flag set, queue a task to fire a version change event named versionchange at entry with db’s version and version.

      Firing this event might cause one or more of the other objects in openConnections to be closed, in which case the versionchange event is not fired at those objects, even if that hasn’t yet been done.

    3. Wait for all of the events to be fired.

    4. If any of the connections in openConnections are still not closed, queue a task to fire a version change event named [blocked](#request-blocked) at request with db’s version and version.

    5. Wait until all connections in openConnections are closed.

    6. Run the steps to run an upgrade transaction using connection, version and request.

    7. If connection was closed, return a newly created[AbortError](https://www.w3.org/TR/WebIDL-1/#aborterror)[DOMException](https://www.w3.org/TR/WebIDL-1/#idl-DOMException) and abort these steps.

    8. If the upgrade transaction was aborted, run the steps to close a database connection with connection, return a newly created[AbortError](https://www.w3.org/TR/WebIDL-1/#aborterror)[DOMException](https://www.w3.org/TR/WebIDL-1/#idl-DOMException) and abort these steps.

  7. Return connection.