Examples

Prev Next

Note:

The first nine examples retain earlier configuration screens and script interfaces. From N3uron version 1.22.8, use Configuring and testing wind-farm transactions for the current pipeline setup.
Older scripts may require adaptation. Some earlier examples construct SQL statements by concatenating strings without general-purpose input escaping. The new History example uses bound parameters instead.

Reading tag and timestamp values from a MySQL database

In this example, SQL Client is used to connect to a MySQL database located in the same machine to extract the following data:

Reading tag and timestamp values from a MySQL database: In this example, SQL Client is used to connect to a MySQL database located in the same machine to extract the following data:

Step 1:

Configuration of the connection.

Figure - SQL 15

Step 2:

Configuration of the transaction.

Reading tag and timestamp values from a MySQL database: Configuration of the transaction

Read the selected sensor columns from test_compact. The table must contain all six columns:

  • SELECT: Requests id, temperature, humidity, status, errorCode and ts.

  • $.output: Holds the SQL query string for the Query stage.

$.output = "SELECT id, temperature, humidity, status, errorCode, ts FROM test_compact";

Convert query rows to sensor tag events. The result must include id, ts and the measurement columns:

  • Dataset: Visits each row and column. It skips id and ts as measurement values.

  • Tag event: Builds the sensor address from the row ID and column name. It copies the value and row timestamp, and sets quality 192.

  • $.output / $.logger.debug: Appends each event and logs the column names and event data.

for(const row of $.input.rows()){
  //Iterate through the columns of the Dataset for each row
  for(const col of $.input.columns()){
    //Get the name of the current column
    const column = col.getName();
    $.logger.debug("Column is %s", column);
    //Ignore id and ts columns
    if(column === "id" || column === "ts") continue;
    const tagData = {};
    //Set the destination tag using the format rowid_columnName
    tagData.tag = "sensor"+row.getValue("id")+"_"+column;
    //Get the value of the current column at this row
    tagData.value = row.getValue(column);
    //Set quality to 192
    tagData.quality = 192;
    //Set the ts to the value of the ts column
    tagData.ts = row.getValue("ts");
    $.logger.debug("Tag data is %j", tagData);
    //Push the tag data object to the output array
    $.output.push(tagData);
  }
}

Step 3:

Tag configuration settings for linking the data received from the database to tags.

Reading tag and timestamp values from a MySQL database: Tag configuration settings for linking the data received from the database to tags

Inserting historical data into a database

This example explains how to use a HistoryTransaction to insert N3uron tag events into a database.

The database in this example is MySQL and as such, a syntax that is compatible with MySQL is used.

Step 1:

 The target table should have the following schema:

Inserting historical data into a database: The target table should have the following schema:

Step 2:

 The following screenshot shows the HistoryTransaction configuration:

Inserting historical data into a database: The following screenshot shows the HistoryTransaction configuration:

Step 3:

Convert History events to rows for the n3_history insert:

  • Dataset: Declares columns for the tag, typed values, quality and timestamp.

  • typeof / switch: Selects the number, string or Boolean field. It leaves the other value fields null.

  • String values: Adds SQL quotes to tag and text values. It does not escape embedded quotes.

  • $.output: Returns the populated Dataset, or a new empty Dataset when no rows were added.

const ds = new Dataset();
//Add all columns that are used to the Dataset
ds.addColumn("tag", "NVARCHAR");
ds.addColumn("number_value", "DOUBLE");
ds.addColumn("string_value", "NVARCHAR");
ds.addColumn("bool_value", "TINY_INT");
ds.addColumn("quality", "TINY_INT");
ds.addColumn("ts", "DATETIME");
for (const event of $.input) {
  const row = {
    //Tag is escaped with the string separator for MySQL
    tag: "'"+event.tag+"'",
    string_value: null,
    number_value: null,
    bool_value: null,
    quality: event.quality,
    ts: event.ts
  }
  //Depending on the type of the event, set the relevant field
  switch (typeof event.value) {
    case "number":
      row.number_value = event.value;
      break;
    case "string":
      //Add string quotes since string values need to be quoted in the query
      row.string_value = sprintf("'%s'", event.value);
      break;
    case "boolean":
      row.bool_value = event.value;
      break;
  }
  //Add the row to the Dataset
  ds.addRow(row);
}

//If the output row count is 0, return empty Dataset
if (ds.getRowCount() === 0) $.output = new Dataset();
else $.output = ds;

Step 4:

Build a MySQL INSERT from the preceding Dataset. The destination table must match its six columns:

  • Empty input: Sets $.output to an empty string when the Dataset has no rows.

  • _insertData: Builds one value list per row and joins the lists for n3_history.

  • FROM_UNIXTIME: Uses each Date timestamp in seconds. The preceding Serializer supplies the quoted tag and text values.

  • $.output: Receives the generated INSERT text. The database user needs INSERT permission.

//If the input Datasets has no rows, return an empty string to abort the query
if($.input.getRowCount() === 0){
  $.output = ""
} else {
  $.output += _insertData();
}

function _insertData(){
  const values = [];
  //Iterate through all the rows in the input Dataset
  for(const row of $.input){
    //String variable that holds the values to insert for each row
    let rowValues = "(";
    rowValues += row.getValue("tag")+",";
    rowValues += row.getValue("string_value")+",";
    rowValues += row.getValue("number_value")+",";
    rowValues += row.getValue("bool_value")+",";
    rowValues += row.getValue("quality")+",";
    //Timestamp is created using the MySQL function FROM_UNIXTIME(epoch).
    rowValues += sprintf("FROM_UNIXTIME(%d)", row.getValue("ts").getTime()/1000);
    rowValues += ")";
    //Push the row values into the values array
    values.push(rowValues);
  }
  //Return the query
  const query = sprintf("INSERT INTO n3_history (tag, string_value, number_value, bool_value, quality, ts) VALUES "+ values.join(",\r\n"));
  return query;
}

This query will execute in event mode (it only sends new tag events) and the trigger will be a buffer size trigger, which means that the transaction triggers whenever there are 500 events or more in the buffer.

Microsoft SQL Server Table Creation and Insert queries from parameters

This example is designed to automate the process of creating a table in a Microsoft SQL Server database and inserting data into it using a query script.

The script first checks if the specified table exists in the database, and if it does not, it creates the table with predefined columns. These columns include an auto-incrementing primary key (id), a timestamp (DateAndTime), and three fields for storing voltage values (VoltageBR, VoltageRY, and VoltageYB).

The script generates an SQL query to insert a new row into the table. The row includes the current date and time and voltage data fetched from external parameters. This script is especially useful in scenarios where data needs to be dynamically stored in a database at regular intervals.

Additionally, the trigger can be customized to respond to specific events, allowing for flexible data storage based on various conditions.

Step 1:

Configuration of the connection.

SqlClient01

Step 2:

 Configuration of the standard transaction includes setting the parameters and defining the trigger. In this case, the trigger is a Cron expression configured to execute the transaction every minute.SqlClient02

Step 3:

Build a SQL Server batch from the numeric parameters tag1, tag2 and tag3:

  • _createTableSqlServer: Builds an existence check and a CREATE TABLE statement for _1MIN, with identity, timestamp and voltage columns.

  • _insertDataSqlServer: Formats the current ISO date-time and the three parameter values into an INSERT statement.

  • $.output: Joins both SQL statements. The database user needs permission to create the table and insert rows.

// Constant representing the name of the target database table. 
// If the table belongs to a specific schema, use the format "schema.table_name".
const TABLE_NAME = "_1MIN";

/**
 * Generates a SQL query to create a table in SQL Server if it doesn't already exist.
 * The table will store data with the following structure:
 * - id: An integer primary key with auto-increment starting from 0.
 * - DateAndTime: A non-nullable datetime field to record the timestamp.
 * - VoltageBR, VoltageRY, VoltageYB: Float fields to store voltage values.
 *
 * @returns {string} The SQL query to create the table.
 */
function _createTableSqlServer() {
  const query = sprintf(
    "IF OBJECT_ID(N'%1$s', N'U') IS NULL BEGIN\
    CREATE TABLE %1$s (\
        \"id\" INT PRIMARY KEY IDENTITY(0, 1),\
        DateAndTime DATETIME2 NOT NULL,\
        VoltageBR FLOAT,\
        VoltageRY FLOAT,\
        VoltageYB FLOAT,\
    )\
    END;\r\n", 
    TABLE_NAME
  );
  return query;
}

/**
 * Generates a SQL query to insert data into the SQL Server table.
 * The data includes:
 * - Current date and time.
 * - Voltage values fetched from external parameters (tag1, tag2, tag3).
 *
 * @returns {string} The SQL query to insert the data.
 */
function _insertDataSqlServer() {
  const currentDateTime = new Date().toISOString().slice(0, 19).replace('T', ' ');
  const query = sprintf(
    "INSERT INTO %s (DateAndTime, VoltageBR, VoltageRY, VoltageYB) VALUES ('%s', %f, %f, %f)",
    TABLE_NAME,
    currentDateTime,
    $.parameter.tag1.value,
    $.parameter.tag2.value,
    $.parameter.tag3.value
  );
  return query;
}

// Execute the functions to create the table (if it doesn't exist) and insert data into it.
$.output = _createTableSqlServer();
$.output += _insertDataSqlServer();

Creating Insert queries from parameters

This example deals with a common scenario where several tag values need to be periodically inserted into the database. Although a History Transaction is usually a more efficient way for this task, we will be using a Standard Transaction to illustrate how to work with Parameters. The database connection is assumed to be already created and working.

The syntax used in this example is compatible with MySQL. If the destination database is different, the syntax might require small changes within the query.

Step 1:

Configuration of the transaction.

Creating Insert queries from parameters: Configuration of the transaction

Step 2:

Build one MySQL INSERT from the configured parameters. Their names must match columns in the existing n3_data table:

  • getColumns: Uses the parameter names as backtick-quoted column names.

  • getValues / cast: Keeps numbers, doubles quotes in strings, converts Booleans to numbers, and converts null to SQL NULL.

  • Type handling: Throws an error for unsupported value types.

  • $.output: Receives the INSERT statement returned by insert().

const TABLE_NAME = "n3_data";

$.output = insert();

function insert(){
  const query = sprintf("INSERT INTO %s (%s) VALUES (%s)", TABLE_NAME, getColumns().join(","), getValues().join(","));
  return query;
}

function getColumns(){
  const columns = [];
  //Iterate through all the parameters
  for(const p of Object.keys($.parameter)){
    //Use the parameter name as column name, and escape it using the escape character `
    columns.push(sprintf("`%s`", p));
  }
  return columns;
}

function getValues(){
  const values = [];
  //Iterate through all the parameters
  for(const value of Object.values($.parameter)){
    //Cast the value into the appropiate type and push it into the values array
    values.push(cast(value.value));
  }
  return values;
}
function cast(value){
  //If the value is null, the string NULL is returned
  if(value === null){
      return "NULL";
  }
  switch (typeof value){
    case "number":
      //If the value is a number, return it without changing
      return value;
    case "string":
      //If the value is a string, convert it to a MySQL string using '
      return "'"+value.replace(/'/g, "''")+"'";
    case "boolean":
      //If the value is a boolean, convert it to a 0 or 1 number
      return Number(value);
    default:
    //If the type is none of the above, throw an error since 
    //only the above types are supported in this example
      throw new Error("Unknown type for value: "+typeof value);
  }
}

Synchronizing data (from N3uron to a database)

In this example, data from N3uron is going to be synchronized with the database, so that both N3uron and the database contain the same data. The tags that will be synchronized come from an external device (whether this be a PLC, a Modbus device, or an OPC UA Server) and are set up as parameters in the transaction.

This example uses a Standard Transaction since this is the ideal transaction for this scenario.

The destination database in this example is MySQL and as such, the syntax for MySQL is used. 

Step 1:

The database destination table has the following schema:

Synchronizing data (from N3uron to a database): The database destination table has the following schema:

Step 2:

Configuration settings for StandardTransaction:

Synchronizing data (from N3uron to a database): Configuration settings for StandardTransaction:

Step 3:

Build an UPDATE from the setpoint, status and is_running parameter values:

  • sprintf: Formats the three values into the SQL string assigned to $.output.

  • UPDATE scope: The statement has no WHERE clause. When executed, it updates every row in n3_db_sync.

  • String formatting: Inserts status inside SQL quotes without escaping its contents.

$.output = sprintf("UPDATE `n3_db_sync` SET `setpoint`=%f, `status`='%s', `is_running`=%d",
  $.parameter.setpoint.value,
  $.parameter.status.value,
  $.parameter.is_running.value);

This query will be executed every 5 seconds and will update the "n3_db_sync" table with the current values in N3uron. This table has a single row, which contains the values that were synchronized between N3uron and the database.

Synchronizing data (from the database to N3uron)

This example is analogous to the previous one, except that the data flows in the opposite direction, from a database to N3uron tags. 

The destination tags in this example are not SQL Client source tags, instead, they are tags whose sources are other modules, such as Modbus, Siemens S7, etc. Like in the previous example we will use a Standard Transaction. It is important to note that these tags must have Read/Write permissions, otherwise, the write command will not succeed.

The source database is MySQL, so the MySQL syntax is being used.

Step 1:

The source table has the following schema:

Synchronizing data (from the database to N3uron): The source table has the following schema:

Step 2:

The following StandardTransaction configuration is used:

Synchronizing data (from the database to N3uron): The following StandardTransaction configuration is used:

Step 3:

Read the demand, label and line-state columns for the Parser script:

  • SELECT: Requests eight named columns from db_n3_sync.

  • Row order: The query has no filter or ORDER BY clause. The next Parser uses row zero.

  • $.output: Holds the SQL query string.

$.output = "SELECT `product1_demand`, `product2_demand`, `product1_label`, `product2_label`, `line1_active`, `line2_active`, `line3_active`, `line4_active` FROM db_n3_sync";

Step 4:

Map the first result row to the eight /PLC/ tags. The query must return at least one row:

  • getValue(0, ...): Reads each named column from row zero.

  • $.output.push: Appends the explicit tag path and value pairs. The script does not assign quality or timestamps.

$.output.push({tag:"/PLC/product1_demand",value:$.input.getValue(0, "product1_demand")});
$.output.push({tag:"/PLC/product2_demand",value:$.input.getValue(0, "product2_demand")});
$.output.push({tag:"/PLC/product1_label",value:$.input.getValue(0, "product1_label")});
$.output.push({tag:"/PLC/product2_label",value:$.input.getValue(0, "product2_label")});
$.output.push({tag:"/PLC/line1_active", value: $.input.getValue(0, "line1_active")});
$.output.push({tag:"/PLC/line2_active", value: $.input.getValue(0, "line2_active")});
$.output.push({tag:"/PLC/line3_active", value: $.input.getValue(0, "line3_active")});
$.output.push({tag:"/PLC/line4_active", value: $.input.getValue(0, "line4_active")});

The configured trigger executes this transaction every 5 seconds.

Data transformation: Converting database rows into JSON tag values

In this example, a SQL client connects to a local MySQL database to extract specific data. The script iterates through rows and focuses on particular 'System' values. Once this data is selected, it is organized into individual JSON objects. These objects are then converted into strings before being passed to tags of string type. These tags can be further used, for example, by publishing their values through an MQTT client.

Step 1:

 The source table has the following schema:

Data transformation: Converting database rows into JSON tag values: The source table has the following schema:

Step 2:

 The source table has the following data:

Data transformation: Converting database rows into JSON tag values: The source table has the following data:

Step 3:

Build a MySQL SELECT for production-order data from mes:

  • COLUMNS / DATE_FORMAT: Selects the named fields and formats both planned date-time fields as text.

  • WHERE: Adds a filter only when the WHERE string is not empty. This configuration has no filter.

  • select / $.output: Builds the SQL string and assigns it to $.output.

// TABLE_NAME => name of the target table of the database. For tables within a schema the name would be "schema.table_name"
const TABLE_NAME = "mes";

// WHERE => clause used in the SELECT query. It may be left blank when no WHERE clause is required.
const WHERE = "";

//COLUMNS => Array of the column names to retrieve from the table. Using "*" wildcard retrieves all columns from the table.
const COLUMNS = [
  "PO",
  "System",
  "SystemPO",
  "DATE_FORMAT(POPlannedStartTime, '%Y-%m-%d %H:%i:%s') AS POPlannedStartTime",
  "DATE_FORMAT(POPlannedEndTime, '%Y-%m-%d %H:%i:%s') AS POPlannedEndTime",
  "Product"
  ];

// The output can be generated using the select() function to retrieve data from the database.
$.output = select();

// This function returns a SELECT query used to retrieve data from the database
function select(){
  let query = sprintf("SELECT %s FROM %s", COLUMNS.join(","), TABLE_NAME);
  // WHERE is added to the query if not blank.
  if(WHERE !== ""){
      query += " WHERE " + WHERE;
  }
  return query;
}

Step 4:

Group the selected production rows into one string value per system:

  • systemValues: Keeps only rows for R112, R113, R114 and R115.

  • filteredData: Groups rows by System and omits null fields and the System column from each row object.

  • JSON.stringify / $.output.push: Converts each group to a JSON string and appends an event named for that system, with quality 192.

  • Configuration constants: INDEX_COLUMN, QUALITY_COLUMN and DATE_COLUMN are declared but are not used by this script.

// INDEX_COLUMN => Column containing the tagpath (or alias) of the target tag.
//    - If present, the tagpath (or alias) will be INDEX_COLUMN_VALUE.CURRENT_COLUMN_NAME.
//    - If empty (""), the tagpath (or alias) will be the current column name directly.
const INDEX_COLUMN = "System";

// QUALITY_COLUMN = Column containing the quality of the tag. If empty (""), Good quality (192) will be used.
const QUALITY_COLUMN = "";

// DATE_COLUMN => Column containing the timestamp in DATETIME or equivalent type such as TIMESTAMP for PostgreSQL.
//    If empty (""), NOW() will be used.
const DATE_COLUMN = "";

const systemValues = ['R112', 'R113', 'R114', 'R115'];
const filteredData = {};

for (const row of $.input.rows()) {
  const systemValue = row.getValue('System');

  if (systemValues.includes(systemValue)) {
    if (!filteredData[systemValue]) {
      filteredData[systemValue] = [];
    }

    const rowObject = {};
    
    for (const column of $.input.columns()) {
      const columnName = column.getName();
      const columnValue = row.getValue(columnName);
      $.logger.debug("%s: %s", columnName, columnValue);
      if (columnValue !== null && columnName !== 'System') {
        rowObject[columnName] = columnValue;
      }
    }
    filteredData[systemValue].push(rowObject);
  }
}

// Store the accumulated JSON for 'R112' and 'R113' in separate tags
for (const system in filteredData) {
  if (Object.hasOwnProperty.call(filteredData, system)) {
    const jsonString = JSON.stringify(filteredData[system]);
    $.output.push({ tag: `${system}`, value: jsonString, quality: 192 });
  }
}

Step 5:

 Tag configuration settings for linking the data received from the database to tags.

Data transformation: Converting database rows into JSON tag values: Tag configuration settings for linking the data received from the database to tags

Step 6:

Real-time Tag data visualization.

Data transformation: Converting database rows into JSON tag values: Real-time Tag data visualization

Step 7:

This JavaScript array illustrates the row data collected for one system:

  • Array entries: Each object represents one production order, with identifiers, planned start/end times and a product.

  • Example format: The unquoted property names and trailing commas are JavaScript syntax. This block is not strict JSON or a pipeline script.

[
  {
    PO: 12002,
    SystemPO: 12002001,
    POPlannedStartTime: "2023-12-28 10:00:00",
    POPlannedEndTime: "2023-12-28 11:00:00",
    Product: "Product_02",
  },
  {
    PO: 12003,
    SystemPO: 12003001,
    POPlannedStartTime: "2023-12-28 11:00:00",
    POPlannedEndTime: "2023-12-28 12:00:00",
    Product: "Product_02",
  },
  {
    PO: 12004,
    SystemPO: 12004001,
    POPlannedStartTime: "2023-12-28 12:00:00",
    POPlannedEndTime: "2023-12-28 13:00:00",
    Product: "Product_02",
  },
];

Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections

Intermittent database disconnections can interrupt data retrieval and processing. This example uses the last captured timestamp as a recovery point.

After reconnection, the query requests rows with a later timestamp. This requires the source rows to remain available and the checkpoint to be retained. A timestamp alone does not distinguish rows with the same timestamp or recover late inserts with an older timestamp.

Once processed, the data can be forwarded to other systems via delivery modules such as MQTT Client or OPC-UA Server.

This is the PostgreSQL table named turbine_data, which stores analog sensor readings for turbine gearbox temperature, shaft-bearing temperature, and wind speed.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Intermittent database disconnections can interrupt data retrieval and processing. This example uses the last captured timestamp as a recovery point. After reconnection, the query requests rows with a later timestamp. This requires the source rows to remain available and the checkpoint to be retained. A timestamp alone does not distinguish rows with the same timestamp or recover late inserts with an older timestamp. Once processed, the data can be forwarded to other systems via delivery modules such as MQTT Client or OPC-UA Server

Step 1:

Create a channel, for example, named db_connector.

Step 2:

  Choose a connector type from options like MariaDB, MySQL, SQL Server, PostgreSQL, OracleDB, or TimescaleDB. In this example, we select PostgreSQL.

Step 3:

  • Connection settings: Host, Port, Default Database.

  • Authentication: Username and Password.  

  • You can leave other settings at their defaults or adjust them as needed.

01.png

Step 4:

 Create a new Standard Transaction in the Template section and name it select for instance, since the SELECT statement is used to query the database.

03.png

Step 5:

 Create the following Custom properties:

  • Run_on_start: Determines whether the trigger should execute automatically upon restart.

  • Scan_rate: Specifying the scan rate for the periodic trigger, expressed in milliseconds. 

  • Table_name: Specifies the name of the database table. This custom property is used to construct the query.

  • Turbine_ID: Specifies the turbine identifier used in the WHERE clause to filter rows by the turbine_id column in the database.

Step 6:

Create a Single tag parameter named Last_ts.

  • Purpose:

    • Provides the path to the tag that holds the last timestamp read from the database at the time of transaction execution.

  • Usage in Query Script:

    • Reads the current tag value of Last_ts to retrieve the last recorded timestamp.

    • Uses this timestamp in the WHERE clause to filter rows with a timestamp greater than the stored value.

  • Usage in Parser Script:

    • Provides the path to the tag for updating the last timestamp after the transaction completes.

      Note:

      Always use parameters to read tag values within both Query and Parser scripts.

02.png

Step 7:

 Create the query script using the default SQL Client query template.

Note:

In Templates, access Custom Property values by enclosing the property name in curly braces.

Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the query script using the default SQL Client query template

Complete Javascript code for the Query script:

Build the timestamp-filtered PostgreSQL query for this turbine. Define the template properties and Last_ts parameter first:

  • Parameters: Reads Last_ts and substitutes the Table_name and Turbine_ID Custom Properties.

  • WHERE: Filters turbine_id. A truthy Last_ts adds a later-than timestamp filter. Removing double quotes does not escape SQL string values.

  • COLUMNS / ORDER BY: Selects time_stamp, temp_shaftbearing, temp_gearbox and wind_speed in ascending timestamp order.

  • select / $.output: Builds and logs the SQL text for SQL Client to execute. The Parser script receives the result Dataset.

// -----------------------------------------------------------------------------
// Parameter Extraction and Logging
// -----------------------------------------------------------------------------

// Retrieve the 'last_ts' parameter, which indicates the starting timestamp
// for the SQL query. The expected format is "2025-02-10T14:42:56.000Z".
const last_ts = $.parameter.Last_ts.value;
$.logger.debug("Retrieved Last Timestamp: %s", last_ts);

// -----------------------------------------------------------------------------
// Table and Turbine Identifier 
// -----------------------------------------------------------------------------

// Define the target table name.
const TABLE_NAME = {Table_name};

// Read the turbine identifier and remove double-quote characters.
// This operation does not escape SQL string literals.
const turbine_id = {Turbine_ID}.replace(/"/g, "");

// -----------------------------------------------------------------------------
// Dynamic WHERE Clause Construction
// -----------------------------------------------------------------------------

// Initialize the WHERE clause with the condition to filter rows by the turbine identifier.
let WHERE = `turbine_id = '${turbine_id}'`;

// If a last timestamp is provided, add an additional condition to only include records
// with a time_stamp greater than the provided value. The "::timestamptz" cast ensures
// that the timestamp is interpreted with time zone awareness.
if (last_ts) {
  WHERE += ` AND time_stamp > '${last_ts}'::timestamptz`;
}

// -----------------------------------------------------------------------------
// Column Selection Setup
// -----------------------------------------------------------------------------

// Define the list of columns to retrieve from the database. These columns should
// match the ones available in the target table. Comments next to each column clarify
// their role or the type of data they represent.
const COLUMNS = [
  "time_stamp",        // Timestamp when the data record was captured.
  "temp_shaftbearing", // Temperature reading for the shaft bearing.
  "temp_gearbox",      // Temperature reading for the gearbox.
  "wind_speed"         // Measured wind speed related to turbine performance.
];

// -----------------------------------------------------------------------------
// SQL Query Generation
// -----------------------------------------------------------------------------

// Generate the SQL SELECT query using the helper function and assign it to the output
// for further processing in the system.
$.output = select();

/**
 * Constructs a SQL SELECT query based on defined parameters.
 *
 * This function dynamically builds a SQL query string by:
 *   - Selecting specific columns from the designated table.
 *   - Incorporating a dynamically built WHERE clause that filters results by the
 *     turbine identifier and, optionally, a starting timestamp.
 *   - Appending an ORDER BY clause to ensure results are returned in ascending order
 *     by the 'time_stamp' column.
 *
 * The constructed query is logged for debugging purposes.
 *
 * @returns {string} The complete SQL query string ready for execution.
 */
function select() {
  // Build the basic SELECT statement by joining the specified columns and appending the table name.
  let query = sprintf("SELECT %s FROM %s", COLUMNS.join(","), TABLE_NAME);

  // If the WHERE clause is non-empty, attach it to the query to filter the results.
  if (WHERE !== "") {
    query += ` WHERE ${WHERE}`;
  }

  // Append an ORDER BY clause to sort the query results by 'time_stamp' in ascending order.
  query += " ORDER BY time_stamp ASC";

  // Log the complete query for debugging to verify the dynamic construction.
  $.logger.debug("Generated SQL query: %s", query);

  // Return the fully constructed SQL query string.
  return query;
}

Step 8:

 Create the parser script using the default SQL Client parser template.

Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the parser script using the default SQL Client parser template

Event Tag Assignment: In the parser, you can assign an "alias" to the event's tag attribute. When using SQL Client as the source, this alias is known as a Tag address, in the tag configuration.

If no Tag address is provided, you must use the full tag path (e.g., /Turbine_A/wind_speed, /Turbine_B/wind_speed). In the parser script, if INDEX_COLUMN is empty, the tag is constructed from the column name (e.g., wind_speed, temp_shaftbearing, temp_gearbox).

Note:

Using Tag address simplifies tag referencing by avoiding long, complex tag paths. This enhances configuration clarity and maintainability, as the tag address alias provides a concise reference within the Parser script code.

Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the parser script using the default SQL Client parser template

Complete Javascript code for the Parser script:

Convert result cells to tag events and produce a timestamp checkpoint. The time_stamp values must support Date methods:

  • Dataset / SKIP_NULL: Visits each row and column. It skips null values and configured metadata columns.

  • Tag event: Creates an event with the field value. With an empty QUALITY_COLUMN, this configuration does not add a quality field.

  • Date methods: Converts time_stamp to milliseconds and retains the last processed timestamp as an ISO string. It does not calculate a maximum.

  • Checkpoint event: Appends the retained string to the Last_ts tag only when a timestamp was processed. It does not assign the parameter directly.

// -----------------------------------------------------------------------------
// Configuration Parameters
// -----------------------------------------------------------------------------
// INDEX_COLUMN: Specifies the column that contains a tag alias or path.
//   - When defined (non-empty), the final tag name is built by concatenating the
//     value from this column and the current column name (format: "INDEX_VALUE.COLUMN_NAME").
//   - When empty, the column name itself is used as the tag name.
const INDEX_COLUMN = "";

// QUALITY_COLUMN: Specifies the column that contains the tag quality indicator.
//   - When defined, the tag quality is extracted from this column.
//   - When empty, a default quality value of 192 (representing 'Good') is assumed.
const QUALITY_COLUMN = "";

// DATE_COLUMN: Specifies the column that contains the timestamp (e.g., DATETIME or TIMESTAMP).
//   - When defined, the tag's timestamp is taken from this column.
//   - When empty, the current system time (NOW) will be used.
const DATE_COLUMN = "time_stamp";

// SKIP_NULL: If set to true, any field with a null value is skipped during processing.
const SKIP_NULL = true;

// -----------------------------------------------------------------------------
// Debug Logging
// -----------------------------------------------------------------------------
// Log the complete input object for debugging purposes.
$.logger.debug("Input: %s", JSON.stringify($.input));

// -----------------------------------------------------------------------------
// Initialization
// -----------------------------------------------------------------------------
// Variable to track the last timestamp encountered in the dataset.
let lastTimestamp = null;

// -----------------------------------------------------------------------------
// Main Processing Loop
// -----------------------------------------------------------------------------
// Iterate over each row in the input data.
for (const row of $.input.rows()) {
  // Iterate over each column in the current row.
  for (const column of $.input.columns()) {
    const columnName = column.getName(); // Retrieve the name of the current column

    // If SKIP_NULL is enabled and the current column's value is null, skip processing this field.
    if (row.getValue(columnName) === null && SKIP_NULL) continue;

    // Skip processing columns that are used as metadata (INDEX_COLUMN, QUALITY_COLUMN, DATE_COLUMN).
    if (
      columnName === INDEX_COLUMN ||
      columnName === QUALITY_COLUMN ||
      columnName === DATE_COLUMN
    ) {
      continue;
    }

    // -------------------------------------------------------------------------
    // Build the Tag Event
    // -------------------------------------------------------------------------
    // Create an empty object to hold the event data for the current column.
    const event = {};

    // Determine and set the tag name:
    // - If INDEX_COLUMN is provided, build the tag as "INDEX_VALUE.COLUMN_NAME".
    // - Otherwise, simply use the column name as the tag.
    if (INDEX_COLUMN !== "") {
      event.tag = sprintf("%s.%s", row.getValue(INDEX_COLUMN), columnName);
    } else {
      event.tag = columnName;
    }

    // Set the tag value from the current column.
    event.value = row.getValue(columnName);

    // Set the tag quality:
    // - If QUALITY_COLUMN is provided, extract the quality from that column.
    // - Otherwise, a default quality of 192 (Good) is assumed (per configuration).
    if (QUALITY_COLUMN !== "") {
      event.quality = row.getValue(QUALITY_COLUMN);
    }

    // Set the timestamp for the tag:
    // - If DATE_COLUMN is provided, extract the timestamp from that column,
    //   convert it to epoch time (milliseconds), and update the lastTimestamp tracker.
    // - Otherwise, the current timestamp (NOW) would be used (implied by system defaults).
    if (DATE_COLUMN !== "") {
      const dateValue = row.getValue(DATE_COLUMN);
      event.ts = dateValue.getTime(); // Convert timestamp to epoch (milliseconds)
      lastTimestamp = dateValue.toISOString(); // Record the last timestamp in ISO format
    }

    // Append the constructed event to the output array.
    $.output.push(event);
  }
}

// -----------------------------------------------------------------------------
// Append Final Timestamp Event
// -----------------------------------------------------------------------------
// After processing all rows, if a timestamp was encountered, create an additional
// event to record the last timestamp. The tag for this event is specified by
// $.parameter.Last_ts.tag.
if (lastTimestamp !== null) {
  $.output.push({ tag: $.parameter.Last_ts.tag, value: lastTimestamp });
}

Step 9:

 Instantiate the standard transaction Template, named select, for each turbine.

Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Instantiate the standard transaction Template, named select, for each turbine

Step 10:

 Navigate to System > Config > Tags and create a new Template named Turbine.

Step 11:

 Create the following Custom Properties:

  •  Module_name: Specifies the name of the SQL Client module instance.

  •  Transaction: Sets the transaction name, combining the channel (e.g., db_connector) with the transaction identifier (e.g., select_turbine_A).Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the following Custom Properties:

Step 12:

 Create the following tags within the Template:

  • Last_TS: A memory tag (without a source) with read-write permissions and disk persistence, ensuring its value is retained even after a system restart. It stores the last timestamp recorded in the database when the SQL transaction is executed.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the following tags within the Template:


  • temp_gearbox: A read-only tag sourced from the SQL Client module. Its value represents the gearbox temperature in degrees Celsius.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the following tags within the Template:


  • temp_shaftbearing: A read-only tag sourced from the SQL Client module. Its value represents the shaft-bearing temperature in degrees Celsius.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the following tags within the Template:

  • wind_speed: A read-only tag sourced from the SQL Client module. Its value represents the wind speed in meters per second.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Create the following tags within the Template:

Step 13:

Instantiate the Turbine Template in the tag model, assigning appropriate names (e.g., Turbine_A, Turbine_B, and Turbine_C), and update the corresponding Custom Properties accordingly.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Instantiate the Turbine Template in the tag model, assigning appropriate names (e.g., Turbine_A, Turbine_B, and Turbine_C ), and update the corresponding Custom Properties accordingly

Step 14:

 Verify in the Diagnostics window that the SQL Client configuration is correct and that data is being successfully retrieved from the database.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: Verify in the Diagnostics window that the SQL Client configuration is correct and that data is being successfully retrieved from the database

Step 15:

If no issues are found in Diagnostics, navigate to Data > Realtime to view the data retrieved from the database. Once everything is set up, you’ll notice that if the SQL Client disconnects from the database, the corresponding tags will show a BAD quality.

When the connection is restored, the SQL Client resumes data retrieval from the last recorded timestamp up to the most recent entry, subject to the source retention and timestamp conditions described above. Verify the recovered rows and the tag quality after reconnection.

Additionally, this data can be delivered using other protocols such as MQTT, OPC UA, Modbus, and more.Resilient Data Handling: Resuming from the Last Timestamp After Database Disconnections: If no issues are found in Diagnostics, navigate to Data > Realtime to view the data retrieved from the database. Once everything is set up, you’ll notice that if the SQL Client disconnects from the database, the corresponding tags will show a BAD quality. When the connection is restored, the SQL Client resumes data retrieval from the last recorded timestamp up to the most recent entry, subject to the source retention and timestamp conditions described above. Verify the recovered rows and the tag quality after reconnection. Additionally, this data can be delivered using other protocols such as MQTT, OPC UA, Modbus, and more

Connecting to Timescale and inserting data

Configuring and testing wind-farm transactions

Note:

From N3uron version 1.22.8. This walkthrough uses the current Standard and History pipelines and the native connection and pipeline tests. The configuration reads active power and wind speed for four wind turbines.

The Standard transaction reads the latest active power and wind speed for each turbine. Its parser produces eight tag events. The History transaction collects events from those tags and writes their values, quality codes and timestamps to a separate table.

Step 1: Prepare the source database

Connect to wind_farm_telemetry as wind_farm_service. Create the login roles scada_sql_client and wind_farm_odbc_reader with your own passwords before you run the script.

The SQL script performs the following operations:

  • CREATE TABLE: Creates turbine_data to store measurements and turbine_tag_history to store historical Tag values.

  • CREATE OR REPLACE VIEW: Creates latest_turbine_data to return the most recent measurement for each turbine.

  • GRANT CONNECT / USAGE: Allows both client roles to connect to the database and access the public schema.

  • GRANT SELECT: Allows both roles to read turbine measurements and the latest-value view.

  • GRANT SELECT / INSERT: Allows scada_sql_client to read and insert historical Tag values in turbine_tag_history.

Existing table data is preserved. Make sure that your data acquisition system writes measurements to public.turbine_data.

-- Run as wind_farm_service in the wind_farm_telemetry PostgreSQL database.
-- Existing source and History rows are preserved.
-- Your data acquisition system must write measurements to public.turbine_data.
CREATE TABLE IF NOT EXISTS public.turbine_data (
    time_stamp timestamptz NOT NULL,
    turbine_id varchar(50) NOT NULL,
    wind_speed real, temp_shaftbearing real, temp_gearbox real,
    power_output real, rotor_speed real, blade_pitch real,
    generator_rpm real, nacelle_position real, grid_voltage real,
    grid_current real,
    PRIMARY KEY (time_stamp, turbine_id)
);
CREATE OR REPLACE VIEW public.latest_turbine_data AS
SELECT DISTINCT ON (turbine_id) *
FROM public.turbine_data
ORDER BY turbine_id, time_stamp DESC;
CREATE TABLE IF NOT EXISTS public.turbine_tag_history (
    tag text NOT NULL,
    value double precision,
    quality integer NOT NULL,
    ts timestamptz NOT NULL,
    PRIMARY KEY (tag, ts)
);
-- Create these login roles separately with your own passwords.
GRANT CONNECT ON DATABASE wind_farm_telemetry TO scada_sql_client, wind_farm_odbc_reader;
GRANT USAGE ON SCHEMA public TO scada_sql_client, wind_farm_odbc_reader;
GRANT SELECT ON public.turbine_data, public.latest_turbine_data TO scada_sql_client, wind_farm_odbc_reader;
GRANT SELECT, INSERT ON public.turbine_tag_history TO scada_sql_client;

Make sure that your data acquisition system writes turbine measurements to public.turbine_data. Use the source columns and turbine identifiers from your installation.

Object

Purpose

turbine_data

Timestamped source measurements. Each row identifies one turbine and one observation time.

latest_turbine_data

The latest row for each turbine. The Standard transaction reads this view.

turbine_tag_history

Tag events written by the History transaction. Its primary key is (tag, ts).

scada_sql_client

Reads source rows and inserts History rows. This database user is used by the direct PostgreSQL channel.

wind_farm_odbc_reader

Reads source rows for the ODBC example below. It has no write permission on these tables.

Read the latest measurements through the prepared PostgreSQL view:

  • SELECT: Requests the turbine identifier, source timestamp, power output and wind speed.

  • ORDER BY: Sorts the returned rows by turbine_id. The query does not insert or change measurements.

SELECT turbine_id, time_stamp, power_output, wind_speed
FROM public.latest_turbine_data ORDER BY turbine_id;

Expected result: Four rows, named WTG01 to WTG04. The measured columns must contain numbers and time_stamp must contain a timestamp.

Step 2: Configure and test the PostgreSQL channel

In Config → Modules, use the module instance SQL Client. In its Model menu, select New Channel and name it WindFarmTelemetry. Set the connector Type to PostgreSQL. Enter the connection settings for the source database.

Setting

Configuration value

Host

Use the PostgreSQL server address that N3uron can reach. For a direct local installation, use 127.0.0.1.

Port

15432. Use the TCP port configured for your PostgreSQL server.

Default database

wind_farm_telemetry

Username

scada_sql_client

Password

The password assigned to scada_sql_client. The native field masks it.

Click the plug icon beside Connector. The Test connection window uses the current editor values. Check the database, user and server information as well as the connection result.

The direct PostgreSQL connection succeeds before the transaction is configured.

Note:

The connection shown is unencrypted. The connection test reports this condition. Configure encryption and certificate validation for your installation. A successful connection does not remove its warnings.

Step 3: Create the Standard transaction and its output tags

At the channel Transactions menu, select New StandardTransaction. Name it ReadTurbineTelemetry. Keep data collection enabled. Add a New Periodic trigger named Every5Seconds. Set Type to Fixed time, Scan rate to 5000 ms and Run on start to Yes. This example needs no parameters.

Create the groups /WindFarm/WTG01 to /WindFarm/WTG04. Add two number tags in each group. Enable their SQL Client source and use module instance SQL Client. Select transaction WindFarmTelemetry/ReadTurbineTelemetry. Configure these addresses for each turbine:

Tag and units

SQL Client tag address

/WindFarm/WTG01/ActivePower, kW

WTG01.ActivePower

/WindFarm/WTG01/WindSpeed, m/s

WTG01.WindSpeed

WTG02, WTG03 and WTG04

Repeat both tags. Replace WTG01 in the group and address with the matching turbine identifier.

The parser output uses these addresses to identify the target tags. The address and the selected transaction must match. Save the tag configuration.

Step 4: Set the query and parser scripts

In the Standard transaction Pipeline, use this Query script for the prepared latest-value view:

  • text: Contains the SELECT statement and sorts rows by turbine_id.

  • values: Is empty because the statement has no value placeholders.

  • $.output: Supplies the statement object to the Query stage.

$.output = {
    text: "SELECT turbine_id, time_stamp, power_output, wind_speed FROM latest_turbine_data ORDER BY turbine_id",
    values: {}
};

Convert each result row to ActivePower and WindSpeed tag events:

  • Dataset: Reads turbine_id, time_stamp, power_output and wind_speed from each row.

  • Timestamp / quality: Converts the source Date to milliseconds and explicitly sets quality 192.

  • $.output.push: Appends two events per turbine, using the configured tag addresses. Four turbine rows produce eight events.

for (const row of $.input.rows()) {
    const turbine = row.getValue("turbine_id");
    const ts = row.getValue("time_stamp").getTime();
    $.output.push({ tag: turbine + ".ActivePower", value: row.getValue("power_output"), quality: 192, ts: ts });
    $.output.push({ tag: turbine + ".WindSpeed", value: row.getValue("wind_speed"), quality: 192, ts: ts });
}

Step 5: Test the Standard pipeline and check the tags

  1. Save the module configuration and confirm the SQL Client restart when prompted.

  2. Select ReadTurbineTelemetry and click the play icon next to Pipeline.

  3. Leave Values (JSON) set to {}.

  4. Click Build statement and review the generated SQL statement.

  5. Click Execute and parse (rolled back).

  6. Verify that the test returns the expected rows and eight valid events

Note:

The pipeline test uses the scripts currently in the editor. It does not save the configuration or write tags. Statements are rolled back, except CREATE, ALTER, DROP or TRUNCATE on MySQL or Oracle, which those engines can commit independently. This example tests SELECT and INSERT statements on PostgreSQL.

Close the test. In Data → Realtime, select WindFarm and enable Sublevels. After a scheduled run, check all eight tags. Compare their values and timestamps with the source rows.

These are actual scheduled tag updates. They are separate from the pipeline test output.

Step 6: Configure the History transaction

At the WindFarmTelemetry Transactions menu, select New HistoryTransaction. Name it StoreTurbineHistory. Set Mode to Event. Use an events buffer size of 10000 and leave Store & Forward disabled. Add a periodic trigger named Every10Seconds. Set Type to Fixed time, Scan rate to 10000 ms and Run on start to Yes.

Under Tag filters, add New TagFilterPath and name it WindTurbineTelemetry. Set Mode to Include, Path to /WindFarm/ and Regex pattern to .*. Keep the final slash in the path. In this setup, it limits the subscription to the eight descendants of /WindFarm/ and excludes the separate /WindFarmODBC/ group used below.

Check the saved trigger and filter values before entering the two History scripts.

Convert numeric History events to a Dataset for the Query script:

  • Dataset columns: Declares tag, value, quality and ts with their specified data types.

  • typeof: Skips events whose value is not a number.

  • addRow / $.output: Copies each retained event's tag, value, quality and timestamp, then returns the Dataset. It also processes any supplied initial events.

const ds = new Dataset();
ds.addColumn("tag", "NVARCHAR");
ds.addColumn("value", "DOUBLE");
ds.addColumn("quality", "SMALLINT");
ds.addColumn("ts", "DATETIME");
for (const ev of $.input) {
    if (typeof ev.value !== "number") continue;
    ds.addRow({ tag: ev.tag, value: ev.value, quality: ev.quality, ts: ev.ts });
}
$.output = ds;

Build a bound PostgreSQL INSERT from the serialized rows:

  • Placeholders / values: Creates unique placeholder names and stores each row's values separately from the SQL text.

  • INSERT: Joins the row placeholders into one statement for turbine_tag_history.

  • ON CONFLICT: Keeps the existing row for each tag/timestamp pair. Choose a different conflict action if values can change at the same timestamp.

  • Empty input: Sets $.output to an empty string when there are no rows.

const values = {};
const rows = [];
let i = 0;
for (const row of $.input.rows()) {
    const id = String(i++);
    rows.push("(:tag" + id + ", :value" + id + ", :quality" + id + ", :ts" + id + ")");
    values["tag" + id] = row.getValue("tag");
    values["value" + id] = row.getValue("value");
    values["quality" + id] = row.getValue("quality");
    values["ts" + id] = row.getValue("ts");
}
$.output = rows.length ? {
    text: "INSERT INTO turbine_tag_history (tag, value, quality, ts) VALUES " + rows.join(", ") + " ON CONFLICT (tag, ts) DO NOTHING",
    values: values
} : "";

Step 7: Separate rollback testing from stored History

Save the module configuration and apply the SQL Client restart. Open the History Pipeline test. In Events (JSON), enter:

  • tag / value: Supplies one numeric event for /WindFarm/WTG01/ActivePower, with value 1825.5.

  • quality / timestamp: Sets quality 192. The JSON does not include an event timestamp.

[{"tag":"/WindFarm/WTG01/ActivePower","value":1825.5,"quality":192}]

Leave Event ts empty to use the test time. Click Serialize and build. Check the Dataset and the four bound values. Click Execute and parse (rolled back).

The INSERT executes in the test transaction. It is then rolled back. This test does not add a stored History row.

After source measurements change, wait for the Standard and History triggers to run. In Data → Realtime, compare the tag values and timestamps with the source measurements.

Read the stored events from PostgreSQL after the History trigger runs:

  • SELECT / ORDER BY: Reads the stored tag, value, quality and timestamp fields, ordered by timestamp and tag.

  • COUNT: Returns the total row count and the number of distinct tags.

SELECT tag, value, quality, ts
FROM public.turbine_tag_history ORDER BY ts, tag;

SELECT count(*) AS events, count(DISTINCT tag) AS tags
FROM public.turbine_tag_history;

Compare the stored values, quality codes and timestamps with the source tags. The row count depends on the tag events received. A rolled-back pipeline test does not add stored rows.

Step 8: Diagnose an error at the stage where it occurs

Observation

Check

Connection test fails

Check the reachable host and port, intended database, database user and server-side access. Read the exact error. Test the channel before the pipeline.

CHANNEL_NOT_FOUND

A saved new channel can still be absent from the running module until the configuration is applied. Apply the SQL Client restart, then repeat the pipeline test.

Build statement fails

Check the Query script and the manual parameter input. Inspect the generated SQL and bound values before execution.

Database execution fails

Check the database object names, SQL dialect and permissions. The test log identifies the database error.

Rows return but tags do not update

Check parser output, the tag source module, selected transaction and tag address. A pipeline test alone does not update runtime tags.

History has no new rows

Check that selected tags receive new events, the filter includes their paths, the trigger runs and the serializer returns rows. Check INSERT permission and the query log.

The controlled test below uses latest_turbine_data_missing in an unsaved query. PostgreSQL reports that the relation does not exist. Restore latest_turbine_data and repeat the test. The corrected test returns four rows and eight valid events. Do not apply the deliberately failing query to runtime.

The test reports DB_ERROR: relation "latest_turbine_data_missing" does not exist. Use that object name to locate the failure. The corrected successful result is shown in Step 5.


Reading an ODBC data source through SQL Server Express

ODBC (Open Database Connectivity) provides a standard interface for accessing different data sources through compatible drivers.

This example shows how N3uron SQL Client reads data from two ODBC sources (Microsoft SQL Server and PostgreSQL) through a SQL Server Express gateway. The gateway uses linked servers to access both sources, while SQL Client connects to the gateway using its native Microsoft SQL Server connector.

Note:

SQL Client provides native, database-specific connectors but does not include a generic ODBC connector. See SQL Client Introduction for the supported connectors.

You can adapt this procedure to other ODBC drivers and data sources. Before doing so:

  • Verify that the ODBC driver is compatible with the MSDASQL linked-server provider.

  • Adjust the connection settings and SQL statements to match the driver and target database.

  • Validate read access and test write support separately, if required.

Use the 64-bit ODBC driver for each source database.

Source

Microsoft SQL Server

PostgreSQL

ODBC driver

ODBC Driver 17 for SQL Server (64-bit)

PostgreSQL Unicode(x64)

System DSN

WindFarmSqlTelemetry

WindFarmTelemetry

Source database

wind_farm_sql_telemetry

wind_farm_telemetry

Turbines

WTG11–WTG14

WTG01–WTG04

SQL Server Express is free to download. For this example, install it on the Windows computer that runs N3uron.

You can use the same SQL Server bridge approach for other compatible ODBC sources.

To adapt this example:

Change

Action

Source database

Adapt the ODBC driver, System DSN and remote SQL.

Connection endpoints

Keep SQL Client → SQL Server separate from SQL Server → source database.

Remote gateway

Use the remote connection instructions in Step 1.

SQL Client connects to SQL Server Express, then a linked server uses the MSDASQL OLE DB provider, a 64-bit System DSN and an ODBC driver to reach the source database

Step 1: Prepare the SQL Server Express instance

Install SQL Server Express on the Windows computer that runs N3uron.

This example uses a dedicated 64-bit SQL Server 2022 Express instance named N3SQL.

  1. Connect to N3SQL in SQL Server Management Studio (SSMS) with an administrator login.

  2. In Object Explorer, right-click N3SQL.

  3. Select Properties.

  4. Select Security.

  5. Make sure that SQL Server and Windows Authentication mode is selected.

  6. If you change this mode on a new instance, select OK.

  7. If you change the mode, restart that instance as specified in the Microsoft procedure.

The gateway reader uses SQL Server authentication. Before you create its login, make sure that the intended instance permits this authentication.

Use an available fixed TCP port for N3SQL. This example uses 15433.

Port 1433 can belong to another instance. Make sure that you configure the intended instance.

  1. Open SQL Server Configuration Manager.

  2. Expand SQL Server Network Configuration.

  3. Select Protocols for N3SQL.

  4. Enable TCP/IP.

Microsoft describes the configuration in its fixed TCP port procedure.

  1. Open TCP/IP Properties.

  2. Select Protocol.

Use these values for this local example:

Setting

Example value

Enabled

Yes

Listen All

No

With Listen All = No, SQL Server uses the configuration for each IP address.

  1. Select IP Addresses.

  2. Find the block with IP Address = 127.0.0.1.

For this local connection, use these values:

Setting

Example value

Enabled

Yes

TCP Dynamic Ports

Empty

TCP Port

15433

Use the TCP port for your instance. These values show a local connection

Use the TCP port configured for your SQL Server instance. The example above uses 127.0.0.1:15433, with N3uron and SQL Server Express running on the same computer.

The loopback address 127.0.0.1 accepts connections only from the local computer.

If SQL Server Express runs on a different computer:

  1. In SQL Client, specify the remote SQL Server hostname or IP address and TCP port.

  2. Enable TCP/IP for the SQL Server instance and the required network interface.

  3. Allow incoming connections to the configured TCP port through the firewall.

Additional considerations:

  • Install the 64-bit ODBC driver and configure the System DSN on the SQL Server computer.

  • Configure the DSN to use the source database address reachable from the SQL Server computer.

  • Use the database names and credentials for your environment.

  • Adapt the linked-server configuration and remote SQL statements if you use a different data source.

Step 2: Prepare the Microsoft SQL Server ODBC source

Use a separate SQL Server instance for the source database. This example uses SQLEXPRESS on 127.0.0.1:1433 and the N3SQL gateway on port 15433.

Make sure that the source instance supports SQL Server authentication, as described in Step 1.

  1. Connect to the source instance with administrator permissions.

  2. Replace REPLACE_SOURCE_READER_PASSWORD with a secure password.

  3. Run the SQL script below.

The script performs these operations:

  • DECLARE / THROW: Verifies that you replaced the password placeholder.

  • IF / CREATE: Creates the database, reader login, and turbine table if they do not exist.

  • CREATE OR ALTER VIEW: Exposes turbine measurements and converts timestamps to Unix epoch milliseconds.

  • CREATE USER / GRANT SELECT: Gives the reader account permission to query the view.

  • SELECT: Queries the view to verify the returned measurements.

Note:

The script preserves existing table data but does not insert measurements or update an existing login password. Make sure that your data acquisition system writes turbine measurements to dbo.turbine_data. The example expects four turbine records.

-- Run on the SOURCE SQL Server instance, not on the gateway instance.
-- Your data acquisition system must write measurements to dbo.turbine_data.
-- Replace this value with a strong password before execution.
DECLARE @reader_password nvarchar(128)=N'REPLACE_SOURCE_READER_PASSWORD';
IF @reader_password=N'REPLACE_SOURCE_READER_PASSWORD'
    THROW 50000, 'Set the source reader password before execution.', 1;
IF DB_ID(N'wind_farm_sql_telemetry') IS NULL
    CREATE DATABASE [wind_farm_sql_telemetry];
IF SUSER_ID(N'wind_farm_sql_reader') IS NULL
BEGIN
    DECLARE @create_login nvarchar(max)=
        N'CREATE LOGIN [wind_farm_sql_reader] WITH PASSWORD=N'''+
        REPLACE(@reader_password,N'''',N'''''')+
        N''', CHECK_POLICY=ON, DEFAULT_DATABASE=[wind_farm_sql_telemetry];';
    EXEC sys.sp_executesql @create_login;
END;
GO
USE [wind_farm_sql_telemetry];
GO
IF OBJECT_ID(N'dbo.turbine_data',N'U') IS NULL
BEGIN
    CREATE TABLE dbo.turbine_data (
        turbine_id nvarchar(16) NOT NULL PRIMARY KEY,
        observed_utc datetime2(3) NOT NULL,
        active_power float NOT NULL,
        wind_speed float NOT NULL
    );
END;
GO
CREATE OR ALTER VIEW dbo.latest_turbine_data AS
SELECT turbine_id,
    DATEDIFF_BIG(millisecond,CONVERT(datetime2(3),'1970-01-01'),observed_utc) AS observed_ts,
    active_power,wind_speed
FROM dbo.turbine_data;
GO
IF USER_ID(N'wind_farm_sql_reader') IS NULL
    CREATE USER [wind_farm_sql_reader] FOR LOGIN [wind_farm_sql_reader];
GRANT SELECT ON dbo.latest_turbine_data TO [wind_farm_sql_reader];
GO
SELECT turbine_id,observed_ts,active_power,wind_speed
FROM dbo.latest_turbine_data ORDER BY turbine_id;

Source resource

Purpose

wind_farm_sql_telemetry

Database for wind-turbine measurements.

dbo.turbine_data

Four turbines, UTC observation times, active power and wind speed.

dbo.latest_turbine_data

Read view. It converts the UTC observation time to Unix milliseconds.

wind_farm_sql_reader

SQL Server login and database user with SELECT access to the source view.

On the gateway computer, install the 64-bit Driver 17 from the Microsoft ODBC Driver download page.

  1. As administrator, open C:\Windows\System32\odbcad32.exe.

  2. On System DSN, add WindFarmSqlTelemetry with ODBC Driver 17 for SQL Server.

  3. Use the following values. Test the connection with the source-reader password.

DSN setting

Example value

Name

WindFarmSqlTelemetry

Server

tcp:127.0.0.1,1433

Database

wind_farm_sql_telemetry

Authentication

SQL Server authentication

Login ID

wind_farm_sql_reader

Use strong encryption for data

Enabled

Trust server certificate

Enabled for the local connection shown.

Password

Supply it for the connection test. Keep it out of the saved DSN.

This connection uses encryption and trusts the source certificate. Configure certificate validation for your installation.

Microsoft describes the SQL Server DSN options.

Step 3: Configure the PostgreSQL ODBC source

The System DSN contains the ODBC connection configuration.

For the PostgreSQL source, first complete Prepare the source database in Configuring and testing wind-farm transactions. Use the database, tables and reader account configured there.

The PostgreSQL query uses public.latest_turbine_data with these columns:

PostgreSQL source column

Content

turbine_id

Turbine identifier.

time_stamp

Observation timestamp with a time zone.

power_output

Turbine active power.

wind_speed

Wind speed at the turbine.

Adapt the source view and column names to your data.

  1. On the SQL Server computer, install the 64-bit ODBC driver for the source database.

  2. As administrator, open the 64-bit ODBC Data Source Administrator: C:\Windows\System32\odbcad32.exe.

    Note:

    On 64-bit Windows, C:\Windows\System32\odbcad32.exe opens the 64-bit ODBC Data Source Administrator, despite the 32 in its filename.

  3. Add a System DSN named WindFarmTelemetry.

This example uses the official PostgreSQL ODBC driver.

The System DSN must exist on the SQL Server computer. The linked server uses it there.

DSN setting

Example value

Driver

PostgreSQL Unicode(x64)

Server / Port

127.0.0.1 / 15432 in the screenshots. Use the source database server address and TCP port. This endpoint is separate from the SQL Server connection on port 15433.

Database

wind_farm_telemetry

User name

wind_farm_odbc_reader

Read Only

Enabled for this read example. The source role also has SELECT-only access.

Password

Do not store it in this DSN. Supply it when testing and in the explicit SQL Server login mapping below.

  1. Select the System DSN tab.

  2. Select WindFarmTelemetry.

  3. Select Configure.

This DSN uses the 64-bit PostgreSQL Unicode(x64) driver.

Make sure that the connection configuration matches the DSN table.

When you save the DSN, leave Password empty.

PostgreSQL ODBC setup shows WindFarmTelemetry, the source database, 127.0.0.1 port 15432 and an empty Password field

The DSN must connect to the source before you configure the linked server.

Make sure that the ODBC driver architecture matches the 64-bit SQL Server process.

Microsoft describes the 32-bit and 64-bit ODBC administrators.

Test the ODBC connection:

  1. Enter the password for wind_farm_odbc_reader.

  2. Click Test and verify that the connection succeeds.

  3. Close the test result.

  4. Clear the Password field and save the DSN.

Note:

Do not store the password in the DSN. SQL Server supplies the credentials through the linked-server login mapping configured in the next step.

In this example, the test result is Connection successful.

ODBC Connection Test reports Connection successful for the wind-farm data source

Step 4: Create the gateway database and explicit login mappings

This example uses the SQL Server connector to read a view in SQL Server Express.

The view reads an ODBC source through a linked server. A linked server connects SQL Server to an external data source.

Use names and database users dedicated to your installation. Before you run a creation script, make sure that its resource names do not conflict with existing resources.

  1. Open an administrator SQL session on N3SQL.

  2. Replace all three password placeholders in the SQL below.

  3. Start the script.

Prepare both source bridges on N3SQL. The two System DSNs and source-reader accounts must already exist:

  • Passwords: Requires three replacement values. It does not change an existing gateway-login password.

  • Linked servers: Creates each missing linked server and removes its default login mapping only during creation.

  • Login mappings: Maps the gateway reader and setup administrator to each source-reader account.

  • Server options: Enables data access and disables RPC only for WIND_FARM_SQL_ODBC.

  • Views / GRANT SELECT: Creates or alters both gateway views and grants the gateway reader permission to read them.

  • EXECUTE AS / REVERT: Reads both views as the gateway reader, then restores the previous login context.

-- Run as an administrator on the dedicated SQL Server Express gateway instance.
-- Create both 64-bit System DSNs on this computer before running this script.
-- Use dedicated reader accounts and replace all three password values.
DECLARE @gateway_password nvarchar(128)=N'REPLACE_GATEWAY_READER_PASSWORD';
DECLARE @sql_password nvarchar(128)=N'REPLACE_MICROSOFT_READER_PASSWORD';
DECLARE @pg_password nvarchar(128)=N'REPLACE_POSTGRESQL_READER_PASSWORD';
IF @gateway_password=N'REPLACE_GATEWAY_READER_PASSWORD'
    OR @sql_password=N'REPLACE_MICROSOFT_READER_PASSWORD'
    OR @pg_password=N'REPLACE_POSTGRESQL_READER_PASSWORD'
    THROW 50000,'Set all three reader passwords before execution.',1;
IF DB_ID(N'WindFarmGateway') IS NULL CREATE DATABASE [WindFarmGateway];
IF SUSER_ID(N'wind_farm_gateway_reader') IS NULL
BEGIN
    DECLARE @create_login nvarchar(max)=
        N'CREATE LOGIN [wind_farm_gateway_reader] WITH PASSWORD=N'''+
        REPLACE(@gateway_password,N'''',N'''''')+
        N''', CHECK_POLICY=ON, DEFAULT_DATABASE=[WindFarmGateway];';
    EXEC sys.sp_executesql @create_login;
END;
IF NOT EXISTS (SELECT 1 FROM sys.servers WHERE name=N'WIND_FARM_SQL_ODBC')
BEGIN
    EXEC master.dbo.sp_addlinkedserver
        @server=N'WIND_FARM_SQL_ODBC', @srvproduct=N'ODBC',
        @provider=N'MSDASQL', @datasrc=N'WindFarmSqlTelemetry';
    EXEC master.dbo.sp_droplinkedsrvlogin
        @rmtsrvname=N'WIND_FARM_SQL_ODBC', @locallogin=NULL;
END;
IF NOT EXISTS (SELECT 1 FROM sys.servers WHERE name=N'WIND_FARM_ODBC')
BEGIN
    EXEC master.dbo.sp_addlinkedserver
        @server=N'WIND_FARM_ODBC', @srvproduct=N'PostgreSQL',
        @provider=N'MSDASQL', @datasrc=N'WindFarmTelemetry';
    EXEC master.dbo.sp_droplinkedsrvlogin
        @rmtsrvname=N'WIND_FARM_ODBC', @locallogin=NULL;
END;
DECLARE @setup_login sysname=SUSER_SNAME();
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname=N'WIND_FARM_SQL_ODBC', @useself=N'false',
    @locallogin=N'wind_farm_gateway_reader',
    @rmtuser=N'wind_farm_sql_reader', @rmtpassword=@sql_password;
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname=N'WIND_FARM_SQL_ODBC', @useself=N'false',
    @locallogin=@setup_login,
    @rmtuser=N'wind_farm_sql_reader', @rmtpassword=@sql_password;
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname=N'WIND_FARM_ODBC', @useself=N'false',
    @locallogin=N'wind_farm_gateway_reader',
    @rmtuser=N'wind_farm_odbc_reader', @rmtpassword=@pg_password;
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname=N'WIND_FARM_ODBC', @useself=N'false',
    @locallogin=@setup_login,
    @rmtuser=N'wind_farm_odbc_reader', @rmtpassword=@pg_password;
EXEC master.dbo.sp_serveroption N'WIND_FARM_SQL_ODBC',N'data access',N'true';
EXEC master.dbo.sp_serveroption N'WIND_FARM_SQL_ODBC',N'rpc',N'false';
EXEC master.dbo.sp_serveroption N'WIND_FARM_SQL_ODBC',N'rpc out',N'false';
GO
USE [WindFarmGateway];
GO
IF USER_ID(N'wind_farm_gateway_reader') IS NULL
    CREATE USER [wind_farm_gateway_reader] FOR LOGIN [wind_farm_gateway_reader];
GO
CREATE OR ALTER VIEW dbo.LatestSqlServerTurbineTelemetry AS
SELECT turbine_id,observed_ts,active_power,wind_speed
FROM OPENQUERY([WIND_FARM_SQL_ODBC],
    'SELECT turbine_id,observed_ts,active_power,wind_speed FROM dbo.latest_turbine_data');
GO
CREATE OR ALTER VIEW dbo.LatestTurbineTelemetry AS
SELECT turbine_id,observed_ts,active_power,wind_speed
FROM OPENQUERY([WIND_FARM_ODBC],
    'SELECT turbine_id,
        CAST(FLOOR(EXTRACT(EPOCH FROM time_stamp)*1000) AS bigint) AS observed_ts,
        power_output AS active_power,wind_speed
     FROM public.latest_turbine_data');
GO
GRANT SELECT ON dbo.LatestSqlServerTurbineTelemetry TO [wind_farm_gateway_reader];
GRANT SELECT ON dbo.LatestTurbineTelemetry TO [wind_farm_gateway_reader];
GO
EXECUTE AS LOGIN='wind_farm_gateway_reader';
SELECT turbine_id,observed_ts,active_power,wind_speed
FROM dbo.LatestSqlServerTurbineTelemetry ORDER BY turbine_id;
SELECT turbine_id,observed_ts,active_power,wind_speed
FROM dbo.LatestTurbineTelemetry ORDER BY turbine_id;
REVERT;

The script creates these database resources:

Gateway resource

Purpose

WindFarmGateway

Common SQL Server database used by SQL Client.

wind_farm_gateway_reader

SQL Server login and database user. It can SELECT from both gateway views.

WIND_FARM_SQL_ODBC

Microsoft source: MSDASQL and System DSN WindFarmSqlTelemetry.

WIND_FARM_ODBC

PostgreSQL source: MSDASQL and System DSN WindFarmTelemetry.

Explicit mappings

The gateway reader and setup administrator each map to the corresponding source reader. The default mapping for all local logins is removed.

The following SQL statement registers the Microsoft SQL Server source as a linked server on the SQL Server Express gateway:

  • sp_addlinkedserver: Creates the linked server WIND_FARM_SQL_ODBC using the MSDASQL provider.

  • @datasrc: Specifies the existing WindFarmSqlTelemetry System DSN used to connect to the source database.

  • Access configuration: This statement does not configure credentials or permissions. The complete setup script adds the login mappings and grants access to the gateway views.

EXEC master.dbo.sp_addlinkedserver
    @server = N'WIND_FARM_SQL_ODBC',
    @srvproduct = N'ODBC',
    @provider = N'MSDASQL',
    @datasrc = N'WindFarmSqlTelemetry';

The following SQL statement registers the PostgreSQL source as a linked server on the SQL Server Express gateway:

  • sp_addlinkedserver: Creates the linked server WIND_FARM_ODBC using the MSDASQL provider.

  • @srvproduct: Identifies PostgreSQL as the source database system.

  • @datasrc: Specifies the existing WindFarmTelemetry System DSN used to connect to PostgreSQL.

  • Access configuration: This statement does not configure credentials or permissions. The complete setup script adds the login mappings and grants access to the gateway views.

EXEC master.dbo.sp_addlinkedserver
    @server = N'WIND_FARM_ODBC',
    @srvproduct = N'PostgreSQL',
    @provider = N'MSDASQL',
    @datasrc = N'WindFarmTelemetry';

The complete two-source gateway configuration uses a separate account for each connection:

Connection

Database user

N3uron → SQL Server gateway

wind_farm_gateway_reader

Gateway → Microsoft source

wind_farm_sql_reader

Gateway → PostgreSQL source

wind_farm_odbc_reader

Microsoft describes the System DSN requirement and explicit login mappings.

For a PostgreSQL-only configuration, use the following script instead of the two-source setup.

Run it as a SQL Server administrator on N3SQL. Replace both password placeholders before execution. Make sure that the database, login, and linked-server names do not already exist.

The script performs these operations:

  • CREATE DATABASE / LOGIN: Creates the gateway database and reader login.

  • sp_addlinkedserver: Registers the PostgreSQL ODBC source through the MSDASQL provider.

  • sp_droplinkedsrvlogin: Removes the default linked-server login mapping.

  • sp_addlinkedsrvlogin: Maps the gateway reader and setup administrator to the PostgreSQL reader account.

  • CREATE VIEW / GRANT SELECT: Exposes PostgreSQL telemetry through a SQL Server view and grants read access.

  • EXECUTE AS / REVERT: Tests the view using the gateway reader account and restores the original login context.

Note:

This script is intended for a new configuration. It does not check whether the database, login, or linked server already exists. The REVERT statement restores the login context; it does not undo the configuration changes.

-- Run as a SQL Server administrator on the intended Express instance.
-- First replace both password placeholders with your own passwords.
-- Use dedicated names. The database, linked server and login must not already exist.
CREATE DATABASE [WindFarmGateway];
GO
CREATE LOGIN [wind_farm_gateway_reader]
WITH PASSWORD = N'<gateway-reader-password>',
     CHECK_POLICY = ON, DEFAULT_DATABASE = [WindFarmGateway];
GO
EXEC master.dbo.sp_addlinkedserver
    @server = N'WIND_FARM_ODBC',
    @srvproduct = N'PostgreSQL',
    @provider = N'MSDASQL',
    @datasrc = N'WindFarmTelemetry';
EXEC master.dbo.sp_droplinkedsrvlogin
    @rmtsrvname = N'WIND_FARM_ODBC', @locallogin = NULL;
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname = N'WIND_FARM_ODBC', @useself = N'false',
    @locallogin = N'wind_farm_gateway_reader',
    @rmtuser = N'wind_farm_odbc_reader',
    @rmtpassword = N'<odbc-reader-password>';
DECLARE @setupLogin sysname = SUSER_SNAME();
EXEC master.dbo.sp_addlinkedsrvlogin
    @rmtsrvname = N'WIND_FARM_ODBC', @useself = N'false',
    @locallogin = @setupLogin,
    @rmtuser = N'wind_farm_odbc_reader',
    @rmtpassword = N'<odbc-reader-password>';
GO
USE [WindFarmGateway];
GO
CREATE USER [wind_farm_gateway_reader]
FOR LOGIN [wind_farm_gateway_reader];
GO
CREATE VIEW dbo.LatestTurbineTelemetry AS
SELECT turbine_id, observed_ts, active_power, wind_speed
FROM OPENQUERY([WIND_FARM_ODBC],
    'SELECT turbine_id,
        CAST(FLOOR(EXTRACT(EPOCH FROM time_stamp)*1000) AS bigint) AS observed_ts,
        power_output AS active_power, wind_speed
     FROM public.latest_turbine_data');
GO
GRANT SELECT ON dbo.LatestTurbineTelemetry TO [wind_farm_gateway_reader];
GO
EXECUTE AS LOGIN = 'wind_farm_gateway_reader';
SELECT turbine_id, observed_ts, active_power, wind_speed
FROM dbo.LatestTurbineTelemetry ORDER BY turbine_id;
REVERT;

After the two-source gateway script finishes, examine both linked servers in SSMS:

Property

Microsoft source

PostgreSQL source

Linked server

WIND_FARM_SQL_ODBC

WIND_FARM_ODBC

Server type

Other data source

Other data source

Provider

Microsoft OLE DB Provider for ODBC Drivers

Microsoft OLE DB Provider for ODBC Drivers

Product name

ODBC

PostgreSQL

Data source

WindFarmSqlTelemetry

WindFarmTelemetry

Local Login

wind_farm_gateway_reader

wind_farm_gateway_reader

Impersonate

Unchecked

Unchecked

Remote User

wind_farm_sql_reader

wind_farm_odbc_reader

Remote Password

Microsoft source-reader password

PostgreSQL source-reader password

Unmapped logins

Not be made

Not be made

Data Access

True

True

RPC / RPC Out

False / False

False / False

For the Microsoft source, the General page shows the provider and System DSN:

Map the gateway reader to wind_farm_sql_reader. Keep Impersonate clear:

The following screens show the corresponding PostgreSQL settings.

  1. Expand Server Objects → Linked Servers.

  2. Right-click WIND_FARM_ODBC.

  3. Select Properties.

  4. Select General.

Use the PostgreSQL values in the source comparison table above.

Data source is the System DSN name. It is not the database name.

These fields are read-only for the existing linked server in this properties dialog.

The General page identifies the linked server and its Windows System DSN.

This detail shows Provider, Product name and Data source in that order.

Select Security and map local login wind_farm_gateway_reader to remote user wind_farm_odbc_reader using its PostgreSQL password. Leave Impersonate unchecked.

The setup administrator has a separate login mapping.

Under Security, locate For a login not defined in the list above, connections will and select Not be made.

The gateway script removes the default login mapping and creates explicit mappings. This prevents local logins without a mapping from accessing the linked server.

Select Server Options and verify the following settings for both linked servers:

  • Data Access: True — Enables queries through OPENQUERY.

  • RPC: False — Disables incoming remote procedure calls.

  • RPC Out: False — Disables outgoing remote procedure calls.

This configuration reads remote views without executing remote stored procedures.

After reviewing the settings, click Cancel to close the properties window without making changes.

For more information, see Create linked servers with SSMS.

Step 5: Expose and test a SQL Server view

The gateway script creates two views in WindFarmGateway.

The Microsoft gateway view uses this definition. The linked server and source view must already exist:

  • CREATE VIEW: Defines dbo.LatestSqlServerTurbineTelemetry in the gateway database. The setup script already creates this view.

  • OPENQUERY / SELECT: Reads the four listed columns from the Microsoft source through WIND_FARM_SQL_ODBC.

CREATE VIEW dbo.LatestSqlServerTurbineTelemetry AS
SELECT turbine_id, observed_ts, active_power, wind_speed
FROM OPENQUERY([WIND_FARM_SQL_ODBC],
    'SELECT turbine_id, observed_ts, active_power, wind_speed FROM dbo.latest_turbine_data');

The PostgreSQL gateway view uses this definition. The linked server and source view must already exist:

  • OPENQUERY: Reads public.latest_turbine_data through WIND_FARM_ODBC.

  • Timestamp / alias: Converts source time to integer epoch milliseconds and renames power_output to active_power.

  • CREATE VIEW: Exposes the four columns as dbo.LatestTurbineTelemetry. The setup script already creates this view.

CREATE VIEW dbo.LatestTurbineTelemetry AS
SELECT turbine_id, observed_ts, active_power, wind_speed
FROM OPENQUERY([WIND_FARM_ODBC],
    'SELECT turbine_id,
        CAST(FLOOR(EXTRACT(EPOCH FROM time_stamp)*1000) AS bigint) AS observed_ts,
        power_output AS active_power, wind_speed
     FROM public.latest_turbine_data');

OPENQUERY sends the quoted query to the source database. For the PostgreSQL source, the inner query uses PostgreSQL syntax.

The PostgreSQL inner query makes these conversions:

PostgreSQL source field

Gateway field / conversion

time_stamp

observed_ts: whole Unix milliseconds.

power_output

active_power: column alias.

SQL Client queries the SQL Server gateway view, which retrieves data from the ODBC source through OPENQUERY.

For other ODBC sources, adapt the remote query to the database's SQL syntax and data types. See OPENQUERY.

Optional PostgreSQL verification: Run the following SQL on WindFarmGateway using an account with permission to impersonate the gateway reader.

  • EXECUTE AS: Switches execution to wind_farm_gateway_reader.

  • SELECT: Retrieves turbine measurements from the PostgreSQL gateway view.

  • REVERT: Restores the original login context without undoing changes.

EXECUTE AS LOGIN = 'wind_farm_gateway_reader';
SELECT turbine_id, observed_ts, active_power, wind_speed
FROM dbo.LatestTurbineTelemetry ORDER BY turbine_id;
REVERT;

This query must return four PostgreSQL turbine rows. The reader-connection checks below test both sources.

Before you configure N3uron, correct errors in the DSN, ODBC driver, remote SQL and permissions.

Keep the provider options unchanged for this PostgreSQL configuration. Other drivers can require different configuration.

  1. Keep one administrator connection in Object Explorer.

  2. Open New Query.

  3. Select its query editor.

  4. Select the Change Connection toolbar button.

In the connection dialog, enter these values:

Setting

Example value

Server

127.0.0.1,15433

Authentication

SQL Server Authentication

Login

wind_farm_gateway_reader

Password

The password for the SQL Server gateway reader.

Database

WindFarmGateway

Select Connect. Then start the query that follows.

Only the query editor connection changes. Object Explorer keeps its one administrator connection.

Check the Microsoft source through the current gateway-reader connection:

  • SUSER_SNAME / DB_NAME: Shows the current query connection's login and database. These functions do not change the connection.

  • SELECT: Reads dbo.LatestSqlServerTurbineTelemetry, ordered by turbine_id.

SELECT SUSER_SNAME() AS sql_login,
       DB_NAME() AS gateway_database;

SELECT turbine_id, observed_ts, active_power, wind_speed
FROM dbo.LatestSqlServerTurbineTelemetry
ORDER BY turbine_id;

Repeat the reader-connection check for the PostgreSQL source:

  • Connection identity: Shows the same login and database information for the current query connection.

  • SELECT: Reads dbo.LatestTurbineTelemetry, ordered by turbine_id.

SELECT SUSER_SNAME() AS sql_login,
       DB_NAME() AS gateway_database;

SELECT turbine_id, observed_ts,
       active_power, wind_speed
FROM dbo.LatestTurbineTelemetry
ORDER BY turbine_id;

Step 6: Configure and test the SQL Client channel

  1. In module SQL Client, create channel WindFarmODBC.

  2. For connector Type, select SQL Server.

  3. Enter the values in the channel table:

Setting

Example value

Host

127.0.0.1 for N3uron on the SQL Server computer. For a remote node, use the SQL Server address from Step 1.

Port

15433

Default database

WindFarmGateway

Authentication Type

User/password

User

wind_farm_gateway_reader

Password

The password assigned to the SQL Server gateway reader, not the PostgreSQL reader.

  1. Click Test connection.

  2. Verify the server version, database, and user.

  3. Review any warnings.

In this example, the test reports SSL disabled and a time-zone difference between SQL Server and the N3uron node. Review the encryption and time-zone settings for your installation.

The gateway view returns timestamps as Unix milliseconds. The parser uses these numeric values to avoid ambiguity associated with SQL timestamps without time-zone information.

Step 7: Read the bridged data and update tags

Add one Standard transaction for each source in the same WindFarmODBC channel.

Standard transaction

Microsoft source

PostgreSQL source

Name

ReadSqlServerTelemetry

ReadBridgedTelemetry

Gateway view

dbo.LatestSqlServerTurbineTelemetry

dbo.LatestTurbineTelemetry

Tag group

/WindFarmSqlODBC

/WindFarmODBC

Turbines

WTG11–WTG14

WTG01–WTG04

Tag addresses

ODBC.WTG11.ActivePower and ODBC.WTG11.WindSpeed; use WTG12–WTG14 for the other turbines.

ODBC.WTG01.ActivePower and ODBC.WTG01.WindSpeed; use WTG02–WTG04 for the other turbines.

Use this Query script for ReadSqlServerTelemetry:

  • SELECT: Reads turbine_id, observed_ts, active_power and wind_speed from dbo.LatestSqlServerTurbineTelemetry, ordered by turbine_id.

  • $.output: Holds the SQL Server query string for ReadSqlServerTelemetry.

$.output = "SELECT turbine_id, observed_ts, active_power, wind_speed FROM dbo.LatestSqlServerTurbineTelemetry ORDER BY turbine_id";

Use the following PostgreSQL example for ReadBridgedTelemetry. Both transactions use the same Parser script.

  1. Add a Standard transaction named ReadBridgedTelemetry to WindFarmODBC.

  2. Add a periodic trigger to each transaction.

For both transactions, use these trigger values:

Setting

Example value

Type

Fixed time

Scan rate

10000 ms

Run on start

Yes

Read PostgreSQL telemetry through the SQL Server gateway view:

  • SELECT: Reads the four telemetry columns from dbo.LatestTurbineTelemetry, ordered by turbine_id.

  • $.output: Holds the SQL Server query string for ReadBridgedTelemetry. The source access occurs through the view.

$.output = "SELECT turbine_id, observed_ts, active_power, wind_speed FROM dbo.LatestTurbineTelemetry ORDER BY turbine_id";

For both transactions, enable the parser.

Convert gateway rows to ODBC turbine tag events. Both source views must return the four named columns:

  • Dataset: Reads turbine_id, observed_ts, active_power and wind_speed from each row.

  • Number: Converts observed_ts to a number for the event timestamp.

  • $.output.push: Appends ActivePower and WindSpeed events with the ODBC turbine prefix, quality 192 and the converted timestamp.

for (const row of $.input.rows()) {
    const turbine = row.getValue("turbine_id");
    const ts = Number(row.getValue("observed_ts"));
    $.output.push({ tag: "ODBC." + turbine + ".ActivePower", value: row.getValue("active_power"), quality: 192, ts: ts });
    $.output.push({ tag: "ODBC." + turbine + ".WindSpeed", value: row.getValue("wind_speed"), quality: 192, ts: ts });
}

Create eight numerical tags under /WindFarmODBC/WTG01 to /WindFarmODBC/WTG04.

Create ActivePower (kW) and WindSpeed (m/s) for each turbine.

For both tag groups, enable the SQL Client source and select module SQL Client.

For Microsoft, create the eight corresponding tags under /WindFarmSqlODBC/WTG11 to /WindFarmSqlODBC/WTG14.

Select transaction WindFarmODBC/ReadSqlServerTelemetry. Use the Microsoft addresses in the table.

For the PostgreSQL tags under /WindFarmODBC:

  1. Enable the SQL Client source.

  2. Select module SQL Client.

  3. Select transaction WindFarmODBC/ReadBridgedTelemetry.

  4. For WTG01, use addresses ODBC.WTG01.ActivePower and ODBC.WTG01.WindSpeed.

  5. For WTG02 to WTG04, use the corresponding addresses.

Apply the configuration:

  1. Save the tags.

  2. Save the module configuration.

  3. Apply the SQL Client restart.

  1. Open the transaction Pipeline test.

  2. Build the statement.

  3. Select Execute and parse (rolled back).

  4. Make sure that the result contains four rows and eight valid events.

Repeat the pipeline test for each transaction. Each must return four rows and eight valid events.

This test reads the source through SQL Server, MSDASQL, the System DSN and the ODBC driver.

Microsoft source: four returned rows and eight valid tag events.

PostgreSQL source:

  1. Open Data → Realtime.

  2. Select WindFarmODBC.

  3. Include the sublevels.

  4. After a periodic execution, make sure that all eight tags update.

The saved PostgreSQL ODBC bridge transaction updates eight Good tags.

The source observation timestamp matches the direct read.

The floating-point precision shown can differ between database drivers.

Eight scheduled WindFarmODBC tags show source measurements, Good quality and matching observation timestamps

In Data → Realtime, also select WindFarmSqlODBC and include its sublevels.

After a periodic execution, make sure that all eight Microsoft tags update with the source values and observation timestamps.

WindFarmSqlODBC contains eight tags for WTG11 to WTG14, with the expected values and Good quality

Step 8: Locate a bridge failure by layer

Layer

Checks before the next layer

Source → ODBC DSN

Do the DSN test on the SQL Server computer.

Make sure that the source endpoint, 64-bit driver and System DSN are correct.

Make sure that the source reader has access.

DSN → SQL Server view

Start the view query as wind_farm_gateway_reader.

Examine the linked-server DSN name and explicit login mapping.

Make sure that the remote column names and SQL dialect are correct.

SQL Server → channel

Select Test connection.

Make sure that the intended instance and fixed TCP port are correct.

Port 1433 can belong to another instance.

Channel → tags

Apply the saved configuration.

Do the Standard pipeline test.

Make sure that the parser aliases match the configured tag addresses.

Make sure that scheduled execution updates the runtime values.

Note:

A successful ODBC connection test confirms connectivity to the source database. It does not validate the gateway view, SQL Client parser, or scheduled Tag updates.

Verify each layer before proceeding to the next. Make sure that each test returns the expected results.

For other compatible ODBC sources, adapt the driver, DSN settings, source credentials, linked-server configuration, and remote SQL statements.

SQL Client Full Product Details