using System.Data.Common;
using System.Data.Odbc;
using System.Globalization;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql;
///
/// Generic ODBC dialect (design §2, P3; lmxopcua#753) over System.Data.Odbc — the ANSI SQL:2008
/// profile: double-quote identifier quoting, positional ? parameter markers, the standard
/// INFORMATION_SCHEMA catalog views, and the standard FETCH FIRST n ROWS ONLY row limit.
/// What that means for a backend. ODBC abstracts the wire, not the SQL: this dialect works
/// against a data source whose SQL accepts all four of those — PostgreSQL (psqlODBC), Snowflake, Oracle 12c+
/// with an INFORMATION_SCHEMA compatibility view set, and similar. A backend that lacks one (SQL Server
/// needs OFFSET … FETCH after an ORDER BY; MySQL has no FETCH FIRST; DB2 has no
/// INFORMATION_SCHEMA) should use its native provider. Unlike every other dialect, ODBC also needs a
/// native driver manager (unixODBC / iODBC / the Windows one) and the vendor's ODBC driver installed on the
/// host.
/// Parameters are positional. ODBC ignores and binds
/// ? markers in the order parameters are added, so every caller must add them in the order their
/// markers appear: the planner's key list is already in marker order, and the catalog SQL below binds
/// schema before table, the order SqlCatalogLoader and the browse session add them.
/// Stateless and immutable, so one instance is safely shared.
///
public sealed class OdbcDialect : ISqlDialect
{
///
/// The identifier ceiling — SQL:2008's 128 characters, which is also SQL Server's and Oracle's. A
/// backend with a lower limit rejects an over-long name itself; the catalog gate only ever quotes
/// names the catalog returned.
///
internal const int MaxIdentifierLength = 128;
/// The positional marker every ODBC parameter is spelled with.
internal const string PositionalMarker = "?";
///
public SqlProvider Provider => SqlProvider.Odbc;
///
public DbProviderFactory Factory => OdbcFactory.Instance;
///
public string ParameterMarker(string baseName) => PositionalMarker;
// The name is ignored by the ODBC driver manager (binding is positional) but kept as the bare base name so
// the parameter collection stays readable in a log.
///
public string ParameterBindName(string baseName) => baseName;
///
public void ConfigureCommand(DbCommand command)
{
// Intentionally empty: OdbcCommand needs no per-command setup.
}
// 1000 — conservative, because the backend behind the DSN is unknown: it is Oracle's IN-list ceiling (the
// strictest common one) and well inside SQL Server's 2100. A larger key-value group is chunked into several
// statements, which costs round-trips and nothing else.
///
public int MaxBindParameters => 1000;
///
public string LivenessSql => "SELECT 1";
///
public string SingleRowLimitPrefix => string.Empty;
///
public string SingleRowLimitSuffix => " FETCH FIRST 1 ROWS ONLY";
///
public string RowLimitPrefix(int rows)
{
ArgumentOutOfRangeException.ThrowIfLessThan(rows, 1);
return string.Empty;
}
///
public string RowLimitSuffix(int rows)
{
ArgumentOutOfRangeException.ThrowIfLessThan(rows, 1);
return " FETCH FIRST " + rows.ToString(CultureInfo.InvariantCulture) + " ROWS ONLY";
}
// The schemas holding relations this connection can see — derived from TABLES (not SCHEMATA, which some
// backends restrict to owned schemas; the PostgresDialect note). The backend is unknown, so the system
// schemas of the common INFORMATION_SCHEMA backends are excluded by name, case-insensitively (UPPER is
// standard): the standard's own, PostgreSQL's pg_catalog / pg_toast* / pg_temp* (psqlODBC lists pg_catalog,
// proven by the live gate), and SQL Server's / MySQL's sys, mysql, performance_schema. Aliases are
// double-quoted so a backend that folds unquoted output names still returns the spelling the consumers read
// by name.
///
public string ListSchemasSql =>
"SELECT DISTINCT TABLE_SCHEMA AS \"TABLE_SCHEMA\" FROM INFORMATION_SCHEMA.TABLES " +
"WHERE UPPER(TABLE_SCHEMA) NOT IN ('INFORMATION_SCHEMA', 'PG_CATALOG', 'SYS', 'MYSQL', 'PERFORMANCE_SCHEMA') " +
"AND UPPER(TABLE_SCHEMA) NOT LIKE 'PG\\_TOAST%' ESCAPE '\\' " +
"AND UPPER(TABLE_SCHEMA) NOT LIKE 'PG\\_TEMP%' ESCAPE '\\' " +
"ORDER BY 1";
// SQL:2008's CURRENT_SCHEMA is the portable spelling where it exists; a backend without it fails the query
// and the loader falls back to the sole visible schema (or authoring must qualify every table).
///
public string DefaultSchemaSql => "SELECT CURRENT_SCHEMA";
///
public string ListTablesSql =>
"SELECT TABLE_NAME AS \"TABLE_NAME\", TABLE_TYPE AS \"TABLE_TYPE\" FROM INFORMATION_SCHEMA.TABLES " +
"WHERE TABLE_SCHEMA = ? ORDER BY 1";
// schema BEFORE table — positional binding makes this order part of the contract.
///
public string ListColumnsSql =>
"SELECT COLUMN_NAME AS \"COLUMN_NAME\", DATA_TYPE AS \"DATA_TYPE\", IS_NULLABLE AS \"IS_NULLABLE\" " +
"FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
// ANSI double-quote quoting, doubling an embedded quote. Same rejection discipline as the sibling dialects
// (blank, over-long, control characters incl. NUL, Unicode format characters), never echoing the value.
///
public string QuoteIdentifier(string ident)
{
if (string.IsNullOrWhiteSpace(ident))
throw new ArgumentException("A SQL identifier must be a non-empty, non-whitespace name.", nameof(ident));
if (ident.Length > MaxIdentifierLength)
throw new ArgumentException(
$"An ODBC identifier may not exceed {MaxIdentifierLength} characters (got {ident.Length}).",
nameof(ident));
foreach (var ch in ident)
{
if (char.IsControl(ch))
throw new ArgumentException(
"A SQL identifier may not contain control characters (including NUL).", nameof(ident));
if (CharUnicodeInfo.GetUnicodeCategory(ch) == UnicodeCategory.Format)
throw new ArgumentException(
"A SQL identifier may not contain Unicode format characters "
+ "(bidi overrides, zero-width spaces, soft hyphen, BOM).", nameof(ident));
}
return string.Concat("\"", ident.Replace("\"", "\"\"", StringComparison.Ordinal), "\"");
}
// The union of the standard type names and the common backends' spellings (INFORMATION_SCHEMA.DATA_TYPE and
// the ODBC driver's GetDataTypeName both reach here). Never throws; unknown ⇒ String.
///
public DriverDataType MapColumnType(string sqlDataType)
{
if (string.IsNullOrWhiteSpace(sqlDataType)) return DriverDataType.String;
var name = sqlDataType.Trim().ToLowerInvariant();
var paren = name.IndexOf('(', StringComparison.Ordinal);
if (paren >= 0) name = name[..paren].Trim();
return name switch
{
"boolean" or "bool" => DriverDataType.Boolean,
"smallint" or "int2" or "tinyint" => DriverDataType.Int16,
"integer" or "int" or "int4" => DriverDataType.Int32,
"bigint" or "int8" => DriverDataType.Int64,
"real" or "float4" => DriverDataType.Float32,
"double precision" or "double" or "float" or "float8" or "decimal" or "numeric" or "number"
=> DriverDataType.Float64,
"character varying" or "varchar" or "character" or "char" or "nvarchar" or "nchar" or "text"
or "varchar2" or "nvarchar2" or "clob" or "uuid" => DriverDataType.String,
"date" or "timestamp" or "timestamp without time zone" or "timestamp with time zone"
or "timestamptz" or "datetime" or "datetime2" => DriverDataType.DateTime,
_ => DriverDataType.String,
};
}
// ---- writes (lmxopcua#781 item 2) ----
// Update and Insert only (SqlWriteSupport): no Upsert (positional markers cannot repeat, and MERGE is missing or
// partial on several ODBC backends) and no Procedure (no portable routine catalog or calling convention).
///
// The driver manager reports the backend's SQLSTATE on each OdbcError.
public SqlWriteFailure ClassifyWriteFailure(Exception exception)
=> exception is OdbcException odbc && odbc.Errors.Count > 0
? SqlWriteFailures.FromSqlState(odbc.Errors[0].SQLState)
: SqlWriteFailure.Other;
}