Skip to content

Commit b554d2b

Browse files
committedDec 4, 2019
feat: support ifNotExists when creating a postgres db
Signed-off-by: Andy Burke <andy.burke@mailbox.earth>
1 parent 42e289b commit b554d2b

File tree

4 files changed

+168
-93
lines changed

4 files changed

+168
-93
lines changed
 

‎index.js

+31-5
Original file line numberDiff line numberDiff line change
@@ -88,12 +88,38 @@ var PgDriver = Base.extend({
8888
createDatabase: function (dbName, options, callback) {
8989
var spec = '';
9090

91-
if (typeof options === 'function') callback = options;
91+
if (typeof options === 'function') {
92+
callback = options;
93+
options = {};
94+
}
9295

93-
this.runSql(
94-
util.format('CREATE DATABASE %s %s', this.escapeDDL(dbName), spec),
95-
callback
96-
);
96+
if (options.ifNotExists) {
97+
this.runSql(
98+
`
99+
DO
100+
$do$
101+
DECLARE
102+
_db TEXT := '${ dbName }';
103+
BEGIN
104+
CREATE EXTENSION IF NOT EXISTS dblink;
105+
IF EXISTS (SELECT 1 FROM pg_database WHERE datname = _db) THEN
106+
RAISE NOTICE 'Database "%" already exists, skipping creation.', _db;
107+
ELSE
108+
PERFORM dblink_connect('dbname=' || current_database());
109+
PERFORM dblink_exec('CREATE DATABASE ' || _db || ' ${ spec }');
110+
END IF;
111+
END
112+
$do$
113+
`,
114+
callback
115+
);
116+
}
117+
else {
118+
this.runSql(
119+
util.format('CREATE DATABASE %s %s', this.escapeDDL(dbName), spec),
120+
callback
121+
);
122+
}
97123
},
98124

99125
dropDatabase: function (dbName, options, callback) {

‎package-lock.json

+100-82
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+6-6
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,14 @@
3030
},
3131
"homepage": "https://github.com/db-migrate/pg",
3232
"dependencies": {
33-
"bluebird": "^3.1.1",
33+
"bluebird": "^3.7.2",
3434
"db-migrate-base": "^2.0.0",
35-
"pg": "^7.8.0",
36-
"semver": "^5.0.3"
35+
"pg": "^7.14.0",
36+
"semver": "^6.3.0"
3737
},
3838
"devDependencies": {
39-
"db-meta": "^0.4.1",
40-
"db-migrate-shared": "^1.1.2",
41-
"vows": "0.8.0"
39+
"db-meta": "^0.5.1",
40+
"db-migrate-shared": "^1.2.0",
41+
"vows": "0.8.3"
4242
}
4343
}

‎test/pg_test.js

+31
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,37 @@ vows
5757
}
5858
}
5959
})
60+
.addBatch({
61+
createDatabase: {
62+
topic: function () {
63+
db.createDatabase(
64+
'test',
65+
this.callback.bind(this)
66+
);
67+
},
68+
69+
'created database': function (err) {
70+
assert.isNotNull(err);
71+
}
72+
}
73+
})
74+
.addBatch({
75+
'create existing database': {
76+
topic: function () {
77+
db.createDatabase(
78+
'test',
79+
{
80+
ifNotExists: true
81+
},
82+
this.callback.bind(this)
83+
);
84+
},
85+
86+
'created existing database': function (err) {
87+
assert.isNotNull(err);
88+
}
89+
}
90+
})
6091
.addBatch({
6192
createTable: {
6293
topic: function () {

0 commit comments

Comments
 (0)
Please sign in to comment.