8000 Merge pull request #276 from slomek/create-db-if-not-exist · yingcloud/influxdb-python@3c16b16 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3c16b16

Browse files
committed
Merge pull request influxdata#276 from slomek/create-db-if-not-exist
Create db only if doesn't exist yet (Thanks @slomek !)
2 parents 203d122 + 528e69a commit 3c16b16

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

influxdb/client.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -454,13 +454,16 @@ def get_list_database(self):
454454
"""
455455
return list(self.query("SHOW DATABASES").get_points())
456456

457-
def create_database(self, dbname):
457+
def create_database(self, dbname, if_not_exists=False):
458458
"""Create a new database in InfluxDB.
459459
460460
:param dbname: the name of the database to create
461461
:type dbname: str
462462
"""
463-
self.query("CREATE DATABASE \"%s\"" % dbname)
463+
if if_not_exists:
464+
self.query("CREATE DATABASE IF NOT EXISTS \"%s\"" % dbname)
465+
else:
466+
self.query("CREATE DATABASE \"%s\"" % dbname)
464467

465468
def drop_database(self, dbname):
466469
"""Drop a database from InfluxDB.

influxdb/tests/client_test.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,19 @@ def test_create_database(self):
413413
'create database "new_db"'
414414
)
415415

416+
def test_create_database_with_exist_check(self):
417+
with requests_mock.Mocker() as m:
418+
m.register_uri(
419+
requests_mock.GET,
420+
"http://localhost:8086/query",
421+
text='{"results":[{}]}'
422+
)
423+
self.cli.create_database('new_db', if_not_exists=True)
424+
self.assertEqual(
425+
m.last_request.qs['q'][0],
426+
'create database if not exists "new_db"'
427+
)
428+
416429
def test_create_numeric_named_database(self):
417430
with requests_mock.Mocker() as m:
418431
m.register_uri(

influxdb/tests/server_tests/client_test_with_server.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,12 @@ def test_create_database(self):
131131
[{'name': 'new_db_1'}, {'name': 'new_db_2'}]
132132
)
133133

134-
def test_create_database_fails(self):
134+
def test_create_database_twice_if_not_exist(self):
135+
self.assertIsNone(self.cli.create_database('new_db'))
136+
self.assertIsNone(
137+
self.cli.create_database('new_db', if_not_exists=True))
138+
139+
def test_create_database_twice_fails(self):
135140
self.assertIsNone(self.cli.create_database('new_db'))
136141
with self.assertRaises(InfluxDBClientError) as ctx:
137142
self.cli.create_database('new_db')

0 commit comments

Comments
 (0)
0