Fast MariaDB and MySQL connector for Node.js with Promise and callback APIs
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Core database connection functionality for establishing, managing, and executing queries on individual database connections. The MariaDB connector provides both Promise-based and callback-based APIs for maximum flexibility.
Creates a new database connection with the specified configuration.
/**
* Create a new database connection (Promise-based API)
* @param config - Connection configuration object or connection string
* @returns Promise resolving to Connection instance
*/
function createConnection(config: string | ConnectionConfig): Promise<Connection>;Usage Example:
import mariadb from "mariadb";
// Using configuration object
const connection = await mariadb.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "test",
port: 3306
});
// Using connection string
const connection2 = await mariadb.createConnection("mariadb://user:password@localhost:3306/database");Main connection interface providing Promise-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): Promise<void>;
/** Execute SQL query using text protocol */
query<T = any>(sql: string | QueryOptions, values?: any): Promise<T>;
/** Execute SQL query using binary (prepared statement) protocol */
execute<T = any>(sql: string | QueryOptions, values?: any): Promise<T>;
/** Prepare SQL statement for repeated execution */
prepare(sql: string | QueryOptions): Promise<Prepare>;
/** Execute batch operations with multiple value sets */
batch<T = UpsertResult | UpsertResult[]>(sql: string | QueryOptions, values?: any): Promise<T>;
/** Execute query returning a Readable stream for large result sets */
queryStream(sql: string | QueryOptions, values?: any): Readable;
/** Start database transaction */
beginTransaction(): Promise<void>;
/** Commit current transaction */
commit(): Promise<void>;
/** Rollback current transaction */
rollback(): Promise<void>;
/** Send ping to ensure connection is active */
ping(): Promise<void>;
/** Reset connection state (rollback transactions, reset variables) */
reset(): Promise<void>;
/** Import SQL file into database */
importFile(config: SqlImportOptions): Promise<void>;
/** Check if connection is valid and active */
isValid(): boolean;
/** Close connection gracefully */
end(): Promise<void>;
/** Alias for end() */
close(): Promise<void>;
/** Force close connection immediately */
destroy(): void;
/** Pause connection (stop reading from socket) */
pause(): void;
/** Resume connection (continue reading from socket) */
resume(): void;
/** Get server version string */
serverVersion(): string;
/** Toggle debug mode */
debug(value: boolean): void;
/** Toggle compression debug mode */
debugCompress(value: boolean): void;
/** Escape SQL parameter to prevent injection */
escape(value: any): string;
/** Escape SQL identifier (table/column names) */
escapeId(identifier: string): string;
/** Event listeners */
on(event: 'end', listener: () => void): Connection;
on(event: 'error', listener: (err: SqlError) => void): Connection;
on(event: string | symbol, listener: (...args: any[]) => void): this;
}Alternative callback-based connection interface for applications preferring callback patterns.
/**
* Create callback-based connection
* @param config - Connection configuration
* @returns Connection instance with callback methods
*/
function createConnection(config: string | ConnectionConfig): Connection;
interface Connection extends EventEmitter {
info: ConnectionInfo | null;
readonly threadId: number | null;
/** All methods use Node.js callback pattern: (error, result) => void */
changeUser(options: UserConnectionConfig, callback: (err: SqlError | null) => void): void;
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<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;
prepare(sql: string | QueryOptions, callback: (err: SqlError | null, prepare?: Prepare) => void): void;
batch<T>(sql: string | QueryOptions, values: any, callback: (err: SqlError | null, result?: T) => void): void;
beginTransaction(callback: (err: SqlError | null) => void): void;
commit(callback: (err: SqlError | null) => void): void;
rollback(callback: (err: SqlError | null) => void): void;
ping(callback: (err: SqlError | null) => void): void;
reset(callback: (err: SqlError | null) => void): void;
importFile(config: SqlImportOptions, callback: (err: SqlError | null) => void): void;
end(callback: (err: SqlError | null) => void): void;
close(callback: (err: SqlError | null) => void): void;
/** Synchronous methods remain the same */
isValid(): boolean;
destroy(): void;
pause(): void;
resume(): void;
serverVersion(): string;
debug(value: boolean): void;
debugCompress(value: boolean): void;
escape(value: any): string;
escapeId(identifier: string): string;
}Configuration options for changing user credentials during connection lifetime.
interface UserConnectionConfig {
/** Name of the database to use */
database?: string;
/** Connection attributes sent to server */
connectAttributes?: any;
/** Protocol character set (default: 'UTF8MB4') */
charset?: string;
/** Connection collation (default: 'UTF8MB4_UNICODE_CI') */
collation?: string;
/** MySQL user to authenticate as */
user?: string;
/** Password for MySQL user */
password?: string;
}Import SQL files directly into the database. The connector supports both standalone import (creates its own connection) and import through existing connections.
/**
* Import SQL file using standalone function (Promise-based)
* @param config - Import configuration including connection details
* @returns Promise that resolves when import completes
*/
function importFile(config: ImportFileConfig): Promise<void>;
/**
* Import SQL file using standalone function (Callback-based)
* @param config - Import configuration including connection details
* @param callback - Callback function (err) => void
*/
function importFile(config: ImportFileConfig, callback: (err: SqlError | null) => void): void;
interface ImportFileConfig extends ConnectionConfig {
/** Path to SQL file to import */
file: string;
}
interface SqlImportOptions {
/** Path to SQL file */
file: string;
/** Target database name (optional, uses current if not specified) */
database?: string;
}Usage Examples:
const mariadb = require("mariadb");
// Promise-based standalone import
await mariadb.importFile({
host: "localhost",
user: "root",
password: "password",
database: "test",
file: "./backup.sql"
});
// Callback-based standalone import
const mariadbCallback = require("mariadb/callback");
mariadbCallback.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');
});
// Import using existing connection (Promise-based)
const connection = await mariadb.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "test"
});
await connection.importFile({
file: "./schema.sql",
database: "production" // Optional: import to different database
});
// Import using existing connection (Callback-based)
const callbackConnection = mariadbCallback.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "test"
});
callbackConnection.on('connect', () => {
callbackConnection.importFile({
file: "./data.sql"
}, (err) => {
if (err) {
console.error('Import error:', err);
return;
}
console.log('Import completed');
});
});Connections emit various events during their lifecycle.
// Connection established (callback API only)
connection.on('connect', () => {
console.log('Connected to database');
});
// Connection ended
connection.on('end', () => {
console.log('Connection closed');
});
// Connection error
connection.on('error', (err: SqlError) => {
console.error('Connection error:', err);
});Get default connection configuration options.
/**
* Get default connection options
* @param opts - Optional configuration to override defaults
* @returns Object containing default options
*/
function defaultOptions(opts?: ConnectionConfig): any;Usage Example:
const defaults = mariadb.defaultOptions();
console.log(defaults.host); // 'localhost'
console.log(defaults.port); // 3306
// Override specific options
const customDefaults = mariadb.defaultOptions({
host: "myserver.com",
timeout: 5000
});