Source of truth (2026)
  • Facade: DataManagementEngineStandard/Helpers/ConnectionHelpers/ConnectionHelper.cs (delegates to sub-helpers)
  • Driver linking: ConnectionDriverLinkingHelper.cs
  • String processing: ConnectionStringProcessingHelper.cs
  • Validation: ConnectionStringValidationHelper.cs
  • Security: ConnectionStringSecurityHelper.cs
  • Parameter utils: ConnectionHelper_GetParameterList.cs
  • Category factories (partial classes): ConnectionHelper_RDBMS.cs, ConnectionHelper_NoSQL.cs, ConnectionHelper_VectorDB.cs, ConnectionHelper_File.cs, ConnectionHelper_Cloud.cs, ConnectionHelper_Streaming.cs, ConnectionHelper_InMemory.cs, ConnectionHelper_Cache.cs, ConnectionHelper_WebAPI.cs, ConnectionHelper_CRM.cs, ConnectionHelper_Marketing.cs, ConnectionHelper_ECommerce.cs, ConnectionHelper_ProjectManagement.cs, ConnectionHelper_Communication.cs, ConnectionHelper_Blockchain.cs, ConnectionHelper_Proxy.cs, ConnectionHelper_File_Misc.cs
  • Liveness: ProxyLivenessHelper.cs, TestConnectionHelper.cs

Overview & File Structure

ConnectionHelper (namespace TheTechIdea.Beep.Helpers) is a static facade split across many partial classes. It bundles four orthogonal concerns — driver discovery, connection-string building, validation, security — together with a library of per-category ConnectionDriversConfig factory methods that pre-populate every field a driver needs (class names, NuGet package, connection-string template, icon, etc.).

Partial file inventory
FileNamespaceResponsibility
ConnectionHelper.csTheTechIdea.Beep.HelpersPublic facade — re-exports every sub-helper method under one type
ConnectionDriverLinkingHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersMatch connection properties to registered drivers
ConnectionStringProcessingHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersPlaceholder substitution, path normalisation
ConnectionStringValidationHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersPer-driver connection-string validation rules
ConnectionStringSecurityHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersMask passwords, API keys, tokens for logging
ConnectionHelper_GetParameterList.csTheTechIdea.Beep.HelpersParse / mutate individual connection-string parameters
ConnectionHelper_RDBMS.csTheTechIdea.Beep.HelpersFactory: SQL Server, MySQL, PostgreSQL, SQLite, Firebird, …
ConnectionHelper_NoSQL.csTheTechIdea.Beep.HelpersFactory: MongoDB, Redis, Cassandra, Elasticsearch, …
ConnectionHelper_VectorDB.csTheTechIdea.Beep.HelpersFactory: ChromaDB, Pinecone, Qdrant, Weaviate, Milvus, …
ConnectionHelper_File.csTheTechIdea.Beep.HelpersFactory: CSV, JSON, XML, Excel, Parquet, Avro, …
ConnectionHelper_File_Misc.csTheTechIdea.Beep.HelpersFactory: DICOM, LAS, HDF5, Markdown, INI, …
ConnectionHelper_Cloud.csTheTechIdea.Beep.HelpersFactory: AWS (S3, Redshift, Athena), Azure, GCP (BigQuery)
ConnectionHelper_Streaming.csTheTechIdea.Beep.HelpersFactory: Kafka, RabbitMQ, Pulsar, Azure Service Bus, …
ConnectionHelper_InMemory.csTheTechIdea.Beep.HelpersFactory: SQLite Memory, DuckDB Memory, Hazelcast, Ignite
ConnectionHelper_Cache.csTheTechIdea.Beep.HelpersFactory: InMemoryCache, Redis Cache, NCache, Hazelcast Cache, …
ConnectionHelper_WebAPI.csTheTechIdea.Beep.HelpersFactory: REST, GraphQL, gRPC, SOAP, OData, WebSocket, …
ConnectionHelper_CRM.csTheTechIdea.Beep.HelpersFactory: Salesforce, HubSpot, Dynamics 365, Zoho, …
ConnectionHelper_Marketing.csTheTechIdea.Beep.HelpersFactory: Mailchimp, Marketo, Klaviyo, SendGrid, …
ConnectionHelper_ECommerce.csTheTechIdea.Beep.HelpersFactory: Shopify, WooCommerce, Magento, BigCommerce, …
ConnectionHelper_ProjectManagement.csTheTechIdea.Beep.HelpersFactory: Jira, Asana, Monday.com, ClickUp, Trello, …
ConnectionHelper_Communication.csTheTechIdea.Beep.HelpersFactory: Slack, Teams, Discord, Zoom, Telegram, …
ConnectionHelper_Blockchain.csTheTechIdea.Beep.HelpersFactory: Ethereum, Hyperledger, Solana, Polkadot, …
ConnectionHelper_Proxy.csTheTechIdea.Beep.HelpersFactory: HTTP proxy, SOCKS, reverse proxy configs
ProxyLivenessHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersCategory-aware liveness probe for a live IDataSource
TestConnectionHelper.csTheTechIdea.Beep.Helpers.ConnectionHelpersAsync setup-time and runtime connection tests

Driver Linking

ConnectionDriverLinkingHelper matches an IConnectionProperties instance to the best available ConnectionDriversConfig registered in IConfigEditor.DataDriversClasses. The lookup chain is:

  1. Exact DriverName + DriverVersion
  2. DriverName only (latest available version)
  3. DatabaseType enum match
  4. File extension match (for Category == FILE)

Signatures

// In ConnectionHelper (facade) and ConnectionDriverLinkingHelper (implementation)
public static ConnectionDriversConfig LinkConnection2Drivers(
    IConnectionProperties cn, IConfigEditor configEditor);

public static List<ConnectionDriversConfig> GetDriversForDataSourceType(
    DataSourceType dataSourceType, IConfigEditor configEditor);

public static List<ConnectionDriversConfig> GetDriversForFileExtension(
    string fileExtension, IConfigEditor configEditor);

public static ConnectionDriversConfig GetBestMatchingDriver(
    IConnectionProperties connectionProperties, IConfigEditor configEditor);

Usage

// Resolve the driver config for an existing connection
var driver = ConnectionHelper.LinkConnection2Drivers(myConn, dmeEditor.ConfigEditor);
if (driver != null)
    Console.WriteLine($"Driver: {driver.PackageName} v{driver.version}");

// Find all drivers that handle SQLite
var sqliteDrivers = ConnectionHelper.GetDriversForDataSourceType(
    DataSourceType.SqlLite, dmeEditor.ConfigEditor);

// Resolve by file extension (e.g. "csv")
var csvDrivers = ConnectionHelper.GetDriversForFileExtension("csv", dmeEditor.ConfigEditor);

// Automatic best-match (tries all strategies)
var best = ConnectionHelper.GetBestMatchingDriver(myConn, dmeEditor.ConfigEditor);

Connection String Processing

ConnectionStringProcessingHelper fills placeholder tokens ({Host}, {Database}, {UserID}, {Password}, etc.) in a driver's connection-string template at connection-open time. It also normalises relative paths (./, ../) to absolute paths relative to IConfigEditor.ExePath.

Signatures

// Fills all {placeholders} in the driver's ConnectionString template
public static string ReplaceValueFromConnectionString(
    ConnectionDriversConfig DataSourceDriver,
    IConnectionProperties ConnectionProp,
    IDMEEditor DMEEditor);

// Converts a relative path to an absolute path under basePath
public static string NormalizePath(string relativePath, string basePath);

// Normalizes FilePath in-place on the connection properties object
public static void NormalizeFilePath(IConnectionProperties connectionProp, string basePath);

// Returns a list of {placeholder} names that have no matching value
public static List<string> ValidateRequiredPlaceholders(
    string connectionStringTemplate, IConnectionProperties connectionProp);

How placeholder substitution works

// Template in driver config:
// "Server={Host};Database={Database};User Id={UserID};Password={Password}"

var conn = new ConnectionProperties
{
    Host     = "db.example.com",
    DataBase = "sales",
    UserID   = "app",
    Password = "s3cr3t"
};

var driver = ConnectionHelper.LinkConnection2Drivers(conn, dmeEditor.ConfigEditor);
string cs = ConnectionHelper.ReplaceValueFromConnectionString(driver, conn, dmeEditor);
// "Server=db.example.com;Database=sales;User Id=app;Password=s3cr3t"

// Validate nothing is missing before opening
var missing = ConnectionHelper.ValidateRequiredPlaceholders(driver.ConnectionString, conn);
if (missing.Any())
    throw new InvalidOperationException($"Missing fields: {string.Join(", ", missing)}");
Priority order for input string

The helper resolves the base string in this order: ConnectionString → Url → FilePath + FileName. Relative paths that start with ./ are automatically expanded to absolute paths.

Connection String Validation

ConnectionStringValidationHelper performs lightweight structural/keyword checks on a connection string before attempting to open a connection. It covers the most common RDBMS and NoSQL drivers; unknown types fall back to a generic structure check.

Signatures

// Dispatch to the correct per-driver validator based on DataSourceType
public static bool IsConnectionStringValid(string connectionString, DataSourceType dataSourceType);

// DB-specific validators (also called directly)
public static bool ValidateSqlServerConnectionString(string connectionString);
public static bool ValidateMySqlConnectionString(string connectionString);
public static bool ValidateSQLiteConnectionString(string connectionString);
// ...and more: PostgreSQL, MongoDB, Redis, OleDB, ODBC

// Human-readable description of what the driver requires
public static string GetValidationRequirements(DataSourceType dataSourceType);

// Generic key=value pair structure check (no driver-specific rules)
public static bool ValidateConnectionStringStructure(string connectionString);

Usage

string cs = "Server=localhost;Database=northwind;Trusted_Connection=True";

// Generic dispatch
bool ok = ConnectionHelper.IsConnectionStringValid(cs, DataSourceType.SqlServer);

// Get human-readable requirements when validation fails
if (!ok)
{
    string reqs = ConnectionHelper.GetValidationRequirements(DataSourceType.SqlServer);
    Console.WriteLine($"Required: {reqs}");
}
Supported DataSourceType validators
DataSourceTypeRequired keyword(s)
SqlServerServer / Data Source / Address
MysqlServer / Host / Data Source
SqlLiteData Source / DataSource
PostgreHost / Server
MongoDBmongodb:// prefix
Redishost:port pattern
OLEDB / ODBCProvider= / DSN= or Driver=
Everything elseGeneric: at least one key=value pair

Connection String Security

ConnectionStringSecurityHelper masks secret values before connection strings are logged, displayed in UIs, or transmitted in error reports. It uses regex to locate and replace well-known secret keywords.

Signatures

// Replace passwords, API keys, access keys, tokens, and secrets with ********
public static string SecureConnectionString(string connectionString);

// Returns true if the string contains any of the masked keyword patterns
public static bool ContainsSensitiveInformation(string connectionString);

Usage

string raw = "Server=db;Database=sales;User Id=app;Password=MyP@ss!;ApiKey=key-abc123";

string safe = ConnectionHelper.SecureConnectionString(raw);
// "Server=db;Database=sales;User Id=app;Password=********;ApiKey=********"

// Guard before logging
if (ConnectionHelper.ContainsSensitiveInformation(raw))
    logger.WriteLog(ConnectionHelper.SecureConnectionString(raw));
else
    logger.WriteLog(raw);
Masked keyword categories
CategoryMatched keywords (case-insensitive)
PasswordsPassword, Pwd, Pass, UserPassword, AuthPassword
API keysApiKey, ApplicationKey, ClientKey, SubscriptionKey
Access keysAccessKey, SecretKey, AwsAccessKey, AwsSecretKey
TokensToken, BearerToken, AccessToken, RefreshToken
SecretsSecret, ClientSecret, AppSecret

Parameter Utilities

Defined in ConnectionHelper_GetParameterList.cs (partial class of ConnectionHelper). These methods parse semi-colon delimited connection strings as key=value dictionaries without opening any database connection.

Signatures

// Returns all parameter names (keys only)
public static List<string> GetParameterList(string connectionString);

// Returns all parameters as Dictionary<key, value>
public static Dictionary<string, string> GetAllParameters(string connectionString);

// Returns the value of a single named parameter (null if absent)
public static string GetParameterValue(string connectionString, string parameterName);

// Replaces an existing key's value, or appends a new key=value pair
public static string SetParameterValue(string connectionString, string parameterName, string parameterValue);

// Removes a key=value pair (returns the remaining string)
public static string RemoveParameter(string connectionString, string parameterName);

Usage

string cs = "Server=localhost;Database=Northwind;User Id=sa;Password=P@ssw0rd";

// Inspect
var keys = ConnectionHelper.GetParameterList(cs);
// ["Server", "Database", "User Id", "Password"]

string db = ConnectionHelper.GetParameterValue(cs, "Database");
// "Northwind"

// Switch database without rebuilding the whole string
cs = ConnectionHelper.SetParameterValue(cs, "Database", "Sales");

// Add a new key
cs = ConnectionHelper.SetParameterValue(cs, "Encrypt", "True");

// Remove a key
cs = ConnectionHelper.RemoveParameter(cs, "Password");

Category Config Factories

Each partial class file exposes a Get*Configs() method that returns a List<ConnectionDriversConfig> pre-populated with all known drivers for that category. Individual Create*Config() factory methods produce a single ConnectionDriversConfig with every field set (GUID, package name, DLL name, class handler, connection-string template, icon, flags, NuGet metadata).

These factories are used at startup to seed IConfigEditor.DataDriversClasses so that drivers are available for LinkConnection2Drivers even before NuGet packages are installed.

RDBMS Config Factory

File: ConnectionHelper_RDBMS.cs

Get all RDBMS configs

List<ConnectionDriversConfig> rdbms = ConnectionHelper.GetRDBMSConfigs();
Individual factory methods and connection-string templates
MethodDataSourceTypeTemplate
CreateSqlServerConfig()SqlServerServer={Host};Database={Database};User Id={UserID};Password={Password}
CreateMySqlConfig()MysqlServer={Host};Database={Database};Uid={UserID};Pwd={Password}
CreatePostgreConfig()PostgreHost={Host};Database={Database};Username={UserID};Password={Password}
CreateSQLiteConfig()SqlLiteData Source={FileName}
CreateDuckDBConfig()DuckDBData Source={FileName}
CreateFirebirdConfig()FirebirdDataSource={Host};Database={FileName};User={UserID};Password={Password}
CreateSnowFlakeConfig()SnowFlakeaccount={Host};user={UserID};password={Password};db={Database}
CreateAzureSQLConfig()AzureSqlAzure SQL connection string template
CreateAWSRDSConfig()AWSRdsAWS RDS connection string template
CreateHanaConfig()HanaSAP HANA connection string template

Example: create and register an SQLite driver at runtime

var sqliteDrv = ConnectionHelper.CreateSQLiteConfig();
// sqliteDrv.ConnectionString == "Data Source={FileName}"
// sqliteDrv.classHandler     == "SQLiteDataSource"
// sqliteDrv.DatasourceType   == DataSourceType.SqlLite

// Seed it into ConfigEditor if not already there
if (!dmeEditor.ConfigEditor.DataDriversClasses
        .Any(d => d.DatasourceType == DataSourceType.SqlLite))
{
    dmeEditor.ConfigEditor.DataDriversClasses.Add(sqliteDrv);
}

NoSQL Config Factory

File: ConnectionHelper_NoSQL.cs

List<ConnectionDriversConfig> nosql = ConnectionHelper.GetNoSQLConfigs();
Drivers produced
MethodTechnology
CreateMongoDBConfig()MongoDB — mongodb://{UserID}:{Password}@{Host}:{Port}/{Database}
CreateRedisConfig()Redis — {Host}:{Port},password={Password}
CreateCassandraConfig()Cassandra — Contact Points={Host};Default Keyspace={Database}
CreateElasticsearchConfig()Elasticsearch — http://{Host}:{Port}/{Database}
CreateDynamoDBConfig()AWS DynamoDB
CreateCouchDBConfig()CouchDB
CreateNeo4jConfig()Neo4j (graph)
CreateInfluxDBConfig()InfluxDB (time series)
CreateClickHouseConfig()ClickHouse

Vector DB Config Factory

File: ConnectionHelper_VectorDB.cs

List<ConnectionDriversConfig> vdbs = ConnectionHelper.GetVectorDBConfigs();
Drivers produced: ChromaDB, Pinecone, Qdrant, Weaviate, Milvus, Zilliz, Redis Vector, Vespa, ShapVector. All have DatasourceCategory = DatasourceCategory.VectorDB and include collection-name, dimension, metric-type placeholders in their templates.

File Config Factory

Files: ConnectionHelper_File.cs, ConnectionHelper_File_Misc.cs

List<ConnectionDriversConfig> files = ConnectionHelper.GetFileConfigs();
List<ConnectionDriversConfig> misc  = ConnectionHelper.GetFileMiscConfigs();
Structured formats (GetFileConfigs): CSV, JSON, XML, YAML, Excel (XLS/XLSX), Parquet, Avro, ORC, Feather, HDF5, DICOM, LAS, LibSVM, GraphML.

Misc formats (GetFileMiscConfigs): INI, Markdown (.md), text logs, BSON, CBOR, YAML alternatives.

All file configs have DatasourceCategory = DatasourceCategory.FILE, CreateLocal = true, and supply an iconname for UI display.

Cloud Config Factory

File: ConnectionHelper_Cloud.cs

List<ConnectionDriversConfig> cloud = ConnectionHelper.GetCloudConfigs();
Drivers produced: AWS (S3, Redshift, Athena, Glue, Step Functions, IoT Core), Azure (Azure SQL, Synapse, Data Factory, Blob Storage), GCP (BigQuery, Cloud Storage), Multi-cloud (Databricks, Supabase, Firebolt). All have DatasourceCategory = DatasourceCategory.CLOUD.

Streaming Config Factory

File: ConnectionHelper_Streaming.cs

List<ConnectionDriversConfig> streams = ConnectionHelper.GetStreamingConfigs();
Drivers produced: Kafka, RabbitMQ, ActiveMQ, Pulsar, NATS, ZeroMQ, MassTransit, AWS (SQS, SNS, Kinesis), Azure (Service Bus, Event Hubs), Apache (Flink, Storm, Spark Streaming). All have DatasourceCategory = DatasourceCategory.STREAM.

In-Memory & Cache Config Factories

Files: ConnectionHelper_InMemory.cs, ConnectionHelper_Cache.cs

List<ConnectionDriversConfig> inmem  = ConnectionHelper.GetInMemoryConfigs();
List<ConnectionDriversConfig> caches = ConnectionHelper.GetCacheConfigs();
In-memory drivers (GetInMemoryConfigs): SQLite in-memory, DuckDB in-memory, H2, Apache Ignite, Hazelcast. All have InMemory = true and CreateLocal = true.

Cache drivers (GetCacheConfigs): InMemoryCache, CachedMemory, DistributedCache, HybridCache, L1/L2 Cache, MemoryCache, RedisCache, NCache, CouchbaseCache, HazelcastCache, ApacheIgniteCache, Infinispan, EhCache, CaffeineCache. Template: CacheName={Database};MaxItems={MaxItems};ExpiryMinutes={ExpiryMinutes}.

Example: create and use an InMemoryCache connection

// Get the pre-built config
var cacheConfig = ConnectionHelper.CreateInMemoryCacheConfig();

// Register a connection using this driver
dmeEditor.ConfigEditor.AddDataConnection(new ConnectionProperties
{
    ConnectionName = "MyCache",
    DatabaseType   = DataSourceType.InMemoryCache,
    DriverName     = cacheConfig.PackageName,
    Database       = "SessionCache",
    ExtraParameters = "MaxItems=5000;ExpiryMinutes=30"
});

var cache = dmeEditor.GetDataSource("MyCache");
cache.Openconnection();

Web API Config Factory

File: ConnectionHelper_WebAPI.cs

List<ConnectionDriversConfig> webapis = ConnectionHelper.GetWebAPIConfigs();
Drivers produced: Generic REST, OData, GraphQL, gRPC, SOAP, XML-RPC, JSON-RPC, WebSocket, Server-Sent Events, OPC, ODBC, OLEDB, ADO. All have DatasourceCategory = DatasourceCategory.WEBAPI or RDBMS (for ADO/ODBC).

Connector Category Factories

These partial classes produce drivers for SaaS platforms. All have DatasourceCategory = DatasourceCategory.Connector.

MethodFilePlatforms included
GetCRMConfigs()ConnectionHelper_CRM.csSalesforce, HubSpot, Dynamics 365, Zoho, Pipedrive, Freshsales, SugarCRM, SAP CRM
GetMarketingConfigs()ConnectionHelper_Marketing.csMailchimp, Marketo, ActiveCampaign, Klaviyo, Sendinblue, SendGrid, Mailgun, Google Ads, Hootsuite
GetECommerceConfigs()ConnectionHelper_ECommerce.csShopify, WooCommerce, Magento, BigCommerce, Squarespace, Etsy, OpenCart, PrestaShop
GetProjectManagementConfigs()ConnectionHelper_ProjectManagement.csJira, Azure Boards, Trello, Asana, Monday.com, ClickUp, Notion, Wrike, Smartsheet
GetCommunicationConfigs()ConnectionHelper_Communication.csSlack, Microsoft Teams, Discord, Zoom, Telegram, WhatsApp Business, Mattermost, Rocket.Chat
GetBlockchainConfigs()ConnectionHelper_Blockchain.csEthereum, Hyperledger Fabric, Solana, Polkadot, Algorand, Cardano, Tezos

Example: register a Slack connector

// Get a pre-built Slack driver config
var slackConfigs = ConnectionHelper.GetCommunicationConfigs();
var slackDriver  = slackConfigs.First(c => c.DatasourceType == DataSourceType.Slack);

// Register a Slack connection
dmeEditor.ConfigEditor.AddDataConnection(new ConnectionProperties
{
    ConnectionName = "SlackWorkspace",
    DatabaseType   = DataSourceType.Slack,
    DriverName     = slackDriver.PackageName,
    ApiKey         = Environment.GetEnvironmentVariable("SLACK_BOT_TOKEN")
});

var slack = dmeEditor.GetDataSource("SlackWorkspace");
slack.Openconnection();

Liveness & Test Connection

Two classes handle connection health checks at different lifecycle stages:

  • ProxyLivenessHelper — tests a live, already-open IDataSource using the cheapest strategy for its category (ping query, metadata call, or connection-state check). Used by the proxy/watchdog subsystem.
  • TestConnectionHelper — async setup-time test against a ConnectionDriversConfig object before a connection is registered (e.g., during the connection wizard UI).

Probe strategy by category

// ProxyLivenessHelper — called by proxy and watchdog internally
bool alive = ProxyLivenessHelper.IsAlive(ds, timeoutMs: 3_000);
// Strategy selected by ds.Category:
//  RDBMS      → cheapest engine-specific ping query (SELECT 1, etc.)
//  NoSQL      → GetEntitesList (metadata)
//  FILE       → GetEntitesList
//  WEBAPI     → GetEntitesList (HEAD request equivalent)
//  CLOUD      → GetEntitesList
//  VectorDB   → GetEntitesList
//  IoT/Stream/Queue/Blockchain/Connector → ConnectionState signal
//  INMEMORY   → alive unless ConnectionState == Broken
//  default    → ConnectionState signal

TestConnectionHelper — async liveness via IDataSource

// Tests a live DMEEditor-managed datasource
var ds = dmeEditor.GetDataSource("MyDb");
ds.Openconnection();

var (ok, msg) = await TestConnectionHelper.TestConnectionAsync(ds);
Console.WriteLine($"{ok}: {msg}");
// "True: MyDb (RDBMS) is alive"

TestConnectionHelper — setup-time config test

// Test a NEW connection config before registering it
var config = new ConnectionDriversConfig
{
    DatasourceCategory = DatasourceCategory.RDBMS,
    DatasourceType     = DataSourceType.SqlServer,
    ConnectionString   = "Server=localhost;Database=test;Trusted_Connection=True"
};

var (ok, msg) = await TestConnectionHelper.TestConnectionAsync(config, timeout: 10);
if (!ok)
    MessageBox.Show($"Cannot connect: {msg}");
else
    dmeEditor.ConfigEditor.AddDataConnection(myConnectionProps);
Never throws

Both helpers catch all exceptions internally and map them to (false, message). It is safe to call them without a try-catch.

DataTypesHelpers Overview

The DataTypesHelpers subsystem (namespace TheTechIdea.Beep.Helpers.DataTypesHelpers) handles all bidirectional mapping between database-native type names and .NET System.* types. It was refactored from a 2,000-line monolith into a layered set of helpers:

Source of truth (2026)
  • Facade: DataTypesHelpers/DataTypeFieldMappingHelper.cs — delegates to all sub-helpers
  • Service class: DataTypesHelpers/DataTypesHelper.cs — injectable IDataTypesHelper
  • Basic ops: DataTypesHelpers/DataTypeBasicOperations.cs
  • Lookup logic: DataTypesHelpers/DataTypeMappingLookup.cs
  • Repository: DataTypesHelpers/DataTypeMappingRepository.cs
  • Reflection util: DataTypesHelpers/TypeHelper.cs
  • Per-DB mappings: DataTypesHelpers/DatabaseTypeMappingRepositories/*.cs (26 files)
Class inventory
ClassTypeRole
DataTypeFieldMappingHelperstatic partialPublic facade — every method delegates to a specialist
DataTypesHelperclass : IDataTypesHelperInjectable service with ConcurrentDictionary caches; registered by DI
DataTypeBasicOperationsstatic.NET type constant strings, GetNetDataTypes, custom converter, field validation
DataTypeMappingLookupstaticCore resolution: net-type → db-type and db-type → net-type; internal caches + regex
DataTypeMappingRepositorystaticReads DataTypesMap from ConfigEditor; resolves by DS name or DataSourceType
DatabaseTypeMappingRepositorystatic partial26 partial files — one per DB family — each with a Generate*DataTypesMapping() method
TypeHelperstaticExtension methods for constructor-based reflection instantiation (1-, 2-, 3-arg overloads)

DataTypesHelper (IDataTypesHelper)

DataTypesHelper is the injectable service class registered with the DI container. It wraps the static helpers with ConcurrentDictionary caches and pre-loads mappings for the most common databases on first use.

Constructor & properties

// Namespace: TheTechIdea.Beep.Helpers
public class DataTypesHelper : IDataTypesHelper
{
    public DataTypesHelper(IDMEEditor pDMEEditor);

    public IDMEEditor DMEEditor         { get; set; }
    public List<DatatypeMapping> mapping { get; set; }
    public int DefaultStringSize        { get; set; }  // default 250
}

Resolving types via the service

// Obtain via DI or DMEEditor
var dt = dmeEditor.GetService<IDataTypesHelper>();
// or: new DataTypesHelper(dmeEditor)

// Look up the .NET type for a SQL Server "nvarchar" column
string netType = DataTypeFieldMappingHelper.GetDataType(
    "Northwind",            // DS connection name
    "nvarchar",             // provider type string
    dmeEditor
);
// => "System.String"

// Look up using an EntityField (reads fld.fieldtype)
string netType2 = DataTypeFieldMappingHelper.GetDataType(
    "Northwind", myField, dmeEditor
);

DataTypeBasicOperations

Provides constant .NET type name collections, a custom-converter hook, and field-mapping validation.

Signatures

// Short alias names: "byte, sbyte, int, uint, short, ..."
public static string[] GetNetDataTypes();

// Fully qualified names: "System.Byte[], System.Int32, ..."
public static string[] GetNetDataTypes2();

// Apply a custom converter on top of the resolved .NET type
public static string GetCustomDataType(
    string DSname, EntityField fld, IDMEEditor DMEEditor,
    Func<string, string> customTypeConverter);

// Returns true when a mapping entry exists for (DSname, fld)
public static bool IsValidFieldMapping(
    string DSname, EntityField fld, IDMEEditor DMEEditor);

Example: populate a type picker

// Short names for UI dropdowns
string[] shortNames = DataTypeFieldMappingHelper.GetNetDataTypes();
// ["bool", "byte", "char", "DateTime", "decimal", ...]

// Fully qualified for reflection / IL emission
string[] fullNames = DataTypeFieldMappingHelper.GetNetDataTypes2();
// ["System.Boolean", "System.Byte", ...]

// Custom mapping — e.g. map System.Decimal to "money" for display
string displayType = DataTypeFieldMappingHelper.GetCustomDataType(
    "Northwind", amountField, dmeEditor,
    netType => netType == "System.Decimal" ? "money" : netType
);
.NET type constants
GetNetDataTypes()GetNetDataTypes2()
byte, sbyte, int, uintSystem.Byte, System.SByte, System.Int32, System.UInt32
short, ushort, long, ulongSystem.Int16, System.UInt16, System.Int64, System.UInt64
float, double, decimalSystem.Single, System.Double, System.Decimal
char, bool, object, stringSystem.Char, System.Boolean, System.Object, System.String
DateTimeSystem.DateTime, System.TimeSpan, System.DateTimeOffset, System.Guid, System.Xml

DataTypeMappingLookup

Core resolution engine with thread-safe ConcurrentDictionary caches and compiled Regex patterns for stripping length/precision tokens ((N), (P,S)) before matching.

Key signatures

// Resolve DB provider type name -> .NET type string
public static string GetDataType(
    string DSname, string providerfldtype, IDMEEditor DMEEditor);

// Resolve via EntityField (uses fld.fieldtype)
public static string GetDataType(
    string DSname, EntityField fld, IDMEEditor DMEEditor);

// Resolve using the class handler name instead of DS connection name
public static string GetDataTypeFromDataSourceClassName(
    string className, EntityField fld, IDMEEditor DMEEditor);

// Full DatatypeMapping record (includes Fav flag, size placeholders)
public static DatatypeMapping GetDataTypeMappingForString(
    string className, string Fieldtype, EntityField fld, IDMEEditor DMEEditor);

Resolution details

// Provider type with precision stripped before lookup
// e.g. "decimal(18,4)" -> matches "decimal" mapping -> "System.Decimal"
string t = DataTypeMappingLookup.GetDataType(
    "Northwind", "decimal(18,4)", dmeEditor);
// => "System.Decimal"

// Full mapping record (useful when you need DbType, size placeholders, Fav flag)
var mapping = DataTypeMappingLookup.GetDataTypeMappingForString(
    "SQLServerDataSource", "System.String", nameField, dmeEditor);
Console.WriteLine(mapping?.DataType);   // e.g. "nvarchar"
Console.WriteLine(mapping?.Fav);        // preferred mapping = true
Lookup cache keys

Cache key format: "{className}|{Fieldtype}|{fld.Size1}". The cache is static and process-wide — entries are never evicted, making repeated lookups essentially free.

DataTypeMappingRepository

Reads the DataTypesMap list from IConfigEditor (loaded from DataTypeMapping.json at startup) and filters it by data-source name or DataSourceType enum.

Signatures

// By connection name (resolves classHandler via DMEEditor)
public static List<DatatypeMapping> GetDataTypes(
    string DSname, IDMEEditor DMEEditor);

// By DataSourceType enum (looks up classHandler in DataDriversClasses)
public static List<DatatypeMapping> GetDataTypes(
    DataSourceType DSname, IDMEEditor DMEEditor);

Usage

// All mappings for a live connection
var mappings = DataTypeMappingRepository.GetDataTypes("Northwind", dmeEditor);

// All mappings for SQL Server (by enum, no connection needed)
var sqlMappings = DataTypeMappingRepository.GetDataTypes(
    DataSourceType.SqlServer, dmeEditor);

foreach (var m in sqlMappings)
    Console.WriteLine($"{m.DataType,20} -> {m.NetDataType}");

DataTypeFieldMappingHelper (Facade)

DataTypeFieldMappingHelper is the recommended entry point for all type-mapping calls. It simply re-exports every method from the three sub-helpers so callers don't need to know which specialist class handles a given operation.

Full public API

// ── .NET types ──────────────────────────────────────────────────────
string[] DataTypeFieldMappingHelper.GetNetDataTypes();          // short aliases
string[] DataTypeFieldMappingHelper.GetNetDataTypes2();         // fully qualified

// ── DB provider type -> .NET type ───────────────────────────────────
string GetDataType(string DSname, string providerType, IDMEEditor dme);
string GetDataType(string DSname, EntityField fld, IDMEEditor dme);
string GetDataTypeFromDataSourceClassName(string className, EntityField fld, IDMEEditor dme);

// ── Full DatatypeMapping record ──────────────────────────────────────
DatatypeMapping GetDataTypeMappingForString(
    string className, string Fieldtype, EntityField fld, IDMEEditor dme);

// ── Repository queries ───────────────────────────────────────────────
List<DatatypeMapping> GetDataTypes(string DSname, IDMEEditor dme);
List<DatatypeMapping> GetDataTypes(DataSourceType DSname, IDMEEditor dme);

// ── Utilities ────────────────────────────────────────────────────────
string GetFieldTypeNoConversion(string DSname, EntityField fld, IDMEEditor dme);
string GetCustomDataType(string DSname, EntityField fld, IDMEEditor dme,
    Func<string, string> customTypeConverter);
bool   IsValidFieldMapping(string DSname, EntityField fld, IDMEEditor dme);

Per-Database Mapping Repositories

Each file in DatabaseTypeMappingRepositories/ is a partial class of DatabaseTypeMappingRepository that exposes a single Generate*DataTypesMapping() method returning List<DatatypeMapping>. These lists are merged into DataTypeMapping.json at build time.

Mapping file inventory
FileDatabases coveredMethod
...SqlServer.csSQL Server (SQLServerDataSource)GenerateSqlServerDataTypesMapping()
...Common.csSQLite, SQL Compact, DuckDBGenerateSQLiteDataTypesMapping(), etc.
...PostgreMySQL.csPostgreSQL, MySQLGeneratePostgreSQLDataTypesMapping(), GenerateMySQLDataTypesMapping()
...FirebirdLiteDB.csFirebird, LiteDBGenerateFirebirdDataTypesMapping(), GenerateLiteDBDataTypesMapping()
...NoSQL.csMongoDB, Cassandra, RedisGenerateMongoDBDataTypesMapping(), etc.
...Enterprise.csDB2, DynamoDB, InfluxDB, Sybase, HBase, CockroachDBGenerateDB2DataTypesMapping(), etc.
...Cloud.csSnowflake, Azure Cosmos DB, Vertica, Teradata, ArangoDB, BerkeleyDBGenerateSnowflakeDataTypesMapping(), etc.
...Services.csFirebase, Supabase, CouchDB, CouchbaseGenerateFirebaseDataTypesMapping(), etc.
...Vector.csPinecone, Qdrant, ShapVector, Weaviate, Milvus, RedisVector, Zilliz, Vespa, ChromaDBGeneratePineconeDataTypesMapping(), etc.
...Modern.csClickHouse, Neo4j, TimescaleDB, ElasticsearchGenerateClickHouseDataTypesMapping(), etc.
...BigData.csHadoop/Hive, Spark, Presto, Trino, Delta LakeGenerateHiveDataTypesMapping(), etc.
...Analytics.csRedshift, BigQuery, Azure Synapse, DatabricksGenerateRedshiftDataTypesMapping(), etc.
...CloudPlatforms.csAWS Athena, Azure Data Lake, GCP SpannerGenerateAthenaDataTypesMapping(), etc.
...FileFormats.csCSV, JSON, Parquet, Avro, ORC, ExcelGenerateCSVDataTypesMapping(), etc.
...Graph.csNeo4j, TigerGraph, JanusGraphGenerateNeo4jDataTypesMapping(), etc.
...Streaming.csKafka, Kinesis, PulsarGenerateKafkaDataTypesMapping(), etc.
...IoT.csInfluxDB IoT, TimescaleDB IoT, AWS IoTGenerateInfluxDBIoTDataTypesMapping(), etc.
...MachineLearning.csONNX, TensorFlow Serving, MLflowGenerateONNXDataTypesMapping(), etc.
...Search.csElasticsearch, Solr, OpenSearchGenerateElasticsearchDataTypesMapping(), etc.
...CRM.csSalesforce, HubSpot, Dynamics 365GenerateSalesforceDataTypesMapping(), etc.
...SocialMedia.csTwitter, LinkedIn, Facebook GraphGenerateTwitterDataTypesMapping(), etc.
...PaymentGateways.csStripe, PayPal, BraintreeGenerateStripeDataTypesMapping(), etc.
...Accounting.csQuickBooks, Xero, SageGenerateQuickBooksDataTypesMapping(), etc.
...Protocols.csODBC, OLE DB, ADO, gRPC, GraphQLGenerateODBCDataTypesMapping(), etc.
...WorkflowIoT.csAzure Logic Apps, AWS Step Functions, Node-REDGenerateLogicAppsDataTypesMapping(), etc.

How mappings get into DataTypeMapping.json

// At build/seed time — collect all partial-class mappings
var allMappings = new List<DatatypeMapping>();
allMappings.AddRange(DatabaseTypeMappingRepository.GenerateSqlServerDataTypesMapping());
allMappings.AddRange(DatabaseTypeMappingRepository.GeneratePostgreSQLDataTypesMapping());
allMappings.AddRange(DatabaseTypeMappingRepository.GenerateMySQLDataTypesMapping());
// ... repeat for every Generate* method ...

// Persist to the config file
var json = System.Text.Json.JsonSerializer.Serialize(allMappings);
File.WriteAllText(Path.Combine(configPath, "DataTypeMapping.json"), json);

SQL Server type map sample

// From DatabaseTypeMappingRepository.SqlServer.cs
// DataSourceName must exactly match the classHandler value in ConnectionDriversConfig
new DatatypeMapping { DataType="bigint",    DataSourceName="SQLServerDataSource", NetDataType="System.Int64"   },
new DatatypeMapping { DataType="bit",       DataSourceName="SQLServerDataSource", NetDataType="System.Boolean" },
new DatatypeMapping { DataType="decimal",   DataSourceName="SQLServerDataSource", NetDataType="System.Decimal" },
new DatatypeMapping { DataType="nvarchar",  DataSourceName="SQLServerDataSource", NetDataType="System.String",  Fav=false },
new DatatypeMapping { DataType="datetime2", DataSourceName="SQLServerDataSource", NetDataType="System.DateTime" },
new DatatypeMapping { DataType="uniqueidentifier", DataSourceName="SQLServerDataSource", NetDataType="System.Guid" },
Adding a new database
  1. Create DatabaseTypeMappingRepository.YourDB.cs as a partial class.
  2. Add a GenerateYourDBDataTypesMapping() method returning List<DatatypeMapping>.
  3. Set DataSourceName to the classHandler value from the driver's ConnectionDriversConfig.
  4. Run the seed step (or add the method call to the existing seed loop) to regenerate DataTypeMapping.json.

TypeHelper

Extension methods on System.Type for creating instances via compiled expression trees — much faster than Activator.CreateInstance for hot paths (entity deserialization, driver instantiation).

Signatures

// No-arg constructor
object GetInstance(this Type type);

// Single-arg constructor
object GetInstance<TArg>(this Type type, TArg argument);

// Two-arg constructor
object GetInstance<TArg1, TArg2>(this Type type, TArg1 arg1, TArg2 arg2);

// Three-arg constructor
object GetInstance<TArg1, TArg2, TArg3>(
    this Type type, TArg1 arg1, TArg2 arg2, TArg3 arg3);

Usage

// Create a data source instance by type (used by AssemblyHandler)
Type dsType = loadedAssembly.GetType("TheTechIdea.Beep.SQLite.SQLiteDataSource");
var ds = (IDataSource)dsType.GetInstance(
    "myConnection",    // string datasourcename
    logger,            // IDMLogger
    dmeEditor          // IDMEEditor
);

// Equivalent to:
// new SQLiteDataSource("myConnection", logger, dmeEditor)

RDBMSHelpers Overview

The RDBMSHelpers group provides a comprehensive toolkit for interacting with relational databases across more than twenty database platforms. All public API surfaces are exposed through two static facade classes — RDBMSHelper and DatabaseDMLHelper — which delegate to focused, single-responsibility helpers.

Source location DataManagementEngineStandard/Helpers/RDBMSHelpers/
FileClassResponsibility
RDBMSHelper.csRDBMSHelperTop-level facade — schema, metadata, DDL
DatabaseFeatureHelper.csDatabaseFeatureHelperFeature flags, sequence / identity queries
DatabaseSchemaQueryHelper.csDatabaseSchemaQueryHelperPer-RDBMS schema discovery SQL
DatabaseObjectCreationHelper.csDatabaseObjectCreationHelperCREATE TABLE, PK, INDEX, DROP DDL
DatabaseQueryRepositoryHelper.csDatabaseQueryRepositoryHelperCached pre-built query repository
DMLHelpers/DatabaseDMLHelper.csDatabaseDMLHelperDML facade — INSERT, UPDATE, DELETE, SELECT
DMLHelpers/DatabaseDMLBasicOperations.csDatabaseDMLBasicOperationsBasic INSERT / UPDATE / DELETE
DMLHelpers/DatabaseDMLBulkOperations.csDatabaseDMLBulkOperationsBulk insert, upsert, bulk delete
DMLHelpers/DatabaseDMLAdvancedQueryGenerator.csDatabaseDMLAdvancedQueryGeneratorSELECT, JOIN, aggregation, window functions
DMLHelpers/DatabaseDMLParameterizedQueries.csDatabaseDMLParameterizedQueriesParameterized INSERT / UPDATE / DELETE
DMLHelpers/DatabaseDMLSpecificHelpers.csDatabaseDMLSpecificHelpersEngine-specific SQL quirks
DMLHelpers/DatabaseDMLUtilities.csDatabaseDMLUtilitiesFormatting, quoting, escaping utilities
EntityHelpers/DatabaseEntityHelper.csDatabaseEntityHelperEntity facade — SQL gen, validation, analysis
EntityHelpers/DatabaseEntitySqlGenerator.csDatabaseEntitySqlGeneratorSQL generation from EntityStructure
EntityHelpers/DatabaseEntityValidator.csDatabaseEntityValidatorEntity structural validation
EntityHelpers/DatabaseEntityNamingValidator.csDatabaseEntityNamingValidatorIdentifier naming rules per RDBMS
EntityHelpers/DatabaseEntityReservedKeywordChecker.csDatabaseEntityReservedKeywordCheckerReserved keyword detection
EntityHelpers/DatabaseEntityAnalyzer.csDatabaseEntityAnalyzerCompatibility info, improvement suggestions
EntityHelpers/DatabaseEntityTypeHelper.csDatabaseEntityTypeHelperEntityField factory helpers

DatabaseFeatureHelper

Provides enumerations for optional database capabilities and utility methods for generating engine-specific sequence / identity SQL.

Enumerations

EnumMembers
DatabaseFeature WindowFunctions, Json, Xml, TemporalTables, FullTextSearch, Partitioning, ColumnStore
TransactionOperation Begin, Commit, Rollback

Sequence Queries

MethodReturnsDescription
GenerateFetchNextSequenceValueQuery(DataSourceType, string sequenceName) string Returns engine-specific SQL to fetch the next sequence value (SELECT NEXT VALUE FOR, SELECT nextval(…), SELECT seq.NEXTVAL FROM dual, etc.)
GenerateFetchLastIdentityQuery(DataSourceType, string sequenceName = "") string Returns engine-specific last-inserted identity SQL (SCOPE_IDENTITY(), LAST_INSERT_ID(), LASTVAL(), currval(…), etc.)

Per-Engine Reference

EngineNext Sequence ValueLast Identity
SQL ServerSELECT NEXT VALUE FOR {seq}SELECT SCOPE_IDENTITY()
MySQL—SELECT LAST_INSERT_ID()
PostgreSQLSELECT nextval('{seq}')SELECT LASTVAL()
FirebirdSELECT NEXT VALUE FOR {seq} FROM RDB$DATABASESELECT GEN_ID({gen},0) FROM RDB$DATABASE
DB2SELECT NEXTVAL FOR {seq} FROM sysibm.sysdummy1SELECT IDENTITY_VAL_LOCAL() FROM sysibm.sysdummy1
// Get next sequence value for PostgreSQL
string sql = DatabaseFeatureHelper.GenerateFetchNextSequenceValueQuery(
    DataSourceType.Postgre, "order_id_seq");
// → "SELECT nextval('order_id_seq')"

// Get last identity value for SQL Server
string idSql = DatabaseFeatureHelper.GenerateFetchLastIdentityQuery(
    DataSourceType.SqlServer);
// → "SELECT SCOPE_IDENTITY()"

Schema & Metadata Queries

DatabaseSchemaQueryHelper and the corresponding methods on RDBMSHelper generate engine-specific SQL for discovering schemas/databases and inspecting table structure.

Facade Methods (RDBMSHelper)

MethodReturnsDescription
GetSchemasorDatabases(DataSourceType, string userName) string Returns the raw SQL to list accessible schemas/databases for the given user.
GetSchemasorDatabasesSafe(DataSourceType, string userName, bool throwOnError) (string Query, bool Success, string ErrorMessage) Safe wrapper — returns a result tuple; never throws unless throwOnError is true.
ValidateSchemaQuery(DataSourceType, string userName, string query) QueryValidationResult Validates a schema query against the known pattern for the specified engine.
GetTableExistsQuery(DataSourceType, string tableName, string schemaName) string Returns SQL that returns a row if the named table exists (used for pre-flight checks).
GetColumnInfoQuery(DataSourceType, string tableName, string schemaName) string Returns SQL that lists columns and their metadata for the specified table.

Schema Discovery SQL — Per Engine

EngineGenerated SQL
SQL Server / AzureSQL / AWSRDSSELECT name FROM sys.databases WHERE HAS_DBACCESS(name)=1 ORDER BY name
MySQLSELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME IN (SELECT DISTINCT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLE_PRIVILEGES WHERE GRANTEE='‘{user}’')
PostgreSQLSELECT datname FROM pg_database WHERE datistemplate=false AND has_database_privilege('{user}',datname,'CONNECT')
DB2SELECT DISTINCT SCHEMANAME FROM SYSCAT.SCHEMAAUTH WHERE GRANTEE='{user}'
SQLitePRAGMA database_list;
FirebirdSELECT RDB$DATABASE_NAME FROM RDB$DATABASE
SnowflakeSHOW DATABASES
SAP HANASELECT SCHEMA_NAME FROM SCHEMAS WHERE HAS_PRIVILEGES_ON_SCHEMA(…)='TRUE'
BigQuerySELECT schema_name FROM INFORMATION_SCHEMA.SCHEMATA
RedshiftSELECT DISTINCT schemaname FROM pg_tables
AthenaSHOW DATABASES
// Safe version — no exception on unsupported engine
var (sql, ok, err) = RDBMSHelper.GetSchemasorDatabasesSafe(
    DataSourceType.Postgre, "appuser");
if (ok)
    await connection.ExecuteAsync(sql);

// Quick table-exists check
string existsQuery = RDBMSHelper.GetTableExistsQuery(
    DataSourceType.SqlServer, "Orders", "dbo");

DDL Generation

DatabaseObjectCreationHelper generates data-definition SQL (CREATE TABLE, primary keys, indexes, DROP) from EntityStructure instances or explicit parameters.

Table Creation

MethodReturnsDescription
GenerateCreateTableSQL(EntityStructure) (string Sql, bool Success, string ErrorMessage) Builds a full CREATE TABLE statement from the entity's fields, types, and constraints.

Primary Key

MethodReturnsDescription
GeneratePrimaryKeyQuery(DataSourceType, string tableName, string primaryKey, string type) string Returns anALTER TABLE … ADD … PRIMARY KEY statement with the engine-correct auto-increment syntax (IDENTITY, AUTO_INCREMENT, GENERATED ALWAYS AS IDENTITY, AUTOINCREMENT).
GeneratePrimaryKeyFromEntity(EntityStructure) (string Sql, bool Success, string ErrorMessage) Iterates all key fields on the entity and combines primary key ALTER statements into one string.

Indexes

MethodReturnsDescription
GenerateCreateIndexQuery(DataSourceType, string tableName, string indexName, string[] columns, Dictionary<string,object> options) string Generates CREATE [UNIQUE] INDEX SQL. Pass {"unique",true} in options for uniqueness.
GenerateUniqueIndexFromEntity(EntityStructure) (string Sql, bool Success, string ErrorMessage) Generates unique-index SQL for every field with IsUnique = true in the entity.
// CREATE TABLE from an EntityStructure
var (createSql, ok, err) = DatabaseObjectCreationHelper.GenerateCreateTableSQL(entity);
if (!ok) Console.WriteLine(err);

// ADD PRIMARY KEY — SQL Server style
string pkSql = DatabaseObjectCreationHelper.GeneratePrimaryKeyQuery(
    DataSourceType.SqlServer, "Orders", "OrderId", "INT");
// → "ALTER TABLE Orders ADD OrderId INT PRIMARY KEY IDENTITY"

// ADD PRIMARY KEY from entity (multi-key aware)
var (pkFromEntity, success, msg) =
    DatabaseObjectCreationHelper.GeneratePrimaryKeyFromEntity(entity);

// CREATE UNIQUE INDEX
string idxSql = DatabaseObjectCreationHelper.GenerateCreateIndexQuery(
    DataSourceType.Postgre, "Orders", "idx_orders_customer",
    new[] { "CustomerId", "OrderDate" });

Query Repository

DatabaseQueryRepositoryHelper provides a static, lazily-initialized cache of pre-built SQL queries keyed by (DataSourceType, Sqlcommandtype). The cache is populated at class-initialisation time from CreateQuerySqlRepos().

API

MethodReturnsDescription
GetQuery(DataSourceType, Sqlcommandtype) string Returns the cached SQL for the specified DB + command type, or string.Empty if absent.
GetQueriesForDatabase(DataSourceType) Dictionary<Sqlcommandtype, string> Returns all pre-built queries available for one database type.
GetDatabasesForQueryType(Sqlcommandtype) List<DataSourceType> Lists every database type that has a pre-built query of the specified command type.
QueryExists(DataSourceType, Sqlcommandtype) bool Fast lookup — returns true if the (DB, type) combination has a cached query.
IsSqlStatementValid(string) bool Checks whether a string contains at least one recognised SQL keyword (SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, DROP, SHOW, PRAGMA, etc.).
// Check if a pre-built query exists, then fetch it
if (DatabaseQueryRepositoryHelper.QueryExists(
        DataSourceType.SqlServer, Sqlcommandtype.getTable))
{
    string sql = DatabaseQueryRepositoryHelper.GetQuery(
        DataSourceType.SqlServer, Sqlcommandtype.getTable);
}

// Get all pre-built queries for MySQL
var mysqlQueries = DatabaseQueryRepositoryHelper.GetQueriesForDatabase(
    DataSourceType.Mysql);

// Basic validation guard before executing user-supplied SQL
bool valid = DatabaseQueryRepositoryHelper.IsSqlStatementValid(userInputSql);

DML Helpers

DatabaseDMLHelper is the top-level DML facade. It exposes all data-manipulation query generators without requiring callers to know which specialised sub-class to use. All methods are static.

Basic Operations

MethodReturnsDescription
GenerateInsertQuery(DataSourceType, string tableName, Dictionary<string,object> data) string Generates an INSERT statement with inline values for the specified engine.
GenerateUpdateQuery(DataSourceType, string tableName, Dictionary<string,object> data, Dictionary<string,object> conditions) string Generates an UPDATE … SET … WHERE statement.
GenerateDeleteQuery(DataSourceType, string tableName, Dictionary<string,object> conditions) string Generates a DELETE FROM … WHERE statement.

Bulk Operations

MethodReturnsDescription
GenerateBulkInsertQuery(DataSourceType, string tableName, IEnumerable<string> columns, int batchSize = 1000) string Generates optimised bulk-insert SQL; uses engine-specific multi-row INSERT syntax where available.
GenerateUpsertQuery(DataSourceType, string tableName, IEnumerable<string> keyColumns, IEnumerable<string> updateColumns, IEnumerable<string> insertColumns) string Generates a MERGE / INSERT ON CONFLICT / INSERT OR REPLACE statement depending on the engine.
GenerateBulkDeleteQuery(DataSourceType, string tableName, string keyColumn, int batchSize = 1000) string Generates a batched DELETE using an IN-clause with the specified batch size.

Advanced Query Generation

MethodReturnsDescription
GenerateSelectQuery(DataSourceType, string tableName, IEnumerable<string> columns, string whereClause, string orderBy, int? pageNumber, int? pageSize) string Generates a SELECT with optional filtering, ordering, and offset-based pagination.
GenerateJoinQuery(DataSourceType, JoinSpecification) string Builds a multi-table JOIN query from a JoinSpecification descriptor.
GenerateAggregationQuery(DataSourceType, string tableName, IEnumerable<string> selectColumns, IEnumerable<string> groupByColumns, string havingClause, string whereClause) string Generates a GROUP BY / HAVING aggregation query.
GenerateWindowFunctionQuery(DataSourceType, string tableName, WindowFunctionSpec) string Generates OVER (PARTITION BY … ORDER BY …) window-function SQL for supporting engines.
GenerateConditionalInsertQuery(DataSourceType, string tableName, IEnumerable<string> columns, IEnumerable<string> values, IEnumerable<string> conflictColumns) string INSERT IF NOT EXISTS — uses engine-specific conditional insert syntax.
GenerateExistsQuery(DataSourceType, string mainTable, string subqueryTable, string joinCondition) string Generates an optimised EXISTS subquery, preferred over IN for large datasets.

Parameterized Queries

MethodReturnsDescription
GenerateParameterizedInsertQuery(DataSourceType, string tableName, IEnumerable<string> columns) string INSERT with engine-correct parameter placeholders (@param, :param, ?).
GenerateParameterizedUpdateQuery(DataSourceType, string tableName, IEnumerable<string> updateColumns, IEnumerable<string> whereColumns) string UPDATE … SET with parameterized SET and WHERE clauses.
GenerateParameterizedDeleteQuery(DataSourceType, string tableName, IEnumerable<string> whereColumns) string DELETE FROM with parameterized WHERE clause.
// Basic INSERT
string insertSql = DatabaseDMLHelper.GenerateInsertQuery(
    DataSourceType.Mysql, "Orders",
    new Dictionary<string, object> { ["CustomerId"] = 42, ["Total"] = 99.99 });

// Paginated SELECT
string pageSql = DatabaseDMLHelper.GenerateSelectQuery(
    DataSourceType.Postgre, "Orders",
    columns: new[] { "Id", "CustomerId", "Total" },
    whereClause: "Total > 50",
    orderBy: "Id",
    pageNumber: 2, pageSize: 25);

// Parameterized INSERT — safe against SQL injection
string paramSql = DatabaseDMLHelper.GenerateParameterizedInsertQuery(
    DataSourceType.SqlServer, "Orders",
    new[] { "CustomerId", "Total", "CreatedAt" });
// SQL Server → INSERT INTO Orders (CustomerId, Total, CreatedAt)
//              VALUES (@CustomerId, @Total, @CreatedAt)

// UPSERT
string upsertSql = DatabaseDMLHelper.GenerateUpsertQuery(
    DataSourceType.Postgre, "Products",
    keyColumns:    new[] { "Id" },
    updateColumns: new[] { "Name", "Price" },
    insertColumns: new[] { "Id", "Name", "Price" });

Entity Helpers

DatabaseEntityHelper is the facade for all entity-oriented operations — SQL generation from EntityStructure, structural validation, quality analysis, and field-factory helpers. It delegates to specialised sub-classes.

SQL Generation (via DatabaseEntitySqlGenerator)

MethodReturnsDescription
GenerateInsertWithValues(EntityStructure, Dictionary<string,object> values) (string Sql, Dictionary<string,object> Parameters, bool Success, string ErrorMessage) Generates a parameterized INSERT and returns both the SQL and the parameter dictionary, ready for execution.
GenerateUpdateEntityWithValues(EntityStructure, Dictionary<string,object> values, Dictionary<string,object> conditions) (string Sql, bool Success, string ErrorMessage) Generates an UPDATE statement using the entity's field metadata and the supplied values and conditions.
GenerateDeleteEntityWithValues(EntityStructure, Dictionary<string,object> values) (string Sql, bool Success, string ErrorMessage) Generates a DELETE statement driven by the entity schema and the provided key values.

Validation (via DatabaseEntityValidator)

MethodReturnsDescription
ValidateEntityStructure(EntityStructure) (bool IsValid, List<string> ValidationErrors) Checks entity name, field definitions, primary keys, data types, and nullability rules. Returns a structured error list so callers can surface specific problems.

Analysis (via DatabaseEntityAnalyzer)

MethodReturnsDescription
GetEntityCompatibilityInfo(EntityStructure) Dictionary<string,object> Returns a dictionary of compatibility flags per database engine (e.g. which engines support all types used in the entity).
SuggestEntityImprovements(EntityStructure) List<string> Analyses the entity and returns a list of human-readable improvement suggestions (missing primary key, over-long strings, no index on FK columns, etc.).
GetEntityStatistics(EntityStructure) Dictionary<string,object> Returns field count, key count, nullable count, unique-field count, and other structural statistics.

Field Factory (via DatabaseEntityTypeHelper)

MethodReturnsDescription
CreateBasicField(string FieldName, string Fieldtype, bool allowNull = true, bool isKey = false) EntityField Creates an EntityField with sensible defaults. Use when programmatically building entity structures.
// Validate before persisting schema changes
var (isValid, errors) = DatabaseEntityHelper.ValidateEntityStructure(entity);
if (!isValid)
    foreach (var e in errors) Console.WriteLine(e);

// Generate a parameterized INSERT and execute it
var (sql, parameters, ok, err) = DatabaseEntityHelper.GenerateInsertWithValues(
    entity,
    new Dictionary<string, object>
    {
        ["CustomerId"] = 42,
        ["OrderDate"] = DateTime.UtcNow,
        ["Total"] = 199.99
    });
if (ok)
    await connection.ExecuteAsync(sql, parameters);

// Get improvement suggestions for a schema review
var suggestions = DatabaseEntityHelper.SuggestEntityImprovements(entity);
foreach (var suggestion in suggestions)
    Console.WriteLine(suggestion);

// Build a field programmatically
var pk = DatabaseEntityHelper.CreateBasicField("OrderId", "INT", allowNull: false, isKey: true);
entity.Fields.Add(pk);

UniversalDataSourceHelpers Overview

The UniversalDataSourceHelpers framework is the next-generation abstraction layer for BeepDM, replacing the RDBMS-only legacy helpers with a datasource-agnostic pattern that covers 40+ datasource types through a single consistent interface.

Source location DataManagementEngineStandard/Helpers/UniversalDataSourceHelpers/

Folder Map

Folder / FileClass(es)Purpose
Core/DataSourceHelperFactory.csDataSourceHelperFactoryCreates the correct IDataSourceHelper for any DataSourceType
Core/GeneralDataSourceHelper.csGeneralDataSourceHelperRuntime delegate wrapper — picks the right helper and forwards all calls
Core/DefaultDataSourceHelper.csDefaultDataSourceHelperFallback helper for unknown / unregistered datasource types
RdbmsHelpers/RdbmsHelper.csRdbmsHelperUnified RDBMS helper (SQL Server, MySQL, PostgreSQL, SQLite, Firebird, …)
MongoDBHelpers/MongoDBHelper.csMongoDBHelperMongoDB, CouchDB, RavenDB, Couchbase, ArangoDB, Firebase, DynamoDB
RedisHelpers/RedisHelper.csRedisHelperRedis, Memcached, Hazelcast, GridGain, ApacheIgnite, in-memory caches
CassandraHelpers/CassandraHelper.csCassandraHelperCassandra, ClickHouse (column-family)
GraphHelpers/GraphDbHelper.csGraphDbHelperNeo4j, TigerGraph, JanusGraph
SearchHelpers/SearchEngineHelper.csSearchEngineHelperElasticsearch, Solr
TimeSeriesHelpers/TimeSeriesHelper.csTimeSeriesHelperInfluxDB, TimeScale
VectorHelpers/VectorDbHelper.csVectorDbHelperPinecone, Qdrant, Weaviate, Milvus, Zilliz, Vespa, RedisVector, …
StreamingHelpers/StreamingHelper.csStreamingHelperKafka, Kinesis, EventHub, Pulsar, RabbitMQ
FileHelpers/FileFormatHelper.csFileFormatHelperCSV, JSON, XML, Parquet, Avro, ORC, Excel file-based sources
Analysis/RelationshipInferencer.csRelationshipInferencerInfers One-to-One / One-to-Many / Many-to-Many from POCO type graphs
Analysis/NavigationPropertyDetector.csNavigationPropertyDetectorDetects collection vs. single-reference navigation properties
Conversion/PocoToEntityConverter.csPocoToEntityConverterConverts C# POCO classes → EntityStructure with DataAnnotations support
Mapping/RelationshipToEntityMapper.csRelationshipToEntityMapperMaps inferred relationships onto EntityStructure relation fields

IDataSourceHelper Interface

Every datasource helper implements IDataSourceHelper. Callers code against this interface and never need to reference a specific helper class directly.

Identity & Capabilities

MemberTypeDescription
SupportedTypeDataSourceTypeThe datasource type this helper is configured for.
NamestringHuman-readable name (e.g. "MongoDB", "Redis").
CapabilitiesDataSourceCapabilitiesCapability flags for this datasource (from DataSourceCapabilityMatrix).
SupportsCapability(CapabilityType)boolFast runtime capability check.

Schema Operations

MethodReturnsDescription
GetSchemaQuery(string userName)(string Query, bool Success)Returns the datasource-specific command to list schemas / collections / keyspaces.
GetTableExistsQuery(string tableName)(string Query, bool Success)Returns a command that resolves to a row if the table/collection exists.
GetColumnInfoQuery(string tableName)(string Query, bool Success)Returns a command that lists column/field metadata for the named table.

DDL Operations

MethodReturnsDescription
GenerateCreateTableSql(EntityStructure, schemaName?, dataSourceType?)(Sql, Success, ErrorMessage)CREATE TABLE / collection from an EntityStructure.
GenerateDropTableSql(tableName, schemaName?)(Sql, Success, ErrorMessage)DROP TABLE / collection.
GenerateTruncateTableSql(tableName, schemaName?)(Sql, Success, ErrorMessage)TRUNCATE / delete all documents.
GenerateCreateIndexSql(tableName, indexName, string[], options?)(Sql, Success, ErrorMessage)CREATE INDEX with optional engine-specific options dictionary.
GenerateAddColumnSql(tableName, EntityField)(Sql, Success, ErrorMessage)ALTER TABLE ADD COLUMN / equivalent for schema-less stores.
GenerateAlterColumnSql(tableName, columnName, EntityField)(Sql, Success, ErrorMessage)ALTER COLUMN type or nullability.
GenerateDropColumnSql(tableName, columnName)(Sql, Success, ErrorMessage)DROP COLUMN.
GenerateRenameTableSql(oldName, newName)(Sql, Success, ErrorMessage)RENAME TABLE / collection.
GenerateRenameColumnSql(tableName, oldName, newName)(Sql, Success, ErrorMessage)RENAME COLUMN.

Constraint Operations

MethodReturnsDescription
GenerateAddPrimaryKeySql(tableName, params string[] columns)(Sql, Success, ErrorMessage)Adds a primary key constraint.
GenerateAddForeignKeySql(tableName, columns[], refTable, refColumns[])(Sql, Success, ErrorMessage)Adds a foreign key constraint.
GenerateAddConstraintSql(tableName, constraintName, definition)(Sql, Success, ErrorMessage)Adds any custom constraint.
GetPrimaryKeyQuery(tableName)(Query, Success, ErrorMessage)Returns SQL to retrieve primary key column names.
GetForeignKeysQuery(tableName)(Query, Success, ErrorMessage)Returns SQL to retrieve foreign key definitions.
GetConstraintsQuery(tableName)(Query, Success, ErrorMessage)Returns SQL to list all constraints on a table.

Transaction Control

MethodReturnsDescription
GenerateBeginTransactionSql()(Sql, Success, ErrorMessage)BEGIN / START TRANSACTION statement.
GenerateCommitSql()(Sql, Success, ErrorMessage)COMMIT statement.
GenerateRollbackSql()(Sql, Success, ErrorMessage)ROLLBACK statement.

DML Operations

MethodReturnsDescription
GenerateInsertSql(tableName, Dictionary<string,object> data)(Sql, Parameters, Success, ErrorMessage)Parameterised INSERT — returns both SQL and the parameter dictionary.
GenerateUpdateSql(tableName, data, conditions)(Sql, Parameters, Success, ErrorMessage)Parameterised UPDATE … SET … WHERE.
GenerateDeleteSql(tableName, conditions)(Sql, Parameters, Success, ErrorMessage)Parameterised DELETE … WHERE.
GenerateSelectSql(tableName, columns?, conditions?, orderBy?, skip?, take?)(Sql, Parameters, Success, ErrorMessage)SELECT with optional column list, WHERE, ORDER BY, and pagination.

Utility Methods

MethodReturnsDescription
QuoteIdentifier(string)stringWraps an identifier in engine-correct quotes ([], "", ``).
MapClrTypeToDatasourceType(Type, size?, precision?, scale?)stringMaps a .NET CLR type to the engine's native type name.
MapDatasourceTypeToClrType(string)TypeReverse mapping — engine type name → .NET Type.
ValidateEntity(EntityStructure)(bool IsValid, List<string> Errors)Validates an entity against the engine's naming and type rules.
GetMaxStringSize()intMaximum allowed string/varchar length for this engine.
GetMaxNumericPrecision()intMaximum numeric precision supported by this engine.

DataSourceHelperFactory

Instantiates and returns the correct IDataSourceHelper for any DataSourceType. The factory covers 60+ registered datasource types across RDBMS, NoSQL, Key-Value, Column-Family, Graph, Search, Time-Series, Vector, Streaming, Big-Data, and File categories.

Direct Usage

// Inject IDMEEditor via DI, then create the factory
var factory = new DataSourceHelperFactory(dmeEditor);
IDataSourceHelper helper = factory.CreateHelper(DataSourceType.MongoDB);

// All operations go through IDataSourceHelper
var (sql, ok) = helper.GetSchemaQuery(userName: null);
var (insertSql, parms, success, err) = helper.GenerateInsertSql(
    "Orders",
    new Dictionary<string, object> { ["CustomerId"] = 42, ["Total"] = 99.99 });

GeneralDataSourceHelper — Runtime Delegate

GeneralDataSourceHelper wraps the factory: it accepts a DataSourceType in its constructor, resolves the correct helper internally, and forwards every IDataSourceHelper call to it. Use this when the datasource type is only known at runtime.

// Type resolved at runtime
var helper = new GeneralDataSourceHelper(DataSourceType.Redis, dmeEditor);
string quoteChar = helper.QuoteIdentifier("myKey"); // uses RedisHelper internally

Helper-to-Engine Mapping

Helper ClassEngines Covered
RdbmsHelperSQL Server, MySQL, PostgreSQL, SQLite, DB2, Firebird, HANA, Teradata, Vertica, AzureSQL, AWSRDS, Snowflake, CockroachDB, Spanner, DuckDB, MariaDB, Hadoop, BigQuery, Redshift, Athena, DataBricks, …
MongoDBHelperMongoDB, CouchDB, RavenDB, Couchbase, ArangoDB, OrientDB, LiteDB, Firebase, DynamoDB
RedisHelperRedis, Memcached, Hazelcast, GridGain, ApacheIgnite, ChronicleMap, RealIM, InMemoryCache, CachedMemory
CassandraHelperCassandra, ClickHouse
GraphDbHelperNeo4j, TigerGraph, JanusGraph
SearchEngineHelperElasticsearch, Solr
TimeSeriesHelperInfluxDB, TimeScale
VectorDbHelperPinecone, Qdrant, Weaviate, Milvus, Zilliz, Vespa, ShapVector, RedisVector
StreamingHelperKafka, Kinesis, EventHub, Pulsar, RabbitMQ
FileFormatHelperCSV, JSON, XML, Parquet, Avro, ORC, Feather, Excel
DefaultDataSourceHelperFallback for any unregistered type

DataSourceCapabilityMatrix

A static matrix that maps every registered DataSourceType to its DataSourceCapabilities flags. Use it to check at runtime whether a feature is available before attempting to generate SQL that relies on it.

API

MethodReturnsDescription
DataSourceCapabilityMatrix.Supports(DataSourceType, string capabilityName)boolReturns true if the datasource supports the named capability.
DataSourceCapabilityMatrix.GetCapabilities(DataSourceType)DataSourceCapabilitiesReturns the full capabilities object for the specified datasource type.
DataSourceCapabilityMatrix.GetDatasourcesSupportingCapability(string capabilityName)List<DataSourceType>Lists every datasource type that supports the named capability.

Selected Capability Names

CapabilityDescription
SupportsTransactionsACID multi-statement transaction support
SupportsJoinsSQL-style JOIN operations
SupportsFullTextSearchNative full-text / semantic search
IsSchemaEnforcedRequires a defined schema before writes
SupportsTTLTime-To-Live on records / keys
SupportsAggregationsGROUP BY / aggregation pipeline
SupportsWindowFunctionsSQL OVER () window functions
SupportsVectorSearchApproximate nearest-neighbour search
// Check before generating JOIN SQL
bool canJoin = DataSourceCapabilityMatrix.Supports(
    DataSourceType.Cassandra, "SupportsJoins"); // false

// Get all FTS-capable datasources
var ftsSources = DataSourceCapabilityMatrix
    .GetDatasourcesSupportingCapability("SupportsFullTextSearch");
// → [ElasticSearch, Solr, MongoDB, PostgreSQL, ClickHouse, …]

// Graceful degradation
var caps = DataSourceCapabilityMatrix.GetCapabilities(type);
string query = caps.SupportsJoins
    ? GenerateJoinSql()
    : GenerateDenormalizedSql();

NoSQL Helpers

The document, key-value, and column-family helpers all implement IDataSourceHelper but translate every call into the native command syntax of their engine rather than SQL.

MongoDBHelper

Covers MongoDB, CouchDB, RavenDB, Couchbase, ArangoDB, LiteDB, Firebase, DynamoDB.

IDataSourceHelper methodMongoDB equivalent
GetSchemaQuery(){ "listCollections": 1 }
GetTableExistsQuery(name){ "listCollections": 1, "filter": { "name": "…" } }
GenerateInsertSql(collection, data)Returns JSON document + parameter map for insertOne/insertMany
GenerateUpdateSql(collection, data, conditions)Returns { $set: {…} } update document
GenerateSelectSql(collection, …)Returns MQL filter document with optional projection and sort

RedisHelper

Covers Redis, Memcached, Hazelcast, GridGain, ApacheIgnite, in-memory caches.

IDataSourceHelper methodRedis command
GetSchemaQuery()KEYS *
GetTableExistsQuery(key)EXISTS <key>
GenerateInsertSql(key, data)HMSET <key> <field> <value> … or SET for scalar values
GenerateSelectSql(key, …)HGETALL <key> or GET <key>

CassandraHelper

Covers Cassandra and ClickHouse.

NoteDetail
Query languageCQL (Cassandra Query Language) — SQL-like with partition key requirements
No JOINsSupportsJoins = false; denormalize data or use wide rows
Partition keyMust include partition key in every WHERE clause
// MongoDB via the universal interface
IDataSourceHelper mongo = factory.CreateHelper(DataSourceType.MongoDB);
var (insertCmd, parms, ok, err) = mongo.GenerateInsertSql(
    "Orders",
    new Dictionary<string, object> { ["customerId"] = 42, ["total"] = 99.99 });
// insertCmd → JSON document for insertOne

// Redis — check exists, then SET
IDataSourceHelper redis = factory.CreateHelper(DataSourceType.Redis);
var (existsCmd, _) = redis.GetTableExistsQuery("session:abc123");
// existsCmd → "EXISTS session:abc123"

Specialized Store Helpers

Helpers for graph databases, search engines, time-series databases, vector databases, and streaming platforms. These stores have fundamentally different semantics from RDBMS; the helpers reflect that by returning engine-native query fragments or indicating that DDL is managed by the engine itself.

HelperEnginesKey Characteristics
GraphDbHelper Neo4j, TigerGraph, JanusGraph Schemas are flexible; DDL methods return empty SQL with explanatory messages. GenerateAddColumnSql produces engine-specific constraint or Gremlin syntax.
SearchEngineHelper Elasticsearch, Solr Indexes are created implicitly. GenerateAddColumnSql generates Elasticsearch mapping PUT or Solr schema API JSON for adding a new field.
TimeSeriesHelper InfluxDB, TimeScale Optimised for time-ordered writes. DDL maps to measurement/bucket creation. SELECT includes time-range predicates automatically when skip/take are used.
VectorDbHelper Pinecone, Qdrant, Weaviate, Milvus, Zilliz, Vespa, RedisVector Collections are created implicitly. GenerateAddColumnSql produces engine-specific payload schema or Weaviate property JSON. INSERT returns a vector upsert command. SELECT returns an ANN search command.
StreamingHelper Kafka, Kinesis, EventHub, Pulsar, RabbitMQ INSERT maps to publish; SELECT maps to consume/peek. No DDL beyond topic creation.
FileFormatHelper CSV, JSON, XML, Parquet, Avro, ORC, Feather, Excel Generates file-specific read/write expressions. DDL is not applicable.
// Graph — Neo4j via Cypher (CREATE CONSTRAINT)
IDataSourceHelper graph = factory.CreateHelper(DataSourceType.Neo4j);
var (cypher, ok, err) = graph.GenerateAddColumnSql("Person", ageField);
// cypher → "CREATE CONSTRAINT ON (n:Person) ASSERT n.Age IS NOT NULL"

// Vector — Weaviate property add
IDataSourceHelper vector = factory.CreateHelper(DataSourceType.Weaviate);
var (json, ok2, err2) = vector.GenerateAddColumnSql("Product", descField);
// json → Weaviate PUT /v1/schema/Product/properties JSON

// Check capability before generating time-series query
bool hasTTL = DataSourceCapabilityMatrix.Supports(
    DataSourceType.InfluxDB, "SupportsTTL"); // true

Analysis Helpers

The Analysis/ sub-folder contains two static helpers for inspecting POCO type graphs and inferring relational structure — a prerequisite when converting C# object models to EntityStructure instances.

NavigationPropertyDetector

MethodReturnsDescription
IsCollectionNavigation(PropertyInfo) bool Returns true if the property is ICollection<T>, IEnumerable<T>, List<T>, etc.
GetNavigationPropertyType(PropertyInfo) NavigationPropertyType Classifies as Collection, SingleReference, or Unknown.

RelationshipInferencer

Determines RelationshipCardinality from POCO property graphs using a four-tier priority: explicit attributes → naming conventions → type analysis → bidirectional detection.

MethodReturnsDescription
InferCardinality(PropertyInfo sourceNavProperty, Type sourceType, Type targetType) RelationshipCardinality Infers the cardinality between source and target types via the given navigation property. Returns: OneToOne, OneToMany, ManyToOne, ManyToMany, SelfReference, or Unknown.

Inference Priority

  1. Explicit attributes — [ForeignKey], [InverseProperty]
  2. Naming conventions — properties ending in Id / ID
  3. Type analysis — ICollection<T> on one side implies One-to-Many
  4. Bidirectional detection — matching navigation property on the target type
// Check whether Order.Customer is a collection or single ref
var prop = typeof(Order).GetProperty("Customer");
bool isCollection = NavigationPropertyDetector.IsCollectionNavigation(prop);
// false — single reference

// Infer cardinality between Order and Customer
var card = RelationshipInferencer.InferCardinality(
    typeof(Order).GetProperty("Customer"),
    typeof(Order),
    typeof(Customer));
// → RelationshipCardinality.ManyToOne

POCO-to-Entity Conversion

PocoToEntityConverter (in Conversion/) uses reflection and DataAnnotations to automatically build a fully-configured EntityStructure from any C# class — eliminating the need to hand-craft entity definitions.

Key Detection Strategy

StrategyBehaviour
AttributeOnlyOnly properties decorated with [Key] are treated as primary keys.
ConventionOnlyProperties named Id or {ClassName}Id are auto-detected as keys.
AttributeThenConvention (default)Tries [Key] first; falls back to naming convention if no attribute is found.

Supported DataAnnotations

AttributeEffect on EntityField
[Key]Sets IsKey = true
[Required]Sets AllowDBNull = false
[StringLength(n)]Sets FieldSize = n
[MaxLength(n)]Sets FieldSize = n
[Range(min, max)]Stores range metadata on the field
[Column(name)]Overrides the field name to the column alias

Circular Reference Guard

The converter tracks visited types and halts recursion when a cycle is detected, preventing infinite loops in deeply nested object graphs.

public class Product
{
    [Key]
    public int ProductId { get; set; }

    [Required, StringLength(100)]
    public string Name { get; set; }

    [Range(0, double.MaxValue)]
    public decimal Price { get; set; }

    public string Description { get; set; }
}

// Convert to EntityStructure in one call
EntityStructure entity = PocoToEntityConverter.ConvertPocoToEntity<Product>(
    strategy: PocoToEntityConverter.KeyDetectionStrategy.AttributeThenConvention,
    entityName: "Products");

// entity.EntityName  → "Products"
// entity.Fields[0]   → ProductId  (IsKey=true, AllowDBNull=false)
// entity.Fields[1]   → Name       (AllowDBNull=false, FieldSize=100)
// entity.Fields[2]   → Price      (range metadata attached)
// entity.Fields[3]   → Description (nullable)

// Then feed directly into any helper
IDataSourceHelper helper = new GeneralDataSourceHelper(
    DataSourceType.Postgre, dmeEditor);
var (createSql, ok, err) = helper.GenerateCreateTableSql(entity);

File & Folder Helpers

FileHelper

public static class FileHelper
{
    // Driver/file extension discovery
    public static string GetFileExtensions(IDMEEditor dmeEditor);
    public static List<ConnectionDriversConfig> GetFileDataSources(IDMEEditor dmeEditor);
    public static DataSourceType GetDataSourceTypeFromExtension(string fileExtension, IDMEEditor dmeEditor);

    // File operations
    public static bool IsFileLocked(string filePath);
    public static string GetFileHash(string filePath, HashAlgorithmName algorithm);
    public static string ComputeFileChecksum(string filePath);

    // Path helpers
    public static string GetRelativePath(string basePath, string fullPath);
    public static string EnsureAbsolutePath(string basePath, string relativePath);
    public static string NormalizePath(string path);
    public static string SanitizeFileName(string fileName);
}

FileOperationHelper

public static class FileOperationHelper
{
    // Safe file operations with locking
    public static bool SafeDelete(string filePath);
    public static bool SafeMove(string sourcePath, string destPath, bool overwrite = false);
    public static bool SafeCopy(string sourcePath, string destPath, bool overwrite = false);

    // Directory operations
    public static void EnsureDirectoryExists(string directoryPath);
    public static void ClearDirectory(string directoryPath, bool recursive = true);

    // Compression
    public static Task CompressDirectoryAsync(string sourceDir, string destZipPath);
    public static Task DecompressArchiveAsync(string archivePath, string destDir);

    // JSON/XML helpers
    public static T LoadJsonFile<T>(string filePath);
    public static Task SaveJsonFileAsync<T>(string filePath, T data, bool indent = true);
    public static XDocument LoadXmlFile(string filePath);
    public static Task SaveXmlFileAsync(string filePath, XDocument doc);
}

Project & Library Helpers

6 helpers in ProjectandLibraryHelpers/ for project management and metadata.

ProjectCreationHelper

public static class ProjectCreationHelper
{
    public static Tuple<IErrorsInfo, RootFolder> CreateProject(
        IDMEEditor dmeEditor, string folderpath, ProjectFolderType folderType = ProjectFolderType.Files);
}

ProjectMetadataHelper

public static class ProjectMetadataHelper
{
    public static ProjectMetadata LoadProjectMetadata(string projectPath);
    public static void SaveProjectMetadata(string projectPath, ProjectMetadata metadata);
    public static ProjectMetadata CreateDefaultMetadata(string projectName, string rootPath);
}

ProjectRetrievalHelper

public static class ProjectRetrievalHelper
{
    public static List<RootFolder> GetProjects(IDMEEditor dmeEditor, string rootPath);
    public static RootFolder LoadProject(IDMEEditor dmeEditor, string projectPath);
}

ProjectSynchronizationHelper

public static class ProjectSynchronizationHelper
{
    public static void SyncProjectDataSources(RootFolder project, IDMEEditor dmeEditor);
    public static void SyncProjectAssemblies(RootFolder project, IAssemblyHandler handler);
}

ProjectLifecycleHelper

public static class ProjectLifecycleHelper
{
    public static bool InitializeProject(RootFolder project, IDMEEditor dmeEditor);
    public static bool ValidateProjectIntegrity(RootFolder project);
    public static void ArchiveProject(RootFolder project, string archivePath);
    public static void RestoreProject(string archivePath, string targetPath);
}

ProjectManagementHelper

public static class ProjectManagementHelper
{
    public static void AddDataSourceToProject(RootFolder project, string datasourceName, IDMEEditor editor);
    public static void RemoveDataSourceFromProject(RootFolder project, string datasourceName, IDMEEditor editor);
    public static List<string> GetProjectDataSources(RootFolder project);
    public static Dictionary<string, int> GetProjectFileStats(RootFolder project);
}

General Utility Helpers

ValidationHelper

public static class ValidationHelper
{
    // ValidationResult class
    public class ValidationResult
    {
        public bool IsValid { get; set; }
        public List<string> Errors { get; set; }
        public List<string> Warnings { get; set; }

        public void AddError(string message);
        public void AddWarning(string message);
        public string ToSummary();
    }

    // Core validation methods
    public static ValidationResult ValidateConnectionProperties(IConnectionProperties props);
    public static ValidationResult ValidateEntityStructure(EntityStructure entity);
    public static ValidationResult ValidateDataType(string dataType, DataSourceType dsType);
    public static ValidationResult ValidateEntityName(string entityName, DataSourceType dsType, bool allowReserved = false);
    public static ValidationResult ValidateColumnName(string columnName, DataSourceType dsType, bool allowReserved = false);
    public static ValidationResult ValidateConnectionString(string connectionString, DataSourceType dsType);

    // Data validation
    public static ValidationResult ValidateDataValue(object value, EntityField field);
    public static ValidationResult ValidatePrimaryKey(object value, EntityStructure entity);
    public static ValidationResult ValidateForeignKey(object value, RelationShipKeys fk);

    // Regex helpers
    public static bool IsValidEmail(string email);
    public static bool IsValidUrl(string url);
    public static bool IsValidIpAddress(string ip);
}

ErrorHandlingHelper

public static class ErrorHandlingHelper
{
    // Structured error handling
    public static void HandleException(Exception ex, string context, IDMEEditor editor,
        bool includeStackTrace = true);
    public static void LogError(string message, string context, IDMEEditor editor,
        Exception ex = null);

    // Error categorization
    public static ErrorCategory CategorizeError(Exception ex);
    public static string GetUserFriendlyMessage(Exception ex);
    public static bool IsTransientError(Exception ex);     // network, timeout
    public static bool IsConfigurationError(Exception ex);  // bad config, missing driver

    public enum ErrorCategory
    {
        Unknown, Validation, Configuration, Connection,
        Query, DataMapping, Security, Permission,
        ResourceNotFound, Timeout, Concurrency,
        Serialization, OutOfMemory
    }
}

StringExtensions

public static class StringExtensions
{
    // String manipulation extensions
    public static string ToCamelCase(this string value);
    public static string ToPascalCase(this string value);
    public static string ToSnakeCase(this string value);
    public static string ToKebabCase(this string value);

    // Splitting and parsing
    public static string[] SplitAndTrim(this string value, char separator = ',');
    public static bool EqualsIgnoreCase(this string value, string other);
    public static bool ContainsIgnoreCase(this string value, string substring);
    public static string Truncate(this string value, int maxLength, string suffix = "...");

    // Encoding/path helpers
    public static string ToSafeFileName(this string value);
    public static string ToUrlSafeString(this string value);
    public static string RemoveSpecialCharacters(this string value, string allowedChars = null);
    public static string ToSqlSafeString(this string value);
    public static string ToXmlSafeString(this string value);
}

VectorDatabaseHelper

public static class VectorDatabaseHelper
{
    public static float[] NormalizeVector(float[] vector);
    public static float CosineSimilarity(float[] a, float[] b);
    public static float EuclideanDistance(float[] a, float[] b);
    public static float DotProduct(float[] a, float[] b);
    public static List<(int Index, float Similarity)> FindNearest(
        float[] query, List<(int Id, float[] Vector)> vectors, int topK = 10);
}

DataSourceLifecycleHelper

public static class DataSourceLifecycleHelper
{
    public static IErrorsInfo OpenDataSource(IDataSource ds);
    public static IErrorsInfo CloseDataSource(IDataSource ds);
    public static ConnectionState RefreshConnection(IDataSource ds);
    public static bool IsHealthy(IDataSource ds);
    public static Task<bool> PingAsync(IDataSource ds, int timeoutMs = 5000, CancellationToken ct = default);
}

Complete Helpers Source File Map (100+ files)

CategoryFileDescription
ConnectionHelpers (22 files) ConnectionHelper.csStatic facade — delegates to sub-helpers
ConnectionDriverLinkingHelper.csLinks connections to driver configs
ConnectionStringProcessingHelper.csParses/builds connection strings
ConnectionStringValidationHelper.csValidates connection string format
ConnectionStringSecurityHelper.csEn/decrypts connection secrets
ConnectionHelper_GetParameterList.csExtracts parameter lists from config
TestConnectionHelper.csTests connection liveness
ProxyLivenessHelper.csProxy-specific health probing
ConnectionHelper_RDBMS.csRDBMS connection config factory
ConnectionHelper_NoSQL.csNoSQL connection config factory
ConnectionHelper_File.cs / .MiscFile-based connection config (2)
ConnectionHelper_Cloud.csCloud service config factory
ConnectionHelper_Streaming.csStreaming data config factory
ConnectionHelper_InMemory.csIn-memory/Cache config factory
ConnectionHelper_WebAPI.csWebAPI/REST config factory
ConnectionHelper_Proxy.csProxy data source config factory
SaaS Connectors (8): ECommerce, CRM, Communication, Cache, ProjectManagement, Marketing, VectorDB, Blockchain
DataTypesHelpers (20 files) DataTypesHelper.csIDataTypesHelper — type conversion, listing
DataTypeBasicOperations.csBasic type operations (null check, coercion)
DataTypeMappingLookup.csCLR ↔ database type lookup tables
DataTypeMappingRepository.csCentral type mapping repository
DataTypeFieldMappingHelper.csPer-field type mapping with defaults
Database-specific repos (14): SQL Server, Oracle, PostgreMySQL, NoSQL, Modern, Search, Vector, Streaming, MachineLearning, WorkflowIoT, Protocols, Services, SocialMedia, PaymentGateways, IoT
RDBMSHelpers — Core RDBMSHelper.csGeneral RDBMS helper facade
DatabaseFeatureHelper.csFeature detection per RDBMS type
DatabaseSchemaQueryHelper.csSchema metadata query builder
DatabaseQueryRepositoryHelper.csQuery template repository
RDBMSHelpers — DML DatabaseDMLHelper.csStatic facade — DML generation
DatabaseDMLBasicOperations.csINSERT, UPDATE, DELETE generators
DatabaseDMLBulkOperations.csBulk insert/update/delete
DatabaseDMLAdvancedQueryGenerator.csAdvanced query patterns
DatabaseDMLParameterizedQueries.csParameterized query helpers
DatabaseDMLUtilities.csSQL utility methods
DatabaseDMLSupportingClasses.csExpression printer, SQL dialect
DatabaseDMLSpecificHelpers.csPer-RDBMS specific DML
RDBMSHelpers — Entity DatabaseEntityHelper.cs / .LegacyEntity CRUD SQL generation (2)
DatabaseEntityAnalyzer.csEntity structure analysis
DatabaseEntityValidator.csEntity validation against schema
DatabaseEntityNamingValidator.csNaming convention validator
DatabaseEntityTypeHelper.csType inference from schema
UniversalDataSourceHelpers — Core DataSourceHelperFactory.csFactory: creates helpers by DataSourceType
GeneralDataSourceHelper.csFacade delegating to type-specific helper
DefaultDataSourceHelper.csDefault fallback helper
DataSourceCapabilityMatrix.csFeature support matrix per DS type
Analysis: RelationshipInferencer, NavigationPropertyDetector
Mapping: RelationshipToEntityMapper
RDBMS: RdbmsHelper, RdbmsHelper.Constraints, RdbmsHelper.Transactions
UniversalDataSourceHelpers — Specialized CassandraHelper.csCassandra-specific helper
MongoDBHelper.csMongoDB-specific helper
RedisHelper.csRedis-specific helper
GraphDbHelper.csGraph DB helper
VectorDbHelper.csVector DB helper
SearchEngineHelper.csSearch engine helper
TimeSeriesHelper.csTime-series DB helper
RestApiHelper.csREST API helper
FileFormatHelper.csFile format (CSV, Excel, Parquet) helper
StreamingHelper.csApache Kafka helper
FileandFolderHelpers FileHelper.csFile extension/data source discovery, hashing, path helpers
FileOperationHelper.csSafe file/dir ops, compression, JSON/XML
ProjectandLibraryHelpers ProjectCreationHelper.csCreate project from folder path
ProjectMetadataHelper.csLoad/Save project metadata
ProjectRetrievalHelper.csList/load projects from root
ProjectSynchronizationHelper.csSync data sources/assemblies with project
ProjectLifecycleHelper.csInit/validate/archive/restore projects
ProjectManagementHelper.csAdd/remove DS, file stats from project
General Utilities ValidationHelper.csConnection/entity/data validation + regex
ErrorHandlingHelper.csStructured error handling, categorization, transience detection
StringExtensions.csString case conversions, encoding, truncation
VectorDatabaseHelper.csVector math: normalize, cosine similarity, nearest neighbors
DataSourceLifecycleHelper.csOpen/close/refresh/ping data sources
DatabaseObjectCreationHelper.csDatabase object (table, view, SP) creation
DatabaseEntitySqlGenerator.csEntity-to-SQL generation pipeline
DatabaseEntityReservedKeywordChecker.csReserved keyword collision detection