Error 42601 using postgresql and dart - postgresql

I get the error 42601 when using postgresql
I created the table using pgAdmin. The autogenerated code looks as follows.
-- Table: posts
-- DROP TABLE posts;
CREATE TABLE posts
(
post_id bigserial NOT NULL,
title character varying(150) NOT NULL,
description character varying(500),
posted_at timestamp with time zone,
last_edited timestamp with time zone,
"user" character varying(50) NOT NULL,
editor character varying(50),
up_votes integer NOT NULL,
down_votes integer NOT NULL,
flag character varying(7),
CONSTRAINT "PK_post_id" PRIMARY KEY (post_id),
CONSTRAINT "FK_user" FOREIGN KEY ("user")
REFERENCES users (login) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
ALTER TABLE posts
OWNER TO postgres;
I execute an insert operation with the following helper method.
addPost(Map values){
connect(uri)
.then((conn){
conn.execute('insert into posts values(#title, #description, now(), now(), #user, #editor, #upVotes, #downVotes, #flag', values)
.then((_) => conn.close())
.catchError((err){
print('Execute error in addPost: $err');
})
.whenComplete(() => conn.close());
})
.catchError((err) => print('Error in addPost: $err'));
}
where Map values has the form:
{'title': 'Sample title', 'description': 'This is a description for a sample post', 'user': 'dartUser', 'editor': 'dartUser', 'upVotes': 0, 'downVotes': 0, 'flag': 'healthy'}
I'm not a postgresql expert, so this might be something trivial I just don't see.

You can find the error codes for postgresql here. Error 42601 means a syntax error.
I suspect the cause is that you are missing a closing bracket on the 'values' clause, after #flag.

Related

How to display a UUID in pg-promise without dashes

As per the stackoverflow question HERE postgres column does not store dashes for the UUID data type
Yet when I load the value of any UUID column using pg-promise it always shows dashes
How do I retrieve these UUIDs without dashes using pg-promise
Code sample illustrating the problem
var pgPromise = require("pg-promise"),
pgp = pgPromise({}),
db = pgp({
database: "mydatabase",
host: "localhost",
password: "somepass",
port: 5432,
ssl: false,
user: "myuser"
});
pgp.pg.types.setTypeParser(20, parseInt);
db.query("CREATE TABLE test(myid uuid not null primary key)")
.then((e => {
var r = require("crypto").createHash("md5").update("test data").digest("hex");
return db.query("INSERT INTO test(myid) VALUES($1) ON CONFLICT DO NOTHING", [r])
}))
.then((e => db.query("SELECT * FROM test")))
.then((e => (console.log(e), db.query("DROP TABLE test"))))
.then((() => console.log("test success!")))
.catch((e => console.error(e)));
This line did the trick
pgp.pg.types.setTypeParser(pgp.pg.types.builtins.UUID, (val) => {
val === null ? null : val.replace(/-/g, '')
});
Thank you for your suggestions #vitaly-t and #Bergi

What is wrong with my MYSQL Workbench Query? (Error Code: 1064)

I am getting an error code (1064) when I attempt to run a query in MYSQL Workbench. I have researched the error code and I'm aware that it is often thrown when a reserved keyword is used, a command is misspelled, or when using a depreciated command. I have checked my code and I don't see any of the aforementioned errors. I have made sure that the strings are all surrounded with quotation marks, the values and properties are in their corresponding positions, and that my sequelize model and datatypes are formatted appropriately. However, when I try to run the query, I get a red squiggly line under one entry (saying that the entry is not valid in it's position and that a ')' is expected) and the error code.
INSERT INTO drycleaningprices(sameDayService, delivery, pickUpFee, dryCleaningPrices1-14, addInfo, sameDayInfo, deliveryHours, pickUpHours, EstablishmentBusinessName)
VALUES (true, true,"$20.00",‍"kill","kill","kill","kill","kill","kill",‍"kill", "kill","kill",‍"kill","kill","kill",‍"kill","kill","kill","kill","kill","kill","Affordable Laundry")
I have even replaced each of the entries with duplicate strings to no avail. In the above code, "dryCleaningPrices1-14" is actually 14 separate entries but was shortened for readability. And here is my model:
module.exports = function(sequelize, DataTypes){
var DryCleaningPrices = sequelize.define("DryCleaningPrices",{
sameDayService:{
type: DataTypes.BOOLEAN,
defaultValue: false
},
delivery:{
type: DataTypes.BOOLEAN,
defaultValue: false
},
pickUpFee:{
type:DataTypes.STRING,
defaultValue: "Enter Info"
},
freePickUp:{
type: DataTypes.BOOLEAN,
defaultValue: false
},
deliveryOrderMinimum:{
type:DataTypes.STRING
},
dryCleaningPrices1-14:{
type:DataTypes.STRING
},
addInfo:{
type:DataTypes.TEXT
},
addInfo2:{
type:DataTypes.TEXT
},
addInfo3:{
type:DataTypes.TEXT
},
sameDayInfo:{
type:DataTypes.TEXT
},
deliveryHours:{
type:DataTypes.STRING
},
pickUpHours:{
type:DataTypes.STRING
},
createdAt:{
type:DataTypes.DATE
},
updatedAt:{
type:DataTypes.DATE
}
})
DryCleaningPrices.associate=function(models){
DryCleaningPrices.belongsTo(models.Establishment,{
foreignKey: {
allowNull: false
}
})
}
return DryCleaningPrices;
}
DDL:
Table Create Table
drycleaningprices CREATE TABLE `drycleaningprices` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`sameDayService` tinyint(1) DEFAULT '0',
`delivery` tinyint(1) DEFAULT '0',
`pickUpFee` varchar(255) DEFAULT 'Enter Info',
`freePickUp` tinyint(1) DEFAULT '0',
`deliveryOrderMinimum` varchar(255) DEFAULT NULL,
`dryCleaningPrices1-14` varchar(255) DEFAULT NULL,
`addInfo` text,
`addInfo2` text,
`addInfo3` text,
`sameDayInfo` text,
`deliveryHours` varchar(255) DEFAULT NULL,
`pickUpHours` varchar(255) DEFAULT NULL,
`createdAt` datetime DEFAULT NULL,
`updatedAt` datetime DEFAULT NULL,
`EstablishmentBusinessName` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `EstablishmentBusinessName` (`EstablishmentBusinessName`),
CONSTRAINT `drycleaningprices_ibfk_1` FOREIGN KEY (`EstablishmentBusinessName`) REFERENCES `establishments` (`businessName`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Your Insert statement is incorrect you have given 9 column names but in Values you have given more than 9. Ideally your insert statement should look like this
INSERT INTO test.drycleaningprices
(sameDayService, delivery, pickUpFee, `dryCleaningPrices1-14`, addInfo, sameDayInfo, deliveryHours, pickUpHours, EstablishmentBusinessName)
VALUES(true, true, "$20.00", "kill", "kill", "kill", "kill","kill", '');
Please refer
https://www.w3schools.com/sql/sql_insert.asp

SQLiteLog( 8646): (1) table tempsettings has no column named user

I'm learning how to upgrade databases in an flutter application, apears to be very simple, but I'm getting this error executing an INSERT:
E/SQLiteLog( 9107): (1) table tempsettings has no column named user
I/flutter ( 9107): DatabaseException(table tempsettings has no column
named user (code 1 SQLITE_ERROR): , while compiling: INSERT INTO
tempsettings('id', 'user', 'company', 'url') SELECT 'id', 'user',
'company', 'url' FROM settings) E/SQLiteLog( 9107): (1) no such
column: user I/flutter ( 9107): DatabaseException(no such column: user
(code 1 SQLITE_ERROR): , while compiling: INSERT INTO settings('id',
'user', 'company', 'url', 'theme') SELECT id, user, company, url, 1
FROM tempsettings)
await db
.execute("CREATE TABLE tempsettings("
"'id' INTEGER "
"'user' TEXT,"
"'company' TEXT,"
"'url' TEXT)")
.catchError((error) => print(error.toString()));
await db.execute(
"INSERT INTO tempsettings('id', 'user', 'company', 'url') SELECT 'id', 'user', 'company', 'url' FROM settings")
.catchError((error) => print(error.toString()));
Does anyone could help me how to do this INSERT?
Thanks.
You're missing a comma after the id column creation
await db.execute("CREATE TABLE tempsettings("
"id INTEGER ", //this comma was missing
"user TEXT,"
"company TEXT,"
"url TEXT)")
.catchError((error) => print(error.toString()));

How can I store Object data type in Postgres?

I have a kind of object like this:
{{generaladdendumlist: {}, microchip: null, freetext: null, additionalpermerchant: null, telephonecompany: null, passengertransportaddendumlist: {}, merchantinformation: {messagetypeidentifier: '1644', functioncode: '696', messagenumber: '53331800', formatcode: 'AA', forwardingreferencedata: '123456000000', cardacceptorbusinesscode: 5411, name: 'PROVE POS', street: 'VIA ROSSI 2', city: 'VERONA', postalcode: '000000', region: 'VR', countrycode: 'ITA'}, lodgingaddendumlist: {}, carrentaladdendumlist: {}, moneytransfer: null, fleetlist: {}, purchasinglist: {}, dccaddendum: null}}
I am retriving it from a Cassandra's table and processing it with Talend Big Data in order to fill my Postgres's table. How can I store it inside my table? I am trying text[] and character varying [], but the field remain empty.
Does anyone could help me, please?
Thank you in advance!

Connecting to postgres database with Node.js

I am running the following command from my command line
npm models/database.js
I am getting the error:
password authentication failed for user "marco"
this is my connection code and its stored in my Database.js file within my models folder at the root level of my project.
var pg = require('pg');
// var connectionString = process.env.DATABASE_URL || 'postgres://localhost:5432/NodeTestProject';
var connectionString = "postgres://marco:Easye123#localhost:5432/NodeTestProject";
var client = new pg.Client(connectionString);
client.connect();
var query = client.query('CREATE TABLE users(id SERIAL PRIMARY KEY, FirstName VARCHAR(40) not null, LastName VARCHAR(40) not null, MiddleName VARCHAR(40) not null, Email VARCHAR(40) not null, UserName VARCHAR(40) not null, Password VARCHAR(40) not null');
query.on('end', function() { client.end(); });
I am 100% sure that when I set up Postgresql I set the password to "Easye123" I can log in to Postgresql no issues and I have created a database called NodeTestProject. Do i have to create a user for the NodeTestProject database? Am I missing a step? Any feedback would be appreciated.
To whoever is new to Postgresql
The credentials you put on your connection file are not the same as the SuperUser you set up while installing Postgresql. Within your pgAdminIII you must create a Group Role and allow that Group Role to "Can Login" once that is set up declare the owner of the Database as that Group Role User. Finally declare that GroupRole user as the username and the password you used for it as the password in your connection string.
var pg = require('pg');
var conString = "postgres://Marco:12345#localhost:5432/NodeTestProject";
var client = new pg.Client(conString);
client.connect(function(err) {
if(err) {
return console.error('could not connect to postgres', err);
}
client.query('SELECT NOW() AS "theTime"', function(err, result) {
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].theTime);
//output: Tue Jan 15 2013 19:12:47 GMT-600 (CST)
client.end();
});
});
I can now successfully log into this local database and interact with it.