CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mariadb

Fast MariaDB and MySQL connector for Node.js with Promise and callback APIs

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

callbacks.mddocs/

Callback API

The MariaDB Node.js connector provides a complete callback-based API that mirrors the Promise-based API. All async methods use Node.js-style callbacks with the signature (err, result, meta?) => void.

Core Imports

const mariadb = require("mariadb/callback");
const { createConnection, createPool, createPoolCluster, importFile, SqlError, version } = require("mariadb/callback");

Capabilities

Create Connection (Callback)

Creates a new database connection using callback-based API.

/**
 * Create a new database connection (Callback-based API)
 * @param config - Connection configuration object or connection string
 * @returns Connection instance (callback-based)
 */
function createConnection(config: string | ConnectionConfig): Connection;

Usage Example:

const mariadb = require("mariadb/callback");

// Create connection - connection is returned immediately
const connection = mariadb.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test"
});

// Listen for connection events
connection.on('connect', () => {
  console.log('Connected to database');
  
  // Now you can use the connection
  connection.query("SELECT * FROM users", (err, rows, meta) => {
    if (err) {
      console.error('Query failed:', err);
      return;
    }
    console.log('Query results:', rows);
    console.log('Query metadata:', meta);
  });
});

connection.on('error', (err) => {
  console.error('Connection error:', err);
});

Connection Interface (Callback-based)

Main connection interface providing callback-based database operations.

interface Connection extends EventEmitter {
  /** Connection information */
  info: ConnectionInfo | null;
  /** Connection thread identifier */
  readonly threadId: number | null;
  
  /** Change connection user and reset session */
  changeUser(options: UserConnectionConfig, callback: (err: SqlError | null) => void): void;
  
  /** Start transaction */
  beginTransaction(callback: (err: SqlError | null) => void): void;
  
  /** Commit a transaction */
  commit(callback: (err: SqlError | null) => void): void;
  
  /** Roll back a transaction */
  rollback(callback: (err: SqlError | null) => void): void;
  
  /** Execute query using text protocol */
  query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  
  /** Prepare statement */
  prepare(sql: string | QueryOptions, callback: (err: SqlError | null, prepare?: Prepare) => void): void;
  
  /** Execute query using binary (prepare) protocol */
  execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  
  /** Execute batch operations */
  batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
  batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
  
  /** Execute query returning a Readable stream */
  queryStream(sql: string | QueryOptions, values?: any): Readable;
  
  /** Send ping to server */
  ping(callback: (err: SqlError | null) => void): void;
  
  /** Reset connection state */
  reset(callback: (err: SqlError | null) => void): void;
  
  /** Import SQL file */
  importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;
  
  /** Check if connection is valid */
  isValid(): boolean;
  
  /** Close connection gracefully */
  end(callback: (err: SqlError | null) => void): void;
  
  /** Alias for end() */
  close(callback: (err: SqlError | null) => void): void;
  
  /** Force connection termination */
  destroy(): void;
  
  /** Connection control methods */
  pause(): void;
  resume(): void;
  
  /** Get server version */
  serverVersion(): string;
  
  /** Debug control */
  debug(value: boolean): void;
  debugCompress(value: boolean): void;
  
  /** Escape utilities */
  escape(value: any): string;
  escapeId(identifier: string): string;
}

Usage Examples:

const mariadb = require("mariadb/callback");

const connection = mariadb.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test"
});

connection.on('connect', () => {
  // Basic query with parameters
  connection.query("SELECT * FROM users WHERE age > ?", [18], (err, rows, meta) => {
    if (err) {
      console.error('Query error:', err);
      return;
    }
    console.log('Users:', rows);
    console.log('Field info:', meta);
  });
  
  // Transaction example
  connection.beginTransaction((err) => {
    if (err) {
      console.error('Begin transaction error:', err);
      return;
    }
    
    connection.query("INSERT INTO users (name, age) VALUES (?, ?)", ["Alice", 25], (err, result) => {
      if (err) {
        return connection.rollback((rollbackErr) => {
          console.error('Insert error:', err);
          console.error('Rollback error:', rollbackErr);
        });
      }
      
      connection.commit((err) => {
        if (err) {
          return connection.rollback((rollbackErr) => {
            console.error('Commit error:', err);
            console.error('Rollback error:', rollbackErr);
          });
        }
        console.log('Transaction committed successfully');
        console.log('Insert ID:', result.insertId);
      });
    });
  });
});

Prepared Statements (Callback)

Prepared statement interface for callback-based API.

interface Prepare {
  id: number;
  
  /** Execute prepared statement */
  execute<T>(values: any, callback: (err: SqlError | null, result?: T, meta?: any) => void): void;
  
  /** Execute prepared statement returning a stream */
  executeStream(values: any): Readable;
  
  /** Close prepared statement */
  close(): void;
}

Usage Example:

connection.prepare("SELECT * FROM users WHERE age > ?", (err, prepare) => {
  if (err) {
    console.error('Prepare error:', err);
    return;
  }
  
  // Execute multiple times with different values
  prepare.execute([18], (err, result) => {
    if (err) {
      console.error('Execute error:', err);
      return;
    }
    console.log('Adults:', result);
  });
  
  prepare.execute([65], (err, result) => {
    if (err) {
      console.error('Execute error:', err);
      return;
    }
    console.log('Seniors:', result);
    
    // Close when done
    prepare.close();
  });
});

Pool Connection (Callback)

Pool connection interface extending the base connection with release functionality.

interface PoolConnection extends Connection {
  /** Release connection back to pool */
  release(callback: (err: SqlError | null) => void): void;
}

Pool Interface (Callback)

Connection pool interface for callback-based API.

interface Pool {
  closed: boolean;
  
  /** Get connection from pool */
  getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
  
  /** Execute query on pool connection */
  query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  
  /** Execute batch on pool connection */
  batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
  batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
  
  /** Execute using prepared statement on pool connection */
  execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  
  /** Close all pool connections */
  end(callback: (err: SqlError | null) => void): void;
  
  /** Import SQL file using pool connection */
  importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;
  
  /** Pool statistics */
  activeConnections(): number;
  totalConnections(): number;
  idleConnections(): number;
  taskQueueSize(): number;
  
  /** Escape utilities */
  escape(value: any): string;
  escapeId(identifier: string): string;
}

Usage Example:

const mariadb = require("mariadb/callback");

const pool = mariadb.createPool({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test",
  connectionLimit: 5
});

// Get connection from pool
pool.getConnection((err, conn) => {
  if (err) {
    console.error('Pool connection error:', err);
    return;
  }
  
  conn.query("SELECT * FROM users", (err, rows) => {
    if (err) {
      console.error('Query error:', err);
    } else {
      console.log('Query result:', rows);
    }
    
    // Always release connection back to pool
    conn.release((err) => {
      if (err) {
        console.error('Release error:', err);
      }
    });
  });
});

// Direct pool query (automatically manages connection)
pool.query("SELECT COUNT(*) as total FROM users", (err, result) => {
  if (err) {
    console.error('Pool query error:', err);
    return;
  }
  console.log('Total users:', result[0].total);
});

Pool Cluster (Callback)

Pool cluster interface for managing multiple pools with callback-based API.

interface PoolCluster {
  /** Add pool to cluster */
  add(id: string, config: PoolConfig): void;
  
  /** Close all pools in cluster */
  end(callback: (err: SqlError | null) => void): void;
  
  /** Get filtered cluster interface */
  of(pattern: string, selector?: string): FilteredPoolCluster;
  of(pattern: undefined | null | false, selector: string): FilteredPoolCluster;
  
  /** Remove pools matching pattern */
  remove(pattern: string): void;
  
  /** Get connection from cluster */
  getConnection(pattern: string | undefined | null, selector: string | undefined | null, callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
  getConnection(pattern: string | undefined | null, callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
  getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
}

interface FilteredPoolCluster {
  /** Get connection from filtered cluster */
  getConnection(callback: (err: SqlError | null, conn?: PoolConnection) => void): void;
  
  /** Execute query on filtered cluster */
  query<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  query<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  
  /** Execute batch on filtered cluster */
  batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
  batch<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T) => void): void;
  
  /** Execute prepared statement on filtered cluster */
  execute<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
  execute<T>(sql: string | QueryOptions, callback: (err: SqlError | null, result?: T, meta?: FieldInfo[]) => void): void;
}

Import File (Callback)

Import SQL files using callback-based API.

/**
 * Import SQL file (Callback-based)
 * @param config - Import configuration including file path and connection options
 * @param callback - Callback function (err) => void
 */
function importFile(config: ImportFileConfig, callback: (err: SqlError | null) => void): void;

Usage Example:

const mariadb = require("mariadb/callback");

mariadb.importFile({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test",
  file: "./schema.sql"
}, (err) => {
  if (err) {
    console.error('Import failed:', err);
    return;
  }
  console.log('SQL file imported successfully');
});

Event Handling

All callback-based connections and pools are EventEmitters and support the same events as their Promise-based counterparts:

// Connection events
connection.on('error', (err) => {
  console.error('Connection error:', err);
});

connection.on('end', () => {
  console.log('Connection ended');
});

// Pool events
pool.on('acquire', (conn) => {
  console.log('Connection acquired from pool');
});

pool.on('release', (conn) => {
  console.log('Connection released to pool');
});

pool.on('connection', (conn) => {
  console.log('New connection created in pool');
});

pool.on('enqueue', () => {
  console.log('Connection request queued');
});

Error Handling

All callback functions follow Node.js conventions with error as the first parameter:

connection.query("SELECT * FROM users", (err, result, meta) => {
  if (err) {
    // Handle error
    console.error('Query failed:', err.message);
    console.error('SQL State:', err.sqlState);
    console.error('Error Code:', err.errno);
    console.error('Fatal:', err.fatal);
    return;
  }
  
  // Process successful result
  console.log('Query succeeded:', result);
  console.log('Metadata:', meta);
});

docs

callbacks.md

clustering.md

configuration.md

connections.md

errors.md

index.md

pooling.md

queries.md

types.md

tile.json