Used to create/drop db
343058
def establish_postgres_connection(name = 'default')
      if database_config[name]
        ActiveRecord::Base.establish_connection(database_config[name][env].merge('database' => 'postgres',
                                                                                 'schema_search_path' => 'public'))
      end
    end
1360923
def drop_db(url):
    
    parsed_url = urlparse(url)
    db_name = parsed_url.path
    db_name = db_name.strip("/")
    db = connect("postgresql://" + parsed_url.netloc)
    # check that db exists
    q = """SELECT 1 as exists
           FROM pg_database
           WHERE datname = '{db_name}'""".format(
        db_name=db_name
    )
    if db.query(q).fetchone():
        # DROP DATABASE must be run outside of a transaction
        conn = db.engine.connect()
        conn.execute("commit")
        conn.execute("DROP DATABASE " + db_name)
        conn.close()
589647
def create(self):
        """"""
        self.db_attrs = self.consul.create_db(
                self.instance_name,
                self.instance_type,
                self.admin_username,
                self.admin_password,
                db_name=self.db_name,
                storage_size_gb=self.storage_size,
                timeout_s=self.launch_timeout_s,
                )
483001
def drop_table(self, dbname, name, deleteData):
    
    self.send_drop_table(dbname, name, deleteData)
    self.recv_drop_table()
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
1372878
def drop_database(self, name, force=False):
        
        tables = []

        if not force or self.database(name):
            tables = self.list_tables(database=name)

        if not force and len(tables):
            raise com.IntegrityError(
                'Database {0} must be empty before being dropped, or set '
                'force=True'.format(name)
            )
        statement = ddl.DropDatabase(name)
        self._execute(statement)
566935
def createDatabase( dbname, dbdesc, createapptoken = "1" )

      @dbname, @dbdesc, @createapptoken = dbname, dbdesc, createapptoken

      xmlRequestData = toXML( :dbname, @dbname )
      xmlRequestData << toXML( :dbdesc, @dbdesc )
      xmlRequestData << toXML( :createapptoken, @createapptoken )

      sendRequest( :createDatabase, xmlRequestData )

      @dbid = getResponseValue( :dbid )
      @appdbid = getResponseValue( :appdbid )
      @apptoken = getResponseValue( :apptoken )

      return self if @chainAPIcalls
      return @dbid, @appdbid
   end
1177135
def create_table(self, drop=False, with_test_data=False):
        
        db = self.get_sql_hook(self.sql_conn_id)
        table = self.table_name
        if drop:
            sql = "DROP TABLE IF EXISTS {table};".format(**locals())
            logging.info("Executing SQL: \n" + sql)
            db.run(sql)
        sql = """CREATE TABLE IF NOT EXISTS honeypot_logs (
                log_filepath VARCHAR(255) ,
                dag_id VARCHAR(255),
                task_id VARCHAR(255),
                job_num INT,
                execution_date DATETIME,
                duration DOUBLE,
                input_date DATETIME,
                num_mappers INT,
                num_reducers INT,
                cpu_time LONG,
                hdfs_reads LONG,
                hdfs_writes LONG,
                owner VARCHAR(255));""".format(**locals())
        logging.info("Executing SQL: \n" + sql)
        db.run(sql)
        if with_test_data:
            self.create_test_data()
566798
def init_db(drop_all=False):
    """"""
    if drop_all:
        Base.metadata.drop_all(bind=engine)
    Base.metadata.create_all(bind=engine)

    return session
51631
def create_db(self):
        
        if self.db_type != "json":
            raise RuntimeError("db_type only supports json now")

        if os.path.exists(self.json_db_path):
            return False

        if os.path.exists(self.factory_json_db_path):
            with self.db_mutex:
                shutil.copy2(
                    self.factory_json_db_path, self.json_db_path)
            return True

        _logger.debug(
            "*** NO such file: %s" % self.factory_json_db_path)
        raise RuntimeError("No *.json.factory file")
377472
def create(self, name):
        """"""
        if not os.path.exists(self.directory):
            os.makedirs(self.directory)

        filename = self.get_new_filename(name)
        with open(os.path.join(self.directory, filename), 'w') as fp:
            fp.write("def up(db): pass\n\n\n")
            fp.write("def down(db): pass\n")
            logger.info(filename)
277019
def _save_db():
    """"""
    from pyci.utility import json_serial
    import json
    vms("Serializing DB to JSON in {}".format(datapath))
    with open(datapath, 'w') as f:
        json.dump(db, f, default=json_serial)
1264929
def db_manager(self):
        
        rc_create = self.create_db()    # for first create
        try:
            self.load_db()  # load existing/factory
        except Exception as e:
            _logger.debug("*** %s" % str(e))
            try:
                self.recover_db(self.backup_json_db_path)
            except Exception:
                pass
        else:
            if rc_create is True:
                self.db_status = "factory"
            else:
                self.db_status = "existing"
            return True

        try:
            self.load_db()  # load backup
        except Exception as b:
            _logger.debug("*** %s" % str(b))
            self.recover_db(self.factory_json_db_path)
            self.load_db()  # load factory
            self.db_status = "factory"
        else:
            self.db_status = "backup"
        finally:
            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"
161892
def create_db(name, **client_args):
    '''
    
    '''
    if db_exists(name, **client_args):
        log.info('DB \'%s\' already exists', name)
        return False

    client = _client(**client_args)
    client.create_database(name)

    return True
90583
def cree_local_DB(scheme):
    
    conn = LocalConnexion()
    req = ""
    for table, fields in scheme.items():
        req += f"DROP TABLE IF EXISTS {table};"
        req_fields = ", ".join(f'{c_name} {c_type}' for c_name, c_type in fields)
        req += f"""CREATE TABLE {table} (  {req_fields} ) ;"""
    cur = conn.cursor()
    cur.executescript(req)
    conn.connexion.commit()
    conn.connexion.close()
    logging.info("Database created with succes.")
278101
def create_db(name, owner=None, encoding=u'UTF-8', template='template1',
              **kwargs):
    """"""

    flags = u''
    if encoding:
        flags = u'-E %s' % encoding
    if owner:
        flags = u'%s -O %s' % (flags, owner)
    if template and template != 'template1':
        flags = u'%s --template=%s' % (flags, template)
    sudo('createdb %s %s' % (flags, name), user='postgres', **kwargs)