aboutsummaryrefslogtreecommitdiffstats
path: root/fabtools/require/postgres.py
blob: 77cfec924a705ef15d1e6ee516b4af8ba48fbda1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
"""
PostgreSQL users and databases
==============================
"""
from __future__ import with_statement

from fabtools.files import is_file, watch
from fabtools.postgres import *
from fabtools.require.deb import package
from fabtools.require.service import started, restarted
from fabtools.require.system import locale as require_locale


def _service_name(version=None):

    if is_file('/etc/init.d/postgresql'):
        return 'postgresql'

    if version and is_file('/etc/init.d/postgresql-%s' % version):
        return 'postgresql-%s' % version

    with cd('/etc/init.d'):
        with settings(hide('running', 'stdout')):
            return run('ls postgresql-*').splitlines()[0]


def server(version=None):
    """
    Require a PostgreSQL server to be installed and running.

    ::

        from fabtools import require

        require.postgres.server()

    """
    if version:
        pkg_name = 'postgresql-%s' % version
    else:
        pkg_name = 'postgresql'
    package(pkg_name)

    started(_service_name(version))


def user(name, password):
    """
    Require a PostgreSQL user.

    ::

        from fabtools import require

        require.postgres.user('dbuser', password='somerandomstring')

    """
    if not user_exists(name):
        create_user(name, password)


def database(name, owner, template='template0', encoding='UTF8',
             locale='en_US.UTF-8'):
    """
    Require a PostgreSQL database.

    ::

        from fabtools import require

        require.postgres.database('myapp', owner='dbuser')

    """
    if not database_exists(name):

        with watch('/etc/locale.gen') as locales:
            require_locale(locale)
        if locales.changed:
            restarted(_service_name())

        create_database(name, owner, template=template, encoding=encoding,
            locale=locale)