Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Imports System
- Imports System.Timers
- Imports System.Collections.Generic
- Imports System.Text
- Imports MySql.Data.MySqlClient
- Imports System.ComponentModel
- Imports System.IO
- Imports System.IO.Compression
- Imports System.Globalization
- Imports System.Security.Cryptography
- Imports System.Reflection
- Namespace MySql.Data.MySqlClient
- Public Class MySqlBackup
- Implements IDisposable
- Enum ProcessType
- Export
- Import
- End Enum
- Public Enum ProcessEndType
- UnknownStatus
- Complete
- Cancelled
- [Error]
- End Enum
- Public Const Version As String = "2.3.1"
- Private _database As MySqlDatabase = New MySqlDatabase()
- Private _server As MySqlServer = New MySqlServer()
- Private ReadOnly Property textEncoding As Encoding
- Get
- Try
- Return ExportInfo.TextEncoding
- Catch
- End Try
- Return New UTF8Encoding(False)
- End Get
- End Property
- Private textWriter As TextWriter
- Private textReader As TextReader
- Private timeStart As DateTime
- Private timeEnd As DateTime
- Private currentProcess As ProcessType
- Private processCompletionType As ProcessEndType
- Private stopProcess As Boolean = False
- Private _lastError As Exception = Nothing
- Private _lastErrorSql As String = ""
- Private _currentTableName As String = ""
- Private _totalRowsInCurrentTable As Long = 0
- Private _totalRowsInAllTables As Long = 0
- Private _currentRowIndexInCurrentTable As Long = 0
- Private _currentRowIndexInAllTable As Long = 0
- Private _totalTables As Integer = 0
- Private _currentTableIndex As Integer = 0
- Private timerReport As Timer = Nothing
- Private _currentBytes As Long = 0L
- Private _totalBytes As Long = 0L
- Private _sbImport As StringBuilder = Nothing
- Private _mySqlScript As MySqlScript = Nothing
- Private _delimiter As String = ""
- Private utf8WithoutBOM As Encoding
- Enum NextImportAction
- Ignore
- SetNames
- CreateNewDatabase
- AppendLine
- ChangeDelimiter
- AppendLineAndExecute
- End Enum
- Public ReadOnly Property LastError As Exception
- Get
- Return _lastError
- End Get
- End Property
- Public ReadOnly Property LastErrorSQL As String
- Get
- Return _lastErrorSql
- End Get
- End Property
- Public ReadOnly Property Database As MySqlDatabase
- Get
- Return _database
- End Get
- End Property
- Public ReadOnly Property Server As MySqlServer
- Get
- Return _server
- End Get
- End Property
- Public Property Command As MySqlCommand
- Public ExportInfo As ExportInformations = New ExportInformations()
- Public ImportInfo As ImportInformations = New ImportInformations()
- Public Delegate Sub exportProgressChange(ByVal sender As Object, ByVal e As ExportProgressArgs)
- Public Event ExportProgressChanged As exportProgressChange
- Public Delegate Sub exportComplete(ByVal sender As Object, ByVal e As ExportCompleteArgs)
- Public Event ExportCompleted As exportComplete
- Public Delegate Sub importProgressChange(ByVal sender As Object, ByVal e As ImportProgressArgs)
- Public Event ImportProgressChanged As importProgressChange
- Public Delegate Sub importComplete(ByVal sender As Object, ByVal e As ImportCompleteArgs)
- Public Event ImportCompleted As importComplete
- Public Delegate Sub getTotalRowsProgressChange(ByVal sender As Object, ByVal e As GetTotalRowsArgs)
- Public Event GetTotalRowsProgressChanged As getTotalRowsProgressChange
- Public Sub New()
- InitializeComponents()
- End Sub
- Public Sub New(ByVal cmd As MySqlCommand)
- InitializeComponents()
- Command = cmd
- End Sub
- Private Sub InitializeComponents()
- AddHandler Me._database.GetTotalRowsProgressChanged, AddressOf Me._database_GetTotalRowsProgressChanged
- Me.timerReport = New Timer
- AddHandler Me.timerReport.Elapsed, New ElapsedEventHandler(AddressOf Me.timerReport_Elapsed)
- Me.utf8WithoutBOM = New UTF8Encoding(False)
- timerReport = New Timer()
- AddHandler timerReport.Elapsed, AddressOf timerReport_Elapsed
- End Sub
- Private Sub _database_GetTotalRowsProgressChanged(ByVal sender As Object, ByVal e As GetTotalRowsArgs)
- RaiseEvent GetTotalRowsProgressChanged(Me, e)
- End Sub
- Public Function ExportToString() As String
- Using ms As MemoryStream = New MemoryStream()
- ExportToMemoryStream(ms)
- ms.Position = 0L
- Using thisReader = New StreamReader(ms)
- Return thisReader.ReadToEnd()
- End Using
- End Using
- End Function
- Public Sub ExportToFile(ByVal filePath As String)
- Using textWriter = New StreamWriter(filePath, False, Me.utf8WithoutBOM)
- Me.ExportStart()
- Me.textWriter.Close()
- End Using
- End Sub
- Public Sub ExportToTextWriter(ByVal tw As TextWriter)
- textWriter = tw
- ExportStart()
- End Sub
- Public Sub ExportToMemoryStream(ByVal ms As MemoryStream)
- ExportToMemoryStream(ms, True)
- End Sub
- Public Sub ExportToMemoryStream(ByVal ms As MemoryStream, ByVal resetMemoryStreamPosition As Boolean)
- If resetMemoryStreamPosition Then
- If ms Is Nothing Then ms = New MemoryStream()
- If ms.Length > 0 Then ms = New MemoryStream()
- ms.Position = 0L
- End If
- textWriter = New StreamWriter(ms, textEncoding)
- ExportStart()
- End Sub
- Private Sub ExportStart()
- Try
- Export_InitializeVariables()
- Dim stage As Integer = 1
- While stage < 11
- If stopProcess Then Exit While
- Select Case stage
- Case 1
- Export_BasicInfo()
- Case 2
- Export_CreateDatabase()
- Case 3
- Export_DocumentHeader()
- Case 4
- Export_TableRows()
- Case 5
- Export_Functions()
- Case 6
- Export_Procedures()
- Case 7
- Export_Events()
- Case 8
- Export_Views()
- Case 9
- Export_Triggers()
- Case 10
- Export_DocumentFooter()
- Case Else
- End Select
- textWriter.Flush()
- stage = stage + 1
- End While
- If stopProcess Then
- processCompletionType = ProcessEndType.Cancelled
- Else
- processCompletionType = ProcessEndType.Complete
- End If
- Catch ex As Exception
- _lastError = ex
- StopAllProcess()
- Throw
- End Try
- ReportEndProcess()
- End Sub
- Private Sub Export_InitializeVariables()
- If Command Is Nothing Then
- Throw New Exception("MySqlCommand is not initialized. Object not set to an instance of an object.")
- End If
- If Command.Connection Is Nothing Then
- Throw New Exception("MySqlCommand.Connection is not initialized. Object not set to an instance of an object.")
- End If
- If Command.Connection.State <> System.Data.ConnectionState.Open Then
- Throw New Exception("MySqlCommand.Connection is not opened.")
- End If
- If ExportInfo.BlobExportMode = BlobDataExportMode.BinaryChar AndAlso Not ExportInfo.BlobExportModeForBinaryStringAllow Then
- Throw New Exception("[ExportInfo.BlobExportMode = BlobDataExportMode.BinaryString] is still under development. Please join the discussion at https://github.com/MySqlBackupNET/MySqlBackup.Net/issues (Title: Help requires. Unable to export BLOB in Char Format)")
- End If
- timeStart = DateTime.Now
- stopProcess = False
- processCompletionType = ProcessEndType.UnknownStatus
- currentProcess = ProcessType.Export
- _lastError = Nothing
- timerReport.Interval = ExportInfo.IntervalForProgressReport
- _database.GetDatabaseInfo(Command, ExportInfo.GetTotalRowsMode)
- _server.GetServerInfo(Command)
- _currentTableName = ""
- _totalRowsInCurrentTable = 0L
- _totalRowsInAllTables = 0L
- Dim dicTables = Export_GetTablesToBeExported()
- For Each kv In dicTables
- _totalRowsInAllTables = _totalRowsInAllTables + _database.Tables(kv.Key).TotalRows
- Next
- _currentRowIndexInCurrentTable = 0
- _currentRowIndexInAllTable = 0
- _totalTables = 0
- _currentTableIndex = 0
- End Sub
- Private Sub Export_BasicInfo()
- Export_WriteComment(String.Format("MySqlBackup.NET {0}", MySqlBackup.Version))
- If ExportInfo.RecordDumpTime Then
- Export_WriteComment(String.Format("Dump Time: {0}", timeStart.ToString("yyyy-MM-dd HH:mm:ss")))
- Else
- Export_WriteComment("")
- End If
- Export_WriteComment("--------------------------------------")
- Export_WriteComment(String.Format("Server version {0}", _server.Version))
- textWriter.WriteLine()
- End Sub
- Private Sub Export_CreateDatabase()
- If Not ExportInfo.AddCreateDatabase AndAlso Not ExportInfo.AddDropDatabase Then Return
- textWriter.WriteLine()
- textWriter.WriteLine()
- If ExportInfo.AddDropDatabase Then Export_WriteLine(String.Format("DROP DATABASE `{0}`;", _database.Name))
- If ExportInfo.AddCreateDatabase Then
- Export_WriteLine(_database.CreateDatabaseSQL)
- Export_WriteLine(String.Format("USE `{0}`;", _database.Name))
- End If
- textWriter.WriteLine()
- textWriter.WriteLine()
- End Sub
- Private Sub Export_DocumentHeader()
- textWriter.WriteLine()
- Dim lstHeaders As List(Of String) = ExportInfo.GetDocumentHeaders(Command)
- If lstHeaders.Count > 0 Then
- For Each s As String In lstHeaders
- Export_WriteLine(s)
- Next
- textWriter.WriteLine()
- textWriter.WriteLine()
- End If
- End Sub
- Private Sub Export_TableRows()
- Dim dicTables As Dictionary(Of String, String) = Export_GetTablesToBeExported()
- _totalTables = dicTables.Count
- If ExportInfo.ExportTableStructure OrElse ExportInfo.ExportRows Then
- If ExportProgressChanged IsNot Nothing Then timerReport.Start()
- For Each kvTable As KeyValuePair(Of String, String) In dicTables
- If stopProcess Then Return
- Dim tableName As String = kvTable.Key
- Dim selectSQL As String = kvTable.Value
- Dim exclude As Boolean = Export_ThisTableIsExcluded(tableName)
- If exclude Then
- Continue For
- End If
- _currentTableName = tableName
- _currentTableIndex = _currentTableIndex + 1
- _totalRowsInCurrentTable = _database.Tables(tableName).TotalRows
- If ExportInfo.ExportTableStructure Then Export_TableStructure(tableName)
- If ExportInfo.ExportRows Then Export_Rows(tableName, selectSQL)
- Next
- End If
- End Sub
- Private Function Export_ThisTableIsExcluded(ByVal tableName As String) As Boolean
- Dim tableNameLower As String = tableName.ToLower()
- For Each blacklistedTable As String In ExportInfo.ExcludeTables
- If blacklistedTable.ToLower() = tableNameLower Then Return True
- Next
- Return False
- End Function
- Private Sub Export_TableStructure(ByVal tableName As String)
- If stopProcess Then Return
- Export_WriteComment("")
- Export_WriteComment(String.Format("Definition of {0}", tableName))
- Export_WriteComment("")
- textWriter.WriteLine()
- If ExportInfo.AddDropTable Then Export_WriteLine(String.Format("DROP TABLE IF EXISTS `{0}`;", tableName))
- If ExportInfo.ResetAutoIncrement Then
- Export_WriteLine(_database.Tables(tableName).CreateTableSqlWithoutAutoIncrement)
- Else
- Export_WriteLine(_database.Tables(tableName).CreateTableSql)
- End If
- textWriter.WriteLine()
- textWriter.Flush()
- End Sub
- Private Function Export_GetTablesToBeExported() As Dictionary(Of String, String)
- Dim dic = New Dictionary(Of String, String)()
- If ExportInfo.TablesToBeExportedDic Is Nothing OrElse ExportInfo.TablesToBeExportedDic.Count = 0 Then
- For Each table As MySqlTable In _database.Tables
- dic(table.Name) = String.Format("SELECT * FROM `{0}`;", table.Name)
- Next
- Else
- For Each kv As KeyValuePair(Of String, String) In ExportInfo.TablesToBeExportedDic
- For Each kv2 In _database.Tables
- If kv2.Name = kv.Key Then
- dic(kv.Key) = kv.Value
- Continue For
- End If
- Next
- Next
- End If
- Dim dic2 As Dictionary(Of String, String) = New Dictionary(Of String, String)()
- For Each kv In dic
- dic2(kv.Key) = _database.Tables(kv.Key).CreateTableSql
- Next
- Dim lst = Export_ReArrangeDependencies(dic2, "foreign key", "`")
- dic2.Clear()
- For Each tbname In lst
- dic2.Add(tbname, dic(tbname))
- Next
- Return dic2
- End Function
- Private Function Export_ReArrangeDependencies(ByVal dic1 As Dictionary(Of String, String), ByVal splitKeyword As String, ByVal keyNameWrapper As String) As List(Of String)
- Dim lst As List(Of String) = New List(Of String)()
- Dim requireLoop As Boolean = True
- While requireLoop
- requireLoop = False
- For Each kv In dic1
- If lst.Contains(kv.Key) Then Continue For
- Dim allReferencedAdded As Boolean = True
- Dim createSql As String = kv.Value.ToLower()
- Dim referenceInfo As String = ""
- Dim referenceTaken As Boolean = False
- If splitKeyword IsNot Nothing AndAlso splitKeyword <> "" Then
- If createSql.Contains(String.Format(" {0} ", splitKeyword)) Then
- Dim sa As String() = createSql.Split(New String() {String.Format(" {0} ", splitKeyword)}, StringSplitOptions.RemoveEmptyEntries)
- referenceInfo = sa(sa.Length - 1)
- referenceTaken = True
- End If
- End If
- If Not referenceTaken Then referenceInfo = createSql
- For Each kv2 In dic1
- If kv.Key = kv2.Key Then Continue For
- If lst.Contains(kv2.Key) Then Continue For
- Dim _thisTBname As String = String.Format("{0}{1}{0}", keyNameWrapper, kv2.Key.ToLower())
- If referenceInfo.Contains(_thisTBname) Then
- allReferencedAdded = False
- Exit For
- End If
- Next
- If allReferencedAdded Then
- If Not lst.Contains(kv.Key) Then
- lst.Add(kv.Key)
- requireLoop = True
- Exit For
- End If
- End If
- Next
- End While
- For Each kv In dic1
- If Not lst.Contains(kv.Key) Then
- lst.Add(kv.Key)
- End If
- Next
- Return lst
- End Function
- Private Sub Export_Rows(ByVal tableName As String, ByVal selectSQL As String)
- Export_WriteComment("")
- Export_WriteComment(String.Format("Dumping data for table {0}", tableName))
- Export_WriteComment("")
- textWriter.WriteLine()
- Export_WriteLine(String.Format("/*!40000 ALTER TABLE `{0}` DISABLE KEYS */;", tableName))
- If ExportInfo.WrapWithinTransaction Then Export_WriteLine("START TRANSACTION;")
- Export_RowsData(tableName, selectSQL)
- If ExportInfo.WrapWithinTransaction Then Export_WriteLine("COMMIT;")
- Export_WriteLine(String.Format("/*!40000 ALTER TABLE `{0}` ENABLE KEYS */;", tableName))
- textWriter.WriteLine()
- textWriter.Flush()
- End Sub
- Private Sub Export_RowsData(ByVal tableName As String, ByVal selectSQL As String)
- _currentRowIndexInCurrentTable = 0L
- If ExportInfo.RowsExportMode = RowsDataExportMode.Insert OrElse ExportInfo.RowsExportMode = RowsDataExportMode.InsertIgnore OrElse ExportInfo.RowsExportMode = RowsDataExportMode.Replace Then
- Export_RowsData_Insert_Ignore_Replace(tableName, selectSQL)
- ElseIf ExportInfo.RowsExportMode = RowsDataExportMode.OnDuplicateKeyUpdate Then
- Export_RowsData_OnDuplicateKeyUpdate(tableName, selectSQL)
- ElseIf ExportInfo.RowsExportMode = RowsDataExportMode.Update Then
- Export_RowsData_Update(tableName, selectSQL)
- End If
- End Sub
- Private Sub Export_RowsData_Insert_Ignore_Replace(ByVal tableName As String, ByVal selectSQL As String)
- Dim table As MySqlTable = _database.Tables(tableName)
- Command.CommandText = selectSQL
- Dim rdr As MySqlDataReader = Command.ExecuteReader()
- Dim insertStatementHeader As String = Nothing
- Dim sb = New StringBuilder(CInt(ExportInfo.MaxSqlLength))
- While rdr.Read()
- If stopProcess Then Return
- _currentRowIndexInAllTable = _currentRowIndexInAllTable + 1
- _currentRowIndexInCurrentTable = _currentRowIndexInCurrentTable + 1
- If insertStatementHeader Is Nothing Then
- insertStatementHeader = Export_GetInsertStatementHeader(ExportInfo.RowsExportMode, tableName, rdr)
- End If
- Dim sqlDataRow As String = Export_GetValueString(rdr, table)
- If sb.Length = 0 Then
- sb.AppendLine(insertStatementHeader)
- sb.Append(sqlDataRow)
- ElseIf CLng(sb.Length) + CLng(sqlDataRow.Length) < ExportInfo.MaxSqlLength Then
- sb.AppendLine(",")
- sb.Append(sqlDataRow)
- Else
- sb.AppendFormat(";")
- Export_WriteLine(sb.ToString())
- textWriter.Flush()
- sb = New StringBuilder(CInt(ExportInfo.MaxSqlLength))
- sb.AppendLine(insertStatementHeader)
- sb.Append(sqlDataRow)
- End If
- End While
- rdr.Close()
- If sb.Length > 0 Then
- sb.Append(";")
- End If
- Export_WriteLine(sb.ToString())
- textWriter.Flush()
- sb = Nothing
- End Sub
- Private Sub Export_RowsData_OnDuplicateKeyUpdate(ByVal tableName As String, ByVal selectSQL As String)
- Dim table As MySqlTable = _database.Tables(tableName)
- Dim allPrimaryField As Boolean = True
- For Each col In table.Columns
- If Not col.IsPrimaryKey Then
- allPrimaryField = False
- Exit For
- End If
- Next
- Command.CommandText = selectSQL
- Dim rdr As MySqlDataReader = Command.ExecuteReader()
- While rdr.Read()
- If stopProcess Then Return
- _currentRowIndexInAllTable = _currentRowIndexInAllTable + 1
- _currentRowIndexInCurrentTable = _currentRowIndexInCurrentTable + 1
- Dim sb As StringBuilder = New StringBuilder()
- If allPrimaryField Then
- sb.Append(Export_GetInsertStatementHeader(RowsDataExportMode.InsertIgnore, tableName, rdr))
- sb.Append(Export_GetValueString(rdr, table))
- Else
- sb.Append(Export_GetInsertStatementHeader(RowsDataExportMode.Insert, tableName, rdr))
- sb.Append(Export_GetValueString(rdr, table))
- sb.Append(" ON DUPLICATE KEY UPDATE ")
- Export_GetUpdateString(rdr, table, sb)
- End If
- sb.Append(";")
- Export_WriteLine(sb.ToString())
- textWriter.Flush()
- End While
- rdr.Close()
- End Sub
- Private Sub Export_RowsData_Update(ByVal tableName As String, ByVal selectSQL As String)
- Dim table As MySqlTable = _database.Tables(tableName)
- Dim allPrimaryField As Boolean = True
- For Each col In table.Columns
- If Not col.IsPrimaryKey Then
- allPrimaryField = False
- Exit For
- End If
- Next
- If allPrimaryField Then Return
- Dim allNonPrimaryField As Boolean = True
- For Each col In table.Columns
- If col.IsPrimaryKey Then
- allNonPrimaryField = False
- Exit For
- End If
- Next
- If allNonPrimaryField Then Return
- Command.CommandText = selectSQL
- Dim rdr As MySqlDataReader = Command.ExecuteReader()
- While rdr.Read()
- If stopProcess Then Return
- _currentRowIndexInAllTable = _currentRowIndexInAllTable + 1
- _currentRowIndexInCurrentTable = _currentRowIndexInCurrentTable + 1
- Dim sb As StringBuilder = New StringBuilder()
- sb.Append("UPDATE `")
- sb.Append(tableName)
- sb.Append("` SET ")
- Export_GetUpdateString(rdr, table, sb)
- sb.Append(" WHERE ")
- Export_GetConditionString(rdr, table, sb)
- sb.Append(";")
- Export_WriteLine(sb.ToString())
- textWriter.Flush()
- End While
- rdr.Close()
- End Sub
- Private Function Export_GetInsertStatementHeader(ByVal rowsExportMode As RowsDataExportMode, ByVal tableName As String, ByVal rdr As MySqlDataReader) As String
- Dim sb As StringBuilder = New StringBuilder()
- If rowsExportMode = RowsDataExportMode.Insert Then
- sb.Append("INSERT INTO `")
- ElseIf rowsExportMode = RowsDataExportMode.InsertIgnore Then
- sb.Append("INSERT IGNORE INTO `")
- ElseIf rowsExportMode = RowsDataExportMode.Replace Then
- sb.Append("REPLACE INTO `")
- End If
- sb.Append(tableName)
- sb.Append("`(")
- For i As Integer = 0 To rdr.FieldCount - 1
- Dim _colname As String = rdr.GetName(i)
- If _database.Tables(tableName).Columns(_colname).IsGeneratedColumn Then Continue For
- If i > 0 Then sb.Append(",")
- sb.Append("`")
- sb.Append(rdr.GetName(i))
- sb.Append("`")
- Next
- sb.Append(") VALUES")
- Return sb.ToString()
- End Function
- Private Function Export_GetValueString(ByVal rdr As MySqlDataReader, ByVal table As MySqlTable) As String
- Dim sb As StringBuilder = New StringBuilder()
- For i As Integer = 0 To rdr.FieldCount - 1
- Dim columnName As String = rdr.GetName(i)
- If table.Columns(columnName).IsGeneratedColumn Then Continue For
- If sb.Length = 0 Then
- sb.AppendFormat("(")
- Else
- sb.AppendFormat(",")
- End If
- Dim ob As Object = rdr(i)
- Dim col = table.Columns(columnName)
- sb.Append(QueryExpress.ConvertToSqlFormat(ob, True, True, col, ExportInfo.BlobExportMode))
- Next
- sb.AppendFormat(")")
- Return sb.ToString()
- End Function
- Private Sub Export_GetUpdateString(ByVal rdr As MySqlDataReader, ByVal table As MySqlTable, ByVal sb As StringBuilder)
- Dim isFirst As Boolean = True
- For i As Integer = 0 To rdr.FieldCount - 1
- Dim colName As String = rdr.GetName(i)
- Dim col = table.Columns(colName)
- If Not col.IsPrimaryKey Then
- If isFirst Then
- isFirst = False
- Else
- sb.Append(",")
- End If
- sb.Append("`")
- sb.Append(colName)
- sb.Append("`=")
- sb.Append(QueryExpress.ConvertToSqlFormat(rdr(i), True, True, col, ExportInfo.BlobExportMode))
- End If
- Next
- End Sub
- Private Sub Export_GetConditionString(ByVal rdr As MySqlDataReader, ByVal table As MySqlTable, ByVal sb As StringBuilder)
- Dim isFirst As Boolean = True
- For i As Integer = 0 To rdr.FieldCount - 1
- Dim colName As String = rdr.GetName(i)
- Dim col = table.Columns(colName)
- If col.IsPrimaryKey Then
- If isFirst Then
- isFirst = False
- Else
- sb.Append(" and ")
- End If
- sb.Append("`")
- sb.Append(colName)
- sb.Append("`=")
- sb.Append(QueryExpress.ConvertToSqlFormat(rdr(i), True, True, col, ExportInfo.BlobExportMode))
- End If
- Next
- End Sub
- Private Sub Export_Procedures()
- If Not ExportInfo.ExportProcedures OrElse _database.Procedures.Count = 0 Then Return
- Export_WriteComment("")
- Export_WriteComment("Dumping procedures")
- Export_WriteComment("")
- textWriter.WriteLine()
- For Each procedure As MySqlProcedure In _database.Procedures
- If stopProcess Then Return
- If procedure.CreateProcedureSQLWithoutDefiner.Trim().Length = 0 OrElse procedure.CreateProcedureSQL.Trim().Length = 0 Then Continue For
- Export_WriteLine(String.Format("DROP PROCEDURE IF EXISTS `{0}`;", procedure.Name))
- Export_WriteLine("DELIMITER " & ExportInfo.ScriptsDelimiter)
- If ExportInfo.ExportRoutinesWithoutDefiner Then
- Export_WriteLine(procedure.CreateProcedureSQLWithoutDefiner & " " + ExportInfo.ScriptsDelimiter)
- Else
- Export_WriteLine(procedure.CreateProcedureSQL & " " + ExportInfo.ScriptsDelimiter)
- End If
- Export_WriteLine("DELIMITER ;")
- textWriter.WriteLine()
- Next
- textWriter.Flush()
- End Sub
- Private Sub Export_Functions()
- If Not ExportInfo.ExportFunctions OrElse _database.Functions.Count = 0 Then Return
- Export_WriteComment("")
- Export_WriteComment("Dumping functions")
- Export_WriteComment("")
- textWriter.WriteLine()
- For Each [function] As MySqlFunction In _database.Functions
- If stopProcess Then Return
- If [function].CreateFunctionSQL.Trim().Length = 0 OrElse [function].CreateFunctionSQLWithoutDefiner.Trim().Length = 0 Then Continue For
- Export_WriteLine(String.Format("DROP FUNCTION IF EXISTS `{0}`;", [function].Name))
- Export_WriteLine("DELIMITER " & ExportInfo.ScriptsDelimiter)
- If ExportInfo.ExportRoutinesWithoutDefiner Then
- Export_WriteLine([function].CreateFunctionSQLWithoutDefiner & " " + ExportInfo.ScriptsDelimiter)
- Else
- Export_WriteLine([function].CreateFunctionSQL & " " + ExportInfo.ScriptsDelimiter)
- End If
- Export_WriteLine("DELIMITER ;")
- textWriter.WriteLine()
- Next
- textWriter.Flush()
- End Sub
- Private Sub Export_Views()
- If Not ExportInfo.ExportViews OrElse _database.Views.Count = 0 Then Return
- Dim dicView_Create As Dictionary(Of String, String) = New Dictionary(Of String, String)()
- For Each view In _database.Views
- dicView_Create(view.Name) = view.CreateViewSQL
- Next
- Dim lst = Export_ReArrangeDependencies(dicView_Create, Nothing, "`")
- Export_WriteComment("")
- Export_WriteComment("Dumping views")
- Export_WriteComment("")
- textWriter.WriteLine()
- For Each viewname In lst
- If stopProcess Then Return
- Dim view = _database.Views(viewname)
- If view.CreateViewSQL.Trim().Length = 0 OrElse view.CreateViewSQLWithoutDefiner.Trim().Length = 0 Then Continue For
- Export_WriteLine(String.Format("DROP TABLE IF EXISTS `{0}`;", view.Name))
- Export_WriteLine(String.Format("DROP VIEW IF EXISTS `{0}`;", view.Name))
- If ExportInfo.ExportRoutinesWithoutDefiner Then
- Export_WriteLine(view.CreateViewSQLWithoutDefiner)
- Else
- Export_WriteLine(view.CreateViewSQL)
- End If
- textWriter.WriteLine()
- Next
- textWriter.WriteLine()
- textWriter.Flush()
- End Sub
- Private Sub Export_Events()
- If Not ExportInfo.ExportEvents OrElse _database.Events.Count = 0 Then Return
- Export_WriteComment("")
- Export_WriteComment("Dumping events")
- Export_WriteComment("")
- textWriter.WriteLine()
- For Each e As MySqlEvent In _database.Events
- If stopProcess Then Return
- If e.CreateEventSql.Trim().Length = 0 OrElse e.CreateEventSqlWithoutDefiner.Trim().Length = 0 Then Continue For
- Export_WriteLine(String.Format("DROP EVENT IF EXISTS `{0}`;", e.Name))
- Export_WriteLine("DELIMITER " & ExportInfo.ScriptsDelimiter)
- If ExportInfo.ExportRoutinesWithoutDefiner Then
- Export_WriteLine(e.CreateEventSqlWithoutDefiner & " " + ExportInfo.ScriptsDelimiter)
- Else
- Export_WriteLine(e.CreateEventSql & " " + ExportInfo.ScriptsDelimiter)
- End If
- Export_WriteLine("DELIMITER ;")
- textWriter.WriteLine()
- Next
- textWriter.Flush()
- End Sub
- Private Sub Export_Triggers()
- If Not ExportInfo.ExportTriggers OrElse _database.Triggers.Count = 0 Then Return
- Export_WriteComment("")
- Export_WriteComment("Dumping triggers")
- Export_WriteComment("")
- textWriter.WriteLine()
- For Each trigger As MySqlTrigger In _database.Triggers
- If stopProcess Then Return
- If trigger.CreateTriggerSQL.Trim().Length = 0 OrElse trigger.CreateTriggerSQLWithoutDefiner.Trim().Length = 0 Then Continue For
- Export_WriteLine(String.Format("DROP TRIGGER /*!50030 IF EXISTS */ `{0}`;", trigger.Name))
- Export_WriteLine("DELIMITER " & ExportInfo.ScriptsDelimiter)
- If ExportInfo.ExportRoutinesWithoutDefiner Then
- Export_WriteLine(trigger.CreateTriggerSQLWithoutDefiner & " " + ExportInfo.ScriptsDelimiter)
- Else
- Export_WriteLine(trigger.CreateTriggerSQL & " " + ExportInfo.ScriptsDelimiter)
- End If
- Export_WriteLine("DELIMITER ;")
- textWriter.WriteLine()
- Next
- textWriter.Flush()
- End Sub
- Private Sub Export_DocumentFooter()
- textWriter.WriteLine()
- Dim lstFooters As List(Of String) = ExportInfo.GetDocumentFooters()
- If lstFooters.Count > 0 Then
- For Each s As String In lstFooters
- Export_WriteLine(s)
- Next
- End If
- timeEnd = DateTime.Now
- If ExportInfo.RecordDumpTime Then
- Dim ts As TimeSpan = timeEnd - timeStart
- textWriter.WriteLine()
- textWriter.WriteLine()
- Export_WriteComment(String.Format("Dump completed on {0}", timeEnd.ToString("yyyy-MM-dd HH:mm:ss")))
- Export_WriteComment(String.Format("Total time: {0}:{1}:{2}:{3}:{4} (d:h:m:s:ms)", ts.Days, ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds))
- End If
- textWriter.Flush()
- End Sub
- Private Sub Export_WriteComment(ByVal text As String)
- Export_WriteLine(String.Format("-- {0}", text))
- End Sub
- Private Sub Export_WriteLine(ByVal text As String)
- textWriter.WriteLine(text)
- End Sub
- Public Sub ImportFromString(ByVal sqldumptext As String)
- Using ms As MemoryStream = New MemoryStream()
- Using thisWriter As StreamWriter = New StreamWriter(ms)
- thisWriter.Write(sqldumptext)
- thisWriter.Flush()
- ms.Position = 0L
- ImportFromMemoryStream(ms)
- End Using
- End Using
- End Sub
- Public Sub ImportFromFile(ByVal filePath As String)
- Dim fi As System.IO.FileInfo = New FileInfo(filePath)
- Using tr As TextReader = New StreamReader(filePath)
- ImportFromTextReaderStream(tr, fi)
- End Using
- End Sub
- Public Sub ImportFromTextReader(ByVal tr As TextReader)
- ImportFromTextReaderStream(tr, Nothing)
- End Sub
- Public Sub ImportFromMemoryStream(ByVal ms As MemoryStream)
- ms.Position = 0
- _totalBytes = ms.Length
- textReader = New StreamReader(ms)
- Import_Start()
- End Sub
- Private Sub ImportFromTextReaderStream(ByVal tr As TextReader, ByVal fileInfo As FileInfo)
- If fileInfo IsNot Nothing Then
- _totalBytes = fileInfo.Length
- Else
- _totalBytes = 0L
- End If
- textReader = tr
- Import_Start()
- End Sub
- Private Sub Import_Start()
- Import_InitializeVariables()
- Dim line As String = ""
- While line IsNot Nothing
- If stopProcess Then
- processCompletionType = ProcessEndType.Cancelled
- Exit While
- End If
- Try
- line = Import_GetLine()
- If line Is Nothing Then Exit While
- If line.Length = 0 Then Continue While
- Import_ProcessLine(line)
- Catch ex As Exception
- line = ""
- _lastError = ex
- _lastErrorSql = _sbImport.ToString()
- If Not String.IsNullOrEmpty(ImportInfo.ErrorLogFile) Then
- File.AppendAllText(ImportInfo.ErrorLogFile, ex.ToString() & Environment.NewLine & Environment.NewLine)
- End If
- _sbImport = New StringBuilder()
- If ImportInfo.IgnoreSqlError Then
- Else
- StopAllProcess()
- Throw
- End If
- End Try
- End While
- ReportEndProcess()
- End Sub
- Private Sub Import_InitializeVariables()
- If Command Is Nothing Then
- Throw New Exception("MySqlCommand is not initialized. Object not set to an instance of an object.")
- End If
- If Command.Connection Is Nothing Then
- Throw New Exception("MySqlCommand.Connection is not initialized. Object not set to an instance of an object.")
- End If
- If Command.Connection.State <> System.Data.ConnectionState.Open Then
- Throw New Exception("MySqlCommand.Connection is not opened.")
- End If
- stopProcess = False
- _lastError = Nothing
- timeStart = DateTime.Now
- _currentBytes = 0L
- _sbImport = New StringBuilder()
- _mySqlScript = New MySqlScript(Command.Connection)
- currentProcess = ProcessType.Import
- processCompletionType = ProcessEndType.Complete
- _delimiter = ";"
- _lastErrorSql = ""
- If ImportProgressChanged IsNot Nothing Then timerReport.Start()
- End Sub
- Private Function Import_GetLine() As String
- Dim line As String = textReader.ReadLine()
- If line Is Nothing Then Return Nothing
- If ImportProgressChanged IsNot Nothing Then
- _currentBytes = _currentBytes + CLng(line.Length)
- End If
- line = line.Trim()
- If Import_IsEmptyLine(line) Then
- Return String.Empty
- End If
- Return line
- End Function
- Private Sub Import_ProcessLine(ByVal line As String)
- Dim nextAction As NextImportAction = Import_AnalyseNextAction(line)
- Select Case nextAction
- Case NextImportAction.Ignore
- Case NextImportAction.AppendLine
- Import_AppendLine(line)
- Case NextImportAction.ChangeDelimiter
- Import_ChangeDelimiter(line)
- Case NextImportAction.AppendLineAndExecute
- Import_AppendLineAndExecute(line)
- Case Else
- End Select
- End Sub
- Private Function Import_AnalyseNextAction(ByVal line As String) As NextImportAction
- If line Is Nothing Then Return NextImportAction.Ignore
- If line = String.Empty Then Return NextImportAction.Ignore
- If line.StartsWith("DELIMITER ", StringComparison.OrdinalIgnoreCase) Then Return NextImportAction.ChangeDelimiter
- If line.EndsWith(_delimiter) Then Return NextImportAction.AppendLineAndExecute
- Return NextImportAction.AppendLine
- End Function
- Private Sub Import_AppendLine(ByVal line As String)
- _sbImport.AppendLine(line)
- End Sub
- Private Sub Import_ChangeDelimiter(ByVal line As String)
- Dim nextDelimiter As String = line.Substring(9)
- _delimiter = nextDelimiter.Replace(" ", String.Empty)
- End Sub
- Private Sub Import_AppendLineAndExecute(ByVal line As String)
- _sbImport.AppendLine(line)
- Dim _importQuery As String = _sbImport.ToString()
- _mySqlScript.Query = _importQuery
- _mySqlScript.Delimiter = _delimiter
- _mySqlScript.Execute()
- _sbImport = New StringBuilder()
- GC.Collect()
- End Sub
- Private Function Import_IsEmptyLine(ByVal line As String) As Boolean
- If line Is Nothing Then Return True
- If line = String.Empty Then Return True
- If line.Length = 0 Then Return True
- If line.StartsWith("--") Then Return True
- If line = Environment.NewLine Then Return True
- If line = vbCr Then Return True
- If line = vbLf Then Return True
- Return False
- End Function
- Private Sub ReportEndProcess()
- timeEnd = DateTime.Now
- StopAllProcess()
- If currentProcess = ProcessType.Export Then
- ReportProgress()
- If ExportCompleted IsNot Nothing Then
- Dim arg As ExportCompleteArgs = New ExportCompleteArgs(timeStart, timeEnd, processCompletionType, _lastError)
- ExportCompleted(Me, arg)
- End If
- ElseIf currentProcess = ProcessType.Import Then
- _currentBytes = _totalBytes
- ReportProgress()
- If ImportCompleted IsNot Nothing Then
- Dim arg As ImportCompleteArgs = New ImportCompleteArgs()
- ImportCompleted(Me, arg)
- End If
- End If
- End Sub
- Private Sub timerReport_Elapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)
- ReportProgress()
- End Sub
- Private Sub ReportProgress()
- If currentProcess = ProcessType.Export Then
- If ExportProgressChanged IsNot Nothing Then
- Dim arg As ExportProgressArgs = New ExportProgressArgs(_currentTableName, _totalRowsInCurrentTable, _totalRowsInAllTables, _currentRowIndexInCurrentTable, _currentRowIndexInAllTable, _totalTables, _currentTableIndex)
- ExportProgressChanged(Me, arg)
- End If
- ElseIf currentProcess = ProcessType.Import Then
- If ImportProgressChanged IsNot Nothing Then
- Dim arg As ImportProgressArgs = New ImportProgressArgs(_currentBytes, _totalBytes)
- ImportProgressChanged(Me, arg)
- End If
- End If
- End Sub
- Public Sub StopAllProcess()
- stopProcess = True
- timerReport.[Stop]()
- End Sub
- Public Sub Dispose()
- Try
- _database.Dispose()
- Catch
- End Try
- Try
- _server = Nothing
- Catch
- End Try
- Try
- _mySqlScript = Nothing
- Catch
- End Try
- End Sub
- Private Class CSharpImpl
- <Obsolete("Please refactor calling code to use normal Visual Basic assignment")>
- Shared Function __Assign(Of T)(ByRef target As T, value As T) As T
- target = value
- Return value
- End Function
- End Class
- Public Sub Dispose1() Implements IDisposable.Dispose
- End Sub
- End Class
- End Namespace
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement