mysql2
| Property | Value |
|---|---|
| Package | mysql2 |
| Versions Covered | >=3.9.8 |
| Contract Version | 1.0.0 |
| Status | production |
| Last Verified | 2026-02-26 |
| Maintainer | corpus-team |
Installationâ
npm install mysql2
Covered Functionsâ
This contract covers 7 function(s):
connect()â
Establishes connection to MySQL server
Import:
import { connect } from 'mysql2/promise';
Postconditionsâ
What happens after calling this function:
đ´ ERROR - connection-failure
Condition: Cannot connect (wrong credentials, host unreachable, etc.)
Throws: Error with code 'ECONNREFUSED', 'ER_ACCESS_DENIED_ERROR', etc.
Required Handling:
Caller MUST catch connection errors. Common error codes: - ECONNREFUSED: MySQL server not running - ER_ACCESS_DENIED_ERROR: Wrong username/password - ETIMEDOUT: Network timeout Implement retry with exponential backoff for transient issues.
đ Source
query()â
Executes SQL query without prepared statements
Import:
import { query } from 'mysql2/promise';
Postconditionsâ
What happens after calling this function:
đ´ ERROR - syntax-error
Condition: SQL syntax error
Throws: Error with code 'ER_PARSE_ERROR' or similar
Required Handling:
Caller MUST validate SQL syntax before execution. DO NOT retry - indicates SQL syntax error. Check error.sqlMessage for details.
đ Source
đ´ ERROR - constraint-violation
Condition: Unique constraint, foreign key, or NOT NULL violation
Throws: Error with code 'ER_DUP_ENTRY', 'ER_NO_REFERENCED_ROW', 'ER_BAD_NULL_ERROR'
Required Handling:
Caller MUST handle constraint violations: - ER_DUP_ENTRY (1062): Duplicate key violation - ER_NO_REFERENCED_ROW_2 (1452): Foreign key constraint - ER_BAD_NULL_ERROR (1048): NOT NULL constraint Extract details from error.sqlMessage. DO NOT retry without fixing data.
đ Source
đ´ ERROR - connection-error
Condition: Connection lost during query execution
Throws: Error with code 'PROTOCOL_CONNECTION_LOST', 'ECONNRESET'
Required Handling:
Caller MUST handle connection errors. Connection may be lost due to timeout or server restart. Implement retry with exponential backoff.
đ Source
đ´ ERROR - table-not-found
Condition: Table or view does not exist
Throws: Error with code 'ER_NO_SUCH_TABLE' (1146)
Required Handling:
Caller MUST verify table exists before querying. DO NOT retry - indicates schema mismatch or missing migration.
đ Source
Edge Casesâ
Known gotchas and sharp edges:
â ī¸ WARNING - sql-injection-risk
NEVER use query() with string concatenation or template literals for user input. Example VULNERABLE code: query(SELECT * FROM users WHERE id = $userId) This creates SQL injection vulnerability. ALWAYS use execute() with parameters instead: execute('SELECT * FROM users WHERE id = ?', [userId])