sqlite3 create database with callback using Node - node.js

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.');
});

Related

How can I load an extension on sqlite3 in nodejs?

This my connection code :
`
var sqlite3 = require('sqlite3').verbose()
const DBSOURCE = "db_path";
let db = new sqlite3.Database(DBSOURCE, (err) => {
if (err) {
console.error(err.message)
throw err
}else{
console.log('Connected to the SQLite database.');
}
});
module.exports = db`
I found something here, but I dont know its the correct way to do or to make it work :
https://github.com/mapbox/node-sqlite3/wiki/Extensions#databaseloadextensionpath-callback
tried this :
` let params = [];
db.all(`select load_extension('./config/math.dll')`, params, (err, rows) => {
console.log(err);
if (err) {
res.status(400).json({ StatusCode: 400, error: err.message });
return;
}
console.log(rows)
})`
and got error : Error: SQLITE_ERROR: not authorized
I couldn't find any sources for loading extension in node.js .
Using SELECT load_extension(...) is disabled by default for security reasons. However, you can load an extension like this:
const db = new sqlite3.Database('db.sqlite3');
db.loadExtension('./lib/uuid.dll');
db.all('SELECT uuid()', (error, rows) => {
console.log(rows);
});
db.close();
Notice the file name uuid.dll is not accidental. In my case, the uuid extension contains entry-point function called sqlite3_uuid_init, therefore the file must be called uuid.<extension> to make it work out of box. You can read more in SQLite documentation.

MongoError : selector must be a valid JavaScript object

I am using mongodb driver for nodejs.
I am getting below error while updating a record.
{"name":"MongoError","message":"selector must be a valid JavaScript
object","driver":true}
Here is my script :
MongoClient.connect(url, function (err, db) {
if (err)
{
console.log('Unable to connect to the mongoDB server. Error:', err);
return;
}
var collName = "bank";
var SelectParas = {"name":"ABC"};
var UpdateValues = {"name":"PQR"};
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated){
if(err)
{
console.log('err');
console.log(err);
return;
}
if(numUpdated)
{
console.log('Updated Successfully %d document(s).', numUpdated);
}
db.close();
});
});
I can write the below line in mongo console & it works.
db.bank.update({"name":"ABC"},{$set:{"name":"PQR"}})
You are passing collecion name i.e. a string as find query of the update. Need not pass collecton name there.
db.collection(collName).update(collName,SelectParas,{$set:UpdateValues},function (err,numUpdated)
// collName need not pass in the update function.
Need to use
db.collection(collName).update(SelectParas,{$set:UpdateValues},function (err,numUpdated) instead.

"ConnectionError: Already connecting to database! Call close before connecting to different database" connecting SQL server with nodejs

Below is the code i am using ,Some times it does not enter .then (function() ,Please let me know how to close the existing connection , I have tried various options like conn.close() after connecting, but it still dint work.
var sql = require("C:/Protractor_Scripts/node_modules/mssql");
function getEmp() {
console.log('results');
var conn = new sql.Connection("Server=, 1433;Database=;User Id=;Password=;Encrypt=true");
console.log(conn);
console.log(conn.connect());
conn.connect().then(function () {
console.log(conn.connect());
var req = new sql.Request(conn);
req.query("select * from").then(function (recordset) {
console.log(recordset);
conn.close();
}).catch(function (err) {
console.log(err);
conn.close();
});
}).catch(function (err) {
console.log(err);
});
}
getEmp();
Below is the full error message
[ConnectionError: Already connecting to database! Call close before connecting to different database.]
name: 'ConnectionError',
message: 'Already connecting to database! Call close before connecting to
different database.',
code: 'EALREADYCONNECTING' }
Try removing multiple conn.connect() calls and have only one call.
After looking at their docs, I would try something like:
var sql = require('mssql');
var connection = new sql.Connection({ /* config */ });
connection.request().query('select * from mytable').then(function(recordset) {
console.dir(recordset);
connection.close();
});

node-postgres create database

I am using node-postgres, and at the beginning of my application I want to check whether the database exists or not. So my workflow idea is as following:
Check whether myDb is existing
If it is there, create the tables
If not, then create first the database, then tables
As you see it is a really easy process, however, the driver implementation requires to have a database name postgres://username:password#host/database to be connected, which means you need to connect to a database first.
So what I am doing now is to connect to postgres database at the beginning, making a query to create database, cathing the exception if it is already there, then closing my connection and connecting to the newly created database, then creating the tables. Here is the code:
var conStringPri = 'postgres://' + username + ':' + password + '#' + host +
'/postgres';
var conStringPost = 'postgres://' + username + ':' + password + '#' + host +
'/' + dbName;
pg.connect(conStringPri, function(err, client, done) { // connect to postgres db
if (err)
console.log('Error while connecting: ' + err);
client.query('CREATE DATABASE ' + dbName, function(err) { // create user's db
if (err)
console.log('ignoring the error'); // ignore if the db is there
client.end(); // close the connection
// create a new connection to the new db
pg.connect(conStringPost, function(err, clientOrg, done) {
// create the table
clientOrg.query('CREATE TABLE IF NOT EXISTS ' + tableName + ' ' +
'(...some sql...)';
});
});
});
As you see I am opening and closing the connection twice, and this way seems wrong to me. I'll be glad if you propose a better way, or maybe explain how did you accomplish this.
As you see it is a really easy process, however, the driver
implementation requires to have a database name
postgres://username:password#host/database to be connected, which
means you need to connect to a database first.
It's not because of the driver implementation, it's PostgreSQL itself. It's the same with any other language or driver.
A client needs to be connected to a database in order to do anything, including a CREATE DATABASE. Besides the postgres database, template1 is often used for this purpose too.
Then, since you must connect to the freshly created database to create objects inside it, there's no way to avoid opening another connection.
In short, what you're doing can't be simplified, it's already optimal.
I've just written a module for that: https://github.com/olalonde/pgtools
var pgtools = require('pgtools');
pgtools.createdb({
user: 'postgres',
password: 'some pass',
port: 5432,
host: 'localhost'
}, 'test-db', function (err, res) {
if (err) {
console.error(err);
process.exit(-1);
}
console.log(res);
});
Hopefully it can make your code a bit cleaner.
This is a bit old but I just want to share how I handled this kind of setup.
You need to call the third param from the callback which is the done from pg.connect(conn, (err, client, done) => {}). This will release the connection and bring back to pool.
async.series([
done => {
pg.connect(connPrimary, (err, client, releaseConn) => {
if (err) return done(err)
client.query(`CREATE DATABASE ${conf.database}`, (err) => {
if (err && !~err.message.indexOf('already exists')) {
return done(err)
}
client.end()
releaseConn()
done()
})
})
},
done => {
let connSecondary = `postgres://${conf.user}:${conf.password}#${conf.host}:${conf.port}/${conf.database}`
pg.connect(connSecondary, (err, client, releaseConn) => {
if (err) return done(err)
let createTableQuery = `CREATE TABLE IF NOT EXISTS test_table(_id bigint primary key, co2_field varchar(40) NOT NULL, temp_field int NOT NULL, quality_field decimal NOT NULL, reading_time_field timestamp NULL)`
client.query(createTableQuery, err => {
if (err) return done(err)
releaseConn()
done()
})
})
}
], err => {
should.ifError(err)
doneInit()
})
Here is a script I use which is essentially just executing shell commands with execa:
import execa from 'execa';
class DatabaseService {
public async setupDatabase() {
const logCmd = (cmd: execa.ExecaChildProcess) => {
cmd.stdout.on('data', (data) => {
this.logger.log(data.toString());
});
cmd.stderr.on('data', (data) => {
this.logger.error(data.toString());
});
};
const createUser = () => {
return new Promise<void>((resolve, reject) => {
const cmd = execa('createuser', [Config.databaseUser, '--superuser']);
logCmd(cmd);
let userExists = false;
cmd.stderr.on('data', (data) => {
if (
data
.toString()
.includes(`role "${Config.databaseUser}" already exists`)
) {
userExists = true;
}
});
cmd.on('exit', (code) => {
if (!userExists && code) {
reject(new Error(`Failed to create user for database: ${code}`));
} else {
resolve();
}
});
});
};
const createDatabase = () => {
return new Promise<void>((resolve, reject) => {
const cmd = execa('createdb', [Config.databaseName]);
logCmd(cmd);
let databaseExists = false;
cmd.stderr.on('data', (data) => {
if (
data
.toString()
.includes(`database "${Config.databaseName}" already exists`)
) {
databaseExists = true;
}
});
cmd.on('exit', (code) => {
if (!databaseExists && code) {
reject(new Error(`Failed to create database: ${code}`));
} else {
resolve();
}
});
});
};
await createUser();
await createDatabase();
}
}
As you can see, the script detects if the user or database already exists and will ignore errors in those events, because the intended state of Postgres will have been met, and thats all I care about when I run it.
Install
npm install --save -g pgtools
CLI Example
createdbjs my_awesome_db --user=admin --password=admin

CouchDb unhandled 'error' event - Node js

I'm new to Node and CouchDb and I'm trying to get my hands on it.
I'm struggling to make a piece of code to work.
I would like to create a table users, insert a new user and 'at the same time' getting another user.
I'm getting this error when starting up node app.js :
antoine#ubuntu:~/projects/couchDb$ node app.js
Database users exists.
{"error":"conflict","reason":"Document update conflict."}
Leaving saveDoc
events.js:48
throw arguments[1]; // Unhandled 'error' event
^
Error: socket hang up
at createHangUpError (http.js:1107:15)
at Socket.onend (http.js:1188:27)
at TCP.onread (net.js:369:26)
And here is my very code, is there something wrong?
(When I remove the getDoc function the error goes away)
I'm using couchDB 1.0.1 and node 0.6.12
The jdoe4 and jdoe documents are already present in the users database.
var dbHost = "127.0.0.1";
var dbPort = 5984;
var dbName = 'users';
var couchdb = require('felix-couchdb');
var client = couchdb.createClient(dbPort, dbHost);
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
var db = client.db(dbName);
db.exists(function(err, exists) {
if (!exists) {
db.create();
console.log('Database ' + dbName + ' created.');
} else {
console.log('Database ' + dbName + ' exists.');
}
db.saveDoc('jdoe4', user, function(err, doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.getDoc('jdoe', function(err,doc) {
if( err) {
console.log(JSON.stringify(err));
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
It seems to be a library problem => Github Issue Socket Hangout
Look here if you dont know which library fit more your needs.
I quickly realized that felix-couchdb is not compatible with node 8 (I know you're not using version 8, but you will someday), so I switched to nano couchdb and here's the following code:
It will check if the db is created
It will insert only if the key given is unique
It will get the user with a key
var couchdb = require('nano')('http://localhost:5984')
, dbName = 'users'
, db = couchdb.use(dbName)
;
var user = {
name: {
first: 'John',
last: 'Doe'
}
}
couchdb.db.create(dbName, function(err, db_body) {
db.insert(user, 'jdoe4', function(err, doc, header) {
if( err) {
console.log('Cannot save user');
} else {
console.log('Saved user.');
}
console.log('Leaving saveDoc');
});
db.get('jdoe', function(err, doc) {
if( err) {
console.log('Cannot get user');
} else {
console.log(JSON.stringify(doc));
}
console.log('Leaving getDoc');
});
});
One thing worth noting is that, while this will get them at the "same time," it's still making 3 requests to the db, 1 to check if it exists, 1 to insert (or not), 1 to get.

Resources