diff --git a/DbComparer.cs b/DbComparer.cs new file mode 100644 index 0000000..2cabe8a --- /dev/null +++ b/DbComparer.cs @@ -0,0 +1,117 @@ +using System; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace DbMigrate { + public class DbComparer { + public SqlDatabase BaseDatabase { get; set; } + public SqlDatabase CompareDatabase { get; set; } + + public bool RemoveUnusedTablesFromBaseDb { get; set; } = false; + public bool RemoveUnusedColumnsFromBaseDb { get; set; } = false; + public bool CopyDataFromNewDb { get; set; } = false; + + public string UpdateSqlScript { get; private set; } + + public DbComparer(SqlDatabase baseDb, SqlDatabase compareDb) { + BaseDatabase = baseDb; + CompareDatabase = compareDb; + } + + + private string[] getCommonColumns(string table) { + string[] baseColumns = BaseDatabase[table].Columns.Keys.ToArray(); + string[] newColumns = CompareDatabase[table].Columns.Keys.ToArray(); + + return baseColumns.Where(f => newColumns.Contains(f)).ToArray(); + } + + public string Compare() { + var sb = new StringBuilder(); + + foreach (var table in CompareDatabase.Tables) { + if (!BaseDatabase.ContainsTable(table.TableName)) { + // Table does not exist; Create it + sb.AppendLine("\r\n-- Create table " + table.TableName); + sb.Append(table.CreateTableSql); + + if (CopyDataFromNewDb) { + // Copy data + sb.AppendLine("\r\n-- Copy data into new table " + table.TableName); + // TODO : Copy data from existing table in the new schema + } + continue; + } + + // The table exists, now we need to compare everything to verify no updates are required! + foreach (var index in table.Indexes) { + if (!BaseDatabase[table.TableName].HasIndex(index.Key)) { + sb.AppendLine("\r\n-- Create index " + index.Key); + sb.AppendLine(index.Value); + } else { + // Index exists, check if it's the same + if (BaseDatabase[table.TableName].Indexes[index.Key] != index.Value) { + sb.AppendLine("\r\n-- Drop and recreate index " + index.Key); + sb.AppendLine("DROP INDEX IF EXISTS " + index.Key + ";"); + sb.AppendLine(index.Value); + } + } + } + + foreach (var trigger in table.Triggers) { + if (!BaseDatabase[table.TableName].HasTrigger(trigger.Key)) { + sb.AppendLine("\r\n-- Create trigger " + trigger.Key); + sb.AppendLine(trigger.Value); + } else { + // Trigger exists, check if it's the same + if (BaseDatabase[table.TableName].Triggers[trigger.Key] != trigger.Value) { + sb.AppendLine("\r\n-- Drop and recreate trigger " + trigger.Key); + sb.AppendLine("DROP TRIGGER IF EXISTS " + trigger.Key + ";"); + sb.AppendLine(trigger.Value); + } + } + } + + bool alterTableRequired = false; + foreach (var column in table.Columns) { + if (!BaseDatabase[table.TableName].HasColumn(column.Key)) { + // The database column does not exist + alterTableRequired = true; + break; + } + if (BaseDatabase[table.TableName].Columns[column.Key] != column.Value) { + // The database column exists but is different + alterTableRequired = true; + break; + } + } + + // TODO : This deletes unused columns - we should probably make this optional + if (alterTableRequired) { + sb.AppendLine("\r\n-- Table " + table.TableName + " requires alteration - Create temp table and move data"); + string[] commonColumns = getCommonColumns(table.TableName); + string columnList = string.Join(",", commonColumns); + + string sql = CompareDatabase[table.TableName].CreateTableSql; + string newTableName = table.TableName + "_" + DateTime.Now.ToString("yyyyMMddHHmmss"); + sql = Regex.Replace(sql, "CREATE TABLE (\\w*)", "CREATE TABLE IF NOT EXISTS $1_" + newTableName.Substring(newTableName.IndexOf("_") + 1)); + sb.AppendLine(sql); + + sb.AppendLine("\r\n-- Copy data from existing table to new table"); + sb.AppendLine("INSERT INTO " + newTableName + " (" + columnList + ")"); + sb.AppendLine("\tSELECT " + columnList); + sb.AppendLine("\tFROM " + table.TableName + ";"); + sb.AppendLine("\r\n-- Drop existing table"); + sb.AppendLine("DROP TABLE " + table.TableName + ";"); + sb.AppendLine("\r\n-- Rename the new table to replace the old table"); + sb.AppendLine("ALTER TABLE " + newTableName + " RENAME TO " + table.TableName + ";"); + } + } + + + UpdateSqlScript = "BEGIN TRANSACTION;\r\n" + sb.ToString() + "\r\nCOMMIT;"; + return UpdateSqlScript; + } + } +} diff --git a/DbMigrate.csproj b/DbMigrate.csproj index 7c5b906..8ed9ad6 100644 --- a/DbMigrate.csproj +++ b/DbMigrate.csproj @@ -12,6 +12,8 @@ v4.7.2 512 true + + true @@ -31,8 +33,29 @@ 4 + + packages\Dapper.2.1.66\lib\net461\Dapper.dll + + + packages\Dapper.Contrib.2.0.78\lib\net461\Dapper.Contrib.dll + + + packages\Microsoft.Bcl.AsyncInterfaces.9.0.1\lib\net462\Microsoft.Bcl.AsyncInterfaces.dll + + + packages\Stub.System.Data.SQLite.Core.NetFramework.1.0.119.0\lib\net46\System.Data.SQLite.dll + + + packages\System.Data.SQLite.Linq.1.0.119.0\lib\net46\System.Data.SQLite.Linq.dll + + + packages\System.Runtime.CompilerServices.Unsafe.4.5.3\lib\net461\System.Runtime.CompilerServices.Unsafe.dll + + + packages\System.Threading.Tasks.Extensions.4.5.4\lib\net461\System.Threading.Tasks.Extensions.dll + @@ -41,10 +64,23 @@ + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + \ No newline at end of file diff --git a/DbMigrate.sln b/DbMigrate.sln index 7972a85..38c3955 100644 --- a/DbMigrate.sln +++ b/DbMigrate.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 17.10.35027.167 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbMigrate", "DbMigrate.csproj", "{A4A58207-CF8C-46FD-9749-3D4D8816E11A}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DbMigrateTester", "DbMigrateTester\DbMigrateTester.csproj", "{33492E2A-4D65-4F78-A3C5-325474921199}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -15,6 +17,10 @@ Global {A4A58207-CF8C-46FD-9749-3D4D8816E11A}.Debug|Any CPU.Build.0 = Debug|Any CPU {A4A58207-CF8C-46FD-9749-3D4D8816E11A}.Release|Any CPU.ActiveCfg = Release|Any CPU {A4A58207-CF8C-46FD-9749-3D4D8816E11A}.Release|Any CPU.Build.0 = Release|Any CPU + {33492E2A-4D65-4F78-A3C5-325474921199}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {33492E2A-4D65-4F78-A3C5-325474921199}.Debug|Any CPU.Build.0 = Debug|Any CPU + {33492E2A-4D65-4F78-A3C5-325474921199}.Release|Any CPU.ActiveCfg = Release|Any CPU + {33492E2A-4D65-4F78-A3C5-325474921199}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/DbMigrateTester/App.config b/DbMigrateTester/App.config new file mode 100644 index 0000000..56efbc7 --- /dev/null +++ b/DbMigrateTester/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/DbMigrateTester/DbMigrateTester.csproj b/DbMigrateTester/DbMigrateTester.csproj new file mode 100644 index 0000000..7c6222a --- /dev/null +++ b/DbMigrateTester/DbMigrateTester.csproj @@ -0,0 +1,116 @@ + + + + + Debug + AnyCPU + {33492E2A-4D65-4F78-A3C5-325474921199} + WinExe + DbMigrateTester + DbMigrateTester + v4.7.2 + 512 + true + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Form + + + MainForm.cs + + + UserControl + + + DatabasePanel.cs + + + + + MainForm.cs + + + DatabasePanel.cs + + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + {a4a58207-cf8c-46fd-9749-3d4d8816e11a} + DbMigrate + + + + \ No newline at end of file diff --git a/DbMigrateTester/Forms/MainForm.Designer.cs b/DbMigrateTester/Forms/MainForm.Designer.cs new file mode 100644 index 0000000..3cb391d --- /dev/null +++ b/DbMigrateTester/Forms/MainForm.Designer.cs @@ -0,0 +1,194 @@ +namespace DbMigrateTester.Forms { + partial class MainForm { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows Form Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + this.components = new System.ComponentModel.Container(); + this.barManager1 = new DevExpress.XtraBars.BarManager(this.components); + this.bar1 = new DevExpress.XtraBars.Bar(); + this.bar2 = new DevExpress.XtraBars.Bar(); + this.bar3 = new DevExpress.XtraBars.Bar(); + this.barDockControlTop = new DevExpress.XtraBars.BarDockControl(); + this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl(); + this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl(); + this.barDockControlRight = new DevExpress.XtraBars.BarDockControl(); + this.dbCurrent = new DbMigrateTester.Forms.UserControls.DatabasePanel(); + this.splitterControl1 = new DevExpress.XtraEditors.SplitterControl(); + this.dbLatest = new DbMigrateTester.Forms.UserControls.DatabasePanel(); + this.bbiGenerateDelta = new DevExpress.XtraBars.BarButtonItem(); + ((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit(); + this.SuspendLayout(); + // + // barManager1 + // + this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] { + this.bar1, + this.bar2, + this.bar3}); + this.barManager1.DockControls.Add(this.barDockControlTop); + this.barManager1.DockControls.Add(this.barDockControlBottom); + this.barManager1.DockControls.Add(this.barDockControlLeft); + this.barManager1.DockControls.Add(this.barDockControlRight); + this.barManager1.Form = this; + this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] { + this.bbiGenerateDelta}); + this.barManager1.MainMenu = this.bar2; + this.barManager1.MaxItemId = 27; + this.barManager1.StatusBar = this.bar3; + // + // bar1 + // + this.bar1.BarName = "Tools"; + this.bar1.DockCol = 0; + this.bar1.DockRow = 1; + this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; + this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] { + new DevExpress.XtraBars.LinkPersistInfo(this.bbiGenerateDelta)}); + this.bar1.Text = "Tools"; + // + // bar2 + // + this.bar2.BarName = "Main menu"; + this.bar2.DockCol = 0; + this.bar2.DockRow = 0; + this.bar2.DockStyle = DevExpress.XtraBars.BarDockStyle.Top; + this.bar2.OptionsBar.MultiLine = true; + this.bar2.OptionsBar.UseWholeRow = true; + this.bar2.Text = "Main menu"; + // + // bar3 + // + this.bar3.BarName = "Status bar"; + this.bar3.CanDockStyle = DevExpress.XtraBars.BarCanDockStyle.Bottom; + this.bar3.DockCol = 0; + this.bar3.DockRow = 0; + this.bar3.DockStyle = DevExpress.XtraBars.BarDockStyle.Bottom; + this.bar3.OptionsBar.AllowQuickCustomization = false; + this.bar3.OptionsBar.DrawDragBorder = false; + this.bar3.OptionsBar.UseWholeRow = true; + this.bar3.Text = "Status bar"; + // + // barDockControlTop + // + this.barDockControlTop.CausesValidation = false; + this.barDockControlTop.Dock = System.Windows.Forms.DockStyle.Top; + this.barDockControlTop.Location = new System.Drawing.Point(0, 0); + this.barDockControlTop.Manager = this.barManager1; + this.barDockControlTop.Size = new System.Drawing.Size(1173, 46); + // + // barDockControlBottom + // + this.barDockControlBottom.CausesValidation = false; + this.barDockControlBottom.Dock = System.Windows.Forms.DockStyle.Bottom; + this.barDockControlBottom.Location = new System.Drawing.Point(0, 537); + this.barDockControlBottom.Manager = this.barManager1; + this.barDockControlBottom.Size = new System.Drawing.Size(1173, 19); + // + // barDockControlLeft + // + this.barDockControlLeft.CausesValidation = false; + this.barDockControlLeft.Dock = System.Windows.Forms.DockStyle.Left; + this.barDockControlLeft.Location = new System.Drawing.Point(0, 46); + this.barDockControlLeft.Manager = this.barManager1; + this.barDockControlLeft.Size = new System.Drawing.Size(0, 491); + // + // barDockControlRight + // + this.barDockControlRight.CausesValidation = false; + this.barDockControlRight.Dock = System.Windows.Forms.DockStyle.Right; + this.barDockControlRight.Location = new System.Drawing.Point(1173, 46); + this.barDockControlRight.Manager = this.barManager1; + this.barDockControlRight.Size = new System.Drawing.Size(0, 491); + // + // dbCurrent + // + this.dbCurrent.DbFilename = ""; + this.dbCurrent.Dock = System.Windows.Forms.DockStyle.Left; + this.dbCurrent.FileLabel = "Current Database:"; + this.dbCurrent.Location = new System.Drawing.Point(0, 46); + this.dbCurrent.Name = "dbCurrent"; + this.dbCurrent.Size = new System.Drawing.Size(560, 491); + this.dbCurrent.TabIndex = 9; + // + // splitterControl1 + // + this.splitterControl1.Location = new System.Drawing.Point(560, 46); + this.splitterControl1.Name = "splitterControl1"; + this.splitterControl1.Size = new System.Drawing.Size(10, 491); + this.splitterControl1.TabIndex = 10; + this.splitterControl1.TabStop = false; + // + // dbLatest + // + this.dbLatest.DbFilename = ""; + this.dbLatest.Dock = System.Windows.Forms.DockStyle.Fill; + this.dbLatest.FileLabel = "Latest Database:"; + this.dbLatest.Location = new System.Drawing.Point(570, 46); + this.dbLatest.Name = "dbLatest"; + this.dbLatest.Size = new System.Drawing.Size(603, 491); + this.dbLatest.TabIndex = 11; + // + // bbiGenerateDelta + // + this.bbiGenerateDelta.Caption = "Generate Delta SQL Script"; + this.bbiGenerateDelta.Id = 26; + this.bbiGenerateDelta.Name = "bbiGenerateDelta"; + this.bbiGenerateDelta.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.ToolbarItemClicked); + // + // MainForm + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(1173, 556); + this.Controls.Add(this.dbLatest); + this.Controls.Add(this.splitterControl1); + this.Controls.Add(this.dbCurrent); + this.Controls.Add(this.barDockControlLeft); + this.Controls.Add(this.barDockControlRight); + this.Controls.Add(this.barDockControlBottom); + this.Controls.Add(this.barDockControlTop); + this.Name = "MainForm"; + this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; + this.Text = "Database Upgrade Tester"; + ((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private DevExpress.XtraBars.BarManager barManager1; + private DevExpress.XtraBars.Bar bar1; + private DevExpress.XtraBars.Bar bar2; + private DevExpress.XtraBars.Bar bar3; + private DevExpress.XtraBars.BarDockControl barDockControlTop; + private DevExpress.XtraBars.BarDockControl barDockControlBottom; + private DevExpress.XtraBars.BarDockControl barDockControlLeft; + private DevExpress.XtraBars.BarDockControl barDockControlRight; + private UserControls.DatabasePanel dbLatest; + private DevExpress.XtraEditors.SplitterControl splitterControl1; + private UserControls.DatabasePanel dbCurrent; + private DevExpress.XtraBars.BarButtonItem bbiGenerateDelta; + } +} \ No newline at end of file diff --git a/DbMigrateTester/Forms/MainForm.cs b/DbMigrateTester/Forms/MainForm.cs new file mode 100644 index 0000000..38fcca4 --- /dev/null +++ b/DbMigrateTester/Forms/MainForm.cs @@ -0,0 +1,19 @@ +using DevExpress.XtraEditors; +using System.Windows.Forms; + +namespace DbMigrateTester.Forms { + public partial class MainForm : DevExpress.XtraEditors.XtraForm { + public MainForm() { + InitializeComponent(); + } + + private void ToolbarItemClicked(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { + if (e.Item.Equals(bbiGenerateDelta)) { + var comparer = new DbMigrate.DbComparer(dbCurrent.SqlDb, dbLatest.SqlDb); + + comparer.Compare(); + XtraMessageBox.Show(comparer.UpdateSqlScript, "Delta SQL Script", MessageBoxButtons.OK, MessageBoxIcon.Information); + } + } + } +} \ No newline at end of file diff --git a/DbMigrateTester/Forms/MainForm.resx b/DbMigrateTester/Forms/MainForm.resx new file mode 100644 index 0000000..52e53df --- /dev/null +++ b/DbMigrateTester/Forms/MainForm.resx @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + 17, 17 + + \ No newline at end of file diff --git a/DbMigrateTester/Forms/UserControls/DatabasePanel.Designer.cs b/DbMigrateTester/Forms/UserControls/DatabasePanel.Designer.cs new file mode 100644 index 0000000..b1f7e4a --- /dev/null +++ b/DbMigrateTester/Forms/UserControls/DatabasePanel.Designer.cs @@ -0,0 +1,232 @@ +namespace DbMigrateTester.Forms.UserControls { + partial class DatabasePanel { + /// + /// Required designer variable. + /// + private System.ComponentModel.IContainer components = null; + + /// + /// Clean up any resources being used. + /// + /// true if managed resources should be disposed; otherwise, false. + protected override void Dispose(bool disposing) { + if (disposing && (components != null)) { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Component Designer generated code + + /// + /// Required method for Designer support - do not modify + /// the contents of this method with the code editor. + /// + private void InitializeComponent() { + DevExpress.XtraEditors.Controls.EditorButtonImageOptions editorButtonImageOptions2 = new DevExpress.XtraEditors.Controls.EditorButtonImageOptions(); + DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject5 = new DevExpress.Utils.SerializableAppearanceObject(); + DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject6 = new DevExpress.Utils.SerializableAppearanceObject(); + DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject7 = new DevExpress.Utils.SerializableAppearanceObject(); + DevExpress.Utils.SerializableAppearanceObject serializableAppearanceObject8 = new DevExpress.Utils.SerializableAppearanceObject(); + this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl(); + this.Root = new DevExpress.XtraLayout.LayoutControlGroup(); + this.xtraTabControl1 = new DevExpress.XtraTab.XtraTabControl(); + this.xtraTabPage1 = new DevExpress.XtraTab.XtraTabPage(); + this.xtraTabPage2 = new DevExpress.XtraTab.XtraTabPage(); + this.txtDbFilename = new DevExpress.XtraEditors.ButtonEdit(); + this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem(); + this.emptySpaceItem1 = new DevExpress.XtraLayout.EmptySpaceItem(); + this.rtfSql = new System.Windows.Forms.RichTextBox(); + this.treeList1 = new DevExpress.XtraTreeList.TreeList(); + this.splitterControl1 = new DevExpress.XtraEditors.SplitterControl(); + this.gridControl1 = new DevExpress.XtraGrid.GridControl(); + this.gridView1 = new DevExpress.XtraGrid.Views.Grid.GridView(); + ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit(); + this.layoutControl1.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.Root)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).BeginInit(); + this.xtraTabControl1.SuspendLayout(); + this.xtraTabPage1.SuspendLayout(); + this.xtraTabPage2.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.txtDbFilename.Properties)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.treeList1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.gridView1)).BeginInit(); + this.SuspendLayout(); + // + // layoutControl1 + // + this.layoutControl1.Controls.Add(this.txtDbFilename); + this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Top; + this.layoutControl1.Location = new System.Drawing.Point(0, 0); + this.layoutControl1.Name = "layoutControl1"; + this.layoutControl1.Root = this.Root; + this.layoutControl1.Size = new System.Drawing.Size(643, 141); + this.layoutControl1.TabIndex = 0; + this.layoutControl1.Text = "layoutControl1"; + // + // Root + // + this.Root.EnableIndentsWithoutBorders = DevExpress.Utils.DefaultBoolean.True; + this.Root.GroupBordersVisible = false; + this.Root.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] { + this.layoutControlItem1, + this.emptySpaceItem1}); + this.Root.Name = "Root"; + this.Root.Size = new System.Drawing.Size(643, 141); + this.Root.TextVisible = false; + // + // xtraTabControl1 + // + this.xtraTabControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.xtraTabControl1.Location = new System.Drawing.Point(0, 141); + this.xtraTabControl1.Name = "xtraTabControl1"; + this.xtraTabControl1.SelectedTabPage = this.xtraTabPage1; + this.xtraTabControl1.Size = new System.Drawing.Size(643, 468); + this.xtraTabControl1.TabIndex = 1; + this.xtraTabControl1.TabPages.AddRange(new DevExpress.XtraTab.XtraTabPage[] { + this.xtraTabPage1, + this.xtraTabPage2}); + // + // xtraTabPage1 + // + this.xtraTabPage1.Controls.Add(this.gridControl1); + this.xtraTabPage1.Controls.Add(this.splitterControl1); + this.xtraTabPage1.Controls.Add(this.treeList1); + this.xtraTabPage1.Name = "xtraTabPage1"; + this.xtraTabPage1.Size = new System.Drawing.Size(641, 442); + this.xtraTabPage1.Text = "Structure"; + // + // xtraTabPage2 + // + this.xtraTabPage2.Controls.Add(this.rtfSql); + this.xtraTabPage2.Name = "xtraTabPage2"; + this.xtraTabPage2.Size = new System.Drawing.Size(641, 442); + this.xtraTabPage2.Text = "SQL Text"; + // + // txtDbFilename + // + this.txtDbFilename.Location = new System.Drawing.Point(82, 12); + this.txtDbFilename.Name = "txtDbFilename"; + this.txtDbFilename.Properties.Buttons.AddRange(new DevExpress.XtraEditors.Controls.EditorButton[] { + new DevExpress.XtraEditors.Controls.EditorButton(), + new DevExpress.XtraEditors.Controls.EditorButton(DevExpress.XtraEditors.Controls.ButtonPredefines.Clear, "", -1, true, false, false, editorButtonImageOptions2, new DevExpress.Utils.KeyShortcut(System.Windows.Forms.Keys.None), serializableAppearanceObject5, serializableAppearanceObject6, serializableAppearanceObject7, serializableAppearanceObject8, "", null, null, DevExpress.Utils.ToolTipAnchor.Default)}); + this.txtDbFilename.Size = new System.Drawing.Size(549, 22); + this.txtDbFilename.StyleController = this.layoutControl1; + this.txtDbFilename.TabIndex = 4; + this.txtDbFilename.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(this.DbFilename_ButtonClick); + // + // layoutControlItem1 + // + this.layoutControlItem1.Control = this.txtDbFilename; + this.layoutControlItem1.Location = new System.Drawing.Point(0, 0); + this.layoutControlItem1.Name = "layoutControlItem1"; + this.layoutControlItem1.Size = new System.Drawing.Size(623, 26); + this.layoutControlItem1.Text = "Database:"; + this.layoutControlItem1.TextSize = new System.Drawing.Size(58, 16); + // + // emptySpaceItem1 + // + this.emptySpaceItem1.AllowHotTrack = false; + this.emptySpaceItem1.Location = new System.Drawing.Point(0, 26); + this.emptySpaceItem1.Name = "emptySpaceItem1"; + this.emptySpaceItem1.Size = new System.Drawing.Size(623, 95); + this.emptySpaceItem1.TextSize = new System.Drawing.Size(0, 0); + // + // rtfSql + // + this.rtfSql.Dock = System.Windows.Forms.DockStyle.Fill; + this.rtfSql.Font = new System.Drawing.Font("Lucida Console", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); + this.rtfSql.Location = new System.Drawing.Point(0, 0); + this.rtfSql.Name = "rtfSql"; + this.rtfSql.ReadOnly = true; + this.rtfSql.Size = new System.Drawing.Size(641, 442); + this.rtfSql.TabIndex = 0; + this.rtfSql.Text = ""; + // + // treeList1 + // + this.treeList1.Dock = System.Windows.Forms.DockStyle.Left; + this.treeList1.Location = new System.Drawing.Point(0, 0); + this.treeList1.Name = "treeList1"; + this.treeList1.OptionsBehavior.Editable = false; + this.treeList1.OptionsBehavior.ReadOnly = true; + this.treeList1.OptionsView.ShowColumns = false; + this.treeList1.OptionsView.ShowHorzLines = false; + this.treeList1.OptionsView.ShowIndicator = false; + this.treeList1.OptionsView.ShowVertLines = false; + this.treeList1.Size = new System.Drawing.Size(164, 442); + this.treeList1.TabIndex = 0; + // + // splitterControl1 + // + this.splitterControl1.Location = new System.Drawing.Point(164, 0); + this.splitterControl1.Name = "splitterControl1"; + this.splitterControl1.Size = new System.Drawing.Size(10, 442); + this.splitterControl1.TabIndex = 1; + this.splitterControl1.TabStop = false; + // + // gridControl1 + // + this.gridControl1.Dock = System.Windows.Forms.DockStyle.Fill; + this.gridControl1.Location = new System.Drawing.Point(174, 0); + this.gridControl1.MainView = this.gridView1; + this.gridControl1.Name = "gridControl1"; + this.gridControl1.Size = new System.Drawing.Size(467, 442); + this.gridControl1.TabIndex = 2; + this.gridControl1.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] { + this.gridView1}); + // + // gridView1 + // + this.gridView1.GridControl = this.gridControl1; + this.gridView1.Name = "gridView1"; + this.gridView1.OptionsView.ShowGroupPanel = false; + this.gridView1.OptionsView.ShowHorizontalLines = DevExpress.Utils.DefaultBoolean.False; + this.gridView1.OptionsView.ShowIndicator = false; + this.gridView1.OptionsView.ShowVerticalLines = DevExpress.Utils.DefaultBoolean.False; + // + // DatabasePanel + // + this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 16F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.Controls.Add(this.xtraTabControl1); + this.Controls.Add(this.layoutControl1); + this.Name = "DatabasePanel"; + this.Size = new System.Drawing.Size(643, 609); + ((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit(); + this.layoutControl1.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.Root)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.xtraTabControl1)).EndInit(); + this.xtraTabControl1.ResumeLayout(false); + this.xtraTabPage1.ResumeLayout(false); + this.xtraTabPage2.ResumeLayout(false); + ((System.ComponentModel.ISupportInitialize)(this.txtDbFilename.Properties)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.emptySpaceItem1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.treeList1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.gridControl1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.gridView1)).EndInit(); + this.ResumeLayout(false); + + } + + #endregion + + private DevExpress.XtraLayout.LayoutControl layoutControl1; + private DevExpress.XtraLayout.LayoutControlGroup Root; + private DevExpress.XtraEditors.ButtonEdit txtDbFilename; + private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1; + private DevExpress.XtraLayout.EmptySpaceItem emptySpaceItem1; + private DevExpress.XtraTab.XtraTabControl xtraTabControl1; + private DevExpress.XtraTab.XtraTabPage xtraTabPage1; + private DevExpress.XtraTab.XtraTabPage xtraTabPage2; + private System.Windows.Forms.RichTextBox rtfSql; + private DevExpress.XtraGrid.GridControl gridControl1; + private DevExpress.XtraGrid.Views.Grid.GridView gridView1; + private DevExpress.XtraEditors.SplitterControl splitterControl1; + private DevExpress.XtraTreeList.TreeList treeList1; + } +} diff --git a/DbMigrateTester/Forms/UserControls/DatabasePanel.cs b/DbMigrateTester/Forms/UserControls/DatabasePanel.cs new file mode 100644 index 0000000..36ecf2d --- /dev/null +++ b/DbMigrateTester/Forms/UserControls/DatabasePanel.cs @@ -0,0 +1,99 @@ +using DbMigrate; +using System; +using System.ComponentModel; +using System.IO; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace DbMigrateTester.Forms.UserControls { + public partial class DatabasePanel : DevExpress.XtraEditors.XtraUserControl { + + public string DbFilename { + get { return txtDbFilename.Text; } + set { + txtDbFilename.Text = value; + if (string.IsNullOrEmpty(value)) { + enableDbFilename(); + } else { + disableDbFilename(); + } + } + } + + public string Sql => rtfSql.Text; + + public SqlDatabase SqlDb { get; private set; } + + [Browsable(true)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] + public string FileLabel { + get { return layoutControlItem1.Text; } + set { layoutControlItem1.Text = value; } + } + + public DatabasePanel() { + InitializeComponent(); + } + + private async void DbFilename_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e) { + try { + if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis) { + OpenFileDialog dlg = new OpenFileDialog() { + Filter = "Database Files (*.sql;*.sqlite;*.db)|*.sql;*.sqlite;*.db|SQL Files (*.sql)|*.sql|Sqlite Files (*.sqlite;*.db)|*.sqlite;*.db|Text Files (*.txt)|*.txt|All Files (*.*)|*.*", + CheckFileExists = true, + Multiselect = false, + Title = "Select Database File" + }; + if (dlg.ShowDialog() == DialogResult.OK) { + await LoadDatabase(dlg.FileName); + } + } else if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Clear) { + txtDbFilename.Text = ""; + rtfSql.Text = ""; + treeList1.DataSource = null; + enableDbFilename(); + } + } catch (Exception ex) { + Console.WriteLine(ex.ToString()); + } + } + + private void enableDbFilename(bool enabled = true) { + txtDbFilename.ReadOnly = !enabled; + txtDbFilename.Properties.Buttons[0].Visible = enabled; + txtDbFilename.Properties.Buttons[1].Visible = !enabled; + } + + private void disableDbFilename() { + enableDbFilename(false); + } + + public async Task LoadDatabase(string filename) { + DbFilename = filename; + disableDbFilename(); + + SqlDatabase db = new SqlDatabase(); + if (Path.GetExtension(filename).ToLower() == ".sql" || Path.GetExtension(filename).ToLower() == ".txt") { + // Load data from SQL file + string sql = File.ReadAllText(filename); + MatchCollection mc = Regex.Matches(sql, "^(CREATE TABLE( IF NOT EXISTS)? (\\w*).*\\);)", RegexOptions.Multiline | RegexOptions.Singleline); + db.LoadSql(sql); + rtfSql.Text = db.SqlScript; + } else if (Path.GetExtension(filename).ToLower() == ".sqlite" || Path.GetExtension(filename).ToLower() == ".db") { + // Load data from SQLite database file + string sql = await db.BuildSql("Data Source=" + filename + "; Version=3;"); + rtfSql.Text = sql; + } else { + MessageBox.Show("Unsupported database file type: " + Path.GetExtension(filename), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); + } + + if (db.Tables != null && db.Tables.Count > 0) { + treeList1.Columns.Clear(); + treeList1.Columns.Add(new DevExpress.XtraTreeList.Columns.TreeListColumn() { Caption = "Table Name", Visible = true, FieldName = "TableName" }); + treeList1.DataSource = db.Tables; + } + SqlDb = db; + } + } +} diff --git a/DbMigrateTester/Forms/UserControls/DatabasePanel.resx b/DbMigrateTester/Forms/UserControls/DatabasePanel.resx new file mode 100644 index 0000000..1af7de1 --- /dev/null +++ b/DbMigrateTester/Forms/UserControls/DatabasePanel.resx @@ -0,0 +1,120 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DbMigrateTester/Program.cs b/DbMigrateTester/Program.cs new file mode 100644 index 0000000..5820ad7 --- /dev/null +++ b/DbMigrateTester/Program.cs @@ -0,0 +1,16 @@ +using System; +using System.Windows.Forms; + +namespace DbMigrateTester { + internal static class Program { + /// + /// The main entry point for the application. + /// + [STAThread] + static void Main() { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new Forms.MainForm()); + } + } +} diff --git a/DbMigrateTester/Properties/AssemblyInfo.cs b/DbMigrateTester/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1a90c2a --- /dev/null +++ b/DbMigrateTester/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("DbMigrateTester")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("DbMigrateTester")] +[assembly: AssemblyCopyright("Copyright © 2025")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("33492e2a-4d65-4f78-a3c5-325474921199")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/DbMigrateTester/Properties/Resources.Designer.cs b/DbMigrateTester/Properties/Resources.Designer.cs new file mode 100644 index 0000000..4d12ee0 --- /dev/null +++ b/DbMigrateTester/Properties/Resources.Designer.cs @@ -0,0 +1,62 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DbMigrateTester.Properties { + + + /// + /// A strongly-typed resource class, for looking up localized strings, etc. + /// + // This class was auto-generated by the StronglyTypedResourceBuilder + // class via a tool like ResGen or Visual Studio. + // To add or remove a member, edit your .ResX file then rerun ResGen + // with the /str option, or rebuild your VS project. + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// Returns the cached ResourceManager instance used by this class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if ((resourceMan == null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("DbMigrateTester.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// Overrides the current thread's CurrentUICulture property for all + /// resource lookups using this strongly typed resource class. + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + } +} diff --git a/DbMigrateTester/Properties/Resources.resx b/DbMigrateTester/Properties/Resources.resx new file mode 100644 index 0000000..af7dbeb --- /dev/null +++ b/DbMigrateTester/Properties/Resources.resx @@ -0,0 +1,117 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + \ No newline at end of file diff --git a/DbMigrateTester/Properties/Settings.Designer.cs b/DbMigrateTester/Properties/Settings.Designer.cs new file mode 100644 index 0000000..8a688e9 --- /dev/null +++ b/DbMigrateTester/Properties/Settings.Designer.cs @@ -0,0 +1,26 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace DbMigrateTester.Properties { + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default { + get { + return defaultInstance; + } + } + } +} diff --git a/DbMigrateTester/Properties/Settings.settings b/DbMigrateTester/Properties/Settings.settings new file mode 100644 index 0000000..3964565 --- /dev/null +++ b/DbMigrateTester/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/DbMigrateTester/Properties/licenses.licx b/DbMigrateTester/Properties/licenses.licx new file mode 100644 index 0000000..ba84954 --- /dev/null +++ b/DbMigrateTester/Properties/licenses.licx @@ -0,0 +1,6 @@ +DevExpress.XtraBars.BarManager, DevExpress.XtraBars.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a +DevExpress.XtraEditors.ButtonEdit, DevExpress.XtraEditors.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a +DevExpress.XtraLayout.LayoutControl, DevExpress.XtraLayout.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a +DevExpress.XtraGrid.GridControl, DevExpress.XtraGrid.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a +DevExpress.XtraTreeList.TreeList, DevExpress.XtraTreeList.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a +DevExpress.XtraRichEdit.RichEditControl, DevExpress.XtraRichEdit.v23.2, Version=23.2.3.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a diff --git a/Extensions.cs b/Extensions.cs index e97bcba..23f170e 100644 --- a/Extensions.cs +++ b/Extensions.cs @@ -16,6 +16,9 @@ namespace DbMigrate { bool inTable = false; bool inColumns = false; + + + Match m = null; foreach (string line in Regex.Split(sql, "\\r\\n")) { if (string.IsNullOrEmpty(line) || line.StartsWith("--")) { diff --git a/SqlDatabase.cs b/SqlDatabase.cs index 8b9f495..404f9e5 100644 --- a/SqlDatabase.cs +++ b/SqlDatabase.cs @@ -1,5 +1,7 @@ -using System.Collections.Generic; -using System.Data.OleDb; +using Dapper; +using System; +using System.Collections.Generic; +using System.Data.SQLite; using System.Diagnostics; using System.IO; using System.Linq; @@ -37,39 +39,142 @@ namespace DbMigrate { LoadSql(sql); } + + public bool ContainsTable(string tableName) { + return Tables.Count(f => f.TableName.ToLower() == tableName.ToLower()) > 0; + } + + + public SqlTable this[string tableName] { + get { + return Tables.FirstOrDefault(f => f.TableName.ToLower() == tableName.ToLower()); + } + } + public IEnumerable ParseTablesFromSql(string sql) { SqlTable table = null; StringBuilder sb = new StringBuilder(); + + Dictionary> indexes = new Dictionary>(); + Dictionary> triggers = new Dictionary>(); + + string currentElementType = ""; foreach (string line in Regex.Split(sql, "\\r\\n")) { if (string.IsNullOrEmpty(line) || line.StartsWith("--")) { continue; } - if (line.ToUpper().StartsWith("CREATE TABLE ")) { - if (table != null) { - table.ParseSql(sb.ToString()); - yield return table; - } + string trimmedLine = line; + if (currentElementType == "trigger" || currentElementType == "index") { + trimmedLine = line.Trim(); + } else { + trimmedLine = line.StartsWith(" ") ? "&&" + line.Trim() : line; + trimmedLine = Regex.Replace(trimmedLine, @"\s+", " "); + trimmedLine = trimmedLine.Replace("&&", "\t"); + } + + if (trimmedLine.ToUpper().StartsWith("CREATE TABLE ")) { // Start a new table table = new SqlTable(); sb = new StringBuilder(); - sb.AppendLine(line); + sb.AppendLine(trimmedLine); + currentElementType = "table"; continue; } - sb.AppendLine(line); + + if (trimmedLine.ToUpper().StartsWith("CREATE INDEX ")) { + var matches = Regex.Match(trimmedLine, "CREATE INDEX( IF NOT EXISTS)? (\\w*) ON (\\w*)"); + if (matches.Success) { + sb = new StringBuilder(); + sb.AppendLine(trimmedLine); + currentElementType = "index"; + if (!indexes.ContainsKey(matches.Groups[2].Value.Trim())) { + indexes[matches.Groups[2].Value.Trim()] = new List(); + } + continue; + } + } + + if (trimmedLine.ToUpper().StartsWith("CREATE TRIGGER ")) { + sb = new StringBuilder(); + sb.AppendLine(trimmedLine); + currentElementType = "trigger"; + continue; + } + + // The element has concluded (may occur on the same line as above) + if (trimmedLine.EndsWith(");") || trimmedLine.EndsWith("END;")) { + sb.AppendLine(trimmedLine); + if (currentElementType == "table" && table != null) { + SqlScript += sb.ToString() + Environment.NewLine + Environment.NewLine; + table.ParseSql(sb.ToString()); + Tables.Add(table); + currentElementType = ""; + yield return table; + } else if (currentElementType == "index") { + string indexSql = sb.ToString().Replace(Environment.NewLine, " "); + SqlScript += indexSql + Environment.NewLine + Environment.NewLine; + var matches = Regex.Match(indexSql, "CREATE INDEX( IF NOT EXISTS)? (\\w*) ON (\\w*)"); + if (matches.Success) { + if (!indexes.ContainsKey(matches.Groups[3].Value.Trim())) { + indexes[matches.Groups[3].Value.Trim()] = new List(); + } + string indexName = matches.Groups[2].Value.Trim(); + string tableName = matches.Groups[3].Value.Trim(); + indexes[tableName].Add(indexName + ";" + indexSql); + } + currentElementType = ""; + } else if (currentElementType == "trigger") { + string triggerSql = sb.ToString().Replace(Environment.NewLine, " "); + SqlScript += triggerSql + Environment.NewLine + Environment.NewLine; + var matches = Regex.Match(triggerSql, "CREATE TRIGGER( IF NOT EXISTS)? (\\w*) ON (\\w*)"); + if (matches.Success) { + if (!triggers.ContainsKey(matches.Groups[3].Value.Trim())) { + triggers[matches.Groups[3].Value.Trim()] = new List(); + } + string triggerName = matches.Groups[2].Value.Trim(); + string tableName = matches.Groups[3].Value.Trim(); + triggers[tableName].Add(triggerName + ";" + triggerSql); + } + currentElementType = ""; + } + continue; + } + + sb.AppendLine(trimmedLine); } - table.ParseSql(sb.ToString()); - yield return table; + foreach (string index in indexes.Keys) { + table = Tables.FirstOrDefault(t => t.TableName == index); + if (table != null) { + foreach (string indexSql in indexes[index]) { + var parts = indexSql.Split(new char[] { ';' }, 2); + if (parts.Length == 2) { + table.Indexes[parts[0]] = parts[1]; + } + } + } + } + + foreach (string trigger in triggers.Keys) { + table = Tables.FirstOrDefault(t => t.TableName == trigger); + if (table != null) { + foreach (string triggerSql in triggers[trigger]) { + var parts = triggerSql.Split(new char[] { ';' }, 2); + if (parts.Length == 2) { + table.Triggers[parts[0]] = parts[1]; + } + } + } + } } public async Task BuildSql(string dbConnectionString, bool includeIfNotExist = false) { - using (OleDbConnection cn = new OleDbConnection(dbConnectionString)) { + using (SQLiteConnection cn = new SQLiteConnection(dbConnectionString)) { string sql = ""; - //List TableSql = new List(); IEnumerable TableDefs = await cn.QueryAsync("select * from sqlite_master"); foreach (SqliteTableDefinition table in TableDefs.Where(f => f.type == "table").OrderBy(f => f.tbl_name)) { @@ -80,37 +185,40 @@ namespace DbMigrate { continue; } + string tableSql = ""; int startIndex = m.Groups[1].Index; int length = m.Groups[1].Length; string columns = Regex.Replace(m.Groups[1].Value, "\\s{2,}", " "); columns = Regex.Replace(columns.Replace(", ", ",").Replace(",\n", ","), ",(?!\\d+\\))", ",\r\n\t"); - sql += "-- BEGIN TABLE " + table.tbl_name + " --\r\n"; - sql += table.sql.Substring(0, startIndex) + "\r\n\t" + + tableSql += "-- BEGIN TABLE " + table.tbl_name + " --\r\n"; + tableSql += table.sql.Substring(0, startIndex) + "\r\n\t" + columns.Trim() + "\r\n" + table.sql.Substring(startIndex + length) + ";\r\n"; List indexes = TableDefs.Where(f => f.type == "index" && f.tbl_name == table.tbl_name && !string.IsNullOrEmpty(f.sql)).ToList(); if (indexes.Count > 0) { - sql += "\r\n-- INDEXES --\r\n"; + tableSql += "\r\n-- INDEXES --\r\n"; foreach (var index in indexes) { if (string.IsNullOrEmpty(index.sql)) { continue; } - sql += index.sql + ";\r\n"; + tableSql += index.sql.Replace(Environment.NewLine, " ") + ";\r\n"; } } List triggers = TableDefs.Where(f => f.type == "trigger" && f.tbl_name == table.tbl_name && !string.IsNullOrEmpty(f.sql)).ToList(); if (triggers.Count > 0) { - sql += "\r\n-- TRIGGERS --\r\n"; + tableSql += "\r\n-- TRIGGERS --\r\n"; foreach (var trigger in triggers) { if (string.IsNullOrEmpty(trigger.sql)) { continue; } - sql += trigger.sql + ";\r\n"; + tableSql += trigger.sql.Replace(Environment.NewLine, " ") + ";\r\n"; } } - sql += "-- END TABLE " + table.tbl_name + " --\r\n\r\n"; - //TableSql.Add(sql); + tableSql += "-- END TABLE " + table.tbl_name + " --\r\n\r\n"; + + Tables.Add(new SqlTable(tableSql)); + sql += tableSql; } return sql; diff --git a/SqlTable.cs b/SqlTable.cs index fdbc95a..d05c9d8 100644 --- a/SqlTable.cs +++ b/SqlTable.cs @@ -14,16 +14,22 @@ namespace DbMigrate { public SqlTable() { - Columns = new Dictionary(); - Indexes = new Dictionary(); - Triggers = new Dictionary(); + initTable(); } public SqlTable(string sql) { + initTable(); OriginalSql = sql; this.ParseSql(sql); } + private void initTable() { + Columns = new Dictionary(); + Indexes = new Dictionary(); + Triggers = new Dictionary(); + CreateTableSql = ""; + } + public string FullSql() { StringBuilder sb = new StringBuilder(); //sb.AppendLine("-- Create Table " + TableName); @@ -67,6 +73,14 @@ namespace DbMigrate { return Triggers.Values.ToArray(); } + public bool HasTrigger(string triggerName) { + return Triggers.ContainsKey(triggerName); + } + + public bool HasIndex(string indexName) { + return Indexes.ContainsKey(indexName); + } + public string[] GetIndexNames() { return Indexes.Keys.ToArray(); } diff --git a/SqliteTableDefinition.cs b/SqliteTableDefinition.cs new file mode 100644 index 0000000..b49189b --- /dev/null +++ b/SqliteTableDefinition.cs @@ -0,0 +1,10 @@ +namespace DbMigrate { + public class SqliteTableDefinition { + public string @type { get; set; } + public string name { get; set; } + public string tbl_name { get; set; } + public int rootpage { get; set; } + public string sql { get; set; } + + } +} diff --git a/app.config b/app.config new file mode 100644 index 0000000..c1ed4d6 --- /dev/null +++ b/app.config @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/packages.config b/packages.config new file mode 100644 index 0000000..559ccdf --- /dev/null +++ b/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file