0

I am using npm mysql module on windows 7.

connection.query(`source D:/mediapropel/wp_default_install.sql`, function (error, results, fields) {
    if(error) throw error;
    console.log("Database should be created1");
    console.log('source '+ path.join(__dirname, '..', "\/\wp_default_install.sql")+'');
    res.send('');
});

What I have tried:

  1. 'source D:/mediapropel/wp_default_install.sql'

  2. 'source '+ path.join(__dirname, '..', "\/\wp_default_install.sql")+''

  3. "source " + "D:/mediapropel/wp_default_install.sql"

  4. "source D:/\mediapropel/\wp_default_install.sql"

  5. "source D:/\mediapropel/\wp_default_install.sql/\/"

Error message:

'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'source D:/mediapropel/wp_default_install.sql\' at line 1'`

The same query runs directly in the mysql command line properly as expected. Please advice where am I going wrong.

Carlos
  • 331
  • 6
  • 14
invinciblemuffi
  • 908
  • 1
  • 11
  • 22

1 Answers1

1

This is not possible with the mysql module, as explained here. Also, you can test this if you try the same SOURCE SQL command in DB admin UIs like phpMyAdmin.
I've tried using child_process.exec on the /bin/mysql executable, but failed for some reason.
A hacky solution(that worked for me) could be the one below, where you read and send the whole script for execution(notice the multipleStatements: true setting, when creating the connection):

const fs = require('fs');
const {promisify} = require('util');
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: '[host]',
  database: '[database]',
  user: '[user]',
  password: '[password]',
  multipleStatements: true
});
const connectionQueryPromise = promisify(connection.query.bind(connection));

const dbImportScript = fs.readFileSync(path.join(__dirname, '..', 'dump.sql'));
await connectionQueryPromise(dbImportScript);

If you get an error about max_allowed_packet, check this answer.

Kinko
  • 259
  • 4
  • 11