Interface Database

Database is a database handle representing a pool of zero or more underlying connections.

 import sql from "k6/x/sql";

// the actual database driver should be used instead of ramsql
import driver from "k6/x/sql/driver/ramsql";

const db = sql.open(driver, "roster_db");
interface Database {
    close(): void;
    exec(query: string, ...args: any[]): Result;
    query(query: string, ...args: any[]): Row[];
}

Methods

Methods

  • Close the database and prevents new queries from starting.

    Close waits for all queries that have started processing on the server to finish.

    Returns void

     import sql from "k6/x/sql";

    // the actual database driver should be used instead of ramsql
    import driver from "k6/x/sql/driver/ramsql";

    const db = sql.open(driver, "roster_db");

    export function teardown() {
    db.close();
    }
  • Execute a query without returning any rows.

    Parameters

    • query: string

      the query to execute

    • Rest...args: any[]

      placeholder parameters in the query

    Returns Result

    summary of the executed SQL commands

     import sql from "k6/x/sql";

    // the actual database driver should be used instead of ramsql
    import driver from "k6/x/sql/driver/ramsql";

    const db = sql.open(driver, "roster_db");

    export function setup() {
    db.exec(`
    CREATE TABLE IF NOT EXISTS roster
    (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    given_name VARCHAR NOT NULL,
    family_name VARCHAR NOT NULL
    );
    `);

    let result = db.exec(`
    INSERT INTO roster
    (given_name, family_name)
    VALUES
    ('Peter', 'Pan'),
    ('Wendy', 'Darling'),
    ('Tinker', 'Bell'),
    ('James', 'Hook');
    `);
    console.log(`${result.rowsAffected()} rows inserted`);
    }
  • Query executes a query that returns rows, typically a SELECT.

    Parameters

    • query: string

      the query to execute

    • Rest...args: any[]

      placeholder parameters in the query

    Returns Row[]

    rows of the query result

     import sql from "k6/x/sql";

    // the actual database driver should be used instead of ramsql
    import driver from "k6/x/sql/driver/ramsql";

    const db = sql.open(driver, "roster_db");

    export default function () {
    let rows = db.query("SELECT * FROM roster WHERE given_name = $1;", "Peter");
    for (const row of results) {
    console.log(`${row.family_name}, ${row.given_name}`);
    }
    }