Search code examples
sqlscalaschemardbmsslick

Slick SourceCodeGenerator From SQL File


Is there a way to use the Slick SourceCodeGenerator to generate source code from a file of SQL CREATE statements? I know there is a way to connect to a DB and read in the schema, but I want to cut out that step and just give it the file. Please advise.


Solution

  • Slick ready meta data via jdbc. If you find a jdbc driver that can do that from a SQL file, you may be in luck. Otherwise, why not use an H2 in-memory database? It has compatibility modes for various SQL dialects. They are limited though. Another option would be using something like this: https://github.com/bgranvea/mysql2h2-converter first to produce an H2 compatible schema file.

    We used the following script to load a sql schema from a mysql database, convert it to H2 compatible format and then use it in-memory for tests. You should be able to adapt it.

    #!/bin/sh
    echo ''
    export IP=192.168.1.123
    export user=foobar
    export password=secret
    export database=foobar
    ping -c 1 $IP &&\
    echo "" &&\
    echo "Server is reachable"
    # dump mysql schema for debuggability (ignore in git)
    # convert the mysql to h2db using the converter.
    
    ## disable foreign key check in begining and enable it in the end. Prevents foreign key errors
    echo "SET FOREIGN_KEY_CHECKS=0;" > foobar-mysql.sql
    
    ## Dump the Db structure and remove the auto_increment so as to set the id column back to 1
    mysqldump --compact -u $user -h $IP -d $database -p$password\
    |sed 's/CONSTRAINT `_*/CONSTRAINT `/g' \
    |sed 's/KEY `_*/KEY `/g' \
    |sed 's/ AUTO_INCREMENT=[0-9]*//' \
    >> foobar-mysql.sql
    
    echo "SET FOREIGN_KEY_CHECKS=1;" >> foobar-mysql.sql &&\
    
    java -jar mysql2h2-converter.jar foobar-mysql.sql \
    |perl -0777 -pe 's/([^`]),/\1,\n  /g' \
    |perl -0777 -pe 's/\)\);/)\n);/g' \
    |perl -0777 -pe 's/(CREATE TABLE [^\(]*\()/\1\n  /g' \
    |sed 's/UNSIGNED/unsigned/g' \
    |sed 's/float/real/' \
    |sed "s/\(int([0-9]*).*\) DEFAULT '\(.*\)'/\1 DEFAULT \2/" \
    |sed "s/tinyint(1)/boolean/" \
     > foobar-h2.sql
    
    perl -ne 'print "$ARGV\n" if /.\z/' -- foobar-h2.sql