postgresql - How can I do Multiple Queries (build out a DB) in Node.JS? -
really new node.js , relatively new postgresql. reason creates first table, not second. totally doing wrong. can't seem find code examples similar enough extrapolate answer from. want create 2 tables. seems can run 1 query , that's it. no more. it's suggested connection ends before second can executed. don't know why. can't find single example of doing in dozen different google searches.
var client = new pg.client(connectionstring); client.connect(); var query = client.query('create table preferences(id serial primary key, food varchar(40) not null, preferred boolean)'); client.query('create table foods(id serial primary key, food varchar(40) not null, type varchar(40) not null, spicy boolean, spiciness varchar(10)'); query.on('end', function() { client.end(); });
i had doubts client.query , have execute @ end. took example out of tutorial second table added. i'm playing , trying learn here test.
just state ultimate end goal: wanna create whole script building out database full of necessary tables , data.
error no matter try:
$ node models/database.js events.js:85 throw er; // unhandled 'error' event ^ error: syntax error @ end of input @ connection.parsee (~/documents/test01/node_modules/pg/lib/connection.js:534:11) @ connection.parsemessage (~/documents/test01/node_modules/pg/lib/connection.js:361:17) @ socket. (~/documents/test01/node_modules/pg/lib/connection.js:105:22) @ socket.emit (events.js:107:17) @ readableaddchunk (_stream_readable.js:163:16) @ socket.readable.push (_stream_readable.js:126:10) @ tcp.onread (net.js:538:20)
the best way place requests transaction , execute within same connection.
here's how can of pg-promise:
var pgp = require('pg-promise')(/*options*/); var db = pgp(connection); db.tx(t => { return t.batch([ t.none('create table preferences(id serial, etc...'), t.none('create table foods(id serial primary key, etc...') ]); }) .then(data => { // success; }) .catch(error => { console.log(error); // print error; });
better yet, place sql external sql files, library provides automatic support.
Comments
Post a Comment