mysql2-core
A lightweight MySQL database adapter built on top of mysql2 for the SQL Repository framework.
This library provides connection management, transaction handling, query execution, object mapping, batch operations, streaming, exporting, and health checking while remaining completely independent from SQL generation.
Unlike traditional ORMs, this library does not build SQL. Instead, it executes SQL generated by the SQL Repository library (or any SQL source) and provides a clean, type-safe runtime layer.
Philosophy
This library has one responsibility:
Execute SQL efficiently.
It intentionally separates SQL execution from SQL generation.
Application
│
▼
SQL Repository Library
(SQL Generation)
│
▼
Executor Interface
│
▼
MySQL Adapter
│
▼
mysql2
│
▼
MySQL
This separation makes the entire stack easier to maintain, test, and extend.
Features
- Built on top of mysql2
- Connection Pool Management
- Transaction Management
- Query Execution
- Command Execution
- Batch Execution
- Streaming Query Results
- Bulk Data Import
- CSV/Data Export
- Object Mapping
- Boolean Conversion
- Database Health Check
- Promise-based API
- Repository Friendly
- Zero ORM Dependencies
Why Another MySQL Library?
Most MySQL libraries are either:
- Low-level drivers (
mysql2) - Full-featured ORMs (TypeORM, Prisma, Sequelize)
This library focuses on infrastructure.
It provides:
- Connection management
- Transactions
- Streaming
- Batch execution
- Repository integration
without hiding SQL from developers.
Architecture
Application
│
▼
SQL Repository Layer
│
▼
Executor Interface
│
▼
MySQL Adapter
┌──────────────┼──────────────┐
▼ ▼ ▼
Connection Transaction Stream
│ │ │
└──────────────┼──────────────┘
▼
mysql2
│
▼
MySQL
Installation
npm install mysql2
npm install mysql2-core
Creating a Database
import { MySQLDB } from "mysql2-core"
const db = new MySQLDB({
host: "localhost",
port: 3306,
database: "demo",
user: "root",
password: "password"
})
Query
const users = await db.query<User>(
`
SELECT *
FROM users
WHERE age > ?
`,
[18]
)
Execute
await db.execute(
`
UPDATE users
SET active = ?
WHERE id = ?
`,
[true, 10]
)
Transactions
const tx = await db.beginTransaction()
try {
await tx.execute(
`
INSERT INTO users(name)
VALUES(?)
`,
["John"]
)
await tx.commit()
}
catch (err) {
await tx.rollback()
}
Batch Execution
await db.executeBatch([
{
query:
"INSERT INTO users(name) VALUES(?)",
params:
["John"]
},
{
query:
"INSERT INTO users(name) VALUES(?)",
params:
["Jane"]
}
])
Streaming
Stream large result sets without loading everything into memory.
await db.stream(
"SELECT * FROM users",
[],
async user => {
console.log(user)
}
)
Ideal for:
- ETL
- Migration
- Reporting
- Exporting millions of rows
Bulk Writer
Insert data efficiently.
const writer = new MySQLWriter(db)
await writer.write(users)
Batch Writer
const writer = new MySQLBatchWriter(db)
await writer.write(users)
Stream Writer
const writer = new MySQLStreamWriter(db)
await writer.write(stream)
Useful for importing very large datasets.
Export
Export query results without loading everything into memory.
await exporter.export(
`
SELECT *
FROM users
`,
"users.csv"
)
Object Mapping
Rows are automatically mapped into TypeScript objects.
interface User {
id: number
name: string
active: boolean
}
const users = await db.query<User>(
sql
)
Boolean Conversion
Automatically converts database values.
0 -> false
1 -> true
NULL -> null
Health Check
const ok = await checker.check()
Perfect for
- Kubernetes
- Docker
- Load Balancers
- Monitoring
Repository Integration
Designed to work seamlessly with SQL Repository.
Application
│
▼
SqlRepository
│
▼
Executor
│
▼
MySQL Adapter
│
▼
mysql2
The repository layer never depends directly on mysql2.
Connection Pool
Internally the adapter manages a connection pool.
Application
│
▼
Pool Manager
│
▼
mysql2 Pool
Connection reuse improves performance.
Transaction Model
Application
│
▼
Transaction
│
▼
PoolConnection
│
▼
mysql2
Transactions are isolated from application code.
Error Handling
Database errors are propagated as Promise rejections.
try {
await db.execute(sql)
}
catch(err){
console.error(err)
}
Performance
The adapter is designed for high throughput.
Features include:
- Connection Pooling
- Prepared Statement Parameters
- Batch Execution
- Streaming Queries
- Minimal Object Allocation
- Thin Wrapper over mysql2
Design Goals
- Lightweight
- Predictable
- SQL-first
- Repository Friendly
- Driver Independent
- Easy to Debug
- Easy to Extend
- High Performance
- Low Memory Usage
Comparison
| Feature | mysql2-core | mysql2 | TypeORM |
|---|---|---|---|
| Connection Pool | |||
| Transactions | |||
| Streaming | Partial | ||
| Repository Support | |||
| Batch Execution | Manual | Partial | |
| SQL Generation | ORM | ||
| ORM | |||
| Lightweight |
Project Structure
MySQLDB
│
├── Connection Pool
├── Transactions
├── Query Execution
├── Execute
├── Batch Execute
├── Stream
├── Exporter
├── Object Mapper
├── Health Checker
└── Utilities
Future Roadmap
Future versions will introduce:
- SQL AST Compiler integration
- PostgreSQL Adapter
- SQL Server Adapter
- Oracle Adapter
- SQLite Adapter
- Dialect Abstraction
- Prepared Statement Cache
- Retry Policies
- Metrics & Tracing
- Connection Observability
Relationship with SQL Repository
This library is intended to be used together with the SQL Repository library.
SQL Repository
(Metadata + SQL Builder)
│
▼
Executor Interface
│
┌─────────────┴─────────────┐
▼ ▼
MySQL Adapter PostgreSQL Adapter
▼ ▼
mysql2 pg
The SQL Repository library generates SQL.
This library executes SQL.
Together they provide a lightweight, SQL-first data access framework.
License
MIT License
Contributing
Contributions are welcome!
Feel free to submit issues, feature requests, or pull requests to improve the project.