{"id":17300,"library":"mysql2-import","title":"MySQL2 SQL File Importer","description":"mysql2-import, currently at version 5.0.22, is a Node.js library specifically designed for importing `.sql` dump files into a MySQL database. It's an adaptation of the `mysql-import` project, updated to seamlessly integrate with the `mysql2` driver. This integration leverages `mysql2`'s enhanced performance and modern features, including prepared statements, which are crucial for secure and efficient database interactions. The library provides an intuitive API for connecting to a database, specifying multiple `.sql` files or directories containing dumps, and executing their commands asynchronously. A key differentiator introduced in version 5.0 is its robust event system, featuring `onProgress` and `onDumpCompleted` callbacks. These allow developers to monitor the import process in real-time, receiving updates on bytes processed and file completion status, making it highly suitable for handling large SQL datasets. While no explicit release cadence is documented, it generally aligns with the versioning of its upstream `mysql-import` project, delivering stable and feature-rich releases.","status":"active","version":"5.0.22","language":"javascript","source_language":"en","source_url":"https://github.com/mar0xy/mysql2-import","tags":["javascript","nodejs","mysql","textfiles","import","sql"],"install":[{"cmd":"npm install mysql2-import","lang":"bash","label":"npm"},{"cmd":"yarn add mysql2-import","lang":"bash","label":"yarn"},{"cmd":"pnpm add mysql2-import","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Core database driver used for all MySQL interactions; the package is an adapter for mysql-import to use mysql2.","package":"mysql2","optional":false}],"imports":[{"note":"The original README example incorrectly uses `mysql-import` instead of `mysql2-import`. The package also supports CommonJS `require` syntax.","wrong":"const Importer = require('mysql-import');","symbol":"Importer","correct":"import Importer from 'mysql2-import';"},{"note":"The default export for `Importer` is the class itself. Avoid named imports unless the package specifically exports named members (which it does not for the main class).","wrong":"import { Importer } from 'mysql2-import';","symbol":"Importer","correct":"const Importer = require('mysql2-import');"},{"note":"The `import` method takes a variadic number of string arguments (file paths) or arrays of paths, not necessarily a single array as the primary form.","wrong":"importer.import(['path/to/dump.sql']);","symbol":"Importer.prototype.import","correct":"importer.import('path/to/dump.sql').then(() => { /* ... */ });"}],"quickstart":{"code":"import Importer from 'mysql2-import';\nimport path from 'path';\n\n// Ensure .env or similar is set up for production\nconst host = process.env.MYSQL_HOST ?? 'localhost';\nconst user = process.env.MYSQL_USER ?? 'root';\nconst password = process.env.MYSQL_PASSWORD ?? 'password';\nconst database = process.env.MYSQL_DATABASE ?? 'mydb';\n\nconst importer = new Importer({ host, user, password, database });\n\n// Create a dummy SQL file for demonstration if it doesn't exist\nimport fs from 'fs';\nconst dummySqlFilePath = path.join(process.cwd(), 'dummy_data.sql');\nif (!fs.existsSync(dummySqlFilePath)) {\n  fs.writeFileSync(dummySqlFilePath, `\nDROP TABLE IF EXISTS \\`users\\`;\nCREATE TABLE \\`users\\` (\n  \\`id\\` INT AUTO_INCREMENT PRIMARY KEY,\n  \\`name\\` VARCHAR(255) NOT NULL\n);\nINSERT INTO \\`users\\` (name) VALUES ('Alice'), ('Bob');\n`);\n  console.log('Created dummy_data.sql for quickstart.');\n}\n\nimporter.onProgress(progress => {\n  const percent = Math.floor(progress.bytes_processed / progress.total_bytes * 10000) / 100;\n  console.log(`File ${progress.file_no} of ${progress.total_files}: ${percent}% Completed (${progress.file_path})`);\n});\n\nimporter.onDumpCompleted(data => {\n  if (data.error) {\n    console.error(`Error completing dump for ${data.file_path}:`, data.error);\n  } else {\n    console.log(`Dump completed for ${data.file_path}`);\n  }\n});\n\nimporter.import(dummySqlFilePath).then(() => {\n  const files_imported = importer.getImported();\n  console.log(`${files_imported.length} SQL file(s) imported successfully.`);\n}).catch(err => {\n  console.error('An error occurred during import:', err);\n}).finally(() => {\n  importer.disconnect();\n  console.log('Importer disconnected.');\n  // Clean up dummy file if it was created\n  if (fs.existsSync(dummySqlFilePath)) {\n    fs.unlinkSync(dummySqlFilePath);\n    console.log('Removed dummy_data.sql.');\n  }\n});","lang":"javascript","description":"This quickstart demonstrates how to initialize the Importer, set up progress and completion callbacks, import a SQL file, and handle potential errors, including creating a dummy SQL file for a runnable example."},"warnings":[{"fix":"Always use `require('mysql2-import')` or `import Importer from 'mysql2-import';`.","message":"The README examples for `require` syntax incorrectly use `require('mysql-import')` instead of the package's actual name, `mysql2-import`. This will lead to a 'Cannot find module' error.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"Review the API documentation for version 5.0+ and update any callback handling accordingly. For older versions, alternative progress tracking methods may be necessary or an upgrade to `mysql2-import@5.x`.","message":"The `onProgress` and `onDumpCompleted` methods were introduced in version 5.0. Code relying on these callbacks will break if upgrading from a version older than 5.0.","severity":"breaking","affected_versions":"<5.0.0"},{"fix":"Double-check all connection parameters. Use environment variables for sensitive credentials. Verify database server accessibility and user privileges independently using a MySQL client.","message":"Providing incorrect database connection parameters (host, user, password, database) is a very common source of errors. Ensure your MySQL server is running, the user has appropriate permissions, and network access is configured correctly.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Change the import statement to `const Importer = require('mysql2-import');` or `import Importer from 'mysql2-import';`","cause":"This error occurs because the example in the `mysql2-import` README uses `require('mysql-import')` which refers to the original package, not `mysql2-import`.","error":"Error: Cannot find module 'mysql-import'"},{"fix":"Verify your MySQL `user`, `password`, and `host` credentials. Ensure the user has `GRANT` privileges for the target database and can connect from `localhost` or the specified `host`.","cause":"The provided username or password for the MySQL connection is incorrect, or the user lacks permissions from the specified host.","error":"Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'user'@'localhost' (using password: YES/NO)"}],"ecosystem":"npm","meta_description":null}