# mysql-mock **Repository Path**: microwww/mysql-mock ## Basic Information - **Project Name**: mysql-mock - **Description**: Mock mysql for Java testing! Embedded MySQL implementation using H2 MySQL mode for unit testing - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2026-07-26 - **Last Updated**: 2026-09-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # mysql-mock `mysql-mock` is a lightweight embedded MySQL server implementation designed for Java applications, suitable for local development testing environments. It uses the H2 database as the underlying storage engine and simulates MySQL server behavior through a custom protocol layer. ## Features - **Embedded Deployment**: No need to install a MySQL server; start quickly via the Java API. - **Protocol Compatibility**: Implements the MySQL Wire Protocol, supporting standard JDBC connections. - **SQL Dialect Conversion**: Built-in MySQL to H2 SQL grammar transpiler (e.g., `DATE_FORMAT` automatically converted). - **Flexible Extension**: - Supports handling unsupported SQL syntax (such as stored procedures, triggers) via callback functions. - Provides lifecycle hooks to intercept and customize before and after SQL execution. - **High Performance**: Non-blocking network communication implemented based on Java NIO. ## Installation Add the dependency to the `pom.xml` of your Maven project: ```xml com.github.microwww mysql-mock Latest Version Number ``` > Note: Please replace `Latest Version Number` with the actual version Tag. ## Quick Start The following example demonstrates how to start an embedded MySQL instance and obtain a JDBC connection: ```java import com.github.microwww.mysql.EmbedMySql; import com.github.microwww.mysql.EmbedMySqlBuilder; import java.sql.Connection; import java.sql.DriverManager; public class MySqlTest { public static void main(String[] args) throws Exception { // 1. Build and start the MySQL service EmbedMySql mysql = new EmbedMySqlBuilder() .port(3306) // Optional, default 3306 .build(); mysql.start(); // 2. Obtain JDBC connection String jdbcUrl = "jdbc:mysql://127.0.0.1:3306/dbname?useSSL=false"; String user = "root"; String password = ""; try (Connection conn = DriverManager.getConnection(jdbcUrl, user, password)) { // Execute your SQL tests here conn.createStatement().execute("CREATE TABLE test (id INT PRIMARY KEY)"); conn.createStatement().execute("INSERT INTO test VALUES (1)"); } finally { // 3. Stop the service mysql.stop(); } } } ``` ## Advanced Configuration `EmbedMySqlBuilder` provides rich configuration options: ### 1. SQL Dialect and Callbacks (Handling Unsupported SQL) Some advanced MySQL features (such as stored procedures) are not natively supported in H2. `mysql-mock` provides a callback mechanism that allows you to hijack these commands and return custom results or execute simulated logic. ```java new EmbedMySqlBuilder() .onCreateProcedure((name, body, conn) -> { System.out.println("Creating stored procedure: " + name); return MySqlResult.ok(); }) .onCallProcedure((name, args, conn) -> { System.out.println("Calling stored procedure: " + name); return MySqlResult.ok(); }) .build(); ``` ### 2. Lifecycle Hooks You can insert custom logic at key nodes such as SQL execution or database reset. ```java new EmbedMySqlBuilder() .beforeExecute((sql, conn) -> System.out.println("Before execution: " + sql)) .afterExecute((sql, conn) -> System.out.println("After execution: " + sql)) .beforeSchemaReset(conn -> System.out.println("Before resetting database")) .afterSchemaReset(conn -> System.out.println("After resetting database")) .build(); ``` ### 3. Database Reset and Initialization Scripts Supports executing initialization SQL scripts when the service starts. ```java new EmbedMySqlBuilder() .initScriptPath("schema.sql") // Path relative to project root directory .build(); ``` ## SQL Support Notes ### Automatic Transpilation The system automatically translates part of the MySQL syntax to H2-compatible syntax: - **Functions**: `DATE_FORMAT(NOW(), '%Y-%m-%d')` -> `FORMATDATETIME(NOW(), 'yyyy-MM-dd')`. Supports mapping of common format specifiers (`%Y`, `%m`, `%d`, `%H`, `%i`, `%s`, etc.). - **IF Function**: Translated to `CASE WHEN ...`. ### Native Support Commands The following commands are handled directly by the framework without callbacks: - `SHOW TABLES`, `SHOW COLUMNS FROM ...`, `SHOW DATABASES` - `SET AUTOCOMMIT = ...` - Standard DDL/DML (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `CREATE TABLE`, `DROP TABLE`) ### Known Limitations - **Character Set**: Default mapped to `utf8mb4`. - **Transactions**: Supports standard ACID transactions. ## Core Architecture - `EmbedMySql`: Core entry point, manages server lifecycle. - `H2Engine`: Responsible for interacting with the underlying H2 database. - `SqlDialectTranslator`: Responsible for parsing and rewriting MySQL SQL to H2 SQL. - `NioTcpServer`: Network service layer based on Java NIO, handles high-concurrency connections. - `CommandDispatcher`: Command dispatcher, routes MySQL protocol commands to corresponding handlers. ## License This project follows the Apache License 2.0 agreement.