Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

highsql

Package Overview
Dependencies
Maintainers
0
Versions
21
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

highsql - npm Package Compare versions

Comparing version 1.2.0 to 1.2.1

2

package.json
{
"name": "highsql",
"version": "1.2.0",
"version": "1.2.1",
"description": "High level MySQL utility",

@@ -5,0 +5,0 @@ "main": "./src/index.js",

@@ -0,41 +1,32 @@

/**
* Project Name: MySQL Database Connection
* Author: Defeeeee
*
* This TypeScript module provides a class `Connection` that encapsulates the functionality of a MySQL database connection.
* It uses the `mysql2/promise` library to create a connection pool and provides methods for common SQL operations.
* It also includes error handling for queries and pool operations.
*
* The `Connection` class requires a configuration object of type `ConnectionConfig` to establish a connection to the database.
*
* The `Connection` class provides the following methods:
* - `query`: Executes a SQL query with optional values and returns the result.
* - `select`, `insert`, `update`, `delete`: Convenience methods for common SQL operations.
* - `get`, `getByID`: Methods to retrieve a single row from a table.
* - `count`, `exists`: Methods to count rows and check existence of rows in a table.
* - `transaction`: Executes multiple queries in a transaction.
* - `close`: Closes the connection pool.
* - `getPool`: Returns the connection pool.
*/
import { createPool } from 'mysql2/promise';
import { DatabaseError, QueryError } from './errors';
// Define the Connection class
export class Connection {
// Constructor for the Connection class
constructor(host, user, password, database, connectionLimit = 10, port = 3306) {
this.host = host;
this.user = user;
this.password = password;
this.database = database;
this.connectionLimit = connectionLimit;
this.port = port;
// Create a new connection pool
try {
this.pool = createPool({
host: this.host,
user: this.user,
password: this.password,
database: this.database,
connectionLimit: this.connectionLimit,
port: this.port,
});
}
catch (error) {
// Log and throw the error if the connection pool fails to create
if (error instanceof Error) {
console.error(error.message);
throw new DatabaseError(error.message);
}
else {
console.error('An unknown error occurred.');
throw new DatabaseError('An unknown error occurred.');
}
}
// Constructor takes a configuration object and creates a connection pool
constructor(config) {
var _a, _b;
this.pool = createPool(Object.assign(Object.assign({}, config), { connectionLimit: (_a = config.connectionLimit) !== null && _a !== void 0 ? _a : 10, port: (_b = config.port) !== null && _b !== void 0 ? _b : 3306 }));
}
// Method to execute a query
// Generic query method with improved error logging
async query(sql, values) {
const connection = await this.pool.getConnection();
try {
// Execute the query
const [rows] = await connection.query(sql, values);

@@ -45,18 +36,20 @@ return rows;

catch (error) {
// Log and throw the error if the query fails
// Log and throw a QueryError on error
if (error instanceof Error) {
console.error(error.message);
console.error('Query error:', error.message);
console.error('Query:', sql);
if (values)
console.error('Values:', values);
throw new QueryError(error.message);
}
else {
console.error('An unknown error occurred.');
throw new QueryError('An unknown error occurred.');
console.error('An unknown query error occurred.');
throw new QueryError('An unknown query error occurred.');
}
}
finally {
// Release the connection back to the pool
connection.release();
connection.release(); // Always release the connection
}
}
// Method to execute a SELECT query
// Convenience methods for common operations
async select(table, columns = '*', where, params) {

@@ -69,3 +62,2 @@ let sql = `SELECT ${columns} FROM ${table}`;

}
// Method to execute an INSERT query
async insert(table, values) {

@@ -75,3 +67,2 @@ const sql = `INSERT INTO ${table} SET ?`;

}
// Method to execute an UPDATE query
async update(table, values, where, params) {

@@ -81,3 +72,2 @@ const sql = `UPDATE ${table} SET ? WHERE ${where}`;

}
// Method to execute a DELETE query
async delete(table, where, params) {

@@ -87,3 +77,33 @@ const sql = `DELETE FROM ${table} WHERE ${where}`;

}
// Method to close the connection pool
async get(table, where, params) {
const rows = await this.select(table, '*', where, params);
return rows.length > 0 ? rows[0] : null;
}
async getByID(table, id) {
return this.get(table, 'id = ?', [id]);
}
async count(table, where, params) {
const rows = await this.select(table, 'COUNT(*) as count', where, params);
return rows[0].count;
}
async exists(table, where, params) {
return (await this.count(table, where, params)) > 0;
}
async transaction(queries) {
const connection = await this.pool.getConnection();
await connection.beginTransaction();
try {
const result = await queries(this); // Assuming your queries access methods from `this`
await connection.commit();
return result;
}
catch (error) {
await connection.rollback();
throw error;
}
finally {
connection.release();
}
}
// Close the connection pool (with improved error handling)
async close() {

@@ -94,14 +114,14 @@ try {

catch (error) {
// Log and throw the error if the connection pool fails to close
// Log and throw a DatabaseError on error
if (error instanceof Error) {
console.error(error.message);
console.error('Pool closing error:', error.message);
throw new DatabaseError(error.message);
}
else {
console.error('An unknown error occurred.');
throw new DatabaseError('An unknown error occurred.');
console.error('An unknown pool closing error occurred.');
throw new DatabaseError('An unknown pool closing error occurred.');
}
}
}
// Method to get the connection pool
// Access the pool directly (if needed)
getPool() {

@@ -108,0 +128,0 @@ return this.pool;

@@ -1,65 +0,72 @@

import { createPool, Pool, RowDataPacket, ResultSetHeader } from 'mysql2/promise';
/**
* Project Name: MySQL Database Connection
* Author: Defeeeee
*
* This TypeScript module provides a class `Connection` that encapsulates the functionality of a MySQL database connection.
* It uses the `mysql2/promise` library to create a connection pool and provides methods for common SQL operations.
* It also includes error handling for queries and pool operations.
*
* The `Connection` class requires a configuration object of type `ConnectionConfig` to establish a connection to the database.
*
* The `Connection` class provides the following methods:
* - `query`: Executes a SQL query with optional values and returns the result.
* - `select`, `insert`, `update`, `delete`: Convenience methods for common SQL operations.
* - `get`, `getByID`: Methods to retrieve a single row from a table.
* - `count`, `exists`: Methods to count rows and check existence of rows in a table.
* - `transaction`: Executes multiple queries in a transaction.
* - `close`: Closes the connection pool.
* - `getPool`: Returns the connection pool.
*/
import {createPool, Pool, RowDataPacket, ResultSetHeader} from 'mysql2/promise';
import {DatabaseError, QueryError} from './errors';
// Define the Connection class
// Interface to define connection configuration
export interface ConnectionConfig {
host: string;
user: string;
password: string;
database: string;
connectionLimit?: number;
port?: number;
}
export class Connection {
private pool: Pool;
// Constructor for the Connection class
constructor(
private host: string,
private user: string,
private password: string,
private database: string,
private connectionLimit: number = 10,
private port: number = 3306,
) {
// Create a new connection pool
try {
this.pool = createPool({
host: this.host,
user: this.user,
password: this.password,
database: this.database,
connectionLimit: this.connectionLimit,
port: this.port,
});
} catch (error) {
// Log and throw the error if the connection pool fails to create
if (error instanceof Error) {
console.error(error.message);
throw new DatabaseError(error.message);
}
else {
console.error('An unknown error occurred.');
throw new DatabaseError('An unknown error occurred.')
}
}
// Constructor takes a configuration object and creates a connection pool
constructor(config: ConnectionConfig) {
this.pool = createPool({
...config,
connectionLimit: config.connectionLimit ?? 10, // Default connection limit is 10
port: config.port ?? 3306, // Default port is 3306
});
}
// Method to execute a query
async query<T extends RowDataPacket[] | RowDataPacket[][] | ResultSetHeader>(sql: string, values?: any[]): Promise<T> {
// Generic query method with improved error logging
async query<T extends RowDataPacket[] | RowDataPacket[][] | ResultSetHeader>(
sql: string,
values?: any[]
): Promise<T> {
const connection = await this.pool.getConnection();
try {
// Execute the query
const [rows] = await connection.query(sql, values);
return rows as T;
} catch (error) {
// Log and throw the error if the query fails
// Log and throw a QueryError on error
if (error instanceof Error) {
console.error(error.message);
console.error('Query error:', error.message);
console.error('Query:', sql);
if (values) console.error('Values:', values);
throw new QueryError(error.message);
} else {
console.error('An unknown query error occurred.');
throw new QueryError('An unknown query error occurred.');
}
else {
console.error('An unknown error occurred.');
throw new QueryError('An unknown error occurred.')
}
} finally {
// Release the connection back to the pool
connection.release();
connection.release(); // Always release the connection
}
}
// Method to execute a SELECT query
// Convenience methods for common operations
async select(table: string, columns: string = '*', where?: string, params?: any[]): Promise<RowDataPacket[]> {

@@ -73,3 +80,2 @@ let sql = `SELECT ${columns} FROM ${table}`;

// Method to execute an INSERT query
async insert(table: string, values: any): Promise<ResultSetHeader> {

@@ -80,3 +86,2 @@ const sql = `INSERT INTO ${table} SET ?`;

// Method to execute an UPDATE query
async update(table: string, values: any, where: string, params?: any[]): Promise<ResultSetHeader> {

@@ -87,3 +92,2 @@ const sql = `UPDATE ${table} SET ? WHERE ${where}`;

// Method to execute a DELETE query
async delete(table: string, where: string, params?: any[]): Promise<ResultSetHeader> {

@@ -94,3 +98,37 @@ const sql = `DELETE FROM ${table} WHERE ${where}`;

// Method to close the connection pool
async get(table: string, where: string, params?: any[]): Promise<RowDataPacket | null> {
const rows = await this.select(table, '*', where, params);
return rows.length > 0 ? rows[0] : null;
}
async getByID(table: string, id: number): Promise<RowDataPacket | null> {
return this.get(table, 'id = ?', [id]);
}
async count(table: string, where?: string, params?: any[]): Promise<number> {
const rows = await this.select(table, 'COUNT(*) as count', where, params);
return rows[0].count;
}
async exists(table: string, where: string, params?: any[]): Promise<boolean> {
return (await this.count(table, where, params)) > 0;
}
async transaction(queries: (connection: Connection) => Promise<any>): Promise<any> {
const connection = await this.pool.getConnection();
await connection.beginTransaction();
try {
const result = await queries(this); // Assuming your queries access methods from `this`
await connection.commit();
return result;
} catch (error) {
await connection.rollback();
throw error;
} finally {
connection.release();
}
}
// Close the connection pool (with improved error handling)
async close(): Promise<void> {

@@ -100,16 +138,14 @@ try {

} catch (error) {
// Log and throw the error if the connection pool fails to close
// Log and throw a DatabaseError on error
if (error instanceof Error) {
console.error(error.message);
console.error('Pool closing error:', error.message);
throw new DatabaseError(error.message);
} else {
console.error('An unknown pool closing error occurred.');
throw new DatabaseError('An unknown pool closing error occurred.');
}
else {
console.error('An unknown error occurred.');
throw new DatabaseError('An unknown error occurred.')
}
}
}
// Method to get the connection pool
// Access the pool directly (if needed)
getPool(): Pool {

@@ -116,0 +152,0 @@ return this.pool;

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc