microo8 / plgo

easily create postgresql extensions in golang; moved to gitlab.com/microo8/plgo
292 stars 23 forks source link

example how get new trigger data #7

Closed remotejob closed 6 years ago

remotejob commented 6 years ago

I try figure out how get new data from trigger.

I tried:

var res interface{}

td.NewRow.Set(&res)`

var res string

td.NewRow.Set(0,&res)

log.Println("res",res)

Don't work for me.??

microo8 commented 6 years ago

Set just sets the column value in the row. You must then return the modified row.

If you want to change a value in the NewRow, eg. the table is:

CREATE TABLE example
(
    id serial primary key,
    value text
)

and you make a trigger that eg concatenates the value:

func DoubleValueTrigger(td *plgo.TriggerData) *plgo.TriggerRow {
    var id int
    var value string
    td.NewRow.Scan(&id, &value) //get values of the new row being inserted  
        td.NewRow.Set(1, value+value) //set the column 1 (not using a pointer, just the value)
    return td.NewRow
}

Set the trigger to run on insert:

CREATE TRIGGER double_trigger
    BEFORE INSERT
    ON public.example
    FOR EACH ROW
    EXECUTE PROCEDURE public.doublevaluetrigger();

And insert some value insert into example (value) values ('foo')

Then in the new row you will have values: [1, 'foofoo']

Maybe I must do a better documentation around these use-cases.