npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ticatec/mysql-common-library

v2.1.0

Published

MySQL database connection implementation for @ticatec/node-common-library framework with connection pooling and transaction support

Readme

@ticatec/mysql-common-library

A MySQL database connection implementation for the @ticatec/node-common-library framework, providing connection pooling, transaction management, and async/await support.

npm version License: MIT

中文文档 | English

Features

  • 🔄 Transaction Management: Full support for BEGIN, COMMIT, and ROLLBACK operations
  • 🏊 Connection Pooling: Built-in MySQL connection pooling with mysql2
  • Async/Await Support: Promise-based API for modern JavaScript/TypeScript
  • 🛡️ Type Safety: Full TypeScript support with proper type definitions
  • 🔍 Query Operations: Support for SELECT, INSERT, UPDATE, DELETE operations
  • 📊 Result Mapping: Automatic field mapping and camelCase conversion
  • 🏗️ Extensible Design: Clean interface implementation following DBConnection pattern

Installation

npm install @ticatec/mysql-common-library

Peer Dependencies

Make sure to install the required peer dependencies:

npm install mysql2 @ticatec/node-common-library

Quick Start

1. Initialize Connection Factory

import { initializeMySQL } from '@ticatec/mysql-common-library';

const dbFactory = initializeMySQL({
  host: 'localhost',
  user: 'root',
  password: 'your_password',
  database: 'your_database',
  port: 3306,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

2. Basic Query Operations

async function performDatabaseOperations() {
  const connection = await dbFactory.createDBConnection();
  
  try {
    // Begin transaction
    await connection.beginTransaction();
    
    // Fetch data
    const users = await connection.fetchData(
      'SELECT * FROM users WHERE status = ?', 
      ['active']
    );
    console.log('Active users:', users.rows);
    
    // Insert record
    await connection.insertRecord(
      'INSERT INTO users (name, email, status) VALUES (?, ?, ?)',
      ['John Doe', '[email protected]', 'active']
    );
    
    // Update record
    const affectedRows = await connection.executeUpdate(
      'UPDATE users SET last_login = NOW() WHERE email = ?',
      ['[email protected]']
    );
    console.log(`Updated ${affectedRows} rows`);
    
    // Commit transaction
    await connection.commit();
    
  } catch (error) {
    // Rollback on error
    await connection.rollback();
    console.error('Transaction failed:', error);
    throw error;
  } finally {
    // Always close connection
    await connection.close();
  }
}

API Reference

initializeMySQL(config): DBFactory

Creates a MySQL database factory with connection pooling.

Parameters:

  • config: MySQL connection configuration object (mysql2 PoolOptions)

Returns: DBFactory instance

MysqlDBFactory

Factory class that implements the DBFactory interface.

Methods

  • createDBConnection(): Promise<DBConnection> - Creates a new database connection from the pool

MysqlDBConnection

Database connection class that implements the DBConnection interface.

Transaction Methods

  • beginTransaction(): Promise<void> - Starts a database transaction
  • commit(): Promise<void> - Commits the current transaction
  • rollback(): Promise<void> - Rolls back the current transaction
  • close(): Promise<void> - Releases the connection back to the pool

Query Methods

  • fetchData(sql: string, params?: any[]): Promise<{rows: any[], fields: any[]}> - Executes SELECT queries
  • executeUpdate(sql: string, params: any[]): Promise<number> - Executes UPDATE/DELETE queries, returns affected row count
  • insertRecord(sql: string, params: any[]): Promise<any> - Executes INSERT queries
  • updateRecord(sql: string, params: any[]): Promise<any> - Executes UPDATE queries with result data
  • deleteRecord(sql: string, params: any[]): Promise<number> - Executes DELETE queries

Utility Methods

  • getFields(result: any): Field[] - Extracts field metadata from query results
  • getRowSet(result: any): any[] - Extracts row data from query results
  • getAffectRows(result: any): number - Gets the number of affected rows
  • getFirstRow(result: any): any | null - Gets the first row from query results

Configuration Options

The config parameter accepts all mysql2 PoolOptions. Common options include:

interface MySQLConfig {
  host?: string;           // Database host (default: 'localhost')
  port?: number;           // Database port (default: 3306)
  user?: string;           // Database username
  password?: string;       // Database password
  database?: string;       // Database name
  connectionLimit?: number; // Maximum connections in pool (default: 10)
  queueLimit?: number;     // Maximum queued requests (default: 0)
  acquireTimeout?: number; // Connection acquisition timeout (ms)
  timeout?: number;        // Query timeout (ms)
  reconnect?: boolean;     // Auto-reconnect on connection loss
  ssl?: any;              // SSL configuration
}

Error Handling

The library includes built-in error handling:

try {
  const connection = await dbFactory.createDBConnection();
  await connection.beginTransaction();
  
  // Your database operations here
  
  await connection.commit();
} catch (error) {
  if (connection) {
    await connection.rollback(); // Automatic rollback on error
  }
  console.error('Database operation failed:', error);
} finally {
  if (connection) {
    await connection.close(); // Always clean up connections
  }
}

Known Issues & Limitations

  1. Insert/Update Return Values: The insertRecord and updateRecord methods currently call getFirstRow(), but INSERT/UPDATE operations typically don't return row data. Consider using executeUpdate() for these operations instead.

  2. Type Safety: Some internal methods use any types. Consider adding more specific type definitions for better type safety.

  3. Result Structure: The getRowSet and getFirstRow methods make assumptions about result structure that may not always match the actual mysql2 response format.

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Related Packages