|
From: <fab...@us...> - 2009-04-18 00:30:04
|
Revision: 4186
http://nhibernate.svn.sourceforge.net/nhibernate/?rev=4186&view=rev
Author: fabiomaulo
Date: 2009-04-18 00:30:01 +0000 (Sat, 18 Apr 2009)
Log Message:
-----------
- Fix NH-1745
- by default we are using format_sql=true in ours tests
Modified Paths:
--------------
trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs
trunk/nhibernate/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs
trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs
trunk/nhibernate/src/NHibernate/Cfg/Settings.cs
trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs
trunk/nhibernate/src/NHibernate/Id/IPersistentIdentifierGenerator.cs
trunk/nhibernate/src/NHibernate/Id/TableGenerator.cs
trunk/nhibernate/src/NHibernate/NHibernate.csproj
trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs
trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs
trunk/nhibernate/src/NHibernate.Test/App.config
trunk/nhibernate/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs
Added Paths:
-----------
trunk/nhibernate/src/NHibernate/AdoNet/Util/
trunk/nhibernate/src/NHibernate/AdoNet/Util/BasicFormatter.cs
trunk/nhibernate/src/NHibernate/AdoNet/Util/DdlFormatter.cs
trunk/nhibernate/src/NHibernate/AdoNet/Util/FormatStyle.cs
trunk/nhibernate/src/NHibernate/AdoNet/Util/IFormatter.cs
trunk/nhibernate/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs
Removed Paths:
-------------
trunk/nhibernate/src/NHibernate/Pretty/
Modified: trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/AdoNet/AbstractBatcher.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1,6 +1,5 @@
using System;
using System.Data;
-using System.Text;
using Iesi.Collections.Generic;
using log4net;
using NHibernate.Driver;
@@ -9,6 +8,7 @@
using NHibernate.SqlCommand;
using NHibernate.SqlTypes;
using NHibernate.Util;
+using NHibernate.AdoNet.Util;
namespace NHibernate.AdoNet
{
@@ -18,7 +18,6 @@
public abstract class AbstractBatcher : IBatcher
{
protected static readonly ILog log = LogManager.GetLogger(typeof(AbstractBatcher));
- protected static readonly ILog logSql = LogManager.GetLogger("NHibernate.SQL");
private static int openCommandCount;
private static int openReaderCount;
@@ -421,50 +420,9 @@
protected void LogCommand(IDbCommand command)
{
- if (logSql.IsDebugEnabled || factory.Settings.IsShowSqlEnabled)
- {
- string outputText = GetCommandLogString(command);
- logSql.Debug(outputText);
-
- if (factory.Settings.IsShowSqlEnabled)
- {
- Console.Out.Write("NHibernate: ");
- Console.Out.WriteLine(outputText);
- }
- }
+ factory.Settings.SqlStatementLogger.LogCommand(command, FormatStyle.Basic);
}
- protected string GetCommandLogString(IDbCommand command)
- {
- string outputText;
-
- if (command.Parameters.Count == 0)
- {
- outputText = command.CommandText;
- }
- else
- {
- StringBuilder output = new StringBuilder();
- output.Append(command.CommandText);
- output.Append("; ");
-
- IDataParameter p;
- int count = command.Parameters.Count;
- for (int i = 0; i < count; i++)
- {
- p = (IDataParameter) command.Parameters[i];
- output.Append(string.Format("{0} = '{1}'", p.ParameterName, p.Value));
-
- if (i + 1 < count)
- {
- output.Append(", ");
- }
- }
- outputText = output.ToString();
- }
- return outputText;
- }
-
private void LogOpenPreparedCommand()
{
if (log.IsDebugEnabled)
Modified: trunk/nhibernate/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/AdoNet/SqlClientBatchingBatcher.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1,5 +1,6 @@
using System.Data;
using System.Text;
+using NHibernate.AdoNet.Util;
namespace NHibernate.AdoNet
{
@@ -31,9 +32,11 @@
totalExpectedRowsAffected += expectation.ExpectedRowCount;
log.Debug("Adding to batch:");
IDbCommand batchUpdate = CurrentCommand;
- string commandLoggedText = GetCommandLogString(batchUpdate);
- currentBatchCommandsLog.Append("Batch command: ").
- AppendLine(commandLoggedText);
+ if (log.IsDebugEnabled)
+ {
+ string commandLoggedText = Factory.Settings.SqlStatementLogger.LogCommand(batchUpdate, FormatStyle.Basic);
+ currentBatchCommandsLog.Append("Batch command: ").AppendLine(commandLoggedText);
+ }
currentBatch.Append((System.Data.SqlClient.SqlCommand) batchUpdate);
if (currentBatch.CountOfCommands >= batchSize)
{
@@ -47,7 +50,7 @@
CheckReaders();
Prepare(currentBatch.BatchCommand);
- logSql.Debug(currentBatchCommandsLog.ToString());
+ Factory.Settings.SqlStatementLogger.LogInfo(currentBatchCommandsLog.ToString());
currentBatchCommandsLog = new StringBuilder();
int rowsAffected = currentBatch.ExecuteNonQuery();
Added: trunk/nhibernate/src/NHibernate/AdoNet/Util/BasicFormatter.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/Util/BasicFormatter.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/AdoNet/Util/BasicFormatter.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -0,0 +1,435 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using Iesi.Collections.Generic;
+using NHibernate.Util;
+
+namespace NHibernate.AdoNet.Util
+{
+ public class BasicFormatter : IFormatter
+ {
+ protected const string IndentString = " ";
+ protected const string Initial = "\n ";
+ protected static readonly HashedSet<string> beginClauses = new HashedSet<string>();
+ protected static readonly HashedSet<string> dml = new HashedSet<string>();
+ protected static readonly HashedSet<string> endClauses = new HashedSet<string>();
+ protected static readonly HashedSet<string> logical = new HashedSet<string>();
+ protected static readonly HashedSet<string> misc = new HashedSet<string>();
+ protected static readonly HashedSet<string> quantifiers = new HashedSet<string>();
+
+ static BasicFormatter()
+ {
+ beginClauses.Add("left");
+ beginClauses.Add("right");
+ beginClauses.Add("inner");
+ beginClauses.Add("outer");
+ beginClauses.Add("group");
+ beginClauses.Add("order");
+
+ endClauses.Add("where");
+ endClauses.Add("set");
+ endClauses.Add("having");
+ endClauses.Add("join");
+ endClauses.Add("from");
+ endClauses.Add("by");
+ endClauses.Add("join");
+ endClauses.Add("into");
+ endClauses.Add("union");
+
+ logical.Add("and");
+ logical.Add("or");
+ logical.Add("when");
+ logical.Add("else");
+ logical.Add("end");
+
+ quantifiers.Add("in");
+ quantifiers.Add("all");
+ quantifiers.Add("exists");
+ quantifiers.Add("some");
+ quantifiers.Add("any");
+
+ dml.Add("insert");
+ dml.Add("update");
+ dml.Add("delete");
+
+ misc.Add("select");
+ misc.Add("on");
+ }
+
+ #region IFormatter Members
+
+ public virtual string Format(string source)
+ {
+ return new FormatProcess(source).Perform();
+ }
+
+ #endregion
+
+ #region Nested type: FormatProcess
+
+ private class FormatProcess
+ {
+ private readonly List<bool> afterByOrFromOrSelects = new List<bool>();
+ private readonly List<int> parenCounts = new List<int>();
+ private readonly StringBuilder result = new StringBuilder();
+ private readonly IEnumerator<string> tokens;
+ private bool afterBeginBeforeEnd;
+ private bool afterBetween;
+ private bool afterByOrSetOrFromOrSelect;
+ private bool afterInsert;
+ private bool afterOn;
+ private bool beginLine = true;
+
+ private int indent = 1;
+ private int inFunction;
+
+ private string lastToken;
+ private string lcToken;
+ private int parensSinceSelect;
+ private string token;
+
+ public FormatProcess(string sql)
+ {
+ // TODO : some delimiter may depend from a specific Dialect/Drive (as ';' to separate multi query)
+ tokens = new StringTokenizer(sql, "()+*/-=<>'`\"[],;" + StringHelper.WhiteSpace, true).GetEnumerator();
+ }
+
+ public string Perform()
+ {
+ result.Append(Initial);
+
+ while (tokens.MoveNext())
+ {
+ token = tokens.Current;
+ lcToken = token.ToLowerInvariant();
+
+ if ("'".Equals(token))
+ {
+ ExtractStringEnclosedBy("'");
+ }
+ else if ("\"".Equals(token))
+ {
+ ExtractStringEnclosedBy("\"");
+ }
+
+ if(IsMultiQueryDelimiter(token))
+ {
+ StartingNewQuery();
+ }
+ else if (afterByOrSetOrFromOrSelect && ",".Equals(token))
+ {
+ CommaAfterByOrFromOrSelect();
+ }
+ else if (afterOn && ",".Equals(token))
+ {
+ CommaAfterOn();
+ }
+ else if ("(".Equals(token))
+ {
+ OpenParen();
+ }
+ else if (")".Equals(token))
+ {
+ CloseParen();
+ }
+ else if (beginClauses.Contains(lcToken))
+ {
+ BeginNewClause();
+ }
+ else if (endClauses.Contains(lcToken))
+ {
+ EndNewClause();
+ }
+ else if ("select".Equals(lcToken))
+ {
+ Select();
+ }
+ else if (dml.Contains(lcToken))
+ {
+ UpdateOrInsertOrDelete();
+ }
+ else if ("values".Equals(lcToken))
+ {
+ Values();
+ }
+ else if ("on".Equals(lcToken))
+ {
+ On();
+ }
+ else if (afterBetween && lcToken.Equals("and"))
+ {
+ Misc();
+ afterBetween = false;
+ }
+ else if (logical.Contains(lcToken))
+ {
+ Logical();
+ }
+ else if (IsWhitespace(token))
+ {
+ White();
+ }
+ else
+ {
+ Misc();
+ }
+
+ if (!IsWhitespace(token))
+ {
+ lastToken = lcToken;
+ }
+ }
+ return result.ToString();
+ }
+
+ private void StartingNewQuery()
+ {
+ Out();
+ indent = 1;
+ Newline();
+ }
+
+ private bool IsMultiQueryDelimiter(string delimiter)
+ {
+ return ";".Equals(delimiter);
+ }
+
+ private void ExtractStringEnclosedBy(string stringDelimiter)
+ {
+ while (tokens.MoveNext())
+ {
+ string t = tokens.Current;
+ token += t;
+ if (stringDelimiter.Equals(t))
+ {
+ break;
+ }
+ }
+ }
+
+ private void CommaAfterOn()
+ {
+ Out();
+ indent--;
+ Newline();
+ afterOn = false;
+ afterByOrSetOrFromOrSelect = true;
+ }
+
+ private void CommaAfterByOrFromOrSelect()
+ {
+ Out();
+ Newline();
+ }
+
+ private void Logical()
+ {
+ if ("end".Equals(lcToken))
+ {
+ indent--;
+ }
+ Newline();
+ Out();
+ beginLine = false;
+ }
+
+ private void On()
+ {
+ indent++;
+ afterOn = true;
+ Newline();
+ Out();
+ beginLine = false;
+ }
+
+ private void Misc()
+ {
+ Out();
+ if ("between".Equals(lcToken))
+ {
+ afterBetween = true;
+ }
+ if (afterInsert)
+ {
+ Newline();
+ afterInsert = false;
+ }
+ else
+ {
+ beginLine = false;
+ if ("case".Equals(lcToken))
+ {
+ indent++;
+ }
+ }
+ }
+
+ private void White()
+ {
+ if (!beginLine)
+ {
+ result.Append(" ");
+ }
+ }
+
+ private void UpdateOrInsertOrDelete()
+ {
+ Out();
+ indent++;
+ beginLine = false;
+ if ("update".Equals(lcToken))
+ {
+ Newline();
+ }
+ if ("insert".Equals(lcToken))
+ {
+ afterInsert = true;
+ }
+ }
+
+ private void Select()
+ {
+ Out();
+ indent++;
+ Newline();
+ parenCounts.Insert(parenCounts.Count, parensSinceSelect);
+ afterByOrFromOrSelects.Insert(afterByOrFromOrSelects.Count, afterByOrSetOrFromOrSelect);
+ parensSinceSelect = 0;
+ afterByOrSetOrFromOrSelect = true;
+ }
+
+ private void Out()
+ {
+ result.Append(token);
+ }
+
+ private void EndNewClause()
+ {
+ if (!afterBeginBeforeEnd)
+ {
+ indent--;
+ if (afterOn)
+ {
+ indent--;
+ afterOn = false;
+ }
+ Newline();
+ }
+ Out();
+ if (!"union".Equals(lcToken))
+ {
+ indent++;
+ }
+ Newline();
+ afterBeginBeforeEnd = false;
+ afterByOrSetOrFromOrSelect = "by".Equals(lcToken) || "set".Equals(lcToken) || "from".Equals(lcToken);
+ }
+
+ private void BeginNewClause()
+ {
+ if (!afterBeginBeforeEnd)
+ {
+ if (afterOn)
+ {
+ indent--;
+ afterOn = false;
+ }
+ indent--;
+ Newline();
+ }
+ Out();
+ beginLine = false;
+ afterBeginBeforeEnd = true;
+ }
+
+ private void Values()
+ {
+ indent--;
+ Newline();
+ Out();
+ indent++;
+ Newline();
+ }
+
+ private void CloseParen()
+ {
+ parensSinceSelect--;
+ if (parensSinceSelect < 0)
+ {
+ indent--;
+ int tempObject = parenCounts[parenCounts.Count - 1];
+ parenCounts.RemoveAt(parenCounts.Count - 1);
+ parensSinceSelect = tempObject;
+
+ bool tempObject2 = afterByOrFromOrSelects[afterByOrFromOrSelects.Count - 1];
+ afterByOrFromOrSelects.RemoveAt(afterByOrFromOrSelects.Count - 1);
+ afterByOrSetOrFromOrSelect = tempObject2;
+ }
+ if (inFunction > 0)
+ {
+ inFunction--;
+ Out();
+ }
+ else
+ {
+ if (!afterByOrSetOrFromOrSelect)
+ {
+ indent--;
+ Newline();
+ }
+ Out();
+ }
+ beginLine = false;
+ }
+
+ private void OpenParen()
+ {
+ if (IsFunctionName(lastToken) || inFunction > 0)
+ {
+ inFunction++;
+ }
+ beginLine = false;
+ if (inFunction > 0)
+ {
+ Out();
+ }
+ else
+ {
+ Out();
+ if (!afterByOrSetOrFromOrSelect)
+ {
+ indent++;
+ Newline();
+ beginLine = true;
+ }
+ }
+ parensSinceSelect++;
+ }
+
+ private static bool IsFunctionName(string tok)
+ {
+ char begin = tok[0];
+ bool isIdentifier = (char.IsLetter(begin) || begin.CompareTo('$') == 0 || begin.CompareTo('_') == 0) || '"' == begin;
+ return isIdentifier && !logical.Contains(tok) && !endClauses.Contains(tok) && !quantifiers.Contains(tok)
+ && !dml.Contains(tok) && !misc.Contains(tok);
+ }
+
+ private static bool IsWhitespace(string token)
+ {
+ return StringHelper.WhiteSpace.IndexOf(token) >= 0;
+ }
+
+ private void Newline()
+ {
+ result.Append("\n");
+ for (int i = 0; i < indent; i++)
+ {
+ result.Append(IndentString);
+ }
+ beginLine = true;
+ }
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
Copied: trunk/nhibernate/src/NHibernate/AdoNet/Util/DdlFormatter.cs (from rev 4185, trunk/nhibernate/src/NHibernate/Pretty/DdlFormatter.cs)
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/Util/DdlFormatter.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/AdoNet/Util/DdlFormatter.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -0,0 +1,150 @@
+using System.Collections.Generic;
+using System.Text;
+using NHibernate.Util;
+
+namespace NHibernate.AdoNet.Util
+{
+ public class DdlFormatter: IFormatter
+ {
+ private const string Indent1 = "\n ";
+ private const string Indent2 = "\n ";
+ private const string Indent3 = "\n ";
+
+ /// <summary> Format an SQL statement using simple rules:
+ /// a) Insert newline after each comma;
+ /// b) Indent three spaces after each inserted newline;
+ /// If the statement contains single/double quotes return unchanged,
+ /// it is too complex and could be broken by simple formatting.
+ /// </summary>
+ public virtual string Format(string sql)
+ {
+ if (sql.ToLowerInvariant().StartsWith("create table"))
+ {
+ return FormatCreateTable(sql);
+ }
+ else if (sql.ToLowerInvariant().StartsWith("alter table"))
+ {
+ return FormatAlterTable(sql);
+ }
+ else if (sql.ToLowerInvariant().StartsWith("comment on"))
+ {
+ return FormatCommentOn(sql);
+ }
+ else
+ {
+ return Indent1 + sql;
+ }
+ }
+
+ protected virtual string FormatCommentOn(string sql)
+ {
+ StringBuilder result = new StringBuilder(60).Append(Indent1);
+ IEnumerator<string> tokens = (new StringTokenizer(sql, " '[]\"", true)).GetEnumerator();
+
+ bool quoted = false;
+ while (tokens.MoveNext())
+ {
+ string token = tokens.Current;
+ result.Append(token);
+ if (IsQuote(token))
+ {
+ quoted = !quoted;
+ }
+ else if (!quoted)
+ {
+ if ("is".Equals(token))
+ {
+ result.Append(Indent2);
+ }
+ }
+ }
+
+ return result.ToString();
+ }
+
+ protected virtual string FormatAlterTable(string sql)
+ {
+ StringBuilder result = new StringBuilder(60).Append(Indent1);
+ IEnumerator<string> tokens = (new StringTokenizer(sql, " (,)'[]\"", true)).GetEnumerator();
+
+ bool quoted = false;
+ while (tokens.MoveNext())
+ {
+ string token = tokens.Current;
+ if (IsQuote(token))
+ {
+ quoted = !quoted;
+ }
+ else if (!quoted)
+ {
+ if (IsBreak(token))
+ {
+ result.Append(Indent3);
+ }
+ }
+ result.Append(token);
+ }
+
+ return result.ToString();
+ }
+
+ protected virtual string FormatCreateTable(string sql)
+ {
+ StringBuilder result = new StringBuilder(60).Append(Indent1);
+ IEnumerator<string> tokens = (new StringTokenizer(sql, "(,)'[]\"", true)).GetEnumerator();
+
+ int depth = 0;
+ bool quoted = false;
+ while (tokens.MoveNext())
+ {
+ string token = tokens.Current;
+ if (IsQuote(token))
+ {
+ quoted = !quoted;
+ result.Append(token);
+ }
+ else if (quoted)
+ {
+ result.Append(token);
+ }
+ else
+ {
+ if (")".Equals(token))
+ {
+ depth--;
+ if (depth == 0)
+ {
+ result.Append(Indent1);
+ }
+ }
+ result.Append(token);
+ if (",".Equals(token) && depth == 1)
+ {
+ result.Append(Indent2);
+ }
+ if ("(".Equals(token))
+ {
+ depth++;
+ if (depth == 1)
+ {
+ result.Append(Indent3);
+ }
+ }
+ }
+ }
+
+ return result.ToString();
+ }
+
+ private static bool IsBreak(string token)
+ {
+ return "drop".Equals(token) || "add".Equals(token) || "references".Equals(token) || "foreign".Equals(token)
+ || "on".Equals(token);
+ }
+
+ private static bool IsQuote(string token)
+ {
+ return "\"".Equals(token) || "`".Equals(token) || "]".Equals(token) || "[".Equals(token) || "'".Equals(token);
+ }
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate/AdoNet/Util/FormatStyle.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/Util/FormatStyle.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/AdoNet/Util/FormatStyle.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -0,0 +1,59 @@
+namespace NHibernate.AdoNet.Util
+{
+ /// <summary> Represents the the understood types or styles of formatting. </summary>
+ public class FormatStyle
+ {
+ public static readonly FormatStyle Basic = new FormatStyle("basic", new BasicFormatter());
+ public static readonly FormatStyle Ddl = new FormatStyle("ddl", new DdlFormatter());
+ public static readonly FormatStyle None = new FormatStyle("none", new NoFormatImpl());
+
+ private FormatStyle(string name, IFormatter formatter)
+ {
+ Name = name;
+ Formatter = formatter;
+ }
+
+ public string Name { get; private set; }
+
+ public IFormatter Formatter { get; private set; }
+
+ public override bool Equals(object obj)
+ {
+ return Equals(obj as FormatStyle);
+ }
+
+ public bool Equals(FormatStyle other)
+ {
+ if (other == null)
+ {
+ return false;
+ }
+ if (ReferenceEquals(this, other))
+ {
+ return true;
+ }
+ return Equals(other.Name, Name);
+ }
+
+ public override int GetHashCode()
+ {
+ return (Name != null ? Name.GetHashCode() : 0);
+ }
+
+ #region Nested type: NoFormatImpl
+
+ private class NoFormatImpl : IFormatter
+ {
+ #region IFormatter Members
+
+ public string Format(string source)
+ {
+ return source;
+ }
+
+ #endregion
+ }
+
+ #endregion
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate/AdoNet/Util/IFormatter.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/Util/IFormatter.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/AdoNet/Util/IFormatter.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -0,0 +1,7 @@
+namespace NHibernate.AdoNet.Util
+{
+ public interface IFormatter
+ {
+ string Format(string source);
+ }
+}
\ No newline at end of file
Added: trunk/nhibernate/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs (rev 0)
+++ trunk/nhibernate/src/NHibernate/AdoNet/Util/SqlStatementLogger.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -0,0 +1,108 @@
+using System;
+using System.Data;
+using System.Text;
+using log4net;
+
+namespace NHibernate.AdoNet.Util
+{
+ /// <summary> Centralize logging handling for SQL statements. </summary>
+ public class SqlStatementLogger
+ {
+ private static readonly ILog log = LogManager.GetLogger("NHibernate.SQL");
+
+ /// <summary> Constructs a new SqlStatementLogger instance.</summary>
+ public SqlStatementLogger() : this(false, false) {}
+
+ /// <summary> Constructs a new SqlStatementLogger instance. </summary>
+ /// <param name="logToStdout">Should we log to STDOUT in addition to our internal logger. </param>
+ /// <param name="formatSql">Should we format SQL ('prettify') prior to logging. </param>
+ public SqlStatementLogger(bool logToStdout, bool formatSql)
+ {
+ LogToStdout = logToStdout;
+ FormatSql = formatSql;
+ }
+
+ public bool LogToStdout { get; set; }
+
+ public bool FormatSql { get; set; }
+
+ /// <summary> Log a SQL statement string. </summary>
+ /// <param name="statement">The SQL statement. </param>
+ /// <param name="style">The requested formatting style. </param>
+ public virtual void LogStatement(string statement, FormatStyle style)
+ {
+ if (!log.IsDebugEnabled && !LogToStdout)
+ {
+ return;
+ }
+ style = DetermineActualStyle(style);
+ statement = style.Formatter.Format(statement);
+ log.Debug(statement);
+ if (LogToStdout)
+ {
+ Console.Out.WriteLine("NHibernate: " + statement);
+ }
+ }
+
+ public virtual void LogInfo(string info)
+ {
+ log.Debug(info);
+ }
+
+ /// <summary> Log a IDbCommand. </summary>
+ /// <param name="command">The SQL statement. </param>
+ /// <param name="style">The requested formatting style. </param>
+ public virtual string LogCommand(IDbCommand command, FormatStyle style)
+ {
+ if (log.IsDebugEnabled || LogToStdout)
+ {
+ style = DetermineActualStyle(style);
+ string statement = style.Formatter.Format(GetCommandLineWithParameters(command));
+ log.Debug(statement);
+ if (LogToStdout)
+ {
+ Console.Out.WriteLine("NHibernate: " + statement);
+ }
+ return statement;
+ }
+ return null;
+ }
+
+ protected string GetCommandLineWithParameters(IDbCommand command)
+ {
+ string outputText;
+
+ if (command.Parameters.Count == 0)
+ {
+ outputText = command.CommandText;
+ }
+ else
+ {
+ var output = new StringBuilder(command.CommandText.Length + (command.Parameters.Count * 20));
+ output.Append(command.CommandText);
+ output.Append("; ");
+
+ IDataParameter p;
+ int count = command.Parameters.Count;
+ bool appendComma = false;
+ for (int i = 0; i < count; i++)
+ {
+ if (appendComma)
+ {
+ output.Append(", ");
+ }
+ appendComma = true;
+ p = (IDataParameter)command.Parameters[i];
+ output.Append(string.Format("{0} = '{1}'", p.ParameterName, p.Value));
+ }
+ outputText = output.ToString();
+ }
+ return outputText;
+ }
+
+ private FormatStyle DetermineActualStyle(FormatStyle style)
+ {
+ return FormatSql ? style : FormatStyle.None;
+ }
+ }
+}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Cfg/Configuration.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1530,7 +1530,11 @@
//protected Settings BuildSettings()
private Settings BuildSettings()
{
- return settingsFactory.BuildSettings(properties);
+ var result = settingsFactory.BuildSettings(properties);
+ // NH : Set configuration for IdGenerator SQL logging
+ PersistentIdGeneratorParmsNames.SqlStatementLogger.FormatSql = result.SqlStatementLogger.FormatSql;
+ PersistentIdGeneratorParmsNames.SqlStatementLogger.LogToStdout = result.SqlStatementLogger.LogToStdout;
+ return result;
}
/// <summary>
Modified: trunk/nhibernate/src/NHibernate/Cfg/Settings.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/Settings.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Cfg/Settings.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Data;
using NHibernate.AdoNet;
+using NHibernate.AdoNet.Util;
using NHibernate.Cache;
using NHibernate.Connection;
using NHibernate.Exceptions;
@@ -14,7 +15,11 @@
/// </summary>
public sealed class Settings
{
- private int maximumFetchDepth = -1;
+ public Settings()
+ {
+ MaximumFetchDepth = -1;
+ }
+
// not ported - private TransactionManagerLookup transactionManagerLookup;
// not ported - private bool strictJPAQLCompliance;
@@ -24,17 +29,10 @@
//private bool isJdbcBatchVersionedData;
#endregion
+ public SqlStatementLogger SqlStatementLogger { get; internal set; }
- public bool IsShowSqlEnabled { get; internal set; }
+ public int MaximumFetchDepth { get; internal set; }
- public bool IsFormatSqlEnabled { get; internal set; }
-
- public int MaximumFetchDepth
- {
- get { return maximumFetchDepth; }
- internal set { maximumFetchDepth = value; }
- }
-
public IDictionary<string, string> QuerySubstitutions { get; internal set; }
public Dialect.Dialect Dialect { get; internal set; }
Modified: trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Cfg/SettingsFactory.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -4,6 +4,7 @@
using System.Data;
using log4net;
using NHibernate.AdoNet;
+using NHibernate.AdoNet.Util;
using NHibernate.Cache;
using NHibernate.Connection;
using NHibernate.Dialect;
@@ -118,6 +119,7 @@
{
log.Info("echoing all SQL to stdout");
}
+ bool formatSql = PropertiesHelper.GetBoolean(Environment.FormatSql, properties);
bool useStatistics = PropertiesHelper.GetBoolean(Environment.GenerateStatistics, properties);
log.Info("Statistics: " + EnabledDisabled(useStatistics));
@@ -232,7 +234,8 @@
// Not ported - settings.StatementFetchSize = statementFetchSize;
// Not ported - ScrollableResultSetsEnabled
// Not ported - GetGeneratedKeysEnabled
- settings.IsShowSqlEnabled = showSql;
+ settings.SqlStatementLogger = new SqlStatementLogger(showSql, formatSql);
+
settings.ConnectionProvider = connectionProvider;
settings.QuerySubstitutions = querySubstitutions;
settings.TransactionFactory = transactionFactory;
Modified: trunk/nhibernate/src/NHibernate/Id/IPersistentIdentifierGenerator.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Id/IPersistentIdentifierGenerator.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Id/IPersistentIdentifierGenerator.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1,9 +1,15 @@
using System;
+using NHibernate.AdoNet.Util;
namespace NHibernate.Id
{
public struct PersistentIdGeneratorParmsNames
{
+ static PersistentIdGeneratorParmsNames()
+ {
+ SqlStatementLogger = new SqlStatementLogger(false, false);
+ }
+
/// <summary> The configuration parameter holding the schema name</summary>
public readonly static string Schema = "schema";
@@ -27,6 +33,8 @@
/// <summary> The configuration parameter holding the catalog name</summary>
public readonly static string Catalog = "catalog";
+
+ public readonly static SqlStatementLogger SqlStatementLogger;
}
/// <summary>
Modified: trunk/nhibernate/src/NHibernate/Id/TableGenerator.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Id/TableGenerator.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Id/TableGenerator.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -14,6 +14,7 @@
namespace NHibernate.Id
{
using System.Transactions;
+ using NHibernate.AdoNet.Util;
/// <summary>
/// An <see cref="IIdentifierGenerator" /> that uses a database table to store the last
@@ -196,9 +197,10 @@
qps.CommandText = query;
qps.CommandType = CommandType.Text;
qps.Transaction = trans;
+ log.Debug(string.Format("Reading high value:"));
+ PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand(qps, FormatStyle.Basic);
try
{
- log.Debug(string.Format("Reading high value:{0}", qps.CommandText));
rs = qps.ExecuteReader();
if (!rs.Read())
{
@@ -224,16 +226,17 @@
session.Factory.ConnectionProvider.Driver.GenerateCommand(CommandType.Text, updateSql, parameterTypes);
ups.Connection = conn;
ups.Transaction = trans;
+ log.Debug(string.Format("Updating high value:"));
+ PersistentIdGeneratorParmsNames.SqlStatementLogger.LogCommand(ups, FormatStyle.Basic);
try
{
columnType.Set(ups, result + 1, 0);
columnType.Set(ups, result, 1);
- log.Debug(string.Format("Updating high value:{0}", ups.CommandText));
rows = ups.ExecuteNonQuery();
}
- // TODO: change to SqlException
+ // TODO: change to SqlException
catch (Exception e)
{
log.Error("could not update hi value in: " + tableName, e);
Modified: trunk/nhibernate/src/NHibernate/NHibernate.csproj
===================================================================
--- trunk/nhibernate/src/NHibernate/NHibernate.csproj 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/NHibernate.csproj 2009-04-18 00:30:01 UTC (rev 4186)
@@ -443,6 +443,10 @@
<Compile Include="AdoNet\ResultSetWrapper.cs" />
<Compile Include="AdoNet\SqlClientBatchingBatcherFactory.cs" />
<Compile Include="AdoNet\TooManyRowsAffectedException.cs" />
+ <Compile Include="AdoNet\Util\BasicFormatter.cs" />
+ <Compile Include="AdoNet\Util\FormatStyle.cs" />
+ <Compile Include="AdoNet\Util\IFormatter.cs" />
+ <Compile Include="AdoNet\Util\SqlStatementLogger.cs" />
<Compile Include="Bytecode\HibernateByteCodeException.cs" />
<Compile Include="Bytecode\ProxyFactoryFactoryNotConfiguredException.cs" />
<Compile Include="Bytecode\UnableToLoadProxyFactoryFactoryException.cs" />
@@ -479,7 +483,7 @@
<Compile Include="Impl\FutureQueryBatch.cs" />
<Compile Include="Impl\FutureCriteriaBatch.cs" />
<Compile Include="Impl\FutureValue.cs" />
- <Compile Include="Pretty\DdlFormatter.cs" />
+ <Compile Include="AdoNet\Util\DdlFormatter.cs" />
<Compile Include="Properties\BackFieldStrategy.cs" />
<Compile Include="Bytecode\CodeDom\BytecodeProviderImpl.cs" />
<Compile Include="Bytecode\IAccessOptimizer.cs" />
Modified: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaExport.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -3,9 +3,9 @@
using System.Data;
using System.IO;
using log4net;
+using NHibernate.AdoNet.Util;
using NHibernate.Cfg;
using NHibernate.Connection;
-using NHibernate.Pretty;
using NHibernate.Util;
using Environment=NHibernate.Cfg.Environment;
@@ -27,7 +27,7 @@
private readonly string[] dropSQL;
private string delimiter;
private string outputFile;
- private readonly bool format;
+ private readonly IFormatter formatter;
/// <summary>
/// Create a schema exported for a given Configuration
@@ -47,7 +47,7 @@
dialect = Dialect.Dialect.GetDialect(configProperties);
dropSQL = cfg.GenerateDropSchemaScript(dialect);
createSQL = cfg.GenerateSchemaCreationScript(dialect);
- format = PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true);
+ formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
}
/// <summary>
@@ -110,7 +110,7 @@
{
try
{
- string formatted = Format(sql);
+ string formatted = formatter.Format(sql);
if (delimiter != null)
{
@@ -303,15 +303,5 @@
}
}
}
-
- /// <summary>
- /// Format an SQL statement.
- /// </summary>
- /// <param name="sql">The string containing the sql to format.</param>
- /// <returns>A string that contains formatted sql.</returns>
- private string Format(string sql)
- {
- return format ? new DdlFormatter(sql).Format() : sql;
- }
}
}
\ No newline at end of file
Modified: trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs
===================================================================
--- trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate/Tool/hbm2ddl/SchemaUpdate.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -5,6 +5,8 @@
using log4net;
using NHibernate.Cfg;
using NHibernate.Util;
+using Environment=NHibernate.Cfg.Environment;
+using NHibernate.AdoNet.Util;
namespace NHibernate.Tool.hbm2ddl
{
@@ -15,20 +17,22 @@
private readonly IConnectionHelper connectionHelper;
private readonly Dialect.Dialect dialect;
private readonly List<Exception> exceptions;
+ private IFormatter formatter;
public SchemaUpdate(Configuration cfg) : this(cfg, cfg.Properties) {}
- public SchemaUpdate(Configuration cfg, IDictionary<string, string> connectionProperties)
+ public SchemaUpdate(Configuration cfg, IDictionary<string, string> configProperties)
{
configuration = cfg;
- dialect = Dialect.Dialect.GetDialect(connectionProperties);
+ dialect = Dialect.Dialect.GetDialect(configProperties);
var props = new Dictionary<string, string>(dialect.DefaultProperties);
- foreach (var prop in connectionProperties)
+ foreach (var prop in configProperties)
{
props[prop.Key] = prop.Value;
}
connectionHelper = new ManagedProviderConnectionHelper(props);
exceptions = new List<Exception>();
+ formatter = (PropertiesHelper.GetBoolean(Environment.FormatSql, configProperties, true) ? FormatStyle.Ddl : FormatStyle.None).Formatter;
}
public SchemaUpdate(Configuration cfg, Settings settings)
@@ -37,6 +41,7 @@
dialect = settings.Dialect;
connectionHelper = new SuppliedConnectionProviderConnectionHelper(settings.ConnectionProvider);
exceptions = new List<Exception>();
+ formatter = (settings.SqlStatementLogger.FormatSql ? FormatStyle.Ddl : FormatStyle.None).Formatter;
}
/// <summary>
@@ -162,11 +167,13 @@
for (int j = 0; j < createSQL.Length; j++)
{
string sql = createSQL[j];
+ string formatted = formatter.Format(sql);
+
try
{
if (scriptAction != null)
{
- scriptAction(sql);
+ scriptAction(formatted);
}
if (doUpdate)
{
Modified: trunk/nhibernate/src/NHibernate.Test/App.config
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/App.config 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate.Test/App.config 2009-04-18 00:30:01 UTC (rev 4186)
@@ -53,6 +53,7 @@
Use the member names - not the values.
-->
<property name="connection.isolation">ReadCommitted</property>
+ <property name="format_sql">true</property>
<!-- This is the System.Data.dll provider for MSSQL Server -->
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
Modified: trunk/nhibernate/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs
===================================================================
--- trunk/nhibernate/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs 2009-04-17 18:01:35 UTC (rev 4185)
+++ trunk/nhibernate/src/NHibernate.Test/SqlTest/Identity/IdentityInsertWithStoredProcsTest.cs 2009-04-18 00:30:01 UTC (rev 4186)
@@ -1,3 +1,4 @@
+using NHibernate.Cfg;
using NUnit.Framework;
namespace NHibernate.Test.SqlTest.Identity
@@ -9,6 +10,12 @@
get { return "NHibernate.Test"; }
}
+ protected override void Configure(NHibernate.Cfg.Configuration configuration)
+ {
+ base.Configure(configuration);
+ configuration.SetProperty(Environment.FormatSql, "false");
+ }
+
protected abstract string GetExpectedInsertOrgLogStatement(string orgName);
/// <summary>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|