SQL Server Connector

A StrataBI Platform Module

Powered by Shaleio

module id sqlserver_connector · requires StrataBI · one of the data-source connectors

Read-only SQL against Microsoft SQL Server for StrataBI tiles. A tile sends one query and its parameters; one Lambda function in your own AWS account, <name_prefix>-sqlserver_connector-query, runs it against your database and writes the rows to your own S3 as the tile's result. Values are bound by the server, each query has a time budget and is cancelled on the server at its deadline, results are typed, and the database sign-in stays in your Secrets Manager. It is made for SQL Server 2016 and later, on Amazon RDS for SQL Server or your own servers. It has been tested against SQL Server 2022 in a container, over TLS, and has not run in AWS yet; Tested lists what has run.

The connector is available. It reads results two ways:

The connector uses the traditional path unless an administrator turns on the optimized path with the install setting native_reader = on. The optimized path is for teams that want its speed and accept that it needs production validation: see The optimized path, with its benchmarks.

text
tile (SQL + inputs) → query Lambda → your SQL Server (read-only login)
                           │
                           └→ typed Parquet in your S3 → the tile

SQL Server has no read-only session and no statement timeout of its own, so the login's grants are the control (What it does on the database).

This page covers dashboard tiles. Using the connector from StrataLake depends on StrataLake changes that are still in development.

Before installing

1. A read-only login

The connector is read-only because its login is. Create one that can read what dashboards should see and nothing else (run as an administrator, with your own database and schemas):

sql
-- in master
CREATE LOGIN stratabi_reader WITH PASSWORD = '<generated>', DEFAULT_DATABASE = analytics;
-- in the database dashboards read
USE analytics;
CREATE USER stratabi_reader FOR LOGIN stratabi_reader;
GRANT SELECT ON SCHEMA::sales TO stratabi_reader;   -- or ALTER ROLE db_datareader ADD MEMBER ...

Give it nothing else: no db_owner (the RDS master user is one: do not use it), db_datawriter or db_ddladmin, no INSERT, UPDATE, DELETE, ALTER, CONTROL or CREATE permission, no UPDATE on a sequence (NEXT VALUE FOR advances it from inside a SELECT), and no sysadmin. That includes permissions that reach the login through a database role or through public. The connector also refuses writes itself (below), but the login is the control.

SQL Server logins only: Windows and Microsoft Entra authentication are not supported.

2. The sign-in: a secret, or a StrataAPI Manager credential

Each connection signs in with exactly one of the two. Both, or neither, is refused at install.

An AWS Secrets Manager secret (secret_arn) with the login. Only username and password are required (user is accepted for username); the AWS console's database credential types write exactly these keys:

json
{"username": "stratabi_reader", "password": "...", "host": "<database host>",
 "port": 1433, "dbname": "analytics"}

Spaces and newlines that a paste into the console adds around a value are removed. The install settings db_host, db_port and db_name take precedence over the secret's host, port and dbname. The function's role may read this secret, and the secrets of any extra connections, and no other. The password never appears in the function's environment, its logs or its answers. A secret encrypted with a customer-managed KMS key needs secret_kms_key_arn.

A StrataAPI Manager credential (strataapi_credential). In StrataAPI Manager, an administrator adds a credential with provider sqlserver and the read-only login's username and password, as a service account (recommended), and binds it to sqlserver_connector. Install with the credential's name and db_host (and db_name): the credential holds only the sign-in.

StrataAPI Manager must be installed in the same deployment.

3. The network

Where the database isWhat to set
Reachable over the internetNothing: the function runs outside a VPC, and TLS is required.
Inside a VPC (the usual RDS case)subnet_ids (private subnets that can reach the database) and security_group_ids (one that the database's security group admits on 1433).

A function inside a VPC also needs to reach S3 (for results), Secrets Manager and Lambda (for StrataBI's status writer) from those subnets: through a NAT gateway, or through VPC endpoints (an S3 gateway endpoint, and interface endpoints for Secrets Manager and Lambda). With a StrataAPI Manager credential, the function also reads StrataAPI Manager's registry in DynamoDB: add a DynamoDB gateway endpoint too.

TLS is always on, for the whole connection (TLS 1.2), and a server that offers no encryption is refused. tls is require by default: encrypted, the server's certificate not checked (SQL Server's own self-signed certificate passes). verify-full also checks the certificate chain and host name; it needs the RDS certificate bundle added to the package when it is built. To make the server insist on encryption too, set rds.force_ssl = 1 in the RDS parameter group (Force Encryption on your own server).

Install

Install StrataBI first: the function uses its AWS SDK for pandas layer for Arrow and Parquet.

powershell
stratactl install sqlserver_connector

The installer asks for the sign-in (secret_arn or strataapi_credential), db_host and db_name. The first two start blank, and an install with no connection stops at its check: "Install at least one connection". Without db_name, the login's default database is used.

SettingDefault
secret_arn or strataapi_credentialOne of the twoThe secret's ARN, or a StrataAPI Manager credential's name (which needs db_host).
db_host, db_port, db_nameThe secret's, 1433, the secret's (else the login's default database)
tlsrequireOr verify-full.
subnet_ids, security_group_idsNoneBoth, or neither.
sync_timeout_seconds25A sync query's budget when the call carries none of its own.
memory_mb10,240The function's memory in MB: Lambda's maximum, about 6 vCPUs. A new AWS account may allow only 3,008 MB until AWS raises it, and the install then stops: ask AWS Support to raise it, or set 3008 (about 1.7 vCPUs; large results take longer).
max_query_seconds900The async timeout: the longest any query runs. You may lower it; see Timing.
max_rows, max_result_mb0, 0 (no limit)Per result. A positive value cuts the result there, and the result says so.
result_layoutautoHow a large result is written: single, prefix (parts plus a manifest), or auto.
native_readeroffoff: the traditional path, pytds with tds_arrow. on: the optimized path (below).
allowed_schemasAll the login can readUnqualified tables count as dbo for this check.
dashboard_tilesOnTurning it off also removes its permissions.
secret_kms_key_arnNone

There is no max_scan_mb.

From a tile

json
{"id": "revenue_by_region", "title": "Revenue by region",
 "exec": {"type": "lambda", "module_id": "sqlserver_connector", "lambda_index": 0},
 "query": {"sql": ["SELECT TOP (20) region, SUM(total) AS revenue",
                   "FROM sales.orders",
                   "WHERE ordered_at >= :since",
                   "GROUP BY region ORDER BY revenue DESC"],
           "params": {"since": "since_date"}},
 "block": {"type": "table"}}

What it does on the database

Every query goes through these, in order:

  1. One read-only statement. The SQL is parsed as T-SQL. Only a SELECT, or a set operation of them, with or without CTEs, may run: nothing that writes, defines, loads, calls out or runs a command, no table functions and no schema-qualified function calls. This check explains a refusal early; it is not the control.
  2. Allowed schemas, from allowed_schemas.
  3. Values bound by the server, through sp_executesql.
  4. No read-only session, because SQL Server has none. Instead the connector runs with autocommit off and never commits: a session's transaction is rolled back when its connection closes.
  5. The read-only login, which is what makes the connection read-only.
  6. Limits: the time budget, max_rows and max_result_mb.

Each query opens one connection, with no pooling between calls, with autocommit off, then sets SET LOCK_TIMEOUT to the time left (a read blocked by a writer's locks gives up at the deadline), SET DEADLOCK_PRIORITY LOW (a dashboard read loses a deadlock, not the business's write) and SET XACT_ABORT ON. Rows stream from the socket in batches. The session's application name is stratabi-sqlserver_connector-tile, so its queries show in sys.dm_exec_sessions as its program_name.

Each query writes one audit line to the function's log: who asked (and whether StrataBI verified it), a SHA-256 fingerprint of the SQL, the tables read, how many values, the connection, the outcome and the database's error code, rows, bytes and times. Never the SQL text, the values, the rows or a secret.

Results

The result is a typed Parquet file at the key StrataBI gives, in your deployment's bucket (or CSV, for a tile that asks for it).

SQL ServerIn the result
tinyint, smallint, int, bigint64-bit integer
real, floatFloat
decimal, numeric, money, smallmoneyDecimal, with the column's precision and scale
bitBoolean
dateDate
datetime, datetime2, smalldatetimeTimestamp, without a time zone
datetimeoffsetTimestamp in UTC (a CSV result keeps its own offset)
char, varchar, nchar, nvarcharText
uniqueidentifier, xmlText
binary, varbinaryBinary

A result cut at max_rows or max_result_mb is marked as cut, never silently short, and the tile says so.

Timing

A tenth of the budget (0.5–3 s) is kept back to cancel, write and report. At the deadline the connector sends TDS's attention packet on the statement's own connection, then closes the connection; measured, the request stops within milliseconds. The tile then says, for example:

The query did not finish within its 25 s budget and was cancelled. Narrow it (filters, fewer columns or rows) or run it as a background tile.

SQL Server has no statement timeout of its own to act as a backstop. If Lambda stops the function first, the driver's socket timeout (the time left plus 1 s) closes the connection, and SQL Server ends a request whose client has gone (measured: under 0.5 s on SQL Server 2022).

Lambda now allows a function up to 1,800 s, but the install accepts at most 900 s for now: the OpenTofu AWS provider still refuses a longer Lambda timeout. Past 15 minutes, a workload needs S3 caching or a module's own async logic (see Data-source connectors).

One attempt per query

Lambda never retries a connector query: automatic retries are off for the function, and that is not a setting. A query runs once, and a late status from an old attempt cannot overwrite a newer run's.

Errors

The tile shows a fixed sentence for each kind of failure. The database's own error text never leaves the function; the audit line keeps its error code.

KindWhat the tile says
InvalidThe database could not run the query as written. Check the SQL and its parameters.
RefusedOnly one read-only query (a SELECT) can run through this connector. (Followed by the check that failed, when it adds one.)
ParametersA query parameter is missing or is not a plain value.
CredentialsThe database did not accept the connector's sign-in. An administrator should check the connection's secret.
DeniedThe database refused this query for the connector's database user.
Not foundThe query names a table, view or column the database does not have, or the connector's database user cannot see.
TimeoutThe query did not finish within its N s budget and was cancelled. Narrow it (filters, fewer columns or rows) or run it as a background tile.
UnavailableThe database could not be reached. An administrator should check the connection's host, port and the connector's network settings.
ThrottledThe database is busy (too many connections or queries). Try again shortly.
FailedThe database reported an error running the query.
ReaderThe connector's native reader stopped before the end of the result, so no result was saved. An administrator can set native_reader = off to read with the traditional driver. (The optimized path only.)

The optimized path: what it does and the risks

What it does. With native_reader = on, the reader is the connection itself. strata_native, Shaleio's own Rust code, signs in to SQL Server as pytds does (TDS 7.4, the same TLS mode and certificate check, application name, session settings and transaction), sends each statement as pytds sends it (the parameters written by pytds's own type classes) and decodes the rows into Arrow on its own thread. It does this for every statement of every size. A result it does not read goes to pytds, on a connection of its own; a wrong password is never tried twice.

Read nativelyAlways pytds (on a connection of its own)
bit, tinyint, smallint, int, bigint, real, float, decimal and numeric up to 38 digits, money, smallmoney, date, time, datetime, datetime2, smalldatetime, char and varchar (single-byte code pages and UTF-8 collations), nchar, nvarchar, binary, varbinary, uniqueidentifier, the max typesa result with a datetimeoffset, xml, sql_variant, text, ntext, image or CLR column (hierarchyid, geometry); char and varchar in a two-byte code page (Japanese, Chinese, Korean collations); a sign-in the reader cannot make (TLS other than 1.2 with an ECDHE suite, an Azure SQL redirect)

A value the first rows cannot hold as its column's type runs the statement again on pytds.

RowsTraditional rows/sPeak memoryOptimized rows/sPeak memory×
100,000117k43 MB252k27 MB2.2
1,000,000174k133 MB728k131 MB4.2
10,000,000160k200 MB747k233 MB4.7

Measured on a laptop against SQL Server 2022 in Docker, over TLS (tls = require). Each figure is one run, and runs of the same query vary: on the optimized path, SQL Server's first 100,000-row query after loading the table ran at 115k and 344k rows/s in two runs, so read differences under about 20% as noise. Lambda reads the database over a network, on slower cores: expect lower rates there on both paths. Traditional and optimized paths has the conditions and every engine.

The risks.

Tested on SQL Server 2022 in Docker over TLS, against pytds and tds_arrow with the reader off, every value the same in Parquet and byte for byte in CSV and JSON: smalldatetime, datetime (its 1/300 s ticks), datetime2(7), date and time(7) at their range edges; money and smallmoney at their limits; every integer width and bit at their limits; real and float -0, their largest, smallest and subnormal values; decimal(38, s) at its edges; uniqueidentifier; multi-megabyte nvarchar(max) with emoji and CJK, varchar(max) in a single-byte code page, a 5 MB varbinary(max); every character of 12 single-byte code pages; a 1,024-column result, empty and all-NULL results, a warning in the middle of a result; parameters at their edges; and a million typical rows compared value by value. The types that go to pytds are tested to go there. A reader that stops without its end marker, one that fails mid-stream, and a row count that differs are tested too. No value differs between the two paths.

Not tested yet.

Turn it on, or back off. Set native_reader: on (or off) for this module in strata.yaml and run stratactl update sqlserver_connector --reconfigure. With off, pytds signs in and tds_arrow reads every result exactly as before, and the connector does no native work at all. The results, limits, timeouts and errors are the same either way; only the throughput changes.

Tested

Has run in tests, through the function's handler against SQL Server 2022 in a test container, over TLS (tls = require):

The module's OpenTofu has its own tests.

Has not run yet: any run in AWS (Lambda against Amazon RDS for SQL Server or a self-managed server); SQL Server 2016 to 2019; Azure SQL; verify-full against a real certificate authority.

AWS services

AWS Lambda (the query function), AWS Secrets Manager (the sign-in), Amazon S3 (results, in your deployment's bucket), Amazon CloudWatch Logs (the audit lines), and optionally Amazon VPC (subnets, a security group, endpoints), AWS KMS (a customer-managed key on the secret) and Amazon DynamoDB (StrataAPI Manager's registry, with a StrataAPI Manager credential).

Data-source connectors · Traditional and optimized paths · Execution types · Build a module · Modules