Node SQLite3 - crashes when running insert on specific table - javascript

I have a SQLite database I am trying to add data to with the sqlite3 package. My query is as follows, and works in the SQLite command line.
'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
And I'm using this code to insert to the database in node.
db.run("begin transaction");
let sql = 'INSERT INTO `EVENTS`(`ID`,`EventName`,`EventSociety`,`BookerName`,`BookerEmail`,`BookerStudentID`,`BookerPhone`,`TimeStart`,`TimeEnd`,`EquipmentList`,`EventSearchYear`,`EventSearchMonth`,`EventSearchDay`) VALUES (NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);';
console.log(sql);
db.run(sql,(err) => {
res.send('ok');
});
db.run("commit");
Trying this in node hard crashes, with a Illegal instruction: 4. However, it is only happening on two tables, both with over 5 fields, in my database, and not any other smaller ones. Is there a character limit I'm unaware of?

To avoid crash, we need to handle error as below:
Example
The line db.run(sql, params, function (err) { in below example:
let sql = `INSERT INTO Users(id,firstName,lastName,email,password,permissionLevel) VALUES (?,?,?, ?,?,?)`;
let params = [uuid4(), "fn1", "ln1", "a#a2.com", "pwd1", 0];
db.run(sql, params, function (err) {
if (err) {
console.error("Error: Insert failed: ", err.message);
console.error("Error: Full error: ", err);
return;
}
console.log("insert success");
});

Related

Node: Failed to execute statement due to the following error: Numeric value

I am really new to Snowflakes. I am using Node Js drive to query Snowflakes database and for that I am using NODE PACKAGE https://www.npmjs.com/package/snowflake-sdk package. I successfully manage to connect my local server to snowflakes. When I query sqlText: select * from Test.deliverydb', I can see all my datas in console rows`.
In my Snowflakes dashboard I am passing conditional value and getting selected value. This is how I did it in my dashboard and getting expected result.
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE
online_store_transaction_id = '39485727'
I would like to this same query in Code. I am having hard time to understand snowflakes' documentation to implement above dashboard logic to my code.
I would like query my data around template string where user will put hardcode value and it will return the data. When I run this below query "Failed to execute statement due to the following error: Numeric value".Because of this where condition WHERE online_store_transaction_id = ${168141924}
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = ${168141924}
`;
connection.execute({
sqlText: sql,
fetchAsString: ['Number'],
complete: function (err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
if (!rows) {
throw new Error("Data not found");
}
console.log('Successfully executed statement: ' + stmt.getSqlText());
let data = {}
rows.forEach(test => data = test);
console.log({ data });
}
}
});
If I query like this this it works:
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = '168141924'
`;
connection.execute({
sqlText: sql,
fetchAsString: ['Number'],
complete: function (err, stmt, rows) {
if (err) {
console.error('Failed to execute statement due to the following error: ' + err.message);
} else {
if (!rows) {
throw new Error("Data not found");
}
console.log('Successfully executed statement: ' + stmt.getSqlText());
let data = {}
rows.forEach(test => data = test);
console.log({ data });
}
}
});
Since the online_store_transaction_id is not a numeric column, you need to add quotes around your value, as you did in your first example:
const sql = `
SELECT
online_store_transaction_id AS order_number,
updated_at_ts,
progress,
status,
service_time,
site_name
FROM
Test.deliverydb
WHERE online_store_transaction_id = '${168141924}'
`;

SQLITE_MISUSE: bad parameter or other API misuse [duplicate]

I've searched on how to create a sqlite3 database with a callback in Node.js and have not been able to find any links. Can someone point me towards documentation or provide a 2-3 line code sample to achieve the following:
Create a sqlite3 database and catch an error if the creation fails for any reason.
Here is what I've tried:
let dbCreate = new sqlite3.Database("./user1.db", sqlite3.OPEN_CREATE, function(err){
if(!err){
logger.infoLog("Successfully created DB file: " + dbFileForUser + " for user: " + username );
} else {
logger.infoLog("Failed to create DB file: " + dbFileForUser + ". Error: " + err );
}
});
dbHandler[username] = dbCreate;
When I execute this, I get the following error:
"Failed to create DB file: ./database/user1.db. Error: Error: SQLITE_MISUSE: bad parameter or other API misuse"
This call without callback works just fine.
var customDB = new sqlite3.Database("./custom.db", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE);
But in this, I will not know if I run into any errors while creating the Database.
Try this:
let userDB = new sqlite3.Database("./user1.db",
sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE,
(err) => {
// do your thing
});
Example.
#Irvin is correct, we can have a look at http://www.sqlitetutorial.net/sqlite-nodejs/connect/ and
check it says if you skip the 2nd parameter, it takes default value as sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
and in this case if database does not exist new database will be created with connection.
sqlite3.OPEN_READWRITE: It is to open database connection and perform read and write operation.
sqlite3.OPEN_CREATE : It is to create database (if it does not exist) and open connection.
So here is the first way where you have to skip the 2nd parameter and close the problem without an extra effort.
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.|');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});
And this is the 2nd way to connect with database (already answered by #Irvin).
const sqlite3 = require("sqlite3").verbose();
let db = new sqlite3.Database('./user1.db', sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE
, (err) => {
if (err) {
console.error(err.message);
} else {
console.log('Connected to the chinook database.');
}
});
db.close((err) => {
if (err) {
return console.error(err.message);
}
console.log('Close the database connection.');
});

Accessing Mongo DB from within Node

I’m trying to connect to a database through node. I’ve got it working with smaller databases using a Mongo URL of the form:
mongodb://[username]:[password]#db1-a0.example.net:27017/[DB-Name]
When I switched it out to use a larger DB, using the Mongo URL of the form:
mongodb://[username]:[password]#db1-a1.example.net:27017,db2.example.net:2500/[DB-Name]?replicaSet=test
It throws a ‘ RangeError: Maximum call stack size exceeded’ error and won’t connect. This URL is the onlything that has changed between the databases.
I’ve checked the db details and can access it through RoboMongo / Robo 3T so the database definitely exists.
Trying to connect through Mongoose version ^5.2.10 using the following code:
function connect() {
if (MONGO_URL) {
mongoose.connect(MONGO_URL, err => {
if (err) {
console.log('error connecting')
console.log(err)
}
})
} else {
mongoose.connect(`mongodb://${host}`, {
user,
pass,
dbName,
useNewUrlParser: true //depresiation issue
}, err => {
if (err) {
console.log('error connecting')
console.log(err)
}
})
}
}
mongoose.connection.on('error', (message) => {
console.log('connection error!') //This is logged
console.log(message)
process.exit()
})
mongoose.connection.on('disconnected', connect)
connect()
Looks like you are trying to use a replica set. If so try to connect like following`
var uri = `mongodb://${userName}:${encodeURIComponent(password)}#${clusterName}/${dbName}?ssl=true&replicaSet=${process.env.replicaSetName}&authSource=${authDB}`
var db = mongoose.connect(uri).then().catch() // Whatever inside the then and catch blocks
`

NodeJs Cassandra driver is getting stuck

I am trying to connect to a Cassandra cluster in NodeJs but when I execute a query, prepared or not, it just gets stuck. The callback isn't called at all and the process is just hanging. What could cause this? I am able to connect using devcenter using the same host/keyspace.
var Cassandra = require('cassandra-driver');
var cassandraClient = new Cassandra.Client({ contactPoints:['*.*.*.*'], keyspace: '*'});
cassandraClient.on('log', function(level, className, message, furtherInfo) {
console.log('log event: %s -- %s', level, message);
});
cassandraClient.connect(function (err) {
console.log(err)
});
console.log("Starting C* getting data");
cassandraClient.execute(query, params, {prepare: true}, function(err, result) {
if(err) console.log(err);
res = result;
console.log("Done C*");
console.log('result: ' + result.rows[0]);
notDone = false;
});
Output:
Init Get IP Info
log event: info -- Adding host *.*.*.*:9042
Starting C* getting data
And it gets stuck there. Any idea what is causing this?

Why is my query working on pgAdming but when I execute it from the server I get a query error (Error: Connection Terminated)?

I'm working on my Capstone project and it requires to store some telemetry data on a database. I'm using PostgreSQL 9.5 for the database and node for the server.
My problem is that when I try to send a query from the server I'm getting a query error [Error: Connection Terminated]. If I use JSON.stringify(err) I only see empty brackets as the result {}. What is interesting is that if I use pgAdmin client and execute the same query, the record is added successfully without any kind on error.
Here is the code I'm using in the server to send the query:
client.connect(function(err) {
if(err){
return console.error('could not connect to postgres', err);
}
//Checks if there is survey data to process
if(surveyFlag){
//Query to insert survey record
//Returns survey record's auto-generated id to use it when creating or updating the //telemetry record in the database
var query = 'INSERT INTO survey_response (perceived_risk, actual_risk) '+
'VALUES (' + telemetryRecord.survey.perceivedRisk +', ' +
telemetryRecord.survey.actualRisk +') ' +
'RETURNING survey_id';
client.query(query, function(err, result) {
console.log("Query: " + query);
if(err) {
console.log(err);
return console.error('error running survey query', err);
}
surveyID = result.rows[0].survey_id;
//Testing
console.log ("Survey response added with ID: " + surveyID);
});
//Close the connection
client.end();
});
The code client.end() is put at the same level of the code client.query(). Since client.query() is asynchronous, the client.end() gets called immediately after you start the query. By the time the query comes back the client has already ended which is causing the problem.
Try placing the client.end() code within the callback function of client.query().
client.query(query, function(err, result) {
console.log("Query: " + query);
if(err) {
console.log(err);
return console.error('error running survey query', err);
}
surveyID = result.rows[0].survey_id;
//Testing
console.log ("Survey response added with ID: " + surveyID);
//Close the connection
client.end();
});

Categories

Resources