1
\$\begingroup\$

I've written a lambda to perform simple steps to a redshift database. It runs multiple queries with transaction. I use pg-promise.

'use strict';
const config = require('./redshift_config_from_env');
const redshiftConn = `pg://${config.user}:${config.password}@${config.host}/${config.database}`;
const pgp = require('pg-promise')();
var tableCopyQuery = function(tableName) {
 return `
 ALTER TABLE ${tableName}_temp
 RENAME TO ${tableName}_process;
 CREATE TABLE ${tableName}_temp (LIKE ${tableName}_process);`;
};
var insertQuery = function(tableName) {
 return `
 INSERT INTO ${tableName}
 SELECT DISTINCT ${tableName}_process.*
 FROM ${tableName}_process
 LEFT JOIN ${tableName} USING (id)
 WHERE ${tableName}.id IS NULL
 ORDER BY ${tableName}_process.id;
 DROP TABLE ${tableName}_process;`;
};
exports.handler = function(event, context) {
 const client = pgp(redshiftConn);
 client.tx(function (t) {
 return t.batch([
 t.none(tableCopyQuery('active_connections')),
 t.none(insertQuery('active_connections')),
 t.none(tableCopyQuery('active_downloads')),
 t.none(insertQuery('active_downloads'))
 ]);
 })
 .then(function () {
 context.succeed(`Successfully Refreshed.`);
 })
 .catch(function (error) {
 context.fail(`Failed to run queries : ${JSON.stringify(error)}`);
 });
};

I think I may move sql queries into .sql file outside of the function.

Maybe the var could be turned into let because the scope will fit?

asked Jan 9, 2017 at 10:27
\$\endgroup\$
0

1 Answer 1

1
\$\begingroup\$

You shouldn't create the database object on every function call. Read this answer (and its question) for an example of this.

Sᴀᴍ Onᴇᴌᴀ
29.5k16 gold badges45 silver badges201 bronze badges
answered Jan 5, 2018 at 12:49
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.