Search code examples
scalasbtmysqlanorm

Loading mysqldump as string


For testing I am loading a full mysqldump (of a test-database with less than 100 lines), I would like to be able to load it from scala+anorm (no bash scripts etc.), and tried this:

import anorm._
import java.sql.DriverManager
object CheckDatabase {
    def main(args: Array[String]): Unit = {
        val jdbcUrl = "jdbc:mysql://db.local.test.com:3306/blackbox?user=dev&password=secret"
        implicit val con: java.sql.Connection = DriverManager.getConnection(jdbcUrl)
        val importSql = SQL(s"""${scala.io.Source.fromFile("blackbox_test.sql").mkString}""")
        importSql.execute()
    }
}

It fails with an error:

[error] (run-main-0)     com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an     error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE    `rapport_blackbox_test` (
[error]   `id` int(11) NOT NULL AUTO_INCREMENT,
[error]  ' at line 13

I assume it has to with linebreaks or something. Is there an option I can use in mysqldump to produce a file that will load correctly, or is there any other workaround?

FYI: if I change the SQL statement to the following it creates a table correctly

val importSql = SQL("CREATE TABLE `rapport_blackbox_test` (`id` int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY)")

Solution

  • Reading the lines one by one (and ignoring blanks) works, provided that the "CREATE TABLE" statement is changed to ont have linebreaks.

    val lines = scala.io.Source.fromFile("src/test/resources/blackbox_test.sql").getLines()
    lines.foreach(line => {
        if(!line.isEmpty) SQL(s"""$line""").execute()
    })