using System.Collections.Generic;
using System.Diagnostics;
using JetBrains.Annotations;
using Npgsql.BackendMessages;
namespace Npgsql
{
///
/// Represents a single SQL statement within Npgsql.
///
/// Instances aren't constructed directly; users should construct an
/// object and populate its property as in standard ADO.NET.
/// Npgsql will analyze that property and constructed instances of
/// internally.
///
/// Users can retrieve instances from
/// and access information about statement execution (e.g. affected rows).
///
public sealed class NpgsqlStatement
{
///
/// The SQL text of the statement.
///
public string SQL { get; set; } = string.Empty;
///
/// Specifies the type of query, e.g. SELECT.
///
public StatementType StatementType { get; internal set; }
///
/// The number of rows affected or retrieved.
///
///
/// See the command tag in the CommandComplete message,
/// http://www.postgresql.org/docs/current/static/protocol-message-formats.html
///
public uint Rows { get; internal set; }
///
/// For an INSERT, the object ID of the inserted row if is 1 and
/// the target table has OIDs; otherwise 0.
///
public uint OID { get; internal set; }
///
/// The input parameters sent with this statement.
///
public List InputParameters { get; } = new List();
///
/// The RowDescription message for this query. If null, the query does not return rows (e.g. INSERT)
///
[CanBeNull]
internal RowDescriptionMessage Description
{
get { return PreparedStatement == null ? _description : PreparedStatement.Description; }
set
{
if (PreparedStatement == null)
_description = value;
else
PreparedStatement.Description = value;
}
}
[CanBeNull]
RowDescriptionMessage _description;
///
/// If this statement has been automatically prepared, references the .
/// Null otherwise.
///
[CanBeNull]
internal PreparedStatement PreparedStatement
{
get
{
if (_preparedStatement != null && _preparedStatement.State == PreparedState.Unprepared)
_preparedStatement = null;
return _preparedStatement;
}
set => _preparedStatement = value;
}
[CanBeNull]
PreparedStatement _preparedStatement;
///
/// Holds the server-side (prepared) statement name. Empty string for non-prepared statements.
///
internal string StatementName => PreparedStatement?.Name ?? "";
///
/// Whether this statement has already been prepared (including automatic preparation).
///
internal bool IsPrepared => PreparedStatement?.IsPrepared == true;
internal void Reset()
{
SQL = string.Empty;
StatementType = StatementType.Select;
_description = null;
Rows = 0;
OID = 0;
InputParameters.Clear();
PreparedStatement = null;
}
internal void ApplyCommandComplete(CommandCompleteMessage msg)
{
StatementType = msg.StatementType;
Rows = msg.Rows;
OID = msg.OID;
}
///
/// Returns the SQL text of the statement.
///
public override string ToString() => SQL ?? "";
}
}