Manually insert into Heroku PostgreSQL - postgresql

I want to add some records in a table on the PostgreSQL db that Heroku offers. I am using Sequelize as ORM.
The query would be this one:
INSERT INTO "Categories" (name) VALUES ('Familie'), ('Liefde'), ('Tienertijd'), ('Kindertijd'), ('Hobbies');
However, I get this error that says I should also specify two more columns that are automatically created by Sequelize, namely createdAt and updatedAt.
ERROR: null value in column "createdAt" violates not-null constraint
DETAIL: Failing row contains (1, Familie, null, null).
How can I manually add these records, without going through Sequelize?
EDIT: this is the Sequelize model for Categories:
module.exports = (sequelize, DataTypes) =>
sequelize.define('Category', {
name: {
type: DataTypes.STRING,
unique: true
}
})

Since I didn't really need the timestamps, I realized you can specify not to use them as shown in the following snippet:
sequelize.define('Category', {
name: { type: DataTypes.STRING , unique: true},
}, {
timestamps: false
});
This way I don't need to specify the createdAt and updatedAt values when doing an INSERT.

Related

Auto increment in postgres/sequelize

I have a Postgres database using Sequelize (node/express) as ORM. I have a table called students, in it there are columns: id and name.
In this students table, I have several registered students, but a detail: the last registered ID is 34550 and the first is 30000, they come from an import from a previous database, I need to continue counting from 34550, or that is, from the last registered student. However, when I register a student via API, the generated ID is below 30000. I know that in mysql the ID field being AUTO INCREMENT would solve it, however, as I understand it, postgres works in a different way.
How could I solve this problem?
The migration used to create the table is as follows:
module.exports = {
up: (queryInterface, Sequelize) => {
return queryInterface.createTable('students', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
name: {
type: Sequelize.STRING,
allowNull: false,
},
});
},
down: (queryInterface) => {
return queryInterface.dropTable('students');
},
};
Table print:
Based on Frank comment, I was able to adjust using:
SELECT setval('public.students_id_seq', 34550, true);

Insert data in a 4D spatial column using Sequelize

My application uses Node.js (v9.3.0), PostgreSQL (v9.5.1.0) as database with PostGIS (v2.2.1) installed as an extension and Sequelize (v4.37.6) as ORM. I'm trying to insert a 4D data - with longitude, latitude, altitude and a unix timestamp - in a LineStringZM column but I'm getting the following error:
DatabaseError: Column has M dimension but geometry does not
After some research, I've found out that Sequelize uses the function ST_GeomFromGeoJSON to insert spatial data. However, this function seems to ignore the 4th dimension in my GeoJSON data, which causes the error above.
I suppose that a raw query using ST_MakeLine (with the appropriated input) instead of ST_GeomFromGeoJSON would solve my problem. However, is there an easier way or a more elegant solution to insert a 4D spatial data using Sequelize?
Aditional info:
Model sample:
const GEOGRAPHY = require('sequelize').GEOGRAPHY
module.exports = function (sequelize, DataTypes) {
let Course = sequelize.define('Course', {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true
},
gps: {
type: GEOGRAPHY('LinestringZM', 4326)
}
}, {
tableName: 'courses',
timestamps: false,
paranoid: false
})
return Course
}
Insertion code generated by Sequelize:
INSERT INTO "courses" ("gps")
VALUES (St_geomfromgeojson(
'{"type":"LineString","crs":{"type":"name","properties"{"name":"EPSG:4326"}},"coordinates":[[-44.058367,-19.964709,0,1521552190]]}'
));
The SQL above returns the following exception: DatabaseError: Column has M dimension but geometry does not.
Successful insertion using ST_MakeLine:
INSERT INTO "courses" ("gps")
VALUES (ST_MakeLine(ST_MakePoint(1,2, 10, 1), ST_MakePoint(3,4, 10, 1)));

Sails 1.0 Models without primary key

I try to use new version 1.0 and refactoring my project. I have one problem and i don't now how i can solve her. Some tables on my BD don't have primary keys and when i migrate to sails 1.0, i have this error
In model friends: The primary key is set to id, but no such
attribute was found on the model. You must define an id attribute in
api/Friends.js or in config/models.js. See
http://sailsjs.com/upgrading#?changes-to-model-configuration for
info
Can i use my model without primary keys?
i have the same problem i used to change the primarykey this:
in file config/model.js
attributes: {
id: {
type: 'number',
autoIncrement: true,
},
}
and in the model api/any_model.js i used:
tableName : 'table',
attributes: {
id: {
type: 'number',
columnName : 'column_you_like_to_be_a_primaryKEY',
required : true
},
}

MongoDB - Duplicate Key Error After Changing Model To Allow Duplicates

I am using the mean stack. In Mongoose I defined a model with these properties:
var personSchema = new mongoose.Schema({
personName:{ type: String, unique: true, required: true, index:true },
start: { type: Date},
end: { type: Date }
});
However, when testing I realised I had made a mistake and that personName should not be unique. I removed the unique: true property and restarted MongoDB and the app.
However, I still get the duplicate key error when submitting.
Can anyone tell me what I'm doing wrong?
You might have created an index for the personName field.
Remove the index associated with field personName and try, it will work.
Reason:
when the field personName in the state "unique: true" index would be fine and now after removal of the state "unique: true". If we are trying to enter a record which is having a personName which is already there in the DB, then DB will throw Duplicate key error.

Sort populated record in sails waterline

I created a Sails application with two models Publication and Worksheet. They are having a one-to-one relationship. Sails-postgresql is the adapter I'm using. I'm using waterline orm to fire query to the database. I'm When I am trying to load publications data along with worksheet and then sort the records depending on a field in the Worksheet using sort() I'm getting an error.
My model is:
Publication.js
module.exports = {
attributes: {
id: {
type: 'integer'
unique: true
},
worksheetId: {
type: 'integer',
model : 'worksheet'
},
status: {
type: 'string',
defaultsTo: 'active',
in : ['active', 'disabled'],
}
}
}
Worksheet.js
module.exports = {
attributes: {
id: {
type: 'integer',
unique: true
},
name: 'string',
orderWeight: {
type: 'integer',
defaultsTo: 0
}
}
}
So now I want to load all the publication where status is "active" and populate worksheet in the data.
So I'm executing the query:
Publication.find({
where: {
status: 'active'
}
})
.populate('worksheetId').limit(1)
.exec(function (error, publications) {
})
And I'm getting a data like :
{
id : 1,
status : "active",
worksheetId : {
id : 1
name : "test",
orderWeight : 10
}
}
So till now it's all working fine. Now I want to increase the limit to 10 and want to sort the data depending on "orderWeight" which is in the populated data. Initially I sorted the whole data depending on publication id and the query worked.
Publication.find({
where: {
status: 'active'
}
})
.populate('worksheetId').sort('id ASC').limit(10)
.exec(function (error, publications) {
})
So I fired similar query to sort the data on "orderWeight"
Publication.find({
where: {
status: 'active'
}
})
.populate('worksheetId').sort('worksheetId.orderWeight ASC').limit(10)
.exec(function (error, publications) {
})
And this query is giving me error that worksheetId.orderWeight is not a column on the publication table. So I want to fire this sort query on the populated data not on the publication table.
Please let me know how I can get my expected result.
Apart from sort() method I also want to run some find command to the populated data to get those publication where the worksheet name matches with certain key as well.
Basically, what you're trying to do, is query an association's attribute. This has been in the waterline roadmap since 2014, but it's still not supported, so you'll have to figure out a workaround.
One option is to query the Worksheet model, and populate the Publication, since sails doesn't let you query across models without using raw queries (i.e. .sort('worksheetId.orderWeight ASC') doesn't work). Unfortunately, you might have to move the active flag to the Worksheet. For example:
Worksheet.find({
status: 'active'
})
.populate('publication') // you should also add publication to Worksheet.js
.sort('orderWeight ASC')
.limit(10)
Alternatively, you could combine Worksheet and Publication into one model, since they're one-to-one. Probably not ideal, but sails.js and Waterline make it very difficult to work with relational data - I'd estimate that half of the queries in the project I'm working on are raw queries due to sails' poor support of postgres. The framework is pretty biased towards using MongoDB, although it claims to "just work" with any of the "supported" DBs.