Adds a databases to the Postgres server.

    CLI Example:

    .. code-block:: bash

        salt '*' postgres.db_create 'dbname'

        salt '*' postgres.db_create 'dbname' template=template_postgis
439414
def db_create(name,
              user=None,
              host=None,
              port=None,
              maintenance_db=None,
              password=None,
              tablespace=None,
              encoding=None,
              lc_collate=None,
              lc_ctype=None,
              owner=None,
              template=None,
              runas=None):
    '''
    

    '''

    # Base query to create a database
    query = 'CREATE DATABASE "{0}"'.format(name)

    # "With"-options to create a database
    with_args = salt.utils.odict.OrderedDict([
        ('TABLESPACE', _quote_ddl_value(tablespace, '"')),
        # owner needs to be enclosed in double quotes so postgres
        # doesn't get thrown by dashes in the name
        ('OWNER', _quote_ddl_value(owner, '"')),
        ('TEMPLATE', template),
        ('ENCODING', _quote_ddl_value(encoding)),
        ('LC_COLLATE', _quote_ddl_value(lc_collate)),
        ('LC_CTYPE', _quote_ddl_value(lc_ctype)),
    ])
    with_chunks = []
    for key, value in with_args.items():
        if value is not None:
            with_chunks += [key, '=', value]
    # Build a final query
    if with_chunks:
        with_chunks.insert(0, ' WITH')
        query += ' '.join(with_chunks)

    # Execute the command
    ret = _psql_prepare_and_run(['-c', query],
                                user=user, host=host, port=port,
                                maintenance_db=maintenance_db,
                                password=password, runas=runas)
    return ret['retcode'] == 0
1320870
def present(name, containment='NONE', options=None, **kwargs):
    '''
    
    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    if __salt__['mssql.db_exists'](name, **kwargs):
        ret['comment'] = 'Database {0} is already present (Not going to try to set its options)'.format(name)
        return ret
    if __opts__['test']:
        ret['result'] = None
        ret['comment'] = 'Database {0} is set to be added'.format(name)
        return ret

    db_created = __salt__['mssql.db_create'](name, containment=containment, new_database_options=_normalize_options(options), **kwargs)
    if db_created is not True:  # Non-empty strings are also evaluated to True, so we cannot use if not db_created:
        ret['result'] = False
        ret['comment'] += 'Database {0} failed to be created: {1}'.format(name, db_created)
        return ret
    ret['comment'] += 'Database {0} has been added'.format(name)
    ret['changes'][name] = 'Present'
    return ret
27553
def add(self, instance):
        '''
        
        '''

        table = instance.__class__.__name__.lower()
        keys = ", ".join(vars(instance).keys())
        values = tuple(vars(instance).values())

        SQL = """INSERT INTO %s (%s) VALUES(""" % (table, keys)
        SQL += """ "%s",""" * len(values) % (values)
        SQL = SQL[:-1] + ")"

        if self.DEBUG: print(SQL)

        with Session(self.settings) as conn:
            try:
                c = conn.cursor()
                c.execute(SQL)
                conn.commit()
                return True
            except mysql.Error as e:
                if e.errno==1062:
                    print("Already saved to the database")
                    return True
                elif e.errno == 1146:
                    # Table does not exist
                    return True
                else:
                    raise e

                return True
244967
def create_db():
    "  "

    from ..ext import db
    db.create_all()

    # Evolution support
    from flask import current_app
    from flaskext.evolution import db as evolution_db
    evolution_db.init_app(current_app)
    evolution_db.create_all()

    print "Database created successfuly"
1319552
def add_database_args(parser):
    '''
    
    '''
    parser.add_argument(
        'url',
        nargs='?',
        default='sqlite:///ncbi_taxonomy.db',
        type=sqlite_default(),
        help=('Database string URI or filename.  If no database scheme '
              'specified \"sqlite:///\" will be prepended. [%(default)s]'))
    db_parser = parser.add_argument_group(title='database options')

    # TODO: better description of what --schema does
    db_parser.add_argument(
        '--schema',
        help=('Name of SQL schema in database to query '
              '(if database flavor supports this).'))

    return parser
1143686
def create_db(with_postgis=False):
    
    local_machine()
    local('psql {0} -c "CREATE USER {1} WITH PASSWORD \'{2}\'"'.format(
        USER_AND_HOST, env.db_role, DB_PASSWORD))
    local('psql {0} -c "CREATE DATABASE {1} ENCODING \'UTF8\'"'.format(
        USER_AND_HOST, env.db_name))
    if with_postgis:
        local('psql {0} {1} -c "CREATE EXTENSION postgis"'.format(
            USER_AND_HOST, env.db_name))
    local('psql {0} -c "GRANT ALL PRIVILEGES ON DATABASE {1}'
          ' to {2}"'.format(USER_AND_HOST, env.db_name, env.db_role))
    local('psql {0} -c "GRANT ALL PRIVILEGES ON ALL TABLES'
          ' IN SCHEMA public TO {1}"'.format(
              USER_AND_HOST, env.db_role))
1015565
def create(cls, name, users=None):
        

        api = Client.instance().api

        database_data = {
            'name': name,
            'active': True,
        }

        if isinstance(users, list) or isinstance(users, tuple):
            database_data['users'] = users

        data = api.database.post(data=database_data)

        db = Database(
            name=name,
            api=api,
            kwargs=data
        )

        Client.instance().set_database(name=name)

        return db
595863
function Database(pg) {
  this.pg = pg;
  this.defaults = pg.defaults;
  this.connect = this.connect.bind(this);
  this.end = this.end.bind(this);
}
932990
def add(name, gid=None, **kwargs):
    '''
    
    '''
    ### NOTE: **kwargs isn't used here but needs to be included in this
    ### function for compatibility with the group.present state
    if info(name):
        raise CommandExecutionError(
            'Group \'{0}\' already exists'.format(name)
        )
    if salt.utils.stringutils.contains_whitespace(name):
        raise SaltInvocationError('Group name cannot contain whitespace')
    if name.startswith('_'):
        raise SaltInvocationError(
            'Salt will not create groups beginning with underscores'
        )
    if gid is not None and not isinstance(gid, int):
        raise SaltInvocationError('gid must be an integer')
    # check if gid is already in use
    gid_list = _list_gids()
    if six.text_type(gid) in gid_list:
        raise CommandExecutionError(
            'gid \'{0}\' already exists'.format(gid)
        )

    cmd = ['dseditgroup', '-o', 'create']
    if gid:
        cmd.extend(['-i', gid])
    cmd.append(name)
    return __salt__['cmd.retcode'](cmd, python_shell=False) == 0
1335682
def pgdump(self, *pgdumpargs):
        
        db, env = self.get_db_args_env()

        args = ['-d', db['name'], '-h', db['host'], '-U', db['user'], '-w'
                ] + list(pgdumpargs)
        stdout, stderr = External.run(
            'pg_dump', args, capturestd=True, env=env)
        if stderr:
            log.warn('stderr: %s', stderr)
        log.debug('stdout: %s', stdout)
        return stdout
392201
def deploy_db(rollback=False):
    
    if not rollback:

        if env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
            db_dir = '/'.join([deployment_root(),'database'])
            db_name = ''.join([env.project_name,'_','site_1','.db'])
            dest_db_path = '/'.join([db_dir,db_name])
            if exists(dest_db_path): return
            if env.verbosity:
                print env.host,"DEPLOYING DEFAULT SQLITE DATABASE"
            if not env.DEFAULT_DATABASE_NAME:
                print "ERROR: A database name has not been defined in your Django settings file"
                sys.exit(1)

            if env.DEFAULT_DATABASE_NAME[0] not in [os.path.sep,'.']: #relative path
                db_path = os.path.join(os.getcwd(),env.project_package_name,env.DEFAULT_DATABASE_NAME)

            elif env.DEFAULT_DATABASE_NAME[:2] == '..':
                print "ERROR: Use a full expanded path to the database in your Django settings"
                sys.exit(1)
            else:
                db_path = env.DEFAULT_DATABASE_NAME

            if not db_path or not os.path.exists(db_path):
                print "ERROR: the database %s does not exist. \nRun python manage.py syncdb to create your database locally first, or check your settings."% db_path
                sys.exit(1)

            db_name = os.path.split(db_path)[1]  
            run('mkdir -p '+db_dir)
            put(db_path,dest_db_path)
            #directory and file must be writable by webserver
            sudo("chown -R %s:www-data %s"% (env.user,db_dir))
            sudo("chmod -R ug+w %s"% db_dir)
        
        elif env.DEFAULT_DATABASE_ENGINE=='django.db.backends.':
            print "ERROR: The default database engine has not been defined in your Django settings file"
            print "At a minimum you must define an sqlite3 database for woven to deploy, or define a database that is managed outside of woven."
            sys.exit(1)
    elif rollback and env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3':
        if env.INTERACTIVE:
            delete = confirm('DELETE the database on the host?',default=False)
            if delete:
                run('rm -f '+db_name)
    return
152858
def add(name, gid=None, **kwargs):
    '''
    
    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)
    if salt.utils.data.is_true(kwargs.pop('system', False)):
        log.warning('pw_group module does not support the \'system\' argument')
    if kwargs:
        log.warning('Invalid kwargs passed to group.add')

    cmd = 'pw groupadd '
    if gid:
        cmd += '-g {0} '.format(gid)
    cmd = '{0} -n {1}'.format(cmd, name)
    ret = __salt__['cmd.run_all'](cmd, python_shell=False)

    return not ret['retcode']
969582
def create_table(self, table_name, obj=None, **kwargs):
        
        return self.client.create_table(
            table_name, obj=obj, database=self.name, **kwargs
        )
1316200
async function run () {
  const {host, port, database, username: user, password, idleTimeoutMillis} = config()
  const client = new Client({host, port, database: 'postgres', user, password, idleTimeoutMillis})

  await client.connect()
  await client.query(`DROP DATABASE IF EXISTS ${database}`)
  await client.query(`CREATE DATABASE ${database}`)
  await client.end()
  console.log(`\x1b[32m\u2714 Database \x1b[1m${database}\x1b[22m created successfully!\x1b[0m`)
}
626329
def install_postgres(user=None, dbname=None, password=None):
    """"""
    execute(pydiploy.django.install_postgres_server,
            user=user, dbname=dbname, password=password)
456910
def database!(name)
      connection.head name # Check if the URL is valid
      database(name)
    rescue CouchRest::NotFound # Thrown if the HTTP HEAD fails
      create_db(name)
    end
200773
def add_pk_if_required(db, table, name):
    
    db.metadata.reflect(bind=db.engine)
    cls_dict = {'__tablename__': name}
    if not table.primary_key:
        for column in table.columns:
            column.primary_key = True
        Table(name, db.metadata, *table.columns, extend_existing=True)
        cls_dict['__table__'] = table
        db.metadata.create_all(bind=db.engine)

    return type(str(name), (sandman_model, db.Model), cls_dict)