@earth-app/collegedb
    Preparing search index...

    Function insert

    • Executes an insert on an automatically selected shard and returns the generated primary key.

      This is the default helper for generated-key tables. CollegeDB picks a shard using the configured allocation strategy, then stores the generated primary key -> shard mapping so routed reads can find the row later.

      A database-generated id is only unique within its own shard. Every shard runs its own AUTOINCREMENT or SERIAL sequence, so spreading a generated-key table across shards eventually mints the same id twice. When that happens this throws GENERATED_KEY_COLLISION rather than overwriting the first mapping and stranding its row. For a generated-key table that spans shards, allocate the id with nextId and pass it explicitly; to keep using the database's own sequence, confine the table to one shard with insertShard.

      The refused row. The INSERT has already run when the collision shows up. CollegeDB takes only a raw SQL string here and does not parse it, so it does not know which table to clean. Pass options.table and it deletes the row it just wrote (matched on idColumn, default id) before it throws. Without table the row stays on the shard and removing it is the caller's job; the error message names the shard and id. If the delete itself fails, the error still has the code GENERATED_KEY_COLLISION, names the shard and id of the leftover row, and carries the delete failure as cause.

      Type Parameters

      • T = Record<string, unknown>

        Type of returned rows when the insert uses RETURNING

      Parameters

      • sql: string

        The INSERT statement to execute

      • bindings: any[] = []

        Parameter values to bind to the statement

      • options: InsertOptions = {}

        idColumn names the generated key column, table enables cleanup of a refused row

      Returns Promise<InsertResult<T>>

      Promise resolving to the write result plus the generated id

      If the insert succeeds but no generated id can be determined

      GENERATED_KEY_COLLISION when another shard already owns the generated id

      1.1.4

      const created = await insert(
      'INSERT INTO auto_users (name, email) VALUES (?, ?)',
      ['Ada', 'ada@example.com']
      );

      const row = await first(String(created.generatedId), 'SELECT * FROM auto_users WHERE id = ?', [created.generatedId]);