2013-02-19 54 views
3

我正在嘗試使用內存中的H2數據庫設置一些單元/集成測試,整個事情與Spring連接起來。這是針對使用MySQL進行開發和生產的現有應用程序。將DDL從MySQL創建錶轉換爲H2

現在,我需要一個DDL SQL腳本來在H2中創建我的數據庫結構。我可以輕鬆地從MySQL導出DDL語句。但我不知道語法上的差異是什麼 - 至少我確信像engine=InnoDB這樣的東西必須去。

我應該注意到有其他語法差異嗎?

有沒有一種工具可以自動將DDL語句從MySQL語法翻譯成H2語法?

回答

0

對於最近的一個項目,我已經很快了解了這一點,而且絕對不應該把它當作最好或最乾淨的解決方案。還應該指出,我純粹用於基於單元的集成測試。理想情況下,我會在接下來的幾周內在github上提供這個功能,以便人們可以添加它,但同時它可能會有所幫助。 Java解決方案:

/** 
* Designed to go through MySQL schema produced from forward engineering tools and normalize slightly to 
* work with H2 for testing. This only works on the SQL constructs themselves and is not able to 
* detect errors such as constraints with the same name. 
* 
* Assumptions 
*  - INDEX is created separately from main SQL body 
*  - Incompatible key words such as order are not used 
*  - Assumes the name of a constraint is not duplicated 
* @author jpgough 
* 
*/ 
import java.io.IOException; 
import java.nio.file.Files; 
import java.nio.file.Paths; 

public class MySqlToH2 { 
    public static String convert(String filePath) throws IOException { 
     String[] rawSQL = new String(Files.readAllBytes(Paths.get(filePath))).split("\\n"); 
     StringBuilder builder = new StringBuilder(); 

     for(String line : rawSQL) { 
      if(line.contains("SET")) { 
       continue; 
      } else if(line.contains("INDEX")) { 
       continue; 
      } else if(line.contains("IF NOT EXISTS")) { 
       line = line.replaceAll("IF NOT EXISTS", ""); 
      } else if(line.contains("--")) { 
       continue; 
      } else if(line.contains("ENGINE")) { 
       line = ";"; 
      } 

      line = line.replace("`", ""); 
      builder.append(line).append("\n"); 
     } 
     return builder.toString(); 
    } 
}