Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Datasets Engine (Reference) manages database interactions, query execution, and data synchronization within the FrameworX runtime environment.

Advanced Topic: This document provides deep technical insight into the Dataset module execution engine. Most solutions don't require this level of understanding - the default engine behavior handles typical database operations automatically.

On this page:

Table of Contents
maxLevel2
minLevel2
stylenone

Overview

The Dataset Engine manages all database operations through a multi-layered architecture that ensures security, performance, and scalability. This reference covers essential practices for production deployments, including concurrency management, security hardening, and performance optimization.

The engine orchestrates:

  • Synchronous and asynchronous database operations
  • Connection pooling and thread management
  • Client/server domain tag mapping
  • Query execution through TServer services
  • Result set propagation and distribution
  • Multi-database coordination

Understanding the engine helps when:

  • Optimizing database performance
  • Managing concurrent operations
  • Implementing client-specific data
  • Troubleshooting connection issues

Architecture & Execution Model

Process Separation

The Dataset Module

runs as

operates through a distributed architecture:

TRunModule.exe (Dataset) handles:

Reads Manages
  • Reading all dataset configurations
  • Does NOT directly connect to databases
  • Consumes TServer database services
    • Managing tag mapping and updates
    • Request coordination and queuing
    • Result distribution to displays, reports, and scripts

    TServer provides:

    • Actual database connections
    • SQL execution services
    • Connection pooling
    • Transaction management
    • Network gateway capabilities

    This separation enables secure database access through controlled gateways and maintains network security policies.

    Connection Management

    Single Thread per DB:

    • Each DB configuration creates ONE connection
    • Single execution thread per database
    • Sequential command execution ensures consistency

    Parallel Execution

    Strategy: For concurrent operations to the same database, create multiple DB connections:

    DB1 → Production Database (Thread 1)
    DB2 → Production Database (Thread 2)  
    DB3 → Production Database (Thread 3)

    Create multiple DB connections to same database for parallelism.


    Execution Methods

    Asynchronous Execution (Default)

    Trigger: Property changes (Select, Insert, Update, Delete)

    Flow:

    1. Property triggered (screen/script)
    2. Request propagated to server
    3. Dataset Module receives request
    4. TServer executes database operation
    5. Results returned to Dataset Module
    6. Tags mapped and updated
    7. Execution continues in parallel

    Advantages:

    • Non-blocking operation
    • Better UI performance
    • Prevents
    UI
    • interface freezing
    • Allows parallel operations

    Use Cases:

    • Display queries
    • Background updates
    • Report generation
    • Real-time monitoring

    Synchronous Execution

    Trigger: Method calls (SelectCommand, ExecuteCommand)

    Flow:

    1. Method called
    2. Execution PAUSES
    3. Dataset Module calls TServer
    4. Database operation completes
    5. Results returned
    6. Tags mapped
    7. Execution RESUMES

    Advantages:

    • Guaranteed completion
    • Sequential logic support
    • Immediate results
    • Transaction support

    Risks:

    • Can freeze UI if called from screen
    • Blocks thread execution
    • Performance bottlenecks

    Use Cases:

    • Script tasks
    • Sequential operations
    • Transaction requirements
    • Data validation

    Concurrency & Domain Management

    Tag Domain Mapping

    Execution Context

    Tag mapping occurs in the original call domain:

    Client-Initiated Calls:

    • From displays or client scripts
    • Mapping uses client domain
    • Results visible to specific client
    • Isolated from other clients

    Server-Initiated Calls:

    • From server scripts or tasks
    • Mapping uses server domain
    • Results visible project-wide
    • Shared across all clients

    Domain Selection Strategy

    RequirementDomainExample
    User-specific dataClientPersonal preferences
    Shared dataServerProduction values
    Session dataClientLogin information
    Global stateServerSystem status

    Performance Optimization

    Connection Pooling

    • Reuse existing connections
    • Minimize connection overhead
    • Configure pool size appropriately

    Query Optimization

    sql

    -- Use parameters to prevent recompilation
    SELECT * FROM Table WHERE ID = @id
    
    -- Limit result sets
    SELECT TOP 100 * FROM LargeTable
    
    -- Use appropriate indexes
    CREATE INDEX idx_timestamp ON Data(Timestamp)

    Asynchronous Patterns

    csharp

    // Good: Asynchronous from screen
    @Dataset.Table.MyTable.SelectCommand = "SELECT * FROM Data";
    
    // Bad: Synchronous from screen (blocks UI)
    @Dataset.Table.MyTable.SelectCommandWithStatus();

    Batch Operations

    • Group multiple operations
    • Use transactions for consistency
    • Minimize round trips

    Threading Model

    Dataset Module Thread

    • Main coordination thread
    • Manages request queue
    • Handles tag mapping

    TServer Database Threads

    • One per DB connection
    • Sequential execution per thread
    • Connection isolation

    Client Request Threads

    • Asynchronous request handling
    • Non-blocking UI operations
    • Parallel client support

    Error Handling

    Connection Failures

    • Automatic retry logic
    • Connection pooling recovery
    • Error event propagation

    Query Errors

    • Exception capture in TServer
    • Error property population
    • Tag mapping skipped on error

    Timeout Management

    • Configurable command timeout
    • Connection timeout settings
    • Automatic cleanup

    Best Practices Checklist 

    •  Prefer asynchronous - Use properties over methods
    •  Avoid UI blocking - No synchronous calls from screens
    •  Use appropriate domains - Client for user, Server for shared
    •  Pool connections - Reuse database connections
    •  Optimize queries - Index, parameterize, limit
    •  Handle errors - Check status properties
    •  Monitor performance - Track execution times

    Troubleshooting

    Slow queries:

    • Check execution plan
    • Add appropriate indexes
    • Reduce result set size
    • Use asynchronous execution

    Connection issues:

    • Verify TServer running
    • Check connection string
    • Review firewall rules
    • Monitor connection pool

    Tag mapping problems:

    • Verify domain selection
    • Check tag existence
    • Review mapping configuration
    • Confirm execution context

    Thread blocking:

    • Avoid synchronous in UI
    • Use Script Tasks
    • Implement async patterns
    • Monitor thread pool

    Overview

    The Dataset Module connects your solution to databases through TServer services, managing data flow, security, and performance. This reference covers essential practices for production deployments, including concurrency management, security hardening, and performance optimization.

    Architecture & Execution Model

    How the Dataset Module Works

    The Dataset Module operates as an intermediary layer between your solution and databases:

    Preventing Concurrency Conflicts

    • TServer Integration: All database operations route through TServer services
    • Execution Modes: Supports both synchronous (blocking) and asynchronous (non-blocking) operations
    • Result Processing: Returns .NET DataTable objects for flexible data manipulation
    • Distribution: Propagates data to displays, reports, scripts, and other modules

    Synchronous vs Asynchronous Operations

    Synchronous Execution:

    • Blocks execution until database responds
    • Returns DataTable directly to calling method
    • Stores result in Local Contents property
    • Best for: Small queries, immediate data needs

    Asynchronous Execution:

    • Non-blocking operation
    • Updates Async Contents property when complete
    • Enables row-by-row navigation
    • Best for: Large datasets, UI responsiveness

    Concurrency & Server Domain Management

    Understanding Server Domain Attributes

    All Dataset Module properties exist in the server domain, creating

    a

    shared resource

    environment

    risks:

    Example Risk Scenario:
    1. Client A sets: SQLStatement = "SELECT * FROM Orders WHERE Status='Open'"
    2. Client B sets: SQLStatement = "SELECT * FROM Orders WHERE Status='Closed'"  
    3. Execute command runs with Client B's statement (last write wins)
    

    Preventing Concurrency Conflicts

    Prevention Strategies:

    Strategy 1:
    1. Dedicated Query Objects
    1. : Create separate query objects for different operations
    Assign unique queries to specific tasks or displaysStrategy 2:
  • Avoid sharing query objects between concurrent processes
    1. Synchronization Patterns
    Strategy 3:
    1. : Use semaphores or locks in scripts
  • Implement request queuing for shared resources
  • Design state machines for complex operations
    1. Client-Side Processing
    1. : Execute queries in scripts with local variables
  • Process DataTables before assignment to tags
  • Minimize server domain property modifications

  • Data Management Strategies

    DataTable Usage Patterns

    The Dataset Module provides three primary patterns for DataTable management:

    Pattern 1: Direct Script Processing

    csharp

    DataTable result = @Dataset.Query.Query1.SelectCommand();
    // Process data locally without server domain impact
    foreach(DataRow row in result.Rows) {
        // Local processing
    }
    

    Pattern 2: Tag Distribution

    csharp

    // Assign to DataTable tag for module sharing
    @Tag.MyDataTable = @Dataset.Query.Query1.SelectCommand();
    // Now available to displays, reports, etc.
    

    Pattern 3: Mapped Navigation

    csharp

    // Configure mapping, then navigate rows
    @Dataset.Query.Query1.Select();
    @Dataset.Query.Query1.Next(); // Moves to next row
    

    Memory & Traffic Optimization

    Control Data Volume:

    • Always use WHERE clauses to filter results
    • Implement pagination for large datasets
    • Use SELECT specific columns instead of SELECT *
    • Consider indexed views for complex queries

    Resource Planning:

    Small Query: < 1,000 rows = Minimal impact
    Medium Query: 1,000-10,000 rows = Monitor memory usage
    Large Query: > 10,000 rows = Implement pagination
    

    Security Implementation

    SQL Injection Prevention

    Never Do This:

    sql

    string query = "SELECT * FROM Users WHERE Name = '" + userInput + "'";
    

    Always Do This:

    sql

    execute GetUserData @userName={Tag.UserInput}, @userId={Tag.UserId}
    

    The platform's parameterization:

    • Treats all parameters as values, not code
    • Prevents malicious SQL execution
    • Maintains data type integrity
    • Supports all major database platforms

    Network Security Architecture

    Gateway Configuration for Restricted Databases:

    1. Identify Restriction: Database accessible only from specific servers
    2. Install Gateway: Deploy platform with TWebServer on authorized machine
    3. Configure ServerIP: Point Dataset connections to gateway machine
    4. Result: Secure database access through controlled gateway

    Benefits:

    • Maintains network security policies
    • Centralizes database connections
    • Enables audit logging
    • Supports DMZ architectures

    Database-Specific Configuration

    Platform Compatibility

    DatabaseSyntax ExampleSpecial Considerations
    SQL ServerSELECT TOP 10 * FROM TableUse TOP for limiting
    SQLiteSELECT * FROM Table LIMIT 10Use LIMIT clause
    MySQLSELECT * FROM \Table` LIMIT 10`Backticks for names
    PostgreSQLSELECT * FROM "Table" LIMIT 10Case-sensitive names
    OracleSELECT * FROM Table WHERE ROWNUM <= 10ROWNUM for limiting

    Time Zone Management

    Default Behavior:

    • Platform stores all DateTime values as UTC
    • Historian and Alarm data always in UTC
    • Automatic conversion for display

    Configuring External Databases:

    DateTimeMode Settings:
    - UTC: No conversion needed
    - LocalTime: Platform converts automatically
    - Custom: Handle in SQL statements
    

    Local Time Queries:

    sql

    -- Adjust for local time zone (example: EST -5 hours)
    WHERE Timestamp >= DATEADD(hour, -5, @Tag.StartTimeUTC)
    

    Performance Optimization

    Query Optimization Checklist

    ? Indexes: Ensure indexes on filtered and joined columns ? Statistics: Update database statistics regularly ? Query Plans: Review execution plans for bottlenecks ? Connection Pooling: Enable for frequent operations ? Batch Operations: Group multiple operations when possible

    Performance Monitoring

    Key Metrics to Track:

    • Query execution time
    • Memory consumption
    • Network latency
    • Connection pool usage
    • Cache hit rates

    Diagnostic Properties:

    @Dataset.Query.Query1.Error         // Last error message
    @Dataset.Query.Query1.ExecutionTime // Query duration
    @Dataset.Query.Query1.RowCount      // Result size
    

    Optimization Patterns

    Good: Asynchronous from screen

    csharp

    @Dataset.Table.MyTable.SelectCommand = "SELECT * FROM Data";

    Bad: Synchronous from screen (blocks UI)

    csharp

    @Dataset.Table.MyTable.SelectCommandWithStatus();

    Error Handling & Recovery

    Error Detection

    Methods

    The module provides multiple error detection methods:

    Method 1: Property Monitoring

    csharp

    @Dataset.Query.Query1.SelectCommand();
    if (@Dataset.Query.Query1.Error != "") {
        // Handle error
    }
    

    Method 2: Status Methods

    csharp

    string status;
    DataTable result = @Dataset.Query.Query1.SelectCommandWithStatusAsync(out status);
    if (status != "OK") {
        // Handle error
    }
    

    Common Error Scenarios

    Error TypeTypical CauseResolution
    Connection TimeoutNetwork issues, server loadIncrease timeout, check connectivity
    Syntax ErrorDatabase-specific SQLVerify syntax for target database
    Permission DeniedInsufficient privilegesCheck database user permissions
    DeadlockConcurrent transactionsImplement retry logic
    Out of MemoryLarge result setAdd pagination, increase resources

    Backup & Recovery

    SQLite Backup Strategies

    Option 1: Command Line Backup

    bash

    sqlite3 source.db ".backup backup.db"
    
    • Simple and reliable
    • Requires database file access
    • Best for scheduled maintenance

    Option 2: Online Backup API

    • Backup while database is active
    • Support for incremental backups
    • Progress monitoring capability

    Option 3: File System Copy

    • Only when database is offline
    • Fastest for large databases
    • Requires downtime

    Backup Best Practices

    1. Schedule: Automate backups during low-activity periods
    2. Verify: Test restore procedures monthly
    3. Rotate: Maintain multiple backup generations
    4. Secure: Store backups in separate physical location
    5. Document: Maintain restore procedure documentation

    Store & Forward Limitations

    The Store & Forward feature has specific requirements:

    • Applies Only To: Historian and Alarm databases
    • Required Schema: Must include control columns
    • Not Available For: Generic application databases
    • Alternative: Implement custom buffering for generic databases

    For Store & Forward configuration, see Historian Archiving Process documentation.


    Best Practices Summary

    Design Principles

    1. Isolation: Use dedicated query objects for different operations
    2. Filtering: Always limit result sets with WHERE clauses
    3. Security: Use parameterized queries exclusively
    4. Monitoring: Track performance metrics and errors
    5. Planning: Design for concurrent access from the start

    Production Checklist

    Before deploying to production:

    [ ]

    ? Parameterized all dynamic queries

    [ ]

    ? Implemented error handling for all operations

    [ ]

    ? Tested concurrent access scenarios

    [ ]

    ? Configured appropriate timeouts

    [ ]

    ? Established backup procedures

    [ ]

    ? Documented recovery processes

    [ ]

    ? Verified timezone handling

    [ ]

    ? Optimized query performance

    [ ]

    ? Planned for data growth

    [ ]

    ? Secured network access


    Troubleshooting Guide

    Slow queries:

    • Check execution plan
    • Add appropriate indexes
    • Reduce result set size
    • Use asynchronous execution

    Connection issues:

    • Verify TServer running
    • Check connection string
    • Review firewall rules
    • Monitor connection pool

    Tag mapping problems:

    • Verify domain selection
    • Check tag existence
    • Review mapping configuration
    • Confirm execution context

    Thread blocking:

    • Avoid synchronous in UI
    • Use Script Tasks
    • Implement async patterns
    • Monitor thread pool

    Related Documentation

    • Datasets SQL Query (Tutorial)
    • Datasets
    • Engine
    • Module (
    • Reference
    • Concept)
    • Datasets
    • Runtime Attributes
    • Module (How-to Guide)
    • Historian Archiving Process
    • TServer Configuration Guide



    In this section...

    Page Tree
    root@parent
    spaces93DRAF