PostgreSQL Connector

A StrataBI Platform Module

Powered by Shaleio

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

Read-only SQL against PostgreSQL for StrataBI tiles. A tile sends one query and its parameters; one Lambda function in your own AWS account, <name_prefix>-postgresql_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 driver, 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 PostgreSQL on Amazon RDS, Aurora PostgreSQL or your own servers. It has run in Shaleio's own AWS test account against Aurora PostgreSQL 16 inside a VPC, from a StrataBI dashboard, but not yet against plain Amazon RDS; Tested lists what has run.

The connector 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 PostgreSQL (read-only user, read-only session)
                           │
                           └→ typed Parquet in your S3 → the tile

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 database user

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

sql
CREATE ROLE stratabi_reader LOGIN PASSWORD '<generated>';
ALTER ROLE stratabi_reader SET default_transaction_read_only = on;
GRANT CONNECT ON DATABASE analytics TO stratabi_reader;
GRANT USAGE ON SCHEMA sales TO stratabi_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA sales TO stratabi_reader;
ALTER DEFAULT PRIVILEGES IN SCHEMA sales GRANT SELECT ON TABLES TO stratabi_reader;

Give it no INSERT, UPDATE, DELETE or TRUNCATE, no sequence USAGE, no superuser or rds_superuser, and no access to extensions that reach out (dblink, postgres_fdw, the lo_* file functions). The connector also refuses writes itself (below), but the user is the control.

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 user's sign-in. Only username and password are required; an RDS-managed secret already has them:

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

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; the role then decrypts through Secrets Manager only.

A StrataAPI Manager credential (strataapi_credential). In StrataAPI Manager, an administrator adds a credential with provider postgresql and the read-only user's username and password, as a service account (recommended), and binds it to postgresql_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 internet (a public endpoint, a managed service)Nothing: the function runs outside a VPC, and TLS is required.
Inside a VPCsubnet_ids (private subnets that can reach the database) and security_group_ids (one that the database's security group admits on its port).

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. No KMS endpoint is needed.

TLS is always on. sslmode is require (encrypted) by default. verify-full also checks the server's certificate and host name; it needs the RDS certificate bundle added to the package when it is built.

Install

Install StrataBI first: the function uses its AWS SDK for pandas layer to write Parquet.

powershell
stratactl install postgresql_connector

The installer asks for the sign-in (secret_arn or strataapi_credential) and db_host. Both start blank, and an install with no connection stops at its check: "Install at least one connection".

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, 5432, the secret's or postgres
sslmoderequireOr 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, 128–10,240 MB.
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, psycopg. on: the optimized path (below).
max_scan_mb0 (off)Refuse a query whose EXPLAIN estimate reads more than this.
allowed_schemasAll the user can read
dashboard_tilesOnTurning it off also removes its permissions.
secret_kms_key_arnNone

More connections (another database, another secret) go in a tfvars map, connections. Tiles use the install's default connection.

From a tile

json
{"id": "revenue_by_region", "title": "Revenue by region",
 "exec": {"type": "lambda", "module_id": "postgresql_connector", "lambda_index": 0},
 "query": {"sql": ["SELECT region, sum(total) AS revenue",
                   "FROM sales.orders",
                   "WHERE ordered_at >= :since AND region = ANY(:regions)",
                   "GROUP BY region ORDER BY revenue DESC"],
           "params": {"since": "since_date", "regions": "region_picker"}},
 "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 PostgreSQL. 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, no schema-qualified function calls, and no row locks (FOR UPDATE, FOR SHARE). This check explains a refusal early; it is not the control.
  2. Allowed schemas, from allowed_schemas.
  3. Values bound by the driver.
  4. A read-only session: default_transaction_read_only = on.
  5. The read-only database user, which is what makes the connection read-only.
  6. Limits: the time budget, max_rows and max_result_mb, and max_scan_mb if set.

Each query opens one connection, with no pooling between calls, then sets statement_timeout (the time left plus 1 s), the read-only session, idle_in_transaction_session_timeout and TimeZone = UTC. Rows are read through a server-side cursor, in batches. The session's application_name is stratabi-postgresql_connector-tile, so its queries show in pg_stat_activity.

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).

PostgreSQLIn the result
smallint, integer, bigint, oid64-bit integer
real, double precision64-bit float
numericDecimal, with the column's declared precision and scale (up to 38)
booleanBoolean
dateDate
timestampTimestamp, without a time zone
timestamptzTimestamp in UTC
timeTime of day
intervalDuration
byteaBinary
json, jsonb, arraysJSON text
uuid, money, timetz, the text, network and xml typesText

A column whose values don't fit its type arrives as text. 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 PostgreSQL's cancel request and closes the connection, so the query stops on the server too; the database's statement_timeout is a backstop. 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.

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 something: row locks, more than one statement, or the allowed schemas.)
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.
LimitThe query would read more than this connector allows (N), so it was not run.
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, for a large result (the planner expects 20,000 rows or more) whose columns are all of the types below, strata_native, Shaleio's own Rust code, reads the result instead of psycopg. It speaks PostgreSQL's wire protocol on a second connection (the same user, TLS mode and read-only, UTC, time-limited session) and decodes the binary rows into Arrow.

Read nativelyAlways psycopg
int2, int4, int8, float8, numeric(p, s) with p up to 38 and s ≥ 0, bool, text, varchar, char(n), name, date, timestamp, timestamptz, bytea, uuidfloat4, oid, time, timetz, interval, arrays, json, jsonb, money, network types, xml, enums, a numeric without a declared precision or with a negative scale, every other type; a result the planner expects under 20,000 rows

A statement whose first rows hold a value the native types cannot (a numeric NaN, a date or timestamp outside the years 1 to 9999, infinity) runs again on psycopg, which gives it as it always has.

Rowspsycopg rows/sPeak memoryOptimized rows/sPeak memory×
100,000147k33 MB226k24 MB1.5
1,000,000200k139 MB455k124 MB2.3
10,000,000221k221 MB368k191 MB1.7

Measured on a laptop against PostgreSQL 16 in Docker: Lambda and a database across a network will be slower on both paths. Traditional and optimized paths has the conditions and every engine.

The risks.

Tested on PostgreSQL 16 in Docker, against psycopg's rows, every value and type the same, NaN and the sign of zero included: floating-point edge values, every integer width at its limits, numeric(38, s) at its limits, dates and timestamps at the years 1 and 9999 and around both epochs, char(n) padding, control characters, uuid, 6 MB text and bytea, parameters, limits, the deadline and cancel, and a million typical rows compared value by value. 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 postgresql_connector --reconfigure. With off, psycopg 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 AWS, in Shaleio's own AWS test account: the function in private subnets with VPC endpoints, against Aurora PostgreSQL 16 with a read-only database user, called by tiles on a StrataBI dashboard:

Has run in tests, through the function's handler against PostgreSQL 16 in a test container, with stand-ins for the AWS services:

The shared connector kit has its own unit tests, with stand-ins for StrataAPI Manager's registry and Secrets Manager. The OpenTofu (the function's role, no retries, the status writer as the failure destination) is tested against mocked AWS providers, including IAM decisions that the role cannot read a credential bound to another module, read another module's registry entries, or bind a credential to itself.

Has not run yet: plain Amazon RDS; verify-full against an RDS certificate; the status writer closing an attempt that Lambda stopped; a StrataAPI Manager credential in AWS.

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 · Execution types · Build a module · Modules