Skip to content

Conversation

gronke
Copy link

@gronke gronke commented Oct 5, 2024

Issue #403 discusses ideas and interfaces to implement SQL triggers. Inspired by this conversation, this pull-request suggests a way to implement triggers.

This PR is in an early stage and meant to provide surface for discussion and tinkering.

// the most simple way to create a trigger
let unnamed_trigger: UnnamedTrigger =  UnnamedTrigger::new();

// it can be named later, and become a NamedTrigger
let named_trigger: NamedTrigger = unnamed_trigger.name("my_trigger");

// this is useful because it allows dropping directly
let drop_sql: String = named_trigger.drop().to_string(MysqlQueryBuilder);

// with a table, action and action time we dare do derive a trigger name
let trigger: DefinedTrigger = unnamed_trigger.before_insert(Glyph::Table);
assert_eq!(trigger.trigger_name(), "t_glyph_before_insert");

// demo expression, blocked by missing features (e.g. IF-ELSE statements)
let action: SimpleExpr = Expr::col(Glyph::Id).eq(1);

// multiple actions will be executed in order of insertion
trigger.actions.push(action);

println!(trigger.create().to_string(MysqlQueryBuilder));
CREATE TRIGGER `t_glyph_before_insert` BEFORE INSERT ON `glyph` FOR EACH ROW
BEGIN
`id` = 1;
END

The action expression (between BEGIN and END) does not make sense yet and exists to outline the idea. With new features to express logic, variable declaration, loops and custom errors this could be achieved though.

New Features

  • Create and drop TRIGGER
  • Named and unnamed triggers (name derived from table, action and time)
  • Concatenate list of statements

TBD

@gronke gronke marked this pull request as draft October 5, 2024 11:57
@gronke gronke changed the title [WIP] Triggers Triggers Oct 5, 2024
self.prepare_table_ref_iden(&trigger_ref, sql);
write!(sql, " {} {} ON ", create.trigger.time, create.trigger.event).unwrap();
self.prepare_table_ref_iden(&create.trigger.table, sql);
write!(sql, " FOR EACH ROW\nBEGIN\n").unwrap();
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be nice to have statement level triggers although they aren't available in mysql.

pub type TriggerActions = Vec<TriggerAction>;

#[derive(Default, Debug, Clone)]
pub struct NamedTrigger {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How about unifying the two into one with fn named(...) and fn unnamed(...)?

Copy link
Author

@gronke gronke Dec 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The two structs UnnamedTrigger and NamedTrigger are distinguished because of slightly different interfaces. Generating trigger names is only needed when a user did not specify an explicit name. Differentiating structs within the Trigger enum allows auto-completion.

The Trigger implementation has two methods new and with_name that are similar to your suggestion:

impl Trigger {
    pub fn new() -> Trigger {
        Trigger::UnnamedTrigger(None, None, None)
    }

    pub fn with_name(name: TriggerRef) -> Trigger {
        Trigger::NamedTrigger(name, None, None, None)
    }
}

@HigherOrderLogic do you think we should get rid of the two variants and accept that users might inadvertently use unnamed triggers? Typically I prefer being explicit, but I also see the potential to reduce complexity. Happy to hear your suggestion. 😊

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you think we should get rid of the two variants and accept that users might inadvertently use unnamed triggers

I think that an unified enum would be better for end users DX, however, I disagree that unnamed should be the default.

As I stated in the previous comment, we can implement different functions for each variants, eg:

impl Trigger {
    pub fn unnamed() -> Trigger {
        Trigger::UnnamedTrigger(None, None, None)
    }

    pub fn named(name: TriggerRef) -> Trigger {
        Trigger::NamedTrigger(name, None, None, None)
    }
}

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've played with the thought of a unified Trigger and find it to conflict with the level of definition a trigger requires to be dropped.

Looking at MySQL tests for instance tests/mysql/trigger.rs#L44-L60:

A NamedTrigger is Referencable and can be dropped right away, without further definition:

#[test]
fn drop_named_trigger() {
    let trigger = NamedTrigger::new("my_trigger");
    assert_eq!(
        trigger.drop().to_string(MysqlQueryBuilder),
        "DROP TRIGGER `my_trigger`"
    );
}

To automatically generate a reasonably unique trigger name, we need to know more information that we will define when configuring the Configurable named or unnamed trigger into a DefinedTrigger.

#[test]
fn drop_unnamed_trigger() {
    let trigger = UnnamedTrigger::new().before_delete(Glyph::Table);
    assert_eq!(
        trigger.drop().to_string(MysqlQueryBuilder),
        "DROP TRIGGER `t_glyph_before_delete`"
    );
}

A DefinedTrigger falls back to generating the trigger name by concatenating table name, trigger action time and event (e.g. t_glyph_before_delete), which occurs in src/trigger/mod.rs#L173-L183

fn trigger_name(&self) -> String {
    match &self.name {
        Some(name) => name.to_string(),
        _ => format!(
            "t_{}_{}_{}",
            self.table.to_string().to_lowercase(),
            self.time.to_string().to_lowercase(),
            self.event.to_string().to_lowercase(),
        ),
    }
}

How about we call the UnnamedTrigger just Trigger and remove the variant enum? One can call .name() on it and make it named without bothering about internals.

@Ichmed
Copy link

Ichmed commented Apr 8, 2025

Hi @gronke, are you still actively working on this?

@gronke
Copy link
Author

gronke commented May 7, 2025

@Ichmed yes, I do. Took me a while to get back to this though. Sorry for the delay.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants