-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
executable file
·245 lines (194 loc) · 6.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env node
/* globals process, console */
import minimist from 'minimist'
import postgres from 'postgres'
import * as M from 'module'
import * as P from 'path'
import * as u from './utils.js'
import dryPostgres from './dryPostgres.js'
// expose argv like zx
const argv = minimist(process.argv.slice(2))
const pkg = M.createRequire(import.meta.url) ('./package.json')
const help =
`
Usage: pgmg [PGMG OPTIONS] [CONNECTION] [OPTIONS] [FILES]
Version: ${pkg.version}
[PGMG OPTiONS]
--help Logs this help message
--version Logs the current pgmg version
[CONNECTION]
- Pass a postgres connection string (just like psql)
- AND/OR Specify host/user etc as env flags (PGHOST, PGUSER, PGPORT)
[FILES]
Any files passed as arguments after the connection string will be imported as JS migration files.
[OPTIONS]
The only way to specify a connection is via a pg connection URL.
--ssl
| --ssl Enables ssl
| --ssl=prefer Prefers ssl
| --ssl=require Requires ssl
| --ssl=reject Reject unauthorized connections
| --ssl=no-reject Do not reject unauthorized connections
| --ssl=heroku --no-ssl-reject if the host ends with a .com
For more detailed connection options, connect to postgres manually
via -X
`
async function main(){
if( process.argv.length == 2 || argv.help ){
console.log(help)
process.exit(argv.help ? 0 : 1)
}
if( argv.version ) {
console.log(pkg.version)
process.exit(0)
}
let [connectionString] = argv._
let {
ssl:theirSSL,
dry=false
} = argv
if ( theirSSL == 'heroku' ) {
let hosts = []
if (process.env.PGHOST) {
hosts = process.env.PGHOST.split(',')
} else if (connectionString ) {
hosts =
connectionString.split('@')[1].split('/')[0].split(',').map( x => x.split(':')[0])
}
theirSSL =
hosts.every( x => x.endsWith('.com') )
? 'no-reject'
: false
}
const ssl =
theirSSL == 'no-reject'
? { rejectUnauthorized: false }
: theirSSL == 'reject'
? { rejectUnauthorized: true }
// inspired by: https://github.com/porsager/postgres/blob/master/lib/index.js#L577
: theirSSL !== 'disabled' && theirSSL !== false && theirSSL
let app = {
async resetConnection(){
if( app.sql ) {
await app.sql.end()
}
app.realSQL = RealSQL()
app.drySQL =
dryPostgres(app.realSQL)
app.sql = dry ? app.drySQL : app.realSQL
app.sql.pgmg = u
app.sql.raw = Raw(app.sql)
app.sql.Raw = Raw
}
}
function onnotice(...args){
if( app.realSQL.onnotice ) {
app.realSQL.onnotice(...args)
} else {
if(args[0].severity == 'NOTICE') return;
console.log(...args)
}
}
const pg = [
connectionString
, { ssl, onnotice, max: 1, prepare: false }
]
const RealSQL = () =>
postgres(...pg)
function Raw(sql){
return function raw(strings, ...values){
return sql.unsafe(String.raw(strings, ...values))
}
}
{
await app.resetConnection()
await app.realSQL.unsafe`
create extension if not exists pgcrypto;
create schema if not exists pgmg;
create table if not exists pgmg.migration (
migration_id uuid primary key default public.gen_random_uuid()
, name text not null
, filename text not null
, description text null
, created_at timestamptz not null default now()
)
;
`
}
const always = []
const migrations =
argv._.filter( x => x.endsWith('.js') || x.endsWith('.mjs') )
for ( let migration of migrations ) {
// so SET EXAMPLE=on is reset per migration
await app.resetConnection()
let module = await import(P.resolve(process.cwd(), migration))
if ( !module.name ) {
console.error('Migration', migration, 'did not export a name.')
process.exit(1)
} else if (!(
module.transaction
|| module.action
|| module.always
)) {
console.error('Migration', migration, 'did not export a transaction or action function.')
process.exit(1)
}
let action =
module.action
|| module.transaction && (SQL => SQL.begin( sql => {
sql.pgmg = u
sql.raw = Raw(sql)
sql.raw.pgmg = u
return module.transaction(sql)
}))
if( module.always ) {
always.push(module.always)
}
const [found] = await app.realSQL`
select * from pgmg.migration where name = ${module.name}
`
let description = module.description ? module.description.split('\n').map( x => x.trim() ).filter(Boolean).join('\n') : null
if (!found && action){
try {
console.log('Running migration', migration)
await action(app.sql)
console.log('Migration complete')
await app.sql`
insert into pgmg.migration(name, filename, description)
values (${module.name}, ${migration}, ${description})
`
} catch (e) {
console.error('Migration failed')
console.error(e)
process.exit(1)
}
}
}
// always are migration hooks that always run
// they run after the other migrations to guarantee
// any checks you perform in always are against the changes made in the prior transactions
// all always checks run within the same transaction
if ( always.length ) {
try {
await app.sql.begin( async sql => {
sql.pgmg = u
sql.raw = Raw(sql)
sql.raw.pgmg = u
for( let f of always ) {
await f(sql)
}
})
} catch (e) {
console.error(e.line)
throw e
}
}
await app.realSQL.end()
}
main()
.catch(
e => {
console.error(e)
process.exit(1)
}
)