using System; using System.Linq; using System.Text.RegularExpressions; namespace DbMigrate { internal static class Extensions { public static string[] GetCommonColumns(this SqlTable table, SqlTable table2) { return table.GetColumnNames().Where(f => table2.HasColumn(f)).ToArray(); } public static void ParseSql(this SqlTable table, string sql, string tableName = null) { if (tableName != null) { table.TableName = tableName; } bool inTable = false; bool inColumns = false; Match m = null; foreach (string line in Regex.Split(sql, "\\r\\n")) { if (string.IsNullOrEmpty(line) || line.StartsWith("--")) { continue; } m = Regex.Match(line, "^CREATE TABLE( IF NOT EXISTS)? (\\S+) "); if (m.Success) { if (string.IsNullOrEmpty(tableName) && string.IsNullOrEmpty(table.TableName)) { // Set table name from the above regex match table.TableName = m.Groups[2].Value.Trim(); } if (!inTable && (table.TableName == null || m.Groups[2].Value.Trim() == table.TableName)) { table.CreateTableSql += line + Environment.NewLine; inTable = true; inColumns = true; continue; } else { if (inTable) { // We are done with this table return; } continue; } } m = Regex.Match(line, "^CREATE INDEX( IF NOT EXISTS)? (\\S+) "); if (m.Success && inTable) { table.Indexes.Add(m.Groups[2].Value.Trim(), line.Trim()); continue; } m = Regex.Match(line, "^CREATE TRIGGER( IF NOT EXISTS)? (\\S+) "); if (m.Success && inTable) { table.Triggers.Add(m.Groups[2].Value.Trim(), line.Trim()); continue; } if (inColumns) { if (line.Trim().StartsWith(")")) { inColumns = false; } else { m = Regex.Match(line.Trim(), "^(\\S+).*"); if (m.Success) { string columnLine = line.Trim(); if (columnLine.EndsWith(",")) { columnLine = columnLine.Substring(0, columnLine.Length - 1); } table.Columns.Add(m.Groups[1].Value.Trim(), columnLine); } } } table.CreateTableSql += line + Environment.NewLine; } } } }