1
I tried to create a trigger
for a table using for it to be activated after each select
, but researching a little I discovered that it is not possible to create triggers
for selections, only for update (update), insertion (Insert) and deletion (delete).
My application is an api and the same is presenting problems in Benchmark test; every time I make one select
i have another function that performs an update and increments a column of that selected record. The problem is that many updates at the same time are causing this error:
Sorry, Too Many clients already
That’s when I thought about creating a trigger
right in the database not to have to run a update
via code to each select
.
This was the code I created in plpgsql
to try incrementing the column:
create table urls(
id integer not null,
url varchar(255) not null,
encoded varchar(255) not null UNIQUE,
clicks integer DEFAULT 0,
created_at timestamp not null DEFAULT current_timestamp,
constraint pk_urls_id primary key (id)
);
CREATE OR REPLACE FUNCTION increment_clicks_counter()
returns trigger as
$BODY$
BEGIN
UPDATE urls SET clicks = clicks + 1 WHERE encoded = OLD.encoded;
END;
$BODY$
language 'plpgsql';
CREATE trigger increment_clicks AFTER SELECT ON urls
for each ROW EXECUTE procedure increment_clicks_counter();
How can I create a routine to increment a column for each selection of a given table?
This is the Benchmark I’m running on GO
:
func BenchmarkAPI(b *testing.B) {
// Valores que estão presentes na coluna 'encoded' da tabela urls
random := []string{
"A", "B", "C", "D", "H", "F", "E", "G",
"8", "5", "9", "6", "7", "2",
}
for n := 0; n < b.N; n++ {
url := fmt.Sprintf("http://localhost:5000/%s", random[rand.Intn(len(random))])
_, err := http.Get(url)
if err != nil {
b.Log(err.Error())
}
}
}
makes perfect sense! thank you.
– RFL