MySQL2 SQL File Importer

5.0.22 · active · verified Wed Apr 22

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.

Common errors

Warnings

Install

Imports

Quickstart

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.

import Importer from 'mysql2-import';
import path from 'path';

// Ensure .env or similar is set up for production
const host = process.env.MYSQL_HOST ?? 'localhost';
const user = process.env.MYSQL_USER ?? 'root';
const password = process.env.MYSQL_PASSWORD ?? 'password';
const database = process.env.MYSQL_DATABASE ?? 'mydb';

const importer = new Importer({ host, user, password, database });

// Create a dummy SQL file for demonstration if it doesn't exist
import fs from 'fs';
const dummySqlFilePath = path.join(process.cwd(), 'dummy_data.sql');
if (!fs.existsSync(dummySqlFilePath)) {
  fs.writeFileSync(dummySqlFilePath, `
DROP TABLE IF EXISTS \`users\`;
CREATE TABLE \`users\` (
  \`id\` INT AUTO_INCREMENT PRIMARY KEY,
  \`name\` VARCHAR(255) NOT NULL
);
INSERT INTO \`users\` (name) VALUES ('Alice'), ('Bob');
`);
  console.log('Created dummy_data.sql for quickstart.');
}

importer.onProgress(progress => {
  const percent = Math.floor(progress.bytes_processed / progress.total_bytes * 10000) / 100;
  console.log(`File ${progress.file_no} of ${progress.total_files}: ${percent}% Completed (${progress.file_path})`);
});

importer.onDumpCompleted(data => {
  if (data.error) {
    console.error(`Error completing dump for ${data.file_path}:`, data.error);
  } else {
    console.log(`Dump completed for ${data.file_path}`);
  }
});

importer.import(dummySqlFilePath).then(() => {
  const files_imported = importer.getImported();
  console.log(`${files_imported.length} SQL file(s) imported successfully.`);
}).catch(err => {
  console.error('An error occurred during import:', err);
}).finally(() => {
  importer.disconnect();
  console.log('Importer disconnected.');
  // Clean up dummy file if it was created
  if (fs.existsSync(dummySqlFilePath)) {
    fs.unlinkSync(dummySqlFilePath);
    console.log('Removed dummy_data.sql.');
  }
});

view raw JSON →