8000 Create db only if doesn't exist yet · yingcloud/influxdb-python@528e69a · GitHub
[go: up one dir, main page]

Skip to content

Commit 528e69a

Browse files
committed
Create db only if doesn't exist yet
1 parent f446930 commit 528e69a

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
@@ -410,6 +410,19 @@ def test_create_database(self):
410410
'create database "new_db"'
411411
)
412412

413+
def test_create_database_with_exist_check(self):
414+
with requests_mock.Mocker() as m:
415+
m.register_uri(
416+
requests_mock.GET,
417+
"http://localhost:8086/query",
418+
text='{"results":[{}]}'
419+
)
420+
self.cli.create_database('new_db', if_not_exists=True)
421+
self.assertEqual(
422+
m.last_request.qs['q'][0],
423+
'create database if not exists "new_db"'
424+
)
425+
413426
def test_create_numeric_named_database(self):
414427
with requests_mock.Mocker() as m:
415428
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