Skip to content

Instantly share code, notes, and snippets.

@koistya
Last active June 18, 2017 12:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save koistya/28c9da83c0eeeb5be5795d583459c162 to your computer and use it in GitHub Desktop.
Save koistya/28c9da83c0eeeb5be5795d583459c162 to your computer and use it in GitHub Desktop.
“camelCase” < = > “snake_case” conversion with PostgreSQL and Knex.js https://medium.com/p/956357872fe4
import knex from 'knex';
import Client from 'knex/lib/dialects/postgres';
import Formatter from 'knex/lib/formatter';
Client.prototype.wrapIdentifier = (value) => {
if (value === '*') return value;
const matched = value.match(/(.*?)(\[[0-9]\])/);
if (matched) return Client.prototype.wrapIdentifier.wrapIdentifier(matched[1]) + matched[2];
return `"${value.replace(/([A-Z])/g, (_, s) => `_${s.toLowerCase()}`).replace(/"/g, '""')}"`;
};
Formatter.prototype.wrapAsIdentifier = value => `"${(value || '').replace(/"/g, '""')}"`;
export default knex({
client: Client,
connection: process.env.DATABASE_URL,
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment