---
source: boltffi_bindgen/src/render/typescript/templates.rs
assertion_line: 1513
expression: template.render().unwrap()
---
const _DatabaseFinalizer: FinalizationRegistry<number> | null =
  typeof FinalizationRegistry === "undefined"
    ? null
    : new FinalizationRegistry<number>((handle) => {
        (_exports.boltffi_database_free as Function)(handle);
      });

export class Database {
  private _handle: number;
  private _disposed: boolean;

  private constructor(handle: number) {
    this._handle = handle;
    this._disposed = false;
    _DatabaseFinalizer?.register(this, handle, this);
  }

  static _fromHandle(handle: number): Database {
    if (handle === 0) {
      throw new Error("Database received a null handle");
    }
    return new Database(handle);
  }

  [Symbol.dispose](): void {
    this.dispose();
  }

  dispose(): void {
    if (this._disposed) {
      return;
    }
    this._disposed = true;
    _DatabaseFinalizer?.unregister(this);
    (_exports.boltffi_database_free as Function)(this._handle);
    this._handle = 0;
  }

  private _assertNotDisposed(): void {
    if (this._disposed) {
      throw new Error("Database has been disposed");
    }
  }

  async query(sql: string): Promise<QueryResult> {
    this._assertNotDisposed();
    const sql_alloc = _module.allocString(sql);
    try {
      const handle = (_exports.boltffi_database_query as Function)(this._handle, sql_alloc.ptr, sql_alloc.len);
      const awaitedHandle = await _module.asyncManager.pollAsync(
        handle,
        (futureHandle: number) => (_exports.boltffi_database_query_poll_sync as Function)(futureHandle),
        (futureHandle: number) => (_exports.boltffi_database_query_panic_message as Function)(futureHandle),
        (futureHandle: number) => (_exports.boltffi_database_query_free as Function)(futureHandle)
      );
      const outPtr = _module.allocBufDescriptor();
      let completeCompleted = false;
      try {
        _module.completeAsync((statusPtr: number) => (_exports.boltffi_database_query_complete as Function)(outPtr, awaitedHandle, statusPtr));
        completeCompleted = true;
        const reader = _module.readerFromBuf(outPtr);
        const result = QueryResultCodec.decode(reader);
        return result;
      } finally {
        if (completeCompleted) {
          _module.freeBuf(outPtr);
        } else {
          _module.freeBufDescriptor(outPtr);
        }
        (_exports.boltffi_database_query_free as Function)(awaitedHandle);
      }
    } finally {
      _module.freeAlloc(sql_alloc);
    }
  }
}
