UNPKG

1.85 kBJavaScriptView Raw
1'use strict'
2
3const co = require('co')
4const cli = require('heroku-cli-util')
5const pg = require('heroku-pg')
6
7const query = prefix => `
8SELECT
9 'CREATE FOREIGN TABLE '
10 || quote_ident('${prefix}_' || c.relname)
11 || '(' || array_to_string(array_agg(quote_ident(a.attname) || ' ' || t.typname), ', ') || ') '
12 || ' SERVER ${prefix}_db OPTIONS'
13 || ' (schema_name ''' || quote_ident(n.nspname) || ''', table_name ''' || quote_ident(c.relname) || ''');'
14FROM
15 pg_class c,
16 pg_attribute a,
17 pg_type t,
18 pg_namespace n
19WHERE
20 a.attnum > 0
21 AND a.attrelid = c.oid
22 AND a.atttypid = t.oid
23 AND n.oid = c.relnamespace
24 AND c.relkind in ('r', 'v')
25 AND n.nspname <> 'pg_catalog'
26 AND n.nspname <> 'information_schema'
27 AND n.nspname !~ '^pg_toast'
28 AND pg_catalog.pg_table_is_visible(c.oid)
29GROUP BY c.relname, n.nspname
30ORDER BY c.relname;
31`
32
33function * run (context, heroku) {
34 const app = context.app
35 const {prefix, database} = context.args
36
37 let db = yield pg.fetcher(heroku).database(app, database)
38 cli.log('CREATE EXTENSION IF NOT EXISTS postgres_fdw;')
39 cli.log(`DROP SERVER IF EXISTS ${prefix}_db;`)
40 cli.log(`CREATE SERVER ${prefix}_db
41 FOREIGN DATA WRAPPER postgres_fdw
42 OPTIONS (dbname '${db.database}', host '${db.host}');`)
43 cli.log(`CREATE USER MAPPING FOR CURRENT_USER
44 SERVER ${prefix}_db
45 OPTIONS (user '${db.user}', password '${db.password}');`)
46 let output = yield pg.psql.exec(query(prefix), db, app)
47 output = output.split('\n').filter(l => /CREATE/.test(l)).join('\n')
48 process.stdout.write(output)
49}
50
51const cmd = {
52 topic: 'pg',
53 description: 'generate fdw install sql for database',
54 needsApp: true,
55 needsAuth: true,
56 args: [
57 {name: 'prefix'},
58 {name: 'database', optional: true}
59 ],
60 run: cli.command(co.wrap(run))
61}
62
63module.exports = [
64 Object.assign({command: 'fdwsql'}, cmd)
65]