geopackage-ts
    Preparing search index...

    Class GeoPackageConnection

    A wrapper around a better-sqlite3 database connection tailored for working with OGC GeoPackage files.

    Instances are created through the static factory methods (open, openReadonly, openBuffer, create, and createInMemory) rather than by calling the constructor directly.

    // Open an existing GeoPackage for reading and writing
    const conn = GeoPackageConnection.open('/path/to/my.gpkg');

    // Query a table
    const rows = conn.all('SELECT * FROM gpkg_contents');

    // Clean up
    conn.close();
    Index

    Properties

    filePath: string | null

    The file-system path that was used to open or create the database, or null when the database was created in-memory or from a buffer.

    Accessors

    • get isOpen(): boolean

      Indicates whether the underlying database connection is currently open.

      Returns boolean

      true if the connection is open, false if it has been closed.

      console.log(conn.isOpen); // true
      conn.close();
      console.log(conn.isOpen); // false
    • get raw(): Database

      Provides direct access to the underlying better-sqlite3 DatabaseType | Database instance.

      Use this escape hatch when you need functionality that is not exposed by the GeoPackageConnection wrapper.

      Returns Database

      The raw better-sqlite3 database handle.

      const rawDb = conn.raw;
      rawDb.pragma('cache_size = -64000');

    Methods

    • Executes a SQL query and returns all matching rows as an array.

      Type Parameters

      • T = Record<string, unknown>

        The expected shape of each row object. Defaults to Record<string, unknown>.

      Parameters

      • sql: string

        The SQL statement to execute (may contain ? placeholders).

      • ...params: unknown[]

        Bind parameters that correspond to the placeholders in sql.

      Returns T[]

      An array of rows typed as T[]. Returns an empty array when no rows match.

      const rows = conn.all<{ table_name: string }>(
      'SELECT table_name FROM gpkg_contents',
      );
    • Closes the database connection if it is currently open.

      Calling this on an already-closed connection is a no-op.

      Returns void

      conn.close();
      console.log(conn.isOpen); // false
    • Checks whether a specific column exists in the given table.

      Parameters

      • tableName: string

        The name of the table to inspect.

      • columnName: string

        The column name to look for.

      Returns boolean

      true if the column exists in the table, false otherwise.

      if (conn.columnExists('my_layer', 'geom')) {
      // column is present
      }
    • Returns the number of rows in a table, optionally filtered by a WHERE clause.

      Parameters

      • tableName: string

        The name of the table to count rows in.

      • Optionalwhere: string

        An optional SQL WHERE clause without the WHERE keyword (e.g. "name = ?").

      • ...params: unknown[]

        Bind parameters for the WHERE clause.

      Returns number

      The row count, or 0 if the table is empty / no rows match.

      // Total rows
      const total = conn.count('gpkg_contents');

      // Filtered rows
      const features = conn.count('gpkg_contents', 'data_type = ?', 'features');
    • Drops a table from the database if it exists.

      This executes DROP TABLE IF EXISTS so it will not throw when the table is absent.

      Parameters

      • tableName: string

        The name of the table to drop.

      Returns void

      conn.dropTable('temp_features');
      
    • Switches the database journal mode to WAL (Write-Ahead Logging).

      WAL mode can improve concurrency and write performance. It is not enabled by default because the GeoPackage specification does not require it.

      Returns void

      conn.enableWAL();
      
    • Executes one or more SQL statements that do not return data.

      Unlike run, this method accepts multiple semicolon-separated statements and does not support bind parameters.

      Parameters

      • sql: string

        One or more SQL statements to execute.

      Returns void

      If any statement is invalid or fails.

      conn.exec(`
      CREATE TABLE foo (id INTEGER PRIMARY KEY);
      CREATE TABLE bar (id INTEGER PRIMARY KEY);
      `);
    • Serialises the entire database to a Buffer.

      This is especially useful for in-memory databases created with createInMemory or openBuffer when you need to persist or transmit the resulting GeoPackage.

      Returns Buffer

      A Buffer containing the full SQLite database image.

      const conn = GeoPackageConnection.createInMemory();
      // ... populate ...
      const buf = conn.export();
      writeFileSync('out.gpkg', buf);
    • Executes a SQL query and returns the first matching row, or undefined if the result set is empty.

      Type Parameters

      • T = Record<string, unknown>

        The expected shape of the returned row object. Defaults to Record<string, unknown>.

      Parameters

      • sql: string

        The SQL statement to execute (may contain ? placeholders).

      • ...params: unknown[]

        Bind parameters that correspond to the placeholders in sql.

      Returns T | undefined

      The first row as T, or undefined when no rows match.

      interface ContentRow { table_name: string; data_type: string }
      const row = conn.get<ContentRow>(
      'SELECT * FROM gpkg_contents WHERE table_name = ?',
      'my_layer',
      );
    • Reads the current SQLite application_id pragma value.

      Returns number

      The 32-bit application ID stored in the database header.

      const id = conn.getApplicationId();
      console.log(id === 0x47504B47); // true for a valid GeoPackage
    • Reads the current SQLite user_version pragma value.

      For a GeoPackage this typically encodes the specification version (e.g. 10200 for version 1.2.0).

      Returns number

      The user version integer stored in the database header.

      const ver = conn.getUserVersion();
      console.log(ver); // e.g. 10200
    • Executes a SQL query and returns a lazy IterableIterator over the result rows. This is more memory-efficient than all for large result sets.

      Type Parameters

      • T = Record<string, unknown>

        The expected shape of each row object. Defaults to Record<string, unknown>.

      Parameters

      • sql: string

        The SQL statement to execute (may contain ? placeholders).

      • ...params: unknown[]

        Bind parameters that correspond to the placeholders in sql.

      Returns IterableIterator<T>

      An iterable iterator yielding rows typed as T.

      for (const row of conn.iterate<{ id: number }>('SELECT id FROM big_table')) {
      process.stdout.write(`${row.id}\n`);
      }
    • Returns the maximum value of a numeric column in the given table.

      Parameters

      • tableName: string

        The name of the table to query.

      • columnName: string

        The name of the column whose maximum value is desired.

      Returns number | null

      The maximum value, or null if the table is empty or all values are NULL.

      const maxLat = conn.maxOfColumn('my_layer', 'max_y');
      
    • Returns the minimum value of a numeric column in the given table.

      Parameters

      • tableName: string

        The name of the table to query.

      • columnName: string

        The name of the column whose minimum value is desired.

      Returns number | null

      The minimum value, or null if the table is empty or all values are NULL.

      const minLat = conn.minOfColumn('my_layer', 'min_y');
      
    • Prepares a SQL statement for repeated execution.

      The returned Statement can be executed multiple times with different parameters, which is more efficient than calling run or get in a loop.

      Parameters

      • sql: string

        The SQL statement to prepare (may contain ? placeholders).

      Returns Statement

      A compiled better-sqlite3 Statement.

      const stmt = conn.prepare('INSERT INTO my_table (name) VALUES (?)');
      stmt.run('Alice');
      stmt.run('Bob');
    • Registers a custom scalar SQL function on this database connection.

      Parameters

      • name: string

        The name of the SQL function (used in queries).

      • fn: (...args: unknown[]) => unknown

        The JavaScript implementation of the function. Receives SQL values as arguments and must return a SQL-compatible value.

      • Optionaloptions: { deterministic?: boolean; varargs?: boolean }

        Optional configuration for the function.

        • Optionaldeterministic?: boolean

          When true (the default), SQLite may cache return values for identical inputs.

        • Optionalvarargs?: boolean

          When true, the function accepts a variable number of arguments. Defaults to false.

      Returns void

      conn.registerFunction('double', (x: unknown) => (x as number) * 2);
      const row = conn.get<{ val: number }>('SELECT double(21) as val');
      console.log(row?.val); // 42
    • Executes a SQL statement that modifies data (INSERT, UPDATE, DELETE) and returns information about the changes made.

      Parameters

      • sql: string

        The SQL statement to execute (may contain ? placeholders).

      • ...params: unknown[]

        Bind parameters that correspond to the placeholders in sql.

      Returns RunResult

      A RunResult containing changes (number of rows affected) and lastInsertRowid.

      const result = conn.run(
      'INSERT INTO my_table (name) VALUES (?)',
      'hello',
      );
      console.log(result.changes); // 1
    • Sets the SQLite application_id pragma.

      By default this writes the GeoPackage magic number (0x47504B47, i.e. the ASCII string GPKG).

      Parameters

      • id: number = APPLICATION_ID

        The application ID to write. Defaults to APPLICATION_ID (0x47504B47).

      Returns void

      conn.setApplicationId(); // sets the standard GPKG application ID
      
    • Sets the SQLite user_version pragma.

      By default this writes the GeoPackage specification version number (10200, representing version 1.2.0).

      Parameters

      • version: number = USER_VERSION

        The user version to write. Defaults to USER_VERSION (10200).

      Returns void

      conn.setUserVersion(); // sets user_version to 10200
      
    • Checks whether a table with the given name exists in the database.

      Parameters

      • tableName: string

        The name of the table to look for.

      Returns boolean

      true if the table exists, false otherwise.

      if (conn.tableExists('gpkg_extensions')) {
      // handle extensions
      }
    • Wraps the given function in a SQLite transaction.

      All statements executed inside fn are committed atomically. If fn throws, the transaction is rolled back.

      Type Parameters

      • T

        The return type of the wrapped function.

      Parameters

      • fn: () => T

        A synchronous function containing the operations to run inside the transaction.

      Returns T

      The value returned by fn.

      Re-throws any error raised inside fn after rolling back.

      conn.transaction(() => {
      conn.run('INSERT INTO my_table (name) VALUES (?)', 'Alice');
      conn.run('INSERT INTO my_table (name) VALUES (?)', 'Bob');
      });
    • Creates a new GeoPackage file at the given path.

      If a file already exists at path it will be opened (and potentially overwritten depending on subsequent operations). Foreign-key enforcement is enabled automatically.

      Parameters

      • path: string

        Absolute or relative path where the .gpkg file should be created.

      Returns GeoPackageConnection

      A new GeoPackageConnection instance.

      If the path is not writable.

      const conn = GeoPackageConnection.create('./output/new.gpkg');
      conn.setApplicationId();
      conn.setUserVersion();
    • Creates a new GeoPackage database entirely in memory.

      The database can later be serialised to a Buffer with export. Foreign-key enforcement is enabled automatically. The resulting connection's filePath will be null.

      Returns GeoPackageConnection

      A new in-memory GeoPackageConnection instance.

      const conn = GeoPackageConnection.createInMemory();
      conn.setApplicationId();
      // ... populate tables ...
      const buffer = conn.export();
    • Opens an existing GeoPackage file for reading and writing.

      Foreign-key enforcement is enabled automatically.

      Parameters

      • path: string

        Absolute or relative path to the .gpkg file.

      Returns GeoPackageConnection

      A new GeoPackageConnection instance.

      If the file does not exist or cannot be opened.

      const conn = GeoPackageConnection.open('./data/countries.gpkg');
      
    • Opens a GeoPackage from an in-memory Buffer.

      This is useful when a GeoPackage has been fetched over the network or read from a non-file source. Foreign-key enforcement is enabled automatically.

      The resulting connection's filePath will be null.

      Parameters

      • buffer: Buffer

        A Buffer containing the raw bytes of a GeoPackage (SQLite) database.

      Returns GeoPackageConnection

      A new GeoPackageConnection instance backed by the buffer.

      If the buffer does not contain a valid SQLite database.

      import { readFileSync } from 'node:fs';
      const buf = readFileSync('./data/countries.gpkg');
      const conn = GeoPackageConnection.openBuffer(buf);
    • Opens an existing GeoPackage file in read-only mode.

      Foreign-key enforcement is not enabled because the database cannot be modified.

      Parameters

      • path: string

        Absolute or relative path to the .gpkg file.

      Returns GeoPackageConnection

      A new read-only GeoPackageConnection instance.

      If the file does not exist or cannot be opened.

      const conn = GeoPackageConnection.openReadonly('./data/countries.gpkg');
      const rows = conn.all('SELECT * FROM gpkg_contents');