Skip to content

Commit

Permalink
postgres: Use Postgres’ jsonb data type for efficience (#133)
Browse files Browse the repository at this point in the history
This is supported since Postgres 9.2.  At the moment, Debian oldstable (jessie)
ships 9.6, and CentOS 6 – which is supported until November this year –
8.something.  I doubt anyone will really run anything older than this, and not
supporting CentOS 6 seems okay to me.

The init function will automatically check the data type of the value column and
migrate if it’s still text.
  • Loading branch information
qsuscs committed Aug 14, 2020
1 parent 77ecd2c commit b9e786e
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
20 changes: 19 additions & 1 deletion databases/postgres_common.js
Expand Up @@ -19,12 +19,20 @@ var async = require("async");
exports.init = function(callback)
{
var testTableExists = "SELECT 1 as exists FROM pg_tables WHERE tablename = 'store'";
var testValueColumnType = "SELECT data_type FROM information_schema.columns " +
"WHERE table_name = 'store' " +
"AND column_name = 'value'";

var createTable = 'CREATE TABLE store (' +
'"key" character varying(100) NOT NULL, ' +
'"value" text NOT NULL, ' +
'"value" jsonb NOT NULL, ' +
'CONSTRAINT store_pkey PRIMARY KEY (key))';

var updateValueColumnType = "ALTER TABLE store " +
"ALTER COLUMN value " +
"TYPE jsonb " +
"USING value::jsonb";

var _this = this;

// this variable will be given a value depending on the result of the
Expand Down Expand Up @@ -80,6 +88,16 @@ exports.init = function(callback)
if (result.rows.length == 0) {
_this.db.query(createTable, detectUpsertMethod(callback));
} else {
_this.db.query(testValueColumnType, function(err, result) {
/* we already checked whether the table exists, so we can reasonably assume
* the column does as well
*/
if (result.rows[0].data_type != "jsonb") {
_this.db.query(updateValueColumnType, function(err, result) {
if (err) {
callback(err, null);
}});
}});
detectUpsertMethod(callback);
}
});
Expand Down
2 changes: 1 addition & 1 deletion databases/postgres_db.js
Expand Up @@ -23,7 +23,7 @@ exports.database = function(settings)

this.settings.cache = settings.cache || 1000;
this.settings.writeInterval = 100;
this.settings.json = true;
this.settings.json = false;

this.db = new pg.Client(this.settings);
this.db.connect();
Expand Down
2 changes: 1 addition & 1 deletion databases/postgrespool_db.js
Expand Up @@ -23,7 +23,7 @@ exports.database = function(settings)

this.settings.cache = settings.cache || 1000;
this.settings.writeInterval = 100;
this.settings.json = true;
this.settings.json = false;

// Pool specific defaults
this.settings.max = this.settings.max || 20;
Expand Down

0 comments on commit b9e786e

Please sign in to comment.