0

I'm trying to migrate a database written in PostgreSQL to cockroachDB I want to know if there's a way to implement the trigger in SQL in cockroachDB. I know cocroachDB not supported triggers but I want to implements trigger functions to cockroachdb diffrent way or solutions.

In postgresql example triggers I wrote here

CREATE OR REPLACE FUNCTION "public"."distance"() RETURNS "pg_catalog"."trigger" AS $BODY$ DECLARE previous_odometer numeric; calculated_distance numeric; BEGIN -- Get the most recent odometer_midnight for the same vehicle prior to the current download_date SELECT odometer_midnight INTO previous_odometer FROM vu_daily_data_activities WHERE vehicle_id = NEW.vehicle_id AND download_date < NEW.download_date ORDER BY download_date DESC LIMIT 1; -- Calculate the day_distance IF previous_odometer IS NOT NULL THEN calculated_distance := NEW.odometer_midnight - previous_odometer; IF calculated_distance < 0 THEN NEW.day_distance := 0; -- Set to 0 if calculated distance is negative ELSE NEW.day_distance := calculated_distance; END IF; ELSE NEW.day_distance := 0; -- If no previous record, set day_distance to 0 END IF; RETURN NEW; END; $BODY$ LANGUAGE plpgsql VOLATILE COST 100 
1

2 Answers 2

0

CockroachDB, unlike traditional relational databases like PostgreSQL or MySQL, does not natively support database triggers. However, you can mimic the behavior of triggers in CockroachDB by implementing CDC, Kafka and write a custom function which updates tables according to your needs.
Steps to be taken:

  1. Enable CDC on the table using CREATE CHANGEFEED FOR TABLE ...
  2. Set Up Kafka and Create a Topic
  3. Set Up a Kafka Consumer to Process Changes (in python, .net, java or any other language you prefer)
    0

    Triggers are now available in preview in CockroachDB v25.1: https://www.cockroachlabs.com/docs/stable/triggers

      Start asking to get answers

      Find the answer to your question by asking.

      Ask question

      Explore related questions

      See similar questions with these tags.