I tried to create a trigger
for a table using it so that it would be activated after every select
, but by searching a little I discovered that it is not possible to create triggers
for selections, only for update, insert ) and delete.
My application is an api and the same one is presenting problems in Benchmark test; every time I make a 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 of creating a% direct% of the database so I would not have to run a trigger
via code every update
.
This was the code I created in select
to try to increment 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 at each selection of a given table?
This is the Benchmark I am running on plpgsql
:
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())
}
}
}