Add template parameter to create_database

This commit is contained in:
Konsta Vesterinen
2014-08-23 11:58:20 +03:00
parent 8274b495fe
commit 9a27f42785
5 changed files with 39 additions and 8 deletions

View File

@@ -4,6 +4,12 @@ Changelog
Here you can see the full list of changes between each SQLAlchemy-Utils release.
0.26.13 (2014-08-23)
^^^^^^^^^^^^^^^^^^^^
- Added template parameter to create_database function
0.26.12 (2014-08-22)
^^^^^^^^^^^^^^^^^^^^

View File

@@ -44,7 +44,7 @@ for name, requirements in extras_require.items():
setup(
name='SQLAlchemy-Utils',
version='0.26.12',
version='0.26.13',
url='https://github.com/kvesteri/sqlalchemy-utils',
license='BSD',
author='Konsta Vesterinen, Ryan Leckey, Janne Vanhala, Vesa Uimonen',

View File

@@ -75,7 +75,7 @@ from .types import (
from .models import Timestamp
__version__ = '0.26.12'
__version__ = '0.26.13'
__all__ = (

View File

@@ -170,11 +170,14 @@ def database_exists(url):
return False
def create_database(url, encoding='utf8'):
def create_database(url, encoding='utf8', template=None):
"""Issue the appropriate CREATE DATABASE statement.
:param url: A SQLAlchemy engine URL.
:param encoding: The encoding to create the database as.
:param template:
The name of the template from which to create the new database. At the
moment only supported by PostgreSQL driver.
To create a database, you can pass a simple URL that would have
been passed to ``create_engine``. ::
@@ -204,10 +207,15 @@ def create_database(url, encoding='utf8'):
if engine.driver == 'psycopg2':
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT
engine.raw_connection().set_isolation_level(
ISOLATION_LEVEL_AUTOCOMMIT)
ISOLATION_LEVEL_AUTOCOMMIT
)
text = "CREATE DATABASE %s ENCODING '%s' TEMPLATE template0" % (
database, encoding)
if not template:
template = 'template0'
text = "CREATE DATABASE %s ENCODING '%s' TEMPLATE %s" % (
database, encoding, template
)
engine.execute(text)
elif engine.dialect.name == 'mysql':

View File

@@ -1,10 +1,14 @@
import os
import sqlalchemy as sa
from flexmock import flexmock
from pytest import mark
pymysql = None
try:
import pymysql
except ImportError:
pass
import os
from tests import TestCase
from sqlalchemy_utils import (
@@ -15,7 +19,6 @@ from sqlalchemy_utils import (
class DatabaseTest(TestCase):
def test_create_and_drop(self):
assert not database_exists(self.url)
create_database(self.url)
@@ -43,3 +46,17 @@ class TestDatabaseMySQL(DatabaseTest):
class TestDatabasePostgres(DatabaseTest):
url = 'postgres://postgres@localhost/db_test_sqlalchemy_util'
def test_template(self):
(
flexmock(sa.engine.Engine)
.should_receive('execute')
.with_args(
"CREATE DATABASE db_test_sqlalchemy_util ENCODING 'utf8' "
"TEMPLATE my_template"
)
)
create_database(
'postgres://postgres@localhost/db_test_sqlalchemy_util',
template='my_template'
)