private byte[] GetCommandText(bool prepare, bool forExtendQuery)
{
NpgsqlEventLog.LogMethodEnter(LogLevel.Debug, CLASSNAME, "GetCommandText");
MemoryStream commandBuilder = new MemoryStream();
StringChunk[] chunks;
chunks = GetDistinctTrimmedCommands(commandText);
if (chunks.Length > 1)
{
if (prepare || commandType == CommandType.StoredProcedure)
{
throw new NpgsqlException("Multiple queries not supported for this command type");
}
}
foreach (StringChunk chunk in chunks)
{
if (commandBuilder.Length > 0)
{
commandBuilder
.WriteBytes((byte)ASCIIBytes.SemiColon)
.WriteBytes(ASCIIByteArrays.LineTerminator);
}
if (prepare && ! forExtendQuery)
{
commandBuilder
.WriteString("PREPARE ")
.WriteString(planName)
.WriteString(" AS ");
}
if (commandType == CommandType.StoredProcedure)
{
if (! prepare && ! functionChecksDone)
{
functionNeedsColumnListDefinition = Parameters.Count != 0 && CheckFunctionNeedsColumnDefinitionList();
functionChecksDone = true;
}
commandBuilder.WriteString(
Connector.SupportsPrepare
? "SELECT * FROM " // This syntax is only available in 7.3+ as well SupportsPrepare.
: "SELECT " //Only a single result return supported. 7.2 and earlier.
);
if (commandText[chunk.Begin + chunk.Length - 1] == ')')
{
AppendCommandReplacingParameterValues(commandBuilder, commandText, chunk.Begin, chunk.Length, prepare, forExtendQuery);
}
else
{
commandBuilder
.WriteString(commandText.Substring(chunk.Begin, chunk.Length))
.WriteBytes((byte)ASCIIBytes.ParenLeft);
if (prepare)
{
AppendParameterPlaceHolders(commandBuilder);
}
else
{
AppendParameterValues(commandBuilder);
}
commandBuilder.WriteBytes((byte)ASCIIBytes.ParenRight);
}
if (! prepare && functionNeedsColumnListDefinition)
{
AddFunctionColumnListSupport(commandBuilder);
}
}
else if (commandType == CommandType.TableDirect)
{
commandBuilder
.WriteString("SELECT * FROM ")
.WriteString(commandText.Substring(chunk.Begin, chunk.Length));
}
else
{
AppendCommandReplacingParameterValues(commandBuilder, commandText, chunk.Begin, chunk.Length, prepare, forExtendQuery);
}
}
return commandBuilder.ToArray();
}