Skip to content
This repository was archived by the owner on Oct 29, 2024. It is now read-only.

Create db only if doesn't exist yet #276

Merged
merged 1 commit into from
Jan 3, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions influxdb/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,13 +454,16 @@ def get_list_database(self):
"""
return list(self.query("SHOW DATABASES").get_points())

def create_database(self, dbname):
def create_database(self, dbname, if_not_exists=False):
"""Create a new database in InfluxDB.

:param dbname: the name of the database to create
:type dbname: str
"""
self.query("CREATE DATABASE \"%s\"" % dbname)
if if_not_exists:
self.query("CREATE DATABASE IF NOT EXISTS \"%s\"" % dbname)
else:
self.query("CREATE DATABASE \"%s\"" % dbname)

def drop_database(self, dbname):
"""Drop a database from InfluxDB.
Expand Down
13 changes: 13 additions & 0 deletions influxdb/tests/client_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,19 @@ def test_create_database(self):
'create database "new_db"'
)

def test_create_database_with_exist_check(self):
with requests_mock.Mocker() as m:
m.register_uri(
requests_mock.GET,
"http://localhost:8086/query",
text='{"results":[{}]}'
)
self.cli.create_database('new_db', if_not_exists=True)
self.assertEqual(
m.last_request.qs['q'][0],
'create database if not exists "new_db"'
)

def test_create_numeric_named_database(self):
with requests_mock.Mocker() as m:
m.register_uri(
Expand Down
7 changes: 6 additions & 1 deletion influxdb/tests/server_tests/client_test_with_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,12 @@ def test_create_database(self):
[{'name': 'new_db_1'}, {'name': 'new_db_2'}]
)

def test_create_database_fails(self):
def test_create_database_twice_if_not_exist(self):
self.assertIsNone(self.cli.create_database('new_db'))
self.assertIsNone(
self.cli.create_database('new_db', if_not_exists=True))

def test_create_database_twice_fails(self):
self.assertIsNone(self.cli.create_database('new_db'))
with self.assertRaises(InfluxDBClientError) as ctx:
self.cli.create_database('new_db')
Expand Down