Insert with id of type serial in pg-promise - pg-promise

In pg-promise, how can I insert data when the primary key is of type Serial? Omitting the field id creates no response in the call.
The code below produces no error in the catch (and also does not execute the then branch).
function postSecao(req, res){
var data = req.body;
var db = pgp(cn);
db.none("insert into public.secoes(nome) values($1)", [data.nome])
.then(function () {
pgp.end();
return res.status(201).end();
})
.catch(function (error) {
console.log(err);
pgp.end();
return res.status(500).end();
});
}
The table:
CREATE TABLE public.secoes
(
id bigint NOT NULL DEFAULT nextval('secoes_id_seq'::regclass),
nome character varying(100),
CONSTRAINT id PRIMARY KEY (id)
)
Manually providing the id works without problem.
function postSecao(req, res){
var data = req.body;
var db = pgp(cn);
db.none("insert into public.secoes(id, nome) values($1,$2)", [data.id, data.nome])
.then(function () {
pgp.end();
return res.status(201).end();
})
.catch(function (error) {
console.log(err);
pgp.end();
return res.status(500).end();
});
}
And of course the SQL runs fine in PGAdmin.
insert into public.secoes(nome) values('test')

I just figured out. The problem was in the privileges control of the user. It is necessary to the user accessing the DB to have privileges over the sequences used in the serial field.
So not a pg-promise problem.

Related

pgpromise insert return message failed, but successfully inserted into table

pg-promise successfully inserted an row into table, but not showing insert return record.
If i not use returning then all is fine. if using then error occurs.
const createEMP = async (req, res, next) => {
try{
let user = await db.none("insert into emp (name, salary, joindate)
values ( ${name}, ${salary}, ${joindate}) returning * ", req.body)
res.status(200).json({
user,
"message": "new user created"
})
}
catch(error) {next(error)}
}
In postman, it shows a very long page of error. It says: <pre>QueryResultError: No return data was expected.<br>.....
change from db.none to db.one Work.

Postgsql 11 Creating an object using UUID but beforeCreate is not being fired to update the id with UUID before save

This seems to occur when using an object as join table in a M:N association.
The beforeCreate hook is not updating the id before DB update.
I have created an instance hook in postgresql Version 11 within the instance model.
I have attempted to use both methods 2 and 3 neither of which work. The id column is not updated with UUID generated at create time
When I log the value within the hook I have a unique uuid but in the creating SQL the default uuid is used resulting in unique violation error.
I expected the values in the before hook to be used for the DB create statement
Log messages:
UserPersonalRelationship.beforeCreate: 19bbc538-c82e-41f5-9bd3-f0eabf9c0193
UserPersonalRelationship.beforeCreate: 3af7d252-ecfe-49e9-b850-a72a78e9773d
In the postgresql error message the field value is shown as:
fields: { id: '2cfe1fb0-4b3c-496b-80fe-f9073302afe8' },
My instance model is:
"use strict";
const { uuid } = require("uuidv4");
module.exports = (sequelize, DataTypes) => {
const UserPersonalRelationship = sequelize.define(
"UserPersonalRelationship",
{
User_rowID: DataTypes.UUID,
PersonalRelationship_rowID: DataTypes.UUID,
},
{}
);
UserPersonalRelationship.associate = function (models) {
// associations can be defined here
};
UserPersonalRelationship.beforeCreate(
async (userPersonalRelationship, options) => {
const objUUID = uuid();
userPersonalRelationship.id = objUUID;
console.log("UserPersonalRelationship.beforeCreate: ", objUUID);
}
);
UserPersonalRelationship.addHook(
"beforeValidate",
(userPersonalRelationship, options) => {
userPersonalRelationship.id = uuid();
console.log("Add hook called");
}
);
return UserPersonalRelationship;
};

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");
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.

How to get auto Id after upsert on a persisted model in loopback?

I have a some models generated from postgresql db using looback-connector postgresql. Id column of these models is a auto incremented integer column of postgresql db.
1) I have a remote method added on one of persisted models, where i perform simple update or insert(upsert.
Car.CreateOrUpdateCar = function (carobj, req) {
Car.upsert(Carobj, function (err, Car) {
if (err)
console.log(err);
else {
req(err, Car);
}
});
};
2) have added a remote hook to execute after this remote method.
Car.afterRemote('CreateOrUpdateCar', function (context, remoteMethodOutput, next) {
//Remaining code goes here
next();
});
3) I want to use Id of newly inserted row in step (1), in the remote hook mentioned in step (2)
I don't have much idea about postgresql db. But Try it like this
var carObj;
Car.CreateOrUpdateCar = function (carobj, req) {
Car.upsert(Carobj, function (err, Car) {
if (err)
console.log(err);
else {
req(err, Car); // Your Car object contains final result after upserting along with Id
carObj = Car;
}
});
};
Now you can get id by using carObj.id and you can use it where ever you want. I hope this helps
You can access to generated id in remote hook like this :
Car.afterRemote('CreateOrUpdateCar', function (context, remoteMethodOutput, next) {
var genId = remoteMethodOutput.id || context.result.id;
next();
});

How can I drop all tables with Sequelize.js using postgresql?

I am trying:
if (process.NODE_ENV === 'test') {
foreignKeyChecks = 0;
forceSync = true;
} else {
foreignKeyChecks = 1;
forceSync = false;
}
global.db.sequelize.query("SET FOREIGN_KEY_CHECKS = " + foreignKeyChecks).then(function() {
return global.db.sequelize.sync({
force: forceSync
});
}).then(function() {
return global.db.sequelize.query('SET FOREIGN_KEY_CHECKS = 1');
}).then(function() {
var server;
console.log('Initialzed database on:');
console.log(config.db);
return server = app.listen(port, function() {
return console.log("Server listening at http://" + (server.address().address) + ":" + (server.address().port));
});
})["catch"](function(err) {
return console.log('err', err);
});
module.exports = app;
But I get: SequelizeDatabaseError: unrecognized configuration parameter "foreign_key_checks"
I assume I can't have that keyword in postgres? But is there an equivalent way to drop all tables and recreate?
This is an updated answer, targeted at the googlers who wound up here like me.
Sequelize offers a drop function:
drop(options) => promise
Drop all tables defined through this sequelize instance. This is done by calling Model.drop on each model. Sequelize docs
Example
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var someModel = sequelize.define('somemodel', {
name: DataTypes.STRING
});
sequelize
.sync() // create the database table for our model(s)
.then(function(){
// do some work
})
.then(function(){
return sequelize.drop() // drop all tables in the db
});
For wiping out data and create all again from scratch (like in tests):
sequelize.sync({force: true});
I don't know anything about that JavaScript library, but Postgres provides a single command to drop everything that is owned by a user:
drop owned by <our_user_name cascade
This will only work if everything is owned by the same user and that user doesn't have some tables (or views, sequences, ...) that you do not want to drop.
More details in the manual:
http://www.postgresql.org/docs/current/static/sql-drop-owned.html
For anyone looking for a solution with sequelize-cli checkout this link Sequelize CLI:
You can just run:
sequelize_cli db:drop
sequelize_cli db:create
To create or drop your db using the cli tool. This way you will have a empty db.