{"record":{"id":"b6cd5e5be17df387","repo":"tursodatabase/turso","slug":"the-database-connection-is-not-open-b6cd5e","errorCode":null,"errorMessage":"The database connection is not open","messagePattern":"The database connection is not open","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"serverless/javascript/src/connection.ts","lineNumber":173,"sourceCode":"  /**\n   * Prepare a SQL statement for execution.\n   * \n   * Prepared statements created from a Connection use the same underlying session so transaction boundaries are preserved.\n   * This method fetches column metadata using the describe functionality.\n   * \n   * @param sql - The SQL statement to prepare\n   * @returns A Promise that resolves to a Statement object with column metadata\n   * \n   * @example\n   * ```typescript\n   * const stmt = await client.prepare(\"SELECT * FROM users WHERE id = ?\");\n   * const columns = stmt.columns();\n   * const user = await stmt.get([123]);\n   * ```\n   */\n  async prepare(sql: string): Promise<Statement> {\n    if (!this.isOpen) {\n      throw new TypeError(\"The database connection is not open\");\n    }\n\n    // Describe on the existing session so it sees uncommitted DDL\n    // (e.g. CREATE TABLE in the same transaction).\n    await this.execLock.acquire();\n    let description;\n    try {\n      description = await this.session.describe(sql);\n    } finally {\n      this.execLock.release();\n    }\n\n    const stmt = Statement.fromSession(this.session, sql, description.cols, this.execLock);\n    if (this.defaultSafeIntegerMode) {\n      stmt.safeIntegers(true);\n    }\n    return stmt;\n  }","sourceCodeStart":155,"sourceCodeEnd":191,"githubUrl":"https://github.com/tursodatabase/turso/blob/c1e59287258d99b309e362a63f48822256e2f65f/serverless/javascript/src/connection.ts#L155-L191","documentation":"`Connection.prepare()` throws a TypeError once the connection has been closed: `close()` flips the internal `isOpen` flag, and every public entry point re-checks it before touching the session. A closed connection cannot describe or prepare statements, so the check fires before any I/O.","triggerScenarios":"`await conn.prepare(sql)` after `await conn.close()`; sharing a module-level Connection and closing it on one request path while another path still prepares statements.","commonSituations":"Server shutdown or test teardown closing a shared connection; retry wrappers that close on error and then continue; singletons replaced during config reload while old references linger.","solutions":["Create a new Connection for further work - closed connections are not reopened by prepare","Sequence teardown so close() runs after all prepares and executions","Track the lifecycle yourself and skip or reconnect before calling prepare"],"exampleFix":"// before\nawait conn.close();\nconst stmt = await conn.prepare('SELECT 1');\n// after\nconst stmt = await conn.prepare('SELECT 1');\nawait conn.close();","handlingStrategy":"try-catch","validationCode":"// Connection exposes no public open-state getter; mirror it in a wrapper.\nlet isClosed = false;\nconst safeClose = async () => { isClosed = true; await conn.close(); };\nif (!isClosed) {\n  const stmt = await conn.prepare(sql);\n}","typeGuard":null,"tryCatchPattern":"try {\n  const stmt = await conn.prepare(sql);\n} catch (e) {\n  if (e instanceof TypeError && /not open/.test(e.message)) {\n    conn = new Connection(config); // recreate, then optionally retry once\n  } else {\n    throw e;\n  }\n}","preventionTips":["Close connections exactly once, at the end of the lifecycle","Never fire-and-forget operations that may outlive teardown","In tests, create a fresh Connection per case instead of sharing one fixture"],"tags":["lifecycle","connection-closed","prepare"],"backgroundTag":"use-after-close","analyzedSha":"c1e59287258d99b309e362a63f48822256e2f65f","analyzedAt":"2026-08-20T07:02:18.389Z","contentChangedAt":"2026-08-20T07:02:18.389Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}