#region License
// Copyright 2005-2019 Paul Kohler (https://github.com/paulkohler/minisqlquery). All rights reserved.
// This source code is made available under the terms of the GNU Lesser General Public License v3.0
// https://github.com/paulkohler/minisqlquery/blob/master/LICENSE
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace MiniSqlQuery.Core
{
///
/// The query batch class represents a series of SQL statements to execute against a database.
///
public class QueryBatch
{
///
/// Initializes a new instance of the class.
/// A singular batch query.
///
/// The SQL to create a single query from.
///
public QueryBatch(string sql)
: this()
{
// OriginalSql = sql;
Add(new Query(sql));
}
///
/// Initializes a new instance of the class.
///
public QueryBatch()
{
Queries = new List();
}
///
/// Gets or sets the end time of the batch.
///
/// The end time.
public DateTime EndTime { get; set; }
///
/// Gets or sets Messages.
///
/// The messages.
public string Messages { get; set; }
///
/// Gets the query list for this batch.
///
/// The queries.
public List Queries { get; private set; }
///
/// Gets or sets the start time of the batch.
///
/// The start time.
public DateTime StartTime { get; set; }
///
/// Parses an string creating a as a result.
/// If query batching is enabled, the string is split into multiple objects.
///
/// The SQL string.
/// A object with 0, 1 or many objects.
public static QueryBatch Parse(string sql)
{
var batch = new QueryBatch();
// exit if nothing to do
if (sql == null || sql.Trim().Length == 0)
{
return batch;
}
foreach (string sqlPart in SplitByBatchIndecator(sql, "GO").Where(sqlPart => !string.IsNullOrEmpty(sqlPart)))
{
batch.Add(new Query(sqlPart));
}
return batch;
}
///
/// Adds a query to this batch.
///
/// The query.
public void Add(Query query)
{
Queries.Add(query);
}
///
/// Clears all queries in this batch.
///
public void Clear()
{
Queries.Clear();
}
///
/// Splits a by the , typically "GO".
/// The batch indicator needs to be on a line by itself.
///
/// The SQL script.
/// The batch indicator, e.g. "GO".
/// An enumerable list of stings.
private static IEnumerable SplitByBatchIndecator(string script, string batchIndicator)
{
string pattern = string.Concat("^\\s*", batchIndicator, "\\s*$");
RegexOptions options = RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Multiline;
foreach (string batch in Regex.Split(script, pattern, options))
{
yield return batch.Trim();
}
}
}
}