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

configuration.mddocs/

Configuration

Comprehensive configuration system covering connection parameters, timeouts, data formatting, SSL settings, and performance tuning options. The MariaDB connector provides extensive customization capabilities for different deployment scenarios.

Capabilities

Connection Configuration

Core connection configuration options for database connectivity.

interface ConnectionConfig {
  /** Database hostname (default: 'localhost') */
  host?: string;
  
  /** Database port (default: 3306) */
  port?: number;
  
  /** Database username */
  user?: string;
  
  /** Database password */
  password?: string;
  
  /** Database name to connect to */
  database?: string;
  
  /** Unix domain socket path (overrides host/port) */
  socketPath?: string;
}

SSL Configuration

Secure connection options for encrypted database communication.

interface ConnectionConfig {
  /** SSL configuration - boolean or detailed options */
  ssl?: boolean | SSLConfig;
}

interface SSLConfig extends SecureContextOptions {
  /** Reject connections with invalid certificates (default: true) */
  rejectUnauthorized?: boolean;
}

SSL Examples:

// Enable SSL with default settings
const connection = await mariadb.createConnection({
  host: "secure.db.com",
  user: "app",
  password: "secret", 
  ssl: true
});

// Custom SSL configuration
const connection2 = await mariadb.createConnection({
  host: "secure.db.com",
  user: "app",
  password: "secret",
  ssl: {
    ca: fs.readFileSync('./ca-cert.pem'),
    cert: fs.readFileSync('./client-cert.pem'),
    key: fs.readFileSync('./client-key.pem'),
    rejectUnauthorized: true
  }
});

Timeout Configuration

Timeout settings for various connection and query operations.

interface ConnectionConfig {
  /** Connection establishment timeout (default: 1000ms) */
  connectTimeout?: number;
  
  /** Socket timeout after connection established */
  socketTimeout?: number;
  
  /** Query execution timeout */
  queryTimeout?: number;
}

Authentication Configuration

Advanced authentication options including RSA keys and plugin settings.

interface ConnectionConfig {
  /** Path/content to MySQL server RSA public key */
  rsaPublicKey?: string;
  
  /** Path/content to MySQL server caching RSA public key */
  cachingRsaPublicKey?: string;
  
  /** Allow client to request public key from server (default: false) */
  allowPublicKeyRetrieval?: boolean;
  
  /** Allow connection with expired password (default: false) */
  permitConnectionWhenExpired?: boolean;
  
  /** Allow connection redirection (default: false) */
  permitRedirect?: boolean;
  
  /** Restricted authentication plugins */
  restrictedAuth?: string[];
  
  /** Custom stream factory for creating socket connections */
  stream?: (callback?: typeof StreamCallback) => void;
}

Character Set and Collation

Character encoding and collation configuration.

interface ConnectionConfig {
  /** Protocol character set (default: 'UTF8MB4') */
  charset?: string;
  
  /** Connection collation (default: 'UTF8MB4_UNICODE_CI') */
  collation?: string;
}

Character Set Examples:

// UTF8MB4 with Unicode collation (recommended)
const config1 = {
  charset: 'UTF8MB4',
  collation: 'UTF8MB4_UNICODE_CI'
};

// Case-insensitive collation
const config2 = {
  charset: 'UTF8MB4', 
  collation: 'UTF8MB4_GENERAL_CI'
};

// Binary collation for exact matching
const config3 = {
  charset: 'UTF8MB4',
  collation: 'UTF8MB4_BIN'
};

Data Format Configuration

Options controlling how query results are formatted and returned.

interface ConnectionConfig {
  /** Return result rows as arrays instead of objects (default: false) */
  rowsAsArray?: boolean;
  
  /** Return metadata as array [rows, metadata] (default: false) */
  metaAsArray?: boolean;
  
  /** Make metadata properties enumerable (default: false) */
  metaEnumerable?: boolean;
  
  /** Nest tables to avoid column name conflicts */
  nestTables?: boolean | string;
  
  /** Return dates as strings instead of Date objects (default: false) */
  dateStrings?: boolean;
  
  /** Force specific timezone usage (default: 'local') */
  timezone?: string;
}

Data Format Examples:

// Return rows as arrays for better performance
const fastConfig = {
  rowsAsArray: true,
  metaAsArray: false
};

// Comprehensive metadata access
const debugConfig = {
  metaAsArray: true,
  metaEnumerable: true,
  dateStrings: true
};

// Handle timezone-sensitive data
const utcConfig = {
  timezone: 'Z', // UTC
  dateStrings: false
};

Type Handling Configuration

Control how different MySQL/MariaDB data types are handled in JavaScript.

interface ConnectionConfig {
  /** Return BIGINT as Number instead of BigInt (default: false) */
  bigIntAsNumber?: boolean;
  
  /** Return insertId as Number instead of BigInt (default: false) */
  insertIdAsNumber?: boolean;
  
  /** Return DECIMAL as Number instead of string (default: false) */
  decimalAsNumber?: boolean;
  
  /** Throw error if number conversion is unsafe (default: false) */
  checkNumberRange?: boolean;
  
  /** Support big numbers (deprecated, use specific options) */
  supportBigNumbers?: boolean;
  
  /** Always return big numbers as strings (deprecated) */
  bigNumberStrings?: boolean;
  
  /** Custom type casting function */
  typeCast?: TypeCastFunction;
}

type TypeCastFunction = (field: FieldInfo, next: TypeCastNextFunction) => TypeCastResult;
type TypeCastNextFunction = () => TypeCastResult;
type TypeCastResult = boolean | number | string | symbol | null | Date | Geometry | Buffer;

Type Handling Examples:

// Handle large numbers safely
const safeNumberConfig = {
  bigIntAsNumber: false,    // Keep as BigInt
  decimalAsNumber: false,   // Keep as string
  checkNumberRange: true,   // Throw if unsafe conversion
  insertIdAsNumber: true    // Convert insertId for convenience
};

// Custom type casting
const customTypeCast: TypeCastFunction = (field, next) => {
  if (field.type === 'TINY' && field.columnLength === 1) {
    // Convert TINYINT(1) to boolean
    return field.string() === '1';
  }
  if (field.type === 'DATE') {
    // Custom date formatting
    const date = field.date();
    return date ? date.toISOString().split('T')[0] : null;
  }
  return next(); // Use default conversion
};

Query Behavior Configuration

Options controlling SQL query execution and parsing behavior.

interface ConnectionConfig {
  /** Allow multiple SQL statements per query (default: false) */
  multipleStatements?: boolean;
  
  /** Use named placeholders (:name) instead of ? (default: false) */
  namedPlaceholders?: boolean;
  
  /** Allow setting multiple values with object placeholders (default: false) */
  permitSetMultiParamEntries?: boolean;
  
  /** Enable LOAD DATA LOCAL INFILE statements (default: false) */
  permitLocalInfile?: boolean;
  
  /** Enable query pipelining for better performance (default: true) */
  pipelining?: boolean;
  
  /** Enable bulk operations in batch commands (default: true) */
  bulk?: boolean;
  
  /** Return FOUND_ROWS() instead of affected rows (default: true) */
  foundRows?: boolean;
}

Performance Configuration

Settings for optimizing connection and query performance.

interface ConnectionConfig {
  /** Enable compression for network traffic (default: false) */
  compress?: boolean;
  
  /** Server max_allowed_packet value for batch optimization (default: 4MB) */
  maxAllowedPacket?: number;
  
  /** Socket keep-alive delay in milliseconds (default: 0 - disabled) */
  keepAliveDelay?: number;
  
  /** Force server version check using SELECT VERSION() (default: false) */
  forceVersionCheck?: boolean;
  
  /** Prepared statement cache size (default: 256) */
  prepareCacheLength?: number;
}

Debug Configuration

Debugging and logging options for development and troubleshooting.

interface ConnectionConfig {
  /** Enable debug mode - log all packets (default: false) */
  debug?: boolean;
  
  /** Enable compression debug logging (default: false) */
  debugCompress?: boolean;
  
  /** Maximum packet length to log when debugging (default: 256) */
  debugLen?: number;
  
  /** Add query creation stack trace to errors (default: false) */
  trace?: boolean;
  
  /** Log query parameters in logger (default: false) */
  logParam?: boolean;
  
  /** Save last exchanged packets for error messages (default: false) */
  logPackets?: boolean;
  
  /** Logger configuration */
  logger?: LoggerConfig;
}

interface LoggerConfig {
  /** Network operation logger */
  network?: (msg: string) => void;
  
  /** Query execution logger */
  query?: (msg: string) => void;
  
  /** Error logger */
  error?: (err: Error) => void;
  
  /** Warning logger */
  warning?: (msg: string) => void;
}

interface SSLConfig extends SecureContextOptions {
  /** Reject connections with invalid certificates (default: true) */
  rejectUnauthorized?: boolean;
}

Debug Configuration Example:

const debugConnection = await mariadb.createConnection({
  host: "localhost",
  user: "root",
  password: "password",
  database: "test",
  
  // Enable comprehensive debugging
  debug: true,
  trace: true,
  logParam: true,
  logPackets: true,
  
  // Custom logger
  logger: {
    query: (sql) => console.log('Query:', sql),
    error: (err) => console.error('DB Error:', err),
    network: (msg) => console.log('Network:', msg)
  }
});

Session Configuration

Options for initializing database session state.

interface ConnectionConfig {
  /** Initial SQL commands to execute after connection */
  initSql?: string | string[];
  
  /** Session variables to set on connection */
  sessionVariables?: Record<string, any>;
  
  /** Connection attributes sent to server */
  connectAttributes?: Record<string, any>;
}

Session Configuration Example:

const connection = await mariadb.createConnection({
  host: "localhost",
  user: "app",
  password: "secret",
  database: "production",
  
  // Initialize session
  initSql: [
    "SET sql_mode = 'STRICT_TRANS_TABLES'",
    "SET time_zone = '+00:00'"
  ],
  
  // Set session variables
  sessionVariables: {
    idle_transaction_timeout: 300,
    wait_timeout: 28800,
    autocommit: 1
  },
  
  // Connection attributes for monitoring
  connectAttributes: {
    application: 'myapp',
    version: '1.2.3',
    environment: 'production'
  }
});

File Import Configuration

Configuration for SQL file import operations.

interface ConnectionConfig {
  /** Custom stream factory for LOAD LOCAL INFILE */
  infileStreamFactory?: (filepath: string) => Readable;
}

interface ImportFileConfig extends ConnectionConfig {
  /** Path to SQL file to import */
  file: string;
}

interface SqlImportOptions {
  /** Path to SQL file */
  file: string;
  
  /** Target database name (optional) */
  database?: string;
}

JSON and Data Processing

Advanced options for JSON handling and data processing.

interface ConnectionConfig {
  /** Auto-map JSON fields to JavaScript objects (default: true) */
  autoJsonMap?: boolean;
  
  /** Include array values in parentheses for compatibility (default: false) */
  arrayParenthesis?: boolean;
  
  /** Check for duplicate column names in results (default: true) */
  checkDuplicate?: boolean;
}

Default Options Function

Retrieve and customize default configuration values.

/**
 * Get default connection options
 * @param opts - Optional overrides for default values
 * @returns Configuration object with defaults applied
 */
function defaultOptions(opts?: ConnectionConfig): any;

Usage Examples:

// Get all defaults
const defaults = mariadb.defaultOptions();
console.log(defaults.host);        // 'localhost'
console.log(defaults.port);        // 3306
console.log(defaults.acquireTimeout); // undefined (pool-specific)

// Override specific defaults
const customDefaults = mariadb.defaultOptions({
  host: 'myserver.com',
  connectTimeout: 5000,
  charset: 'latin1'
});

// Use defaults as base for configuration
const config = {
  ...mariadb.defaultOptions(),
  user: 'myuser',
  password: 'mypass',
  database: 'mydb'
};

Configuration Best Practices

Production Configuration:

const productionConfig = {
  // Connection basics
  host: process.env.DB_HOST,
  port: parseInt(process.env.DB_PORT || '3306'),
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
  
  // Security
  ssl: {
    ca: fs.readFileSync('./ca-cert.pem'),
    rejectUnauthorized: true
  },
  
  // Performance
  compress: true,
  pipelining: true,
  prepareCacheLength: 512,
  
  // Reliability
  connectTimeout: 5000,
  queryTimeout: 30000,
  acquireTimeout: 10000,
  
  // Data handling
  charset: 'UTF8MB4',
  collation: 'UTF8MB4_UNICODE_CI',
  bigIntAsNumber: false,
  checkNumberRange: true,
  
  // Monitoring
  trace: false, // Only in development
  logger: {
    error: (err) => logger.error('Database error', err),
    warning: (msg) => logger.warn('Database warning', msg)
  }
};

Development Configuration:

const developmentConfig = {
  host: 'localhost',
  user: 'dev',
  password: 'dev',
  database: 'app_dev',
  
  // Debug settings
  debug: true,
  trace: true,
  logParam: true,
  
  // Permissive settings for testing
  multipleStatements: true,
  permitLocalInfile: true,
  
  // Fast feedback
  connectTimeout: 2000,
  queryTimeout: 10000
};

docs

callbacks.md

clustering.md

configuration.md

connections.md

errors.md

index.md

pooling.md

queries.md

types.md

tile.json