Skip to content
Oxford Harrison edited this page Nov 19, 2024 · 11 revisions

DOCSAPITable API


Programmatically perform an INSERT query.

See related ➞ INSERT

Syntax

table.insert(
    spec: InsertSpec | Callback
): Promise<InsertResult>;
Param Interfaces Description
spec InsertSpec The Insert spec. Can be Callback—a callback function that recieves the underlying UpdateStatement instance for manipulation.

InsertSpec

interface InsertSpec {
    data?: Data | Data[];
    columns?: Column[];
    values?: any[][];
    returning?: Field[];
}
Param Interfaces Description
data? Data An optional key/value data object or an array of data objects.
columns? Column An optional array of columns. Required if data is not specified.
values? - A optional two-dimensional array of values; i.e. an array of values to a row. Required if columns is specified.
returning? Field Optional list of fields to return from the just created records.

InsertResult

type InsertResult = number | Array<object> | object;
Type Interfaces Description
number - The default insert result—a number indicating the number of records created.
object - The insert result of the first call pattern in combination with a RETURNING clause—an object representing the created record.
Array<object> - The insert result of the second and third call patterns in combination with a RETURNING clause—an array of objects representing the created records.

Usage

Insert single record:

await table.insert({
    data: {
        first_name: 'John',
        last_name: 'Doe',
        email: '[email protected]'
    }
});

Insert multiple records:

await table.insert({
    data: [
        { first_name: 'John', last_name: 'Doe', email: '[email protected]'},
        { first_name: 'James', last_name: 'Clerk', email: '[email protected]'}
    ]
});

Repeat the previous using the columns/values syntax:

await table.insert({
    columns: ['first_name', 'last_name', 'email'],
    values: [
        ['John', 'Doe', '[email protected]'],
        ['James', 'Clerk', '[email protected]'],
    ]
});

See more ➞ INSERT

Returning Records

Return the just created records (array):

const result = await table.insert({
    data: [
        {
            first_name: 'John',
            last_name: 'Doe',
            email: '[email protected]'
        }
    ],
    returning: 'id'
});

Return the just created record (object):

const result = await table.insert({
    data: {
        first_name: 'John',
        last_name: 'Doe',
        email: '[email protected]'
    },
    returning: 'id'
});
Clone this wiki locally