Search code examples
postgresqlvuejs2axiospostgrest

How to insert a record with id (auto increment) PostgREST?


I have a function

        axios.post('http://localhost:3000/unitsmeasure', {
            id: 20,
            name: 'name'
        })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });

It inserts an entry in the table. Its works.

But when I do not specify the id it does not work. id (serial PRIMARY KEY).

        axios.post('http://localhost:3000/unitsmeasure', {
            name: 'name'
        })
        .then(function (response) {
            console.log(response);
        })
        .catch(function (error) {
            console.log(error);
        });

This does not work

SQL Table:

CREATE TABLE "unitsmeasure" (
  "id" serial PRIMARY KEY,
  "name" varchar(100)
)

SQL Dump:

CREATE TABLE "unitsmeasure" (
  "id" int8 NOT NULL DEFAULT nextval('"Request".unitsmeasure_id_seq'::regclass),
  "name" varchar(100) COLLATE "pg_catalog"."default"
);
ALTER TABLE "unitsmeasure" OWNER TO "postgres";

ALTER TABLE "unitsmeasure" ADD CONSTRAINT "unitsmeasure_pkey" PRIMARY KEY ("id");

Solution

  • The most likely culprit is not having granted usage permissions to the sequence.

    Try this:

    GRANT USAGE ON SEQUENCE unitsmeasure_id_seq TO user_name;
    

    The inserting user needs access to the sequence in order to insert a value from the sequence.