How CKAN DataStore triggers validate and clean rows
A DataStore trigger is a PL/pgSQL function attached to a DataStore table that runs whenever rows are written to it. Teams need one when a published table receives bad or inconsistent values on every load or upsert, and the portal team wants the same rule applied no matter how the data arrived. Because the rule lives in the PostgreSQL database, it sits below the Data API and the loaders, so it covers every write path, including a script or service that someone adds later. This section covers three uses: validation that stops a write that breaks a rule, cleaning that normalizes values before they are stored, and change history that records what changed and when. The CKAN DataStore extension documentation is the next read, and the parameter names used here come from that page.
Start by deciding, table by table, which of the three uses the portal needs, because each one changes what writers see. A validation trigger that rejects rows will make a load fail, so the publishing team needs to know in advance which rule causes which error. Before a trigger goes on a live table, confirm in the DataStore documentation who is allowed to create one on your CKAN version. Then choose how it is attached: attaching it through datastore_create sets it up with the table, while datastore_run_triggers reruns triggers against rows already stored. Test both paths on a copy of the table first, because a cleaning trigger that rewrites values changes what every later reload and upsert produces.
Trigger use cases and the options each one fits
This table compares three trigger use cases, validation, cleaning and change history, and what each does to a DataStore table on the write path. Read each row against your own upsert and reload process, because the cost of a trigger depends on how often rows are written. The main takeaway is that checks on a single file are usually simpler in the source pipeline, while triggers suit rules that must hold for every write.
| Use case | What it changes and the write-path risk | Interaction with upserts and full reloads | When a source check is simpler |
|---|---|---|---|
| Validation (reject rows that break a rule) | Leaves valid rows unchanged and blocks invalid ones before they are stored. The write fails, so the caller must handle the error. | A batch with one bad row can fail as a whole, so decide whether a bad row stops the load or is handled upstream. | Check the upsert response for errors on rejected rows, and confirm how your CKAN version reports them. |
| Cleaning (normalize values before storage) | Rewrites values before storage, such as trimming whitespace, normalizing casing or converting date formats. The stored value differs from the file. | Each insert and update runs extra logic, so keep the function short and avoid lookups to other tables. | Cleaned values no longer match the source file, so reconciliation against the publisher's copy needs its own rules. |
| Change history (audit inserts and updates) | Writes an audit record of each insert and update to a separate table, leaving the main table's rows as the current values. | Every write does extra work and grows a second table, so plan storage and check write latency under your load. | Reloads and upserts that write rows fire the trigger again, so history grows with every reload. Confirm the reload method first. |
| Rerunning triggers after a rule change | Reruns attached triggers on rows already stored, which is how a changed cleaning rule reaches old data. Confirm the scope in your version. | A rerun writes to every affected row at once, so run it in a quiet window and test on a copy first. | Reruns after a full reload may be unnecessary if the source file is corrected and reloaded instead. |
| Confirm before building | Confirm trigger creation rights, the attach step in datastore_create and the rerun command against your CKAN version. | Confirm whether triggers run on the datastore_upsert path in your version, and how errors are returned. | Confirm who may create or change triggers on each table, and record the owner of each trigger. |
How a PL/pgSQL trigger attaches to a DataStore table
A validation or cleaning trigger on a DataStore table is a trigger function written in PL/pgSQL and stored in the DataStore PostgreSQL database, the separate database that holds rows for CKAN resources. Because the function runs inside PostgreSQL, it checks every row written to the table, not only rows sent by one client. You attach it when the table is created through datastore_create, so the trigger definition travels with the first call that makes the resource. Anyone who can change trigger logic can change what the portal accepts, so decide before launch who owns the function and who may modify it. Then confirm that the database role used for writes cannot alter the trigger definitions meant to enforce your rules.
Write order decides what the trigger checks. A trigger only acts on writes that happen after it is attached. If a loader fills the table before the trigger exists, those rows stay unchecked until you run datastore_run_triggers to apply the triggers to rows already stored. Plan the sequence for every resource: create the table with its triggers, load the data, then rerun the triggers on anything that arrived earlier. A cleaning trigger that rewrites values changes data users may already have downloaded, so record which rows it touched and tell consumers when a rerun changed published values. Test this sequence on a copy of the resource before it reaches production.
Confirm two things in your CKAN version before you depend on this design. First, check whether XLoader reloads and datastore_upsert calls pass through the same triggers as the initial load. Test each path with one row that should be rejected and one that should be cleaned, then query the table to see the result. Second, copy the current parameter names for datastore_create and datastore_run_triggers from the DataStore extension docs before you write any calls. Record the CKAN and loader versions with your test results so you can repeat the same checks after an upgrade.
How a write passes the trigger before it reaches the stored table
A loader or client sends each write to the Data API, which connects with the write user and passes the rows to the trigger function on the DataStore table. The function accepts a row, cleans it, or rejects it, and only accepted or cleaned rows reach the stored table. The second path shows datastore_run_triggers applying the same function to rows that are already stored, so check the output against existing data after you change a function. Public read queries go through the read-only user, so they never use the write path. The subgraph marks the PostgreSQL database as the trust boundary.
Writes hit the trigger inside the database; public reads use the read-only user.
Setup sequence for CKAN DataStore triggers, with checks
This sequence takes a DataStore table from a version check through a tested, documented trigger that validates or cleans rows on write. Each step ends with a check, so the platform owner can see what passed before the trigger reaches the production portal. The result is a trigger you can explain, rerun and roll back.
Confirm CKAN and PostgreSQL versions and support
Record the CKAN version and the PostgreSQL major version on staging and production, then check each against its support status. Read the DataStore documentation for how the DataStore database and its users fit together. CKAN supports the latest patch of the current minor version and the previous minor version, and CKAN 2.12.0 was released on August 26, 2026. Source installs need PostgreSQL 12 or newer, and the PostgreSQL versioning policy lists version 14 as supported only until November 12, 2026. Check: a written record of both versions, their support end dates and the platform owner's sign-off before trigger work starts.
Build a test DataStore table in staging
In the staging portal, load a sample resource that includes rows you expect to pass and rows you expect to fail, such as a missing key, an out-of-range value and an unexpected text format (illustrative). Load it through the same loader production uses, so column types match what production will receive. The engineer records the table name, column names, types and row count in the test plan. Confirm that the loader finished without errors and that the Data API returns the expected number of rows. Check: a row count and column list that match the test plan exactly, with no rows lost during loading.
Write the trigger function in a reviewed file
Write the PL/pgSQL trigger function in a file kept under version control, so every change is recorded. Keep each rule narrow: each check should name the column it tests, and a rejected row should raise a clear exception and never pass through quietly. Cleaning logic, such as trimming whitespace, belongs in a separate function from validation so each can be reviewed and tested alone. A second engineer reviews the file against the written rule list before deployment. Check: the review is recorded in the change ticket, and every rule on the list maps to a specific line of code in the file.
Attach the trigger with datastore_create
Attach the function to the staging table through the triggers option of datastore_create, which names the function to run on the table. The function must already exist in the database, so deploy it before the API call. Confirm with the DataStore documentation which account may create and attach trigger functions in your CKAN version. Then check the attachment at the database level by querying the PostgreSQL catalog for triggers on the table, confirming the trigger name, its timing and the function it calls. Record the API request in the change ticket so the same attachment can be repeated on the production table. Check: the catalog shows exactly one trigger with the expected name and function.
Send valid and invalid rows through the API
Send a batch of valid rows and a batch of invalid rows through the Data API write path on staging, using the same request format your publishing tool will use. Confirm that valid rows are stored with any cleaning applied, and that invalid rows return the error the function was designed to raise. Confirm also whether one failing row rejects the whole request in your CKAN version, so no partial batch is stored by accident. Keep each request and response pair as test evidence. Check: every test case matches its expected outcome in the test plan, including the error text for each rejected row.
Run datastore_run_triggers on existing data
Before running anything, save a full copy of the table as it stands, using a dump or a query that exports every row and column. Run datastore_run_triggers on the staging table so the trigger acts on rows already stored. Confirm what the action changes in your CKAN version, then compare the result to the saved copy with a row-by-row diff. List every changed row and the rule that changed it, and confirm that no row changed without a matching rule. Check: the diff contains only the changes listed in the test plan, and the saved copy is stored outside the table.
Check what the read-only user can see
Connect as the read-only DataStore user and query the table through datastore_search and, if SQL search is enabled, datastore_search_sql. Confirm that cleaned values appear, that the table returns only the columns the publication plan lists, and that any helper or change-history tables the trigger uses are not readable by that user. If the portal serves the data publicly, repeat the check as an anonymous visitor would see it. A missed grant here can expose raw values or helper tables that the trigger was meant to hide. Check: the read-only user receives exactly the intended output and is denied on every helper table.
Document the rule and the rollback path
Write one page per trigger that states the rule in plain language, the function name, the columns it reads, the test cases that cover it and who approved it. Record the rollback path beside it: the statement that detaches the trigger, the saved copy to restore from and who may run both. Confirm the rollback on staging before production by detaching the trigger, restoring the saved copy and rerunning one test case. Store the page with the function file so the two cannot drift apart. Check: a second engineer can follow the page, detach the trigger on staging and restore the table without asking the author for help.
Choosing validation, cleaning or change history triggers
Illustrative example: a city publishes a permit register with a fixed column list, a date column and a controlled status code list. Start with a validation trigger that runs BEFORE INSERT OR UPDATE and raises an exception for any row that breaks the published schema, so the bad row is refused before it is stored. Keep cleaning minimal in this situation, because silent fixes make it harder for the publisher to correct the source file.
- Trigger type: a validation trigger on insert and update, with light cleaning limited to trimming whitespace and matching case on code columns.
- Test first: a load of a small file with one row per failure class, including a malformed date, an unknown status code and a missing required field.
- Confirm on reruns: whether running the trigger on existing rows flags or reports rows that already fail, and whether those rows stay visible to the public until the publisher corrects them.
- Confirm on schema changes: whether adding a new status code means editing the trigger function and rerunning it across the whole table.
Check that the error message reaches the person who publishes the file, because a refused row is only useful when the publisher can act on it.
Illustrative example: a transport operator upserts vehicle positions and sensor readings every few minutes, with a primary key per vehicle and timestamp. Start with a cleaning trigger on BEFORE INSERT OR UPDATE that converts timestamps to one time zone, clears readings outside a physical range and sets a derived field that consumers rely on. Keep validation thin here, because refusing one reading can leave a gap in a feed that is updated every few minutes.
- Trigger type: a cleaning trigger that normalizes timestamps, bounds readings and fills derived columns on every write.
- Test first: a replay of one batch with duplicate keys, a late arriving row and a reading just outside the accepted range, checking the stored values after each upsert.
- Confirm on upserts: that an update to an existing key fires the trigger again and that stored values reflect the cleaned output of the latest write.
- Confirm on reruns: whether a rerun across all rows is practical at your table size, and whether it can be limited to a recent window in your CKAN version.
- Confirm on corrections: whether a rerun overwrites values that an upstream correction already fixed, since cleaning rules applied twice can change values again.
Measure the run time of a rerun on a copy of production volume before scheduling any rerun during live publishing.
Illustrative example: a public body publishes grant awards and must show who changed a record and when. Start with a change history trigger on AFTER INSERT OR UPDATE OR DELETE that writes the operation, old values, new values and timestamp to a separate history table. The published table remains the source for the Data API, and the history table stays out of the public query path. Validation still belongs on the write path, so the history trigger records only changes that passed the checks.
- Trigger type: an after-row change history trigger that records the operation, old and new values, and timestamp for every change.
- Test first: an insert, an update and a delete on a copy table, then a refused write, confirming history rows exist for the first three and none for the refused write.
- Confirm the actor: which database identity the trigger records, since a shared write account would record only the service account name.
- Confirm on reruns: whether a rerun writes history rows for values that did not change, which would make audit records look like edits that never happened.
- Confirm access: who can create triggers and start reruns in your CKAN version, and who can read the history table.
Agree the retention period and export format for history rows with the audit team before the trigger goes live.
Who can create CKAN DataStore triggers and what they can write
Triggers run as part of every write to a DataStore table, so who can attach them and what they can write is a security question as well as a data quality one. The cards below cover the access, change control, audit and rerun decisions that govern trigger functions in a production portal.
Confirm who can create triggers
Check your CKAN version and permission model to see which accounts may create triggers on a DataStore table. Do not assume the ability is open to every editor. Ask the platform team to confirm the rule in writing, then test it with an ordinary editor account on a staging portal before the first production load. Test with an ordinary editor account.
CKAN DataStore docsKeep write and read-only users apart
The DataStore keeps a write user and a read-only user in its own PostgreSQL database. Trigger functions run during writes, so they belong to the write path and should never be reachable through the read-only account that serves public queries. Confirm that the read-only role cannot create, replace or drop functions or triggers by attempting each action with that account. Never grant the read-only user write rights.
Put trigger functions under change control
Keep every trigger function in version control, review it like application code and deploy it through the same change process you use for other production systems. Record the table each function attaches to, the reviewer and the date it went live. A function edited directly in the database is a change nobody reviewed, and it will be hard to explain when a row is rejected or altered unexpectedly. Edits go through review.
Give audit tables their own controls
A trigger that writes change history needs an audit table with its own grants, a named owner and a written retention period. The write user should insert into it, but the public API and general readers should not see raw history rows unless you decide they should. Agree retention with the data owner before launch, since the audit table grows with every write and every rerun. Set retention before launch.
Expect rejection messages in responses
When a trigger rejects a row, its error text can reach the caller through the API response. Write messages that name the field and the rule that failed, and leave out internal table names, connection details and values from other records. Test a deliberately bad row through the public API on staging so you can see exactly what an outside client receives. Check the text callers receive.
Log every rerun as a write
Running datastore_run_triggers rewrites rows, so treat each rerun as a write operation that needs a change record. Note the table, the reason, the trigger function version, the approver and the time, and keep the output so you can explain what changed. A rerun without this record is the hardest kind of change to reconstruct later. Every rerun needs a change record.
Questions buyers ask before outside help on DataStore triggers
What does outside help on DataStore triggers cost?
Cost follows the written scope, and DeployOpen does not publish a price list, so a quote comes after the scope is agreed. The main drivers are the number of validation and cleaning rules, the amount of test data needed to prove each rule, the size of the tables that must be rerun with datastore_run_triggers, and the CKAN and PostgreSQL versions in use. Each rule adds design, code and test work, and cleaning rules that change data need more review than checks that only flag problems. Large tables raise the cost of reruns and staging tests. Ask for a quote that separates one-time build work, testing and handover documentation from any recurring retainer for support or continuous testing, and ask which items depend on your versions.
How long does a DataStore trigger project take?
Duration depends on the rule set, not on the trigger code alone, so no fixed timeline applies before the rules are listed. Rules that are simple checks, such as required fields or allowed values, take less design and testing time than rules that clean or reshape data, match records across columns, or need a business owner to decide what counts as valid. Edge cases multiply testing, and each one needs sample rows. Reruns against large tables also add elapsed time in staging before production. Once the rule list and sample data exist, a written scope sets milestones and a delivery date, and DeployOpen agrees timelines in writing before work starts. Ask for the timeline to be tied to the rule count and to a staging rerun plan, so you can see which milestones depend on your team's answers.
What must our team provide for DataStore trigger validation?
Your team supplies the business rules, representative data and a staging environment. Start with sample data that includes the bad rows you already see, since those rows show what each rule must catch and what it must leave alone. Next, provide written rule definitions: what a valid value is, which fields each rule reads, and whether a failing row should be rejected, corrected or flagged. Your team also needs staging access to a CKAN instance and PostgreSQL database that match production versions as closely as possible, with the DataStore set up for the resource under test. Name one owner who can answer rule questions within the project window, and confirm who may create triggers and run datastore_run_triggers in each environment. Listing these items in the written scope makes gaps visible before work starts.
Can our internal team build DataStore triggers without outside help?
Yes, an internal team can build and run DataStore triggers alone if it has PostgreSQL and CKAN operations skills. The work needs PL/pgSQL for trigger functions, a working knowledge of how triggers are attached with datastore_create and rerun with datastore_run_triggers, and a staging copy of the DataStore to test against. Check each trigger change against the write and read-only database users before release. Keep sample rows and expected results under version control, and document each rule for the people who will maintain it. Outside help tends to make sense when the rule set is large, when an independent reviewer should check cleaning logic that changes published data, or when the internal team lacks time. A written scope shows which parts DeployOpen would deliver.
Should we validate DataStore rows in the loader or at the source?
Validate at the source where you can, and use DataStore triggers for checks that must hold on every row in the table, whatever path loaded it. Source checks stop bad values before they reach CKAN, so the fix stays with the data owner. Loader checks catch format problems during ingest, but only for files that pass through that loader. Triggers run inside PostgreSQL, so they see rows written to the table by any path that touches it. Confirm in staging that every write path you use, including datastore_upsert, fires the triggers you expect before you rely on them. Decide rule by rule where a check belongs, and record the reason so later changes to the source or loader do not quietly remove a control.
What changes when we upgrade CKAN or PostgreSQL?
Plan a retest of every trigger and PL/pgSQL function on each CKAN minor release and each PostgreSQL major upgrade. CKAN patch releases do not break backwards compatibility and exclude schema changes and new features, but minor releases may include backwards-incompatible changes, so read the notes for each minor version, including 2.12.0, released August 26, 2026. CKAN targets about two minor releases a year, and the tech team supports the latest patch of the current minor and the previous minor. PostgreSQL minor updates keep the storage format, so they mean replacing executables and restarting. Major upgrades use pg_dumpall and restore, pg_upgrade, or logical replication, and after any of them, confirm that triggers still fire and that functions still compile. PostgreSQL 14 support ended on November 12, 2026, so older clusters need a major upgrade plan.
Limits to confirm before relying on triggers in production
Triggers run inside the DataStore database, so their behavior depends on the PostgreSQL server, the CKAN release and the hosting platform underneath them. The six checks below cover the versions, load paths and hosting limits that can change whether a trigger behaves in production the way it did in testing.
PostgreSQL 14 is out of support
PostgreSQL 14 support ended on November 12, 2026, and PostgreSQL 13 and earlier are unsupported. Triggers are PL/pgSQL functions stored in the DataStore database, so the server version sets which language features and security fixes you receive. Confirm the running server version by querying the DataStore database directly, and do not rely on the package name alone. Plan the major upgrade first, then test your trigger functions against the target version on a copy of the database.
PostgreSQL versioning policyTrigger behavior across CKAN minor versions
CKAN 2.12.0 was released on August 26, 2026. CKAN patch releases exclude schema changes and new features, but minor releases may include backwards-incompatible changes. Confirm how the minor version your portal runs handles DataStore triggers and the actions that run them, and read the release notes for that version before any upgrade. Treat every minor upgrade as a change that needs its own test pass, covering each validation rule and cleaning rule you have attached to a table.
CKAN release policyTimeouts when rerunning on large tables
Rerunning triggers with datastore_run_triggers touches every row the rules apply to, and on large tables the run can hit timeouts before it finishes. Ask the hosting team which statement and request timeouts apply to the web tier and the database, then time a rerun on a copy of a production-sized table. Check whether a timed-out run leaves some rows processed and others not, and confirm how you would resume or reverse it. If the copy shows long runtimes, plan reruns in batches outside publication windows.
Triggers during upserts and full reloads
Triggers fire on the writes that the load path makes, so the same rule can behave differently under datastore_upsert and under a full reload. Confirm which inserts and updates each trigger fires on, and check whether a cleaning rule runs on rows that an upsert changes but not on rows it leaves alone. Test each write path with a sample file that includes known bad values, and record the expected output for each path. That record lets you spot a change in behavior after a loader or CKAN upgrade.
Data API output after trigger changes
The Data API reads the DataStore table, so a change a trigger makes is what consumers see in search results, SQL queries and downloads. Confirm that each cleaning rule changes only the values you intend, and that a change history table is not readable through the same resource by accident. Check whether any trigger writes to a table that the read-only user can read. Review a sample search, a SQL query and a full download after each rule change.
CKAN DataStore docsHosting limits on PostgreSQL features
Managed hosts can restrict procedural language support, extensions or database roles, so a rule that works on a self-managed server may fail on the host. List every PostgreSQL feature and extension your trigger functions call, then ask the provider to confirm each one is allowed on the DataStore database. Also confirm whether a connection pooler sits in front of PostgreSQL, since session settings and transaction handling can behave differently through pooling. Keep the rules within the features the host confirms in writing.
How DeployOpen scopes and delivers DataStore trigger work
DeployOpen starts with the rows you need to validate or clean, the CKAN DataStore tables they live in, and who is allowed to change them. Most engagements are fixed-scope, so the trigger logic, the datastore_create attachments, the reruns with datastore_run_triggers and the handover documentation are agreed in writing before build starts. The work runs against your own CKAN and DataStore databases, inside infrastructure you control.
How we scope
- Inventory the DataStore tables, resources and columns that need validation or cleaning rules.
- Confirm, against your CKAN version's documentation, who may create triggers and who may rerun them.
- Write the scope in writing before work starts, listing tables, trigger behavior, test data, and handover items.
How we build
- Write PL/pgSQL trigger functions for each validation rule, rejecting or correcting rows before they are stored.
- Attach triggers with
datastore_createon the DataStore tables, then test each rule against representative sample rows. - Test reruns with
datastore_run_triggerson sample data, covering cleaning passes and any change history tables.
How we hand over
- Document each trigger's purpose, its inputs, the columns it changes and the order in which triggers run.
- Provide the SQL for trigger functions and attachments in your repository, with a runbook for reruns.
- Walk your database and CKAN administrators through the rule set, the test results and the rollback steps.
How we support
- Ongoing support, upgrades and continuous testing are available as retainers, agreed separately from the build.
- Retainers can cover trigger reviews after CKAN or PostgreSQL upgrades, since trigger behavior should be retested.
- Where a rule change affects existing rows, agree in writing whether to rerun triggers or reload the resource.

