Connection Helpers Reference
ConnectionHelper facade, driver linking, connection-string processing, validation, security, category config factories, and liveness probing
Contents
- Overview & File Structure
- Driver Linking
- Connection String Processing
- Connection String Validation
- Connection String Security
- Parameter Utilities
- Category Config Factories
- Liveness & Test Connection
- DataTypesHelpers Overview
- DataTypesHelper (IDataTypesHelper)
- DataTypeBasicOperations
- DataTypeMappingLookup
- DataTypeMappingRepository
- DataTypeFieldMappingHelper
- Per-Database Mapping Repositories
- TypeHelper
- RDBMSHelpers Overview
- DatabaseFeatureHelper
- Schema & Metadata Queries
- DDL Generation
- Query Repository
- DML Helpers
- Entity Helpers
- UniversalDataSourceHelpers Overview
- IDataSourceHelper Interface
- DataSourceHelperFactory
- DataSourceCapabilityMatrix
- NoSQL Helpers
- Specialized Store Helpers
- Analysis Helpers
- POCO-to-Entity Conversion
- File & Folder Helpers
- Project & Library Helpers
- General Utility Helpers
- Complete Source File Map
- 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.).
| File | Namespace | Responsibility |
|---|---|---|
ConnectionHelper.cs | TheTechIdea.Beep.Helpers | Public facade — re-exports every sub-helper method under one type |
ConnectionDriverLinkingHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Match connection properties to registered drivers |
ConnectionStringProcessingHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Placeholder substitution, path normalisation |
ConnectionStringValidationHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Per-driver connection-string validation rules |
ConnectionStringSecurityHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Mask passwords, API keys, tokens for logging |
ConnectionHelper_GetParameterList.cs | TheTechIdea.Beep.Helpers | Parse / mutate individual connection-string parameters |
ConnectionHelper_RDBMS.cs | TheTechIdea.Beep.Helpers | Factory: SQL Server, MySQL, PostgreSQL, SQLite, Firebird, … |
ConnectionHelper_NoSQL.cs | TheTechIdea.Beep.Helpers | Factory: MongoDB, Redis, Cassandra, Elasticsearch, … |
ConnectionHelper_VectorDB.cs | TheTechIdea.Beep.Helpers | Factory: ChromaDB, Pinecone, Qdrant, Weaviate, Milvus, … |
ConnectionHelper_File.cs | TheTechIdea.Beep.Helpers | Factory: CSV, JSON, XML, Excel, Parquet, Avro, … |
ConnectionHelper_File_Misc.cs | TheTechIdea.Beep.Helpers | Factory: DICOM, LAS, HDF5, Markdown, INI, … |
ConnectionHelper_Cloud.cs | TheTechIdea.Beep.Helpers | Factory: AWS (S3, Redshift, Athena), Azure, GCP (BigQuery) |
ConnectionHelper_Streaming.cs | TheTechIdea.Beep.Helpers | Factory: Kafka, RabbitMQ, Pulsar, Azure Service Bus, … |
ConnectionHelper_InMemory.cs | TheTechIdea.Beep.Helpers | Factory: SQLite Memory, DuckDB Memory, Hazelcast, Ignite |
ConnectionHelper_Cache.cs | TheTechIdea.Beep.Helpers | Factory: InMemoryCache, Redis Cache, NCache, Hazelcast Cache, … |
ConnectionHelper_WebAPI.cs | TheTechIdea.Beep.Helpers | Factory: REST, GraphQL, gRPC, SOAP, OData, WebSocket, … |
ConnectionHelper_CRM.cs | TheTechIdea.Beep.Helpers | Factory: Salesforce, HubSpot, Dynamics 365, Zoho, … |
ConnectionHelper_Marketing.cs | TheTechIdea.Beep.Helpers | Factory: Mailchimp, Marketo, Klaviyo, SendGrid, … |
ConnectionHelper_ECommerce.cs | TheTechIdea.Beep.Helpers | Factory: Shopify, WooCommerce, Magento, BigCommerce, … |
ConnectionHelper_ProjectManagement.cs | TheTechIdea.Beep.Helpers | Factory: Jira, Asana, Monday.com, ClickUp, Trello, … |
ConnectionHelper_Communication.cs | TheTechIdea.Beep.Helpers | Factory: Slack, Teams, Discord, Zoom, Telegram, … |
ConnectionHelper_Blockchain.cs | TheTechIdea.Beep.Helpers | Factory: Ethereum, Hyperledger, Solana, Polkadot, … |
ConnectionHelper_Proxy.cs | TheTechIdea.Beep.Helpers | Factory: HTTP proxy, SOCKS, reverse proxy configs |
ProxyLivenessHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Category-aware liveness probe for a live IDataSource |
TestConnectionHelper.cs | TheTechIdea.Beep.Helpers.ConnectionHelpers | Async 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:
- Exact
DriverName+DriverVersion DriverNameonly (latest available version)DatabaseTypeenum match- 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)}");
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}");
}
| DataSourceType | Required keyword(s) |
|---|---|
| SqlServer | Server / Data Source / Address |
| Mysql | Server / Host / Data Source |
| SqlLite | Data Source / DataSource |
| Postgre | Host / Server |
| MongoDB | mongodb:// prefix |
| Redis | host:port pattern |
| OLEDB / ODBC | Provider= / DSN= or Driver= |
| Everything else | Generic: 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);
| Category | Matched keywords (case-insensitive) |
|---|---|
| Passwords | Password, Pwd, Pass, UserPassword, AuthPassword |
| API keys | ApiKey, ApplicationKey, ClientKey, SubscriptionKey |
| Access keys | AccessKey, SecretKey, AwsAccessKey, AwsSecretKey |
| Tokens | Token, BearerToken, AccessToken, RefreshToken |
| Secrets | Secret, 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();
| Method | DataSourceType | Template |
|---|---|---|
CreateSqlServerConfig() | SqlServer | Server={Host};Database={Database};User Id={UserID};Password={Password} |
CreateMySqlConfig() | Mysql | Server={Host};Database={Database};Uid={UserID};Pwd={Password} |
CreatePostgreConfig() | Postgre | Host={Host};Database={Database};Username={UserID};Password={Password} |
CreateSQLiteConfig() | SqlLite | Data Source={FileName} |
CreateDuckDBConfig() | DuckDB | Data Source={FileName} |
CreateFirebirdConfig() | Firebird | DataSource={Host};Database={FileName};User={UserID};Password={Password} |
CreateSnowFlakeConfig() | SnowFlake | account={Host};user={UserID};password={Password};db={Database} |
CreateAzureSQLConfig() | AzureSql | Azure SQL connection string template |
CreateAWSRDSConfig() | AWSRds | AWS RDS connection string template |
CreateHanaConfig() | Hana | SAP 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();
| Method | Technology |
|---|---|
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();
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();
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();
DatasourceCategory = DatasourceCategory.CLOUD.
Streaming Config Factory
File: ConnectionHelper_Streaming.cs
List<ConnectionDriversConfig> streams = ConnectionHelper.GetStreamingConfigs();
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();
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();
DatasourceCategory = DatasourceCategory.WEBAPI or RDBMS (for ADO/ODBC).
Connector Category Factories
These partial classes produce drivers for SaaS platforms. All have
DatasourceCategory = DatasourceCategory.Connector.
| Method | File | Platforms included |
|---|---|---|
GetCRMConfigs() | ConnectionHelper_CRM.cs | Salesforce, HubSpot, Dynamics 365, Zoho, Pipedrive, Freshsales, SugarCRM, SAP CRM |
GetMarketingConfigs() | ConnectionHelper_Marketing.cs | Mailchimp, Marketo, ActiveCampaign, Klaviyo, Sendinblue, SendGrid, Mailgun, Google Ads, Hootsuite |
GetECommerceConfigs() | ConnectionHelper_ECommerce.cs | Shopify, WooCommerce, Magento, BigCommerce, Squarespace, Etsy, OpenCart, PrestaShop |
GetProjectManagementConfigs() | ConnectionHelper_ProjectManagement.cs | Jira, Azure Boards, Trello, Asana, Monday.com, ClickUp, Notion, Wrike, Smartsheet |
GetCommunicationConfigs() | ConnectionHelper_Communication.cs | Slack, Microsoft Teams, Discord, Zoom, Telegram, WhatsApp Business, Mattermost, Rocket.Chat |
GetBlockchainConfigs() | ConnectionHelper_Blockchain.cs | Ethereum, 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-openIDataSourceusing 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 aConnectionDriversConfigobject 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);
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:
- Facade:
DataTypesHelpers/DataTypeFieldMappingHelper.cs— delegates to all sub-helpers - Service class:
DataTypesHelpers/DataTypesHelper.cs— injectableIDataTypesHelper - 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 | Type | Role |
|---|---|---|
DataTypeFieldMappingHelper | static partial | Public facade — every method delegates to a specialist |
DataTypesHelper | class : IDataTypesHelper | Injectable service with ConcurrentDictionary caches; registered by DI |
DataTypeBasicOperations | static | .NET type constant strings, GetNetDataTypes, custom converter, field validation |
DataTypeMappingLookup | static | Core resolution: net-type → db-type and db-type → net-type; internal caches + regex |
DataTypeMappingRepository | static | Reads DataTypesMap from ConfigEditor; resolves by DS name or DataSourceType |
DatabaseTypeMappingRepository | static partial | 26 partial files — one per DB family — each with a Generate*DataTypesMapping() method |
TypeHelper | static | Extension 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
);
| GetNetDataTypes() | GetNetDataTypes2() |
|---|---|
byte, sbyte, int, uint | System.Byte, System.SByte, System.Int32, System.UInt32 |
short, ushort, long, ulong | System.Int16, System.UInt16, System.Int64, System.UInt64 |
float, double, decimal | System.Single, System.Double, System.Decimal |
char, bool, object, string | System.Char, System.Boolean, System.Object, System.String |
DateTime | System.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
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.
| File | Databases covered | Method |
|---|---|---|
...SqlServer.cs | SQL Server (SQLServerDataSource) | GenerateSqlServerDataTypesMapping() |
...Common.cs | SQLite, SQL Compact, DuckDB | GenerateSQLiteDataTypesMapping(), etc. |
...PostgreMySQL.cs | PostgreSQL, MySQL | GeneratePostgreSQLDataTypesMapping(), GenerateMySQLDataTypesMapping() |
...FirebirdLiteDB.cs | Firebird, LiteDB | GenerateFirebirdDataTypesMapping(), GenerateLiteDBDataTypesMapping() |
...NoSQL.cs | MongoDB, Cassandra, Redis | GenerateMongoDBDataTypesMapping(), etc. |
...Enterprise.cs | DB2, DynamoDB, InfluxDB, Sybase, HBase, CockroachDB | GenerateDB2DataTypesMapping(), etc. |
...Cloud.cs | Snowflake, Azure Cosmos DB, Vertica, Teradata, ArangoDB, BerkeleyDB | GenerateSnowflakeDataTypesMapping(), etc. |
...Services.cs | Firebase, Supabase, CouchDB, Couchbase | GenerateFirebaseDataTypesMapping(), etc. |
...Vector.cs | Pinecone, Qdrant, ShapVector, Weaviate, Milvus, RedisVector, Zilliz, Vespa, ChromaDB | GeneratePineconeDataTypesMapping(), etc. |
...Modern.cs | ClickHouse, Neo4j, TimescaleDB, Elasticsearch | GenerateClickHouseDataTypesMapping(), etc. |
...BigData.cs | Hadoop/Hive, Spark, Presto, Trino, Delta Lake | GenerateHiveDataTypesMapping(), etc. |
...Analytics.cs | Redshift, BigQuery, Azure Synapse, Databricks | GenerateRedshiftDataTypesMapping(), etc. |
...CloudPlatforms.cs | AWS Athena, Azure Data Lake, GCP Spanner | GenerateAthenaDataTypesMapping(), etc. |
...FileFormats.cs | CSV, JSON, Parquet, Avro, ORC, Excel | GenerateCSVDataTypesMapping(), etc. |
...Graph.cs | Neo4j, TigerGraph, JanusGraph | GenerateNeo4jDataTypesMapping(), etc. |
...Streaming.cs | Kafka, Kinesis, Pulsar | GenerateKafkaDataTypesMapping(), etc. |
...IoT.cs | InfluxDB IoT, TimescaleDB IoT, AWS IoT | GenerateInfluxDBIoTDataTypesMapping(), etc. |
...MachineLearning.cs | ONNX, TensorFlow Serving, MLflow | GenerateONNXDataTypesMapping(), etc. |
...Search.cs | Elasticsearch, Solr, OpenSearch | GenerateElasticsearchDataTypesMapping(), etc. |
...CRM.cs | Salesforce, HubSpot, Dynamics 365 | GenerateSalesforceDataTypesMapping(), etc. |
...SocialMedia.cs | Twitter, LinkedIn, Facebook Graph | GenerateTwitterDataTypesMapping(), etc. |
...PaymentGateways.cs | Stripe, PayPal, Braintree | GenerateStripeDataTypesMapping(), etc. |
...Accounting.cs | QuickBooks, Xero, Sage | GenerateQuickBooksDataTypesMapping(), etc. |
...Protocols.cs | ODBC, OLE DB, ADO, gRPC, GraphQL | GenerateODBCDataTypesMapping(), etc. |
...WorkflowIoT.cs | Azure Logic Apps, AWS Step Functions, Node-RED | GenerateLogicAppsDataTypesMapping(), 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" },
- Create
DatabaseTypeMappingRepository.YourDB.csas a partial class. - Add a
GenerateYourDBDataTypesMapping()method returningList<DatatypeMapping>. - Set
DataSourceNameto theclassHandlervalue from the driver'sConnectionDriversConfig. - 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.
DataManagementEngineStandard/Helpers/RDBMSHelpers/
| File | Class | Responsibility |
|---|---|---|
| RDBMSHelper.cs | RDBMSHelper | Top-level facade — schema, metadata, DDL |
| DatabaseFeatureHelper.cs | DatabaseFeatureHelper | Feature flags, sequence / identity queries |
| DatabaseSchemaQueryHelper.cs | DatabaseSchemaQueryHelper | Per-RDBMS schema discovery SQL |
| DatabaseObjectCreationHelper.cs | DatabaseObjectCreationHelper | CREATE TABLE, PK, INDEX, DROP DDL |
| DatabaseQueryRepositoryHelper.cs | DatabaseQueryRepositoryHelper | Cached pre-built query repository |
| DMLHelpers/DatabaseDMLHelper.cs | DatabaseDMLHelper | DML facade — INSERT, UPDATE, DELETE, SELECT |
| DMLHelpers/DatabaseDMLBasicOperations.cs | DatabaseDMLBasicOperations | Basic INSERT / UPDATE / DELETE |
| DMLHelpers/DatabaseDMLBulkOperations.cs | DatabaseDMLBulkOperations | Bulk insert, upsert, bulk delete |
| DMLHelpers/DatabaseDMLAdvancedQueryGenerator.cs | DatabaseDMLAdvancedQueryGenerator | SELECT, JOIN, aggregation, window functions |
| DMLHelpers/DatabaseDMLParameterizedQueries.cs | DatabaseDMLParameterizedQueries | Parameterized INSERT / UPDATE / DELETE |
| DMLHelpers/DatabaseDMLSpecificHelpers.cs | DatabaseDMLSpecificHelpers | Engine-specific SQL quirks |
| DMLHelpers/DatabaseDMLUtilities.cs | DatabaseDMLUtilities | Formatting, quoting, escaping utilities |
| EntityHelpers/DatabaseEntityHelper.cs | DatabaseEntityHelper | Entity facade — SQL gen, validation, analysis |
| EntityHelpers/DatabaseEntitySqlGenerator.cs | DatabaseEntitySqlGenerator | SQL generation from EntityStructure |
| EntityHelpers/DatabaseEntityValidator.cs | DatabaseEntityValidator | Entity structural validation |
| EntityHelpers/DatabaseEntityNamingValidator.cs | DatabaseEntityNamingValidator | Identifier naming rules per RDBMS |
| EntityHelpers/DatabaseEntityReservedKeywordChecker.cs | DatabaseEntityReservedKeywordChecker | Reserved keyword detection |
| EntityHelpers/DatabaseEntityAnalyzer.cs | DatabaseEntityAnalyzer | Compatibility info, improvement suggestions |
| EntityHelpers/DatabaseEntityTypeHelper.cs | DatabaseEntityTypeHelper | EntityField factory helpers |
DatabaseFeatureHelper
Provides enumerations for optional database capabilities and utility methods for generating engine-specific sequence / identity SQL.
Enumerations
| Enum | Members |
|---|---|
DatabaseFeature |
WindowFunctions, Json, Xml, TemporalTables,
FullTextSearch, Partitioning, ColumnStore |
TransactionOperation |
Begin, Commit, Rollback |
Sequence Queries
| Method | Returns | Description |
|---|---|---|
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
| Engine | Next Sequence Value | Last Identity |
|---|---|---|
| SQL Server | SELECT NEXT VALUE FOR {seq} | SELECT SCOPE_IDENTITY() |
| MySQL | — | SELECT LAST_INSERT_ID() |
| PostgreSQL | SELECT nextval('{seq}') | SELECT LASTVAL() |
| Firebird | SELECT NEXT VALUE FOR {seq} FROM RDB$DATABASE | SELECT GEN_ID({gen},0) FROM RDB$DATABASE |
| DB2 | SELECT NEXTVAL FOR {seq} FROM sysibm.sysdummy1 | SELECT 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)
| Method | Returns | Description |
|---|---|---|
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
| Engine | Generated SQL |
|---|---|
| SQL Server / AzureSQL / AWSRDS | SELECT name FROM sys.databases WHERE HAS_DBACCESS(name)=1 ORDER BY name |
| MySQL | SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME IN (SELECT DISTINCT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLE_PRIVILEGES WHERE GRANTEE='‘{user}’') |
| PostgreSQL | SELECT datname FROM pg_database WHERE datistemplate=false AND has_database_privilege('{user}',datname,'CONNECT') |
| DB2 | SELECT DISTINCT SCHEMANAME FROM SYSCAT.SCHEMAAUTH WHERE GRANTEE='{user}' |
| SQLite | PRAGMA database_list; |
| Firebird | SELECT RDB$DATABASE_NAME FROM RDB$DATABASE |
| Snowflake | SHOW DATABASES |
| SAP HANA | SELECT SCHEMA_NAME FROM SCHEMAS WHERE HAS_PRIVILEGES_ON_SCHEMA(…)='TRUE' |
| BigQuery | SELECT schema_name FROM INFORMATION_SCHEMA.SCHEMATA |
| Redshift | SELECT DISTINCT schemaname FROM pg_tables |
| Athena | SHOW 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
| Method | Returns | Description |
|---|---|---|
GenerateCreateTableSQL(EntityStructure) |
(string Sql, bool Success, string ErrorMessage) |
Builds a full CREATE TABLE statement from the entity's fields, types, and constraints. |
Primary Key
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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)
| Method | Returns | Description |
|---|---|---|
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)
| Method | Returns | Description |
|---|---|---|
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)
| Method | Returns | Description |
|---|---|---|
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)
| Method | Returns | Description |
|---|---|---|
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.
DataManagementEngineStandard/Helpers/UniversalDataSourceHelpers/
Folder Map
| Folder / File | Class(es) | Purpose |
|---|---|---|
| Core/DataSourceHelperFactory.cs | DataSourceHelperFactory | Creates the correct IDataSourceHelper for any DataSourceType |
| Core/GeneralDataSourceHelper.cs | GeneralDataSourceHelper | Runtime delegate wrapper — picks the right helper and forwards all calls |
| Core/DefaultDataSourceHelper.cs | DefaultDataSourceHelper | Fallback helper for unknown / unregistered datasource types |
| RdbmsHelpers/RdbmsHelper.cs | RdbmsHelper | Unified RDBMS helper (SQL Server, MySQL, PostgreSQL, SQLite, Firebird, …) |
| MongoDBHelpers/MongoDBHelper.cs | MongoDBHelper | MongoDB, CouchDB, RavenDB, Couchbase, ArangoDB, Firebase, DynamoDB |
| RedisHelpers/RedisHelper.cs | RedisHelper | Redis, Memcached, Hazelcast, GridGain, ApacheIgnite, in-memory caches |
| CassandraHelpers/CassandraHelper.cs | CassandraHelper | Cassandra, ClickHouse (column-family) |
| GraphHelpers/GraphDbHelper.cs | GraphDbHelper | Neo4j, TigerGraph, JanusGraph |
| SearchHelpers/SearchEngineHelper.cs | SearchEngineHelper | Elasticsearch, Solr |
| TimeSeriesHelpers/TimeSeriesHelper.cs | TimeSeriesHelper | InfluxDB, TimeScale |
| VectorHelpers/VectorDbHelper.cs | VectorDbHelper | Pinecone, Qdrant, Weaviate, Milvus, Zilliz, Vespa, RedisVector, … |
| StreamingHelpers/StreamingHelper.cs | StreamingHelper | Kafka, Kinesis, EventHub, Pulsar, RabbitMQ |
| FileHelpers/FileFormatHelper.cs | FileFormatHelper | CSV, JSON, XML, Parquet, Avro, ORC, Excel file-based sources |
| Analysis/RelationshipInferencer.cs | RelationshipInferencer | Infers One-to-One / One-to-Many / Many-to-Many from POCO type graphs |
| Analysis/NavigationPropertyDetector.cs | NavigationPropertyDetector | Detects collection vs. single-reference navigation properties |
| Conversion/PocoToEntityConverter.cs | PocoToEntityConverter | Converts C# POCO classes → EntityStructure with DataAnnotations support |
| Mapping/RelationshipToEntityMapper.cs | RelationshipToEntityMapper | Maps 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
| Member | Type | Description |
|---|---|---|
SupportedType | DataSourceType | The datasource type this helper is configured for. |
Name | string | Human-readable name (e.g. "MongoDB", "Redis"). |
Capabilities | DataSourceCapabilities | Capability flags for this datasource (from DataSourceCapabilityMatrix). |
SupportsCapability(CapabilityType) | bool | Fast runtime capability check. |
Schema Operations
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
GenerateBeginTransactionSql() | (Sql, Success, ErrorMessage) | BEGIN / START TRANSACTION statement. |
GenerateCommitSql() | (Sql, Success, ErrorMessage) | COMMIT statement. |
GenerateRollbackSql() | (Sql, Success, ErrorMessage) | ROLLBACK statement. |
DML Operations
| Method | Returns | Description |
|---|---|---|
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
| Method | Returns | Description |
|---|---|---|
QuoteIdentifier(string) | string | Wraps an identifier in engine-correct quotes ([], "", ``). |
MapClrTypeToDatasourceType(Type, size?, precision?, scale?) | string | Maps a .NET CLR type to the engine's native type name. |
MapDatasourceTypeToClrType(string) | Type | Reverse 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() | int | Maximum allowed string/varchar length for this engine. |
GetMaxNumericPrecision() | int | Maximum 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 Class | Engines Covered |
|---|---|
RdbmsHelper | SQL Server, MySQL, PostgreSQL, SQLite, DB2, Firebird, HANA, Teradata, Vertica, AzureSQL, AWSRDS, Snowflake, CockroachDB, Spanner, DuckDB, MariaDB, Hadoop, BigQuery, Redshift, Athena, DataBricks, … |
MongoDBHelper | MongoDB, CouchDB, RavenDB, Couchbase, ArangoDB, OrientDB, LiteDB, Firebase, DynamoDB |
RedisHelper | Redis, Memcached, Hazelcast, GridGain, ApacheIgnite, ChronicleMap, RealIM, InMemoryCache, CachedMemory |
CassandraHelper | Cassandra, ClickHouse |
GraphDbHelper | Neo4j, TigerGraph, JanusGraph |
SearchEngineHelper | Elasticsearch, Solr |
TimeSeriesHelper | InfluxDB, TimeScale |
VectorDbHelper | Pinecone, Qdrant, Weaviate, Milvus, Zilliz, Vespa, ShapVector, RedisVector |
StreamingHelper | Kafka, Kinesis, EventHub, Pulsar, RabbitMQ |
FileFormatHelper | CSV, JSON, XML, Parquet, Avro, ORC, Feather, Excel |
DefaultDataSourceHelper | Fallback 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
| Method | Returns | Description |
|---|---|---|
DataSourceCapabilityMatrix.Supports(DataSourceType, string capabilityName) | bool | Returns true if the datasource supports the named capability. |
DataSourceCapabilityMatrix.GetCapabilities(DataSourceType) | DataSourceCapabilities | Returns 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
| Capability | Description |
|---|---|
SupportsTransactions | ACID multi-statement transaction support |
SupportsJoins | SQL-style JOIN operations |
SupportsFullTextSearch | Native full-text / semantic search |
IsSchemaEnforced | Requires a defined schema before writes |
SupportsTTL | Time-To-Live on records / keys |
SupportsAggregations | GROUP BY / aggregation pipeline |
SupportsWindowFunctions | SQL OVER () window functions |
SupportsVectorSearch | Approximate 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 method | MongoDB 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 method | Redis 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.
| Note | Detail |
|---|---|
| Query language | CQL (Cassandra Query Language) — SQL-like with partition key requirements |
| No JOINs | SupportsJoins = false; denormalize data or use wide rows |
| Partition key | Must 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.
| Helper | Engines | Key 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
| Method | Returns | Description |
|---|---|---|
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.
| Method | Returns | Description |
|---|---|---|
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
- Explicit attributes —
[ForeignKey],[InverseProperty] - Naming conventions — properties ending in
Id/ID - Type analysis —
ICollection<T>on one side implies One-to-Many - 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
| Strategy | Behaviour |
|---|---|
AttributeOnly | Only properties decorated with [Key] are treated as primary keys. |
ConventionOnly | Properties 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
| Attribute | Effect 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)
| Category | File | Description |
|---|---|---|
| ConnectionHelpers (22 files) | ConnectionHelper.cs | Static facade — delegates to sub-helpers |
ConnectionDriverLinkingHelper.cs | Links connections to driver configs | |
ConnectionStringProcessingHelper.cs | Parses/builds connection strings | |
ConnectionStringValidationHelper.cs | Validates connection string format | |
ConnectionStringSecurityHelper.cs | En/decrypts connection secrets | |
ConnectionHelper_GetParameterList.cs | Extracts parameter lists from config | |
TestConnectionHelper.cs | Tests connection liveness | |
ProxyLivenessHelper.cs | Proxy-specific health probing | |
ConnectionHelper_RDBMS.cs | RDBMS connection config factory | |
ConnectionHelper_NoSQL.cs | NoSQL connection config factory | |
ConnectionHelper_File.cs / .Misc | File-based connection config (2) | |
ConnectionHelper_Cloud.cs | Cloud service config factory | |
ConnectionHelper_Streaming.cs | Streaming data config factory | |
ConnectionHelper_InMemory.cs | In-memory/Cache config factory | |
ConnectionHelper_WebAPI.cs | WebAPI/REST config factory | |
ConnectionHelper_Proxy.cs | Proxy data source config factory | |
| SaaS Connectors (8): ECommerce, CRM, Communication, Cache, ProjectManagement, Marketing, VectorDB, Blockchain | ||
| DataTypesHelpers (20 files) | DataTypesHelper.cs | IDataTypesHelper — type conversion, listing |
DataTypeBasicOperations.cs | Basic type operations (null check, coercion) | |
DataTypeMappingLookup.cs | CLR ↔ database type lookup tables | |
DataTypeMappingRepository.cs | Central type mapping repository | |
DataTypeFieldMappingHelper.cs | Per-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.cs | General RDBMS helper facade |
DatabaseFeatureHelper.cs | Feature detection per RDBMS type | |
DatabaseSchemaQueryHelper.cs | Schema metadata query builder | |
DatabaseQueryRepositoryHelper.cs | Query template repository | |
| RDBMSHelpers — DML | DatabaseDMLHelper.cs | Static facade — DML generation |
DatabaseDMLBasicOperations.cs | INSERT, UPDATE, DELETE generators | |
DatabaseDMLBulkOperations.cs | Bulk insert/update/delete | |
DatabaseDMLAdvancedQueryGenerator.cs | Advanced query patterns | |
DatabaseDMLParameterizedQueries.cs | Parameterized query helpers | |
DatabaseDMLUtilities.cs | SQL utility methods | |
DatabaseDMLSupportingClasses.cs | Expression printer, SQL dialect | |
DatabaseDMLSpecificHelpers.cs | Per-RDBMS specific DML | |
| RDBMSHelpers — Entity | DatabaseEntityHelper.cs / .Legacy | Entity CRUD SQL generation (2) |
DatabaseEntityAnalyzer.cs | Entity structure analysis | |
DatabaseEntityValidator.cs | Entity validation against schema | |
DatabaseEntityNamingValidator.cs | Naming convention validator | |
DatabaseEntityTypeHelper.cs | Type inference from schema | |
| UniversalDataSourceHelpers — Core | DataSourceHelperFactory.cs | Factory: creates helpers by DataSourceType |
GeneralDataSourceHelper.cs | Facade delegating to type-specific helper | |
DefaultDataSourceHelper.cs | Default fallback helper | |
DataSourceCapabilityMatrix.cs | Feature support matrix per DS type | |
| Analysis: RelationshipInferencer, NavigationPropertyDetector | ||
| Mapping: RelationshipToEntityMapper | ||
| RDBMS: RdbmsHelper, RdbmsHelper.Constraints, RdbmsHelper.Transactions | ||
| UniversalDataSourceHelpers — Specialized | CassandraHelper.cs | Cassandra-specific helper |
MongoDBHelper.cs | MongoDB-specific helper | |
RedisHelper.cs | Redis-specific helper | |
GraphDbHelper.cs | Graph DB helper | |
VectorDbHelper.cs | Vector DB helper | |
SearchEngineHelper.cs | Search engine helper | |
TimeSeriesHelper.cs | Time-series DB helper | |
RestApiHelper.cs | REST API helper | |
FileFormatHelper.cs | File format (CSV, Excel, Parquet) helper | |
StreamingHelper.cs | Apache Kafka helper | |
| FileandFolderHelpers | FileHelper.cs | File extension/data source discovery, hashing, path helpers |
FileOperationHelper.cs | Safe file/dir ops, compression, JSON/XML | |
| ProjectandLibraryHelpers | ProjectCreationHelper.cs | Create project from folder path |
ProjectMetadataHelper.cs | Load/Save project metadata | |
ProjectRetrievalHelper.cs | List/load projects from root | |
ProjectSynchronizationHelper.cs | Sync data sources/assemblies with project | |
ProjectLifecycleHelper.cs | Init/validate/archive/restore projects | |
ProjectManagementHelper.cs | Add/remove DS, file stats from project | |
| General Utilities | ValidationHelper.cs | Connection/entity/data validation + regex |
ErrorHandlingHelper.cs | Structured error handling, categorization, transience detection | |
StringExtensions.cs | String case conversions, encoding, truncation | |
VectorDatabaseHelper.cs | Vector math: normalize, cosine similarity, nearest neighbors | |
DataSourceLifecycleHelper.cs | Open/close/refresh/ping data sources | |
DatabaseObjectCreationHelper.cs | Database object (table, view, SP) creation | |
DatabaseEntitySqlGenerator.cs | Entity-to-SQL generation pipeline | |
DatabaseEntityReservedKeywordChecker.cs | Reserved keyword collision detection | |