> For the complete documentation index, see [llms.txt](https://help.qtech.co.nz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.qtech.co.nz/datran/datran-vi-scada/datran-vi/sql-server.md).

# Database logging and SQL Server

How DATRAN VI logs to SQL Server: the ADO service, the database tables, checking logging, an alarm for a stalled database, TLS 1.2, and the V6.78 diagnostic messages.

The DATRAN ADO Database Connectivity (ADO service) provides a database logging capability for the DATRAN Scada system to connect with Microsoft SQL Server. The ADO and HDI services attempt to write data to the SQL Server Datran Database. Clients of the database include DATRAN Trending and Reporting. MS SQL Server is not a QTech product.

{% hint style="info" %}
**Applies to:** DATRAN VI with SQL Server. For V6.78's persistent queues, see [Persistent queues](https://help.qtech.co.nz/datran/datran-vi-scada/datran-vi/persistent-queues.md).
{% endhint %}

## How data gets logged

* Previously a new and more efficient way of logging data to the DATRAN database was introduced called `_Log_Analogue_`. A few DATRAN systems still utilise the previous and more complicated DATRAN Alarm based `_Log_` method for logging values. We recommend that all systems implement the "new" `_Log_Analogue_` mechanism as it is less CPU intensive and more accurate. When a `_Log_Analogue_` is placed under a node with a known name, the Units field will be automatically populated. E.g. units of l/s for a node called Flow.
* A user-defined `_ADO_Execute_` or `_ADO_Query_` node contains SQL. The `_ADO_Query_` node will query the database.
* Records retrieved from the RTU by HDI are stored in the SQL server. See [RTU data logging (HDI)](https://help.qtech.co.nz/datran/datran-vi-scada/datran-vi/rtu-data-logging.md).

### Connection settings

The ADO connection is under **Applications\ADO Database Connectivity\Databases\DATRANdatabase\Properties**:

| Setting                          | What it is                                                                                                                                                            |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Database                         | The database name, typically expected to be "DatranDatabase"                                                                                                          |
| Database Provider                | The OLE DB provider: SQLOLEDB, MSOLEDBSQL or MSOLEDBSQL19. See [Use TLS 1.2](#use-tls-1.2-for-the-sql-server-connection).                                             |
| Active Connection                | Shows if Datran is connected to the SQL server or not                                                                                                                 |
| Recovery Path, HDI Recovery Path | Used to configure where the persistent queue data is stored. See [Persistent queues](https://help.qtech.co.nz/datran/datran-vi-scada/datran-vi/persistent-queues.md). |

## The database tables

When data is logged to the database from DATRAN, depending on the type of data it will be stored in either tblDigital, tblAnalog or tblEvent. These tables contain as little information as possible as they usually contain many million entries.

| Table           | Holds                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| tblAnalog       | Information relating to analogue points in DATRAN: Point ID (iPointId), Log Time (dtTime) and Value (fltValue)                                                                                                                                                                                                                                                                                                                                                                                      |
| tblDigital      | The sequence of events relating to a particular digital event, or alarm: the digital turning on, turning off, and being acknowledged (for alarms). Point ID (iPointId), On Time (dtStart), Off Time (dtStop), Acknowledgement Time (dtAcknowledged) and Acknowledgement Operator (strAcknowledgedBy)                                                                                                                                                                                                |
| tblEvent        | Information about a digital event: Event Occurrence Time (dtTimeStamp), Event Type (strType, usually ALM, RTN, or ACK), Point ID (iPointId), Cause Of Event (strCause) and Operator ID (iOperatorID)                                                                                                                                                                                                                                                                                                |
| tblPoint        | The table which maps points to unique integer ids                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| tblPoints       | Additional information about any points that are logged to the database: Point ID (iPointId), Site Name (strSite), Equipment Type (strEquipType), Equipment Name (strEquipName), Point Name (strPoint), Point Units (strUnits), System Name (strSystem), Station Address (StationNo), Point Type (strDomain, i.e. analogue, alarm or event), Point Maximum Value (iMax) and Point Minimum Value (iMin), used by historical trending to determine the maximum and minimum value to use on the Y-axis |
| tblOperator     | Associates a unique ID to every operator that is used within the database: Operator ID (iOperatorID) and Operator Name (strName)                                                                                                                                                                                                                                                                                                                                                                    |
| tblAlias        | Alias ID (iAliasID) and Alias Name (strName), the human readable alias name such as "After Hours"                                                                                                                                                                                                                                                                                                                                                                                                   |
| tblSMSMessaging | Information about any text messages that have been sent out from DATRAN to the Datashed Gateway due to any alarm, acknowledgement or return to normal event (if the SMS Message with Logging annunciator has been used)                                                                                                                                                                                                                                                                             |

The above table contains many foreign keys to obtain information from other tables. To simplify this a new view has been created (as of DATRAN v6.68SP2) called vwSMSAlarmInfo. A new extended view for SMS Message logging (vwSMSMessageEx) has been created in the DATRANDatabase which includes both the Operator Name and the Operator Alias.

For tblAnalog the primary key is a combination of the point id and the timestamp. The timestamp resolution is governed by how quick DATRAN can process the data. i.e. if two logs on the same point were to occur on the same 100th second then the second log would be lost.

For the full layout, see [Database tables and views for reports](https://help.qtech.co.nz/datran/datran-vi-scada/datran-reporting/database-views.md).

## Check that data is being logged

* **In DATRAN Trending,** or with **Trend** in Supervisor: select I/O which is confirmed as being written to the SQL Tables, select a date range no older than 1 day from the current date, and ensure that data displayed are current (recent).
* **In DATRAN Browser:** the ADO service's **Active** node should be 1 and the database's **Active Connection** should be "Connected".
* **In DATRAN Diagnostics:** select the following Categories: ADO Database Connectivity: Diagnostic, Execute and LogNodes, and Historical Data Interface: AdoDCM, AdoDCM Error and AdoDCM Execute. Ensure that data from the out stations are being written to MSSQL with no errors.
* **In SQL Server Management Studio:**
  1. Expand DatranDatabase > Tables. Right-click `dbo.tblPoints` and select **Select Top 1000 Rows**. Add `where strSite = '<site name as in DATRAN>'` and click **Execute**. Look for and record the relevant Data Point ID.
  2. Right-click `dbo.tblAnalog` and select **Select Top 1000 Rows** if the required I/O is an Analog Input. Add `where iPointId = <point ID> order by dtTime desc` and click **Execute**. Check that the data displayed reflects the current date/time.

If data isn't arriving, see [Trending shows no new data](https://help.qtech.co.nz/datran/datran-vi-scada/datran-vi/troubleshooting/no-new-data.md).

## Get an alarm when the database stops logging

On rare occasions the ADO service will report that the database is connected but in fact a problem with the server running the database is preventing data to be written. A simple mechanism lets DATRAN operators configure their system for alerting both when the ADO service has lost connection, as well as if data isn't being sent or received by the database.

The easiest way to install the facility is to copy and paste the components from a sample TBD file called "DatabaseAlarm.tbd" into your own DATRAN system TBD. The sample TBD can be provided by QTech on request. The control mechanism consists of two parts:

* A node placed under the Sites folder (**ADO Not Logging**) containing an `_ADO_Query_` to read from the database, an `_Alarm_`, a formula to set the alarm and a `_Template_` for a script. For best use, the node should be put in a location with a `_Comms_Object_` to be visible and listed in the Site List in DATRAN Supervisor.
* A node placed under the system folder to hold the script itself. The script is a DATRAN script written to automatically rerun the `_ADO_Query_` and update the time it returned.

| Setting under the template | Default    | What it does                                                        |
| -------------------------- | ---------- | ------------------------------------------------------------------- |
| Poll Interval              | 5 minutes  | How often the `_ADO_Query_` is run                                  |
| Alarm Interval             | 10 minutes | How long it waits until raising the alarm if no update happens      |
| Most Recent Result         |            | Updated with the most recent logged time if the query is successful |
| Finish Time                |            | Updated to the current time to prove that it ran                    |
| Time Taken                 |            | Increases from 0 to 60, or "Unable to read the database."           |

Once the `_Script_` and `_Template_` have been copied over, the `_Template_` will need to be applied for it to run. After this it will automatically start whenever the DATRAN Server reboots following an update. If the downtime from updates is longer than the Alarm Interval specified above then the alarm will be raised immediately, so a step should be included in the alarm sequence to wait a couple minutes for the script to run and update the `_Template_`/Most Recent Result time.

To check that the script is running, look for the Finish Time node inside the `_Template_`. This will update every time the database is queried. **If this value is more than a few minutes in the past and not updating, then there can be a few reasons:**

* The ADO service has stopped or DATRAN hasn't connected to the database (such as by passwords or the name/IP address changing). This is expected behaviour for the script and it will set `_Template_\Time Taken` to be "Unable to read the database." To fix, you may need to restart the ADO service or contact your IT team to see if anything has been changed with the database.
* The database was queried but no value was returned. This could be caused by the database slowing down and not processing the query. When this happens, the value of `_Template_\Time Taken` will increase from 0 to 60 and then change to "Unable to read the database." This is also the expected behaviour by the script.
* There was an issue with the Derived Value Generator service and the script has stopped. Apply the `_Template_` to start it again.

To test the alarm manually, change the value of the Alarm Interval to be less than the Poll Interval. It can also be tested by renaming the `_Template_` node to stop it running. If the ADO service is not running or the Active Connection status for the database is not "Connected" then the script will skip querying the database. A separate alarm to monitor the status of these nodes may also be wanted to give an early warning.

## Use TLS 1.2 for the SQL Server connection

DATRAN can support the use of TLS 1.2 for its connections to SQL Server. Utilising a higher-level protocol helps prevent eavesdropping or attacks on internal "trusted" networks should attackers be able to penetrate firewall systems. Whether TLS 1.2 or another version is used in practice depends on Operating System settings, security policies and how the SQL Server is configured or whichever ciphers its supports.

| Provider                | TLS support                                                                                                                                                                                                                                                                      |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| SQLOLEDB                | This is what DATRAN shipped with as the default and what many customers are still using. It is deprecated and officially only supports SSL 3.0 and TLS 1.0 (in practice what it supports is highly OS dependent).                                                                |
| MSOLEDBSQL (version 18) | This version does not enforce encryption by default but supports TLS 1.2. It is more permissive in terms of encryption enforcement and is compatible with older SQL Server versions (SQL Server 2016-2019).                                                                      |
| MSOLEDBSQL19            | The current, actively maintained and recommended provider with full support for TLS 1.2+ (including TLS 1.3). It enforces mandatory encryption. TLS 1.3 support requires at least Windows Server 2022 and SQL Server 2022, and it will make more demands regarding certificates. |

To enable support for TLS 1.2 we recommend that customers switch to the MSOLEDBSQL provider if they are currently using SQLOLEDB:

1. MSOLEDBSQL (or MSOLEDBSQL19) must be installed to enable DATRAN to use it. It does not ship with Windows automatically so may need to be downloaded and installed.
2. In DATRAN Browser, under **Applications\ADO Database Connectivity\Databases**, change the Database Provider property on the DATRANdatabase node from `SQLOLEDB` to `MSOLEDBSQL` (or `MSOLEDBSQL19`).
3. Restart the ADO and HDI services.

If the DATRAN system uses a custom connection string that includes the OLE DB provider name, then the string should be updated to the new provider (MSOLEDBSQL or MSOLEDBSQL19). For systems that use a Data Source Name (e.g. an ODBC connection) the Data Source may need to be reconfigured to use strong encryption, plus the ODBC or OLE DB driver may need to be patched on the server to the latest versions. Please refer this issue to the IT SYSADMIN. Both MSOLEDBSQL and MSOLEDBSQL19 drivers can coexist on the same system. If you are troubleshooting connection issues or cannot immediately upgrade your SQL Server certificate to support mandatory encryption, then use MSOLEDBSQL as the Database provider.

Configuring the IT system for TLS 1.2 support is in the domain of IT SYSADMIN.

## Diagnostic messages

In V6.78 there are new diagnostic categories in DATRAN, for the ADO and HDI, that can show you exactly what SQL is being executed, and the responses from the server, among other things. These will contribute to a significant performance bottleneck when turned on.

| Category                                | Message                                                                                                                                                                   | Severity | Meaning                                                                                                                                                                                                                                                                                                                                                                                                                                                        | Suggested Action                                                                                                                                                                                                                                                                          |
| --------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| LogAnalogError/ LogEventError           | One or more chunks failed to be processed due to a connection error: {specific error message}. Processing will be re-attempted when a connection is re-established.       | Medium   | Indicates that a previously established connection to the SQL Server has been lost. The inner message may give more insight into cause but it is likely to just be something along the lines of "general network error".                                                                                                                                                                                                                                       | If persisting, investigate the SQL Server health and network connectivity.                                                                                                                                                                                                                |
| LogAnalogError/ LogEventError           | One or more chunks failed to be processed due to an unexpected error: {specific error message}. Chunks will be moved to unrecoverable to be re-attempted at a later time. | High     | These are not supposed to occur during normal operation. This indicates that some kind of error occurred that the program doesn't know how to handle. This most likely represents a deficiency in the software.                                                                                                                                                                                                                                                | Report the issue to QTech                                                                                                                                                                                                                                                                 |
| LogAnalogError/ LogEventError           | Upload of chunk {i} failed due to Primary Key Exception. Removing any records already in Db from chunk and uploading again...                                             | Low      | The service is trying to upload at least one record that already exists in the database. This happens often during normal operation of the HDI, as retrieved record datagrams of RTU logged data may have some overlapping records. Not expected to occur in the ADO service, because ADO data is not historical, it is real-time and timestamped by the ADO service with the current time (so should not be possible that it is already in the SQL database). | None.                                                                                                                                                                                                                                                                                     |
| LogAnalogError/ LogEventError           | Upload of chunk {i} failed due to {exception type}: {exception message}.                                                                                                  | Medium   | A chunk of records failed to be uploaded to the SQL server. This may be because of a connection error or some other type of error. The type of the exception and its error message will give some insight. This will be followed by one or the other of the "One or more chunks…" error messages depending on whether the system diagnoses the error type as a connection error or unrecoverable error.                                                        | Defer to subsequent error message.                                                                                                                                                                                                                                                        |
| ExecuteNonQueryError/ ExecuteQueryError | {Command/Query} execution failed due to connection loss: {error message}.                                                                                                 | Medium   | Indicates that a previously established connection to the SQL Server has been lost. The inner message may give more insight into cause but it is likely to just be something along the lines of "general network error".                                                                                                                                                                                                                                       | If persisting, investigate the SQL Server health and network connectivity.                                                                                                                                                                                                                |
| ExecuteNonQueryError/ ExecuteQueryError | {Command/Query} execution failed due to OleDb Exception: {error message}.                                                                                                 | Medium   | Most likely indicates something wrong with the SQL command trying to be executed. ExecuteNonQuery/ExecuteQuery can be doing a lot of different things and could be e.g. a user-defined *ADO\_Execute* or *ADO\_Query* so could contain malformed SQL.                                                                                                                                                                                                          | Depends on underlying cause. Refer to the inner error message. If error persists, the RawSql and RawSqlError diagnostic categories can be enabled to inspect the exact SQL being executed and the SQL server responses.                                                                   |
| Connection                              | Autocreate failed due to connection error: {error message}. Reattempting {in timespan}…                                                                                   | Medium   | Only occurs when trying to autocreate the Datran Database (requires changing "Database" property to "master" and "Auto Create" property to 1 on database object in the TBD). Indicates that a previously established connection to the SQL Server has been lost. The inner message may give more insight into cause but it is likely to just be something along the lines of "general network error".                                                          | If persisting, investigate the SQL Server health and network connectivity.                                                                                                                                                                                                                |
| Connection                              | Autocreate failed due to error: {error message}. Abandoning autocreate attempt.                                                                                           | High     | Only occurs when trying to autocreate the Datran Database (requires changing "Database" property to "master" and "Auto Create" property to 1 on database object in the TBD). Indicates that the autocreate process failed.                                                                                                                                                                                                                                     | Refer to the inner error message. Try to resolve whatever issue is preventing the auto create process from succeeding. The RawSql and RawSqlError diagnostic categories can be enabled to inspect the exact SQL command that is failing.                                                  |
| Connection                              | Connection lost during {auto-update/validation} attempt: {error message}. Reattempting {in timespan}…                                                                     | Medium   | Indicates that a previously established connection to the SQL Server has been lost. The inner message may give more insight into cause but it is likely to just be something along the lines of "general network error".                                                                                                                                                                                                                                       | If persisting, investigate the SQL Server health and network connectivity.                                                                                                                                                                                                                |
| Connection                              | Database schema validation failed: {error message}. Reattempting {in timespan}…                                                                                           | High     | Indicates that the SQL server database schema does not match the expected schema for the Datran database. No further operations can be performed on the database until the validation errors have been resolved.                                                                                                                                                                                                                                               | Check that the database is named correctly in the TBD (the "Database" property under "Applications\ADO Database Connectivity\Databases\\{database}\Properties\Database", this is typically expected to be "DatranDatabase". Verify that this database exists on your SQL server instance. |
| Connection                              | encountered error during auto-update: {error message}.                                                                                                                    | Low      | Something went wrong executing the ADO's auto-update script. The script is old and parts may not work on modern systems. This does not seem to have any negative effects in practice.                                                                                                                                                                                                                                                                          | None.                                                                                                                                                                                                                                                                                     |
| RawSqlError                             | Execute {NonQuery/Reader/Scalar} Failed: {error message}.                                                                                                                 | Medium   | An error occurred trying to execute some SQL. The exact SQL executing that produced the error can be seen if the RawSql diagnostic category is also enabled. Most likely the context will also be clarified by having the other error categories enabled (LogAnalogError, LogEventError, etc.).                                                                                                                                                                | Depends on underlying cause. Refer to inner error message and other error diagnostic categories for context, and RawSql category if necessary.                                                                                                                                            |
