Creates database table for custom URL alias backup.
499174
protected function createGlobalUrlAliasBackupTable()
    {
        $schema = new Schema();

        $table = $schema->createTable(static::GLOBAL_ALIAS_BACKUP_TABLE);

        $table->addColumn('id', 'integer', ['autoincrement' => true]);
        $table->addColumn('resource', 'text');
        $table->addColumn('path', 'text');
        $table->addColumn('language_code', 'string');
        $table->addColumn('always_available', 'integer');
        $table->addColumn('forwarding', 'integer');
        $table->setPrimaryKey(['id']);

        $queries = $schema->toSql($this->connection->getDatabasePlatform());

        foreach ($queries as $query) {
            $this->connection->exec($query);
        }
    }
344340
def export_db(self, dirpath):
        
        if self.db is not None:
            self.db.commit()
            
        import virtualchain_hooks
        
        db_path = os.path.join(dirpath, os.path.basename(self.get_db_path()))
        snapshots_path = os.path.join(dirpath, os.path.basename(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir)))
        atlas_path = os.path.join(dirpath, 'atlas.db')
        subdomain_path = os.path.join(dirpath, 'subdomains.db')
        subdomain_queue_path = os.path.join(dirpath, 'subdomains.db.queue')

        src_atlas_path = os.path.join(self.working_dir, 'atlas.db')
        src_subdomain_path = os.path.join(self.working_dir, 'subdomains.db')
        src_subdomain_queue_path = os.path.join(self.working_dir, 'subdomains.db.queue')
        
        virtualchain.sqlite3_backup(self.get_db_path(), db_path)
        virtualchain.sqlite3_backup(virtualchain.get_snapshots_filename(virtualchain_hooks, self.working_dir), snapshots_path)

        if os.path.exists(src_atlas_path):
            virtualchain.sqlite3_backup(src_atlas_path, atlas_path)

        if os.path.exists(src_subdomain_path):
            virtualchain.sqlite3_backup(src_subdomain_path, subdomain_path)

        if os.path.exists(src_subdomain_queue_path):
            virtualchain.sqlite3_backup(src_subdomain_queue_path, subdomain_queue_path)
1313299
public static DataSource createDataSource(String url) throws SQLException {
        assertNotNull(url);

        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);

        return ds;
    }
22007
public function backupAction()
    {
        $filter = $this->getSearchFilter();
        $model = $this->getModel();

        $tables = $model->load();
        $allTables = [];
        $noDataTables = [];
        foreach($tables as $table) {
            if ($table['type'] == 'view' && (!array_key_exists('include_views', $filter) || $filter['include_views'] != '1')) {
                continue;
            }
            $allTables[] = $table['name'];
            if ($table['respondentData'] === true && (!array_key_exists('include_respondent_data', $filter) || $filter['include_respondent_data'] != '1')) {
                $noDataTables[] = $table['name'];
            }
        }

        $filename = $this->getBackupFilename($filter);
        $dbConfig = $this->getDatabaseConfig();
        $dumpSettings = [
            'include-tables' => $allTables,
            'no-data' => $noDataTables,
            'single-transaction' => true,
            'lock-tables' => false,
            'add-locks' => false,
            'add-drop-table' => true,
        ];

        ini_set('max_execution_time', 300);

        try {
            $dump = new \Ifsnop\Mysqldump\Mysqldump($dbConfig['dsn'], $dbConfig['username'], $dbConfig['password'], $dumpSettings);
            $dump->start($filename);
            echo sprintf($this->_('Database backup completed. File can be found in %s'), $filename);
        } catch (\Exception $e) {
            echo 'mysqldump-php error: ' . $e->getMessage();
        }
    }
495583
def create_table(db, schema_name, table_name, columns):
    
    table = '{0}.{1}'.format(schema_name, table_name) if schema_name else table_name
    db.execute('DROP TABLE IF EXISTS {0}'.format(table))
    columns_list = ', '.join(columns)
    db.execute('CREATE TABLE {0} ({1})'.format(table, columns_list))
424601
def _create_table():
    '''
    
    '''
    # Explicitely check if the table already exists as the library logs a
    # warning on CREATE TABLE
    query = """SELECT COUNT(TABLE_NAME) FROM information_schema.tables
        WHERE table_schema = '{0}' AND table_name = '{1}'""".format(
            _mysql_kwargs['db'],
            _table_name,
        )
    cur, _ = run_query(client, query)
    r = cur.fetchone()
    cur.close()
    if r[0] == 1:
        return

    query = """CREATE TABLE IF NOT EXISTS {0} (
      bank CHAR(255),
      etcd_key CHAR(255),
      data MEDIUMBLOB,
      PRIMARY KEY(bank, etcd_key)
    );""".format(_table_name)
    log.info("mysql_cache: creating table %s", _table_name)
    cur, _ = run_query(client, query)
    cur.close()
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()
963646
def create_sqlite_backup_db(audit_tables):
    
    #we always want to create a whole new DB, so delete the old one first
    #if it exists.
    try:
        Popen("rm %s"%(config.get('sqlite', 'backup_url')), shell=True)
        logging.warn("Old sqlite backup DB removed")
    except Exception as e:
        logging.warn(e)

    try:
        aux_dir = config.get('DEFAULT', 'hydra_aux_dir')
        os.mkdir(aux_dir)
        logging.warn("%s created", aux_dir)
    except Exception as e:
        logging.warn(e)

    try:
        backup_dir = config.get('db', 'export_target')
        os.mkdir(backup_dir)
        logging.warn("%s created", backup_dir)
    except Exception as e:
        logging.warn(e)

    db = create_engine(sqlite_engine, echo=True)
    db.connect()
    metadata = MetaData(db)

    for main_audit_table in audit_tables:
        cols = []
        for c in main_audit_table.columns:
            col = c.copy()
            if col.type.python_type == Decimal:
                col.type = DECIMAL()

            cols.append(col)
        Table(main_audit_table.name, metadata, *cols, sqlite_autoincrement=True)

    metadata.create_all(db)
965813
def custom_db_creator(self, number_of_rows, cursor, conn, custom):
        '''
        '''

        custom_d = faker_options_container()
        sqlst = "CREATE TABLE custom (id serial PRIMARY KEY,"
        custom_payload = "INSERT INTO custom ("
        
        # form the sql query that will set the db up
        for c in custom:
            if custom_d.get(c):
                sqlst += " " + c + " " + custom_d[c] + ","
                custom_payload += " " + c + ","
                logger.warning("fake2db found valid custom key provided: %s" % c, extra=d)
            else:
                logger.error("fake2db does not support the custom key you provided.", extra=d )
                sys.exit(1)
                
        # the indice thing is for trimming the last extra comma
        sqlst = sqlst[:-1]
        sqlst += ");"
        custom_payload = custom_payload[:-1]
        custom_payload += ") VALUES ("

        for i in range(0, len(custom)):
            custom_payload += "%s, "
        custom_payload = custom_payload[:-2] + ")"
        cursor.execute(sqlst)
        conn.commit()

        multi_lines = []
        try:
            for i in range(0, number_of_rows):
                multi_lines.append([])
                for c in custom:
                    multi_lines[i].append(getattr(self.faker, c)())
            
            cursor.executemany(custom_payload, multi_lines)
            conn.commit()
            logger.warning('custom Commits are successful after write job!', extra=d)
        except Exception as e:
            logger.error(e, extra=d)
531418
def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit):
    """"""

    internal_backup(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit)
376576
def create_temporary_table(from_table, name=None, on_commit=None):
    
    from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table

    name = name or f"temporary_{from_table.name}"

    # copy the origin table into the metadata with the new name.
    temporary_table = copy_table(from_table, name)

    # change create clause to: CREATE TEMPORARY TABLE
    temporary_table._prefixes = list(from_table._prefixes)
    temporary_table._prefixes.append("TEMPORARY")

    # change post create clause to: ON COMMIT DROP
    if on_commit:
        temporary_table.dialect_options["postgresql"].update(
            on_commit=on_commit,
        )

    temporary_table.insert_many = MethodType(insert_many, temporary_table)
    temporary_table.select_from = MethodType(select_from, temporary_table)
    temporary_table.upsert_into = MethodType(upsert_into, temporary_table)

    return temporary_table
693142
def _create_table(self, table_name):
        ''' 
        '''
        if self.fieldnames:
            sql_fields = []
            for field in self._fields:
                if field != '_id':
                    if 'dblite' in self._fields[field]:
                        sql_fields.append(' '.join([field, self._fields[field]['dblite']]))
                    else:
                        sql_fields.append(field)
            sql_fields = ','.join(sql_fields)
            SQL = 'CREATE TABLE IF NOT EXISTS %s (%s);' % (table_name, sql_fields)
            try:
                self._cursor.execute(SQL)
            except sqlite3.OperationalError, err:
                raise RuntimeError('Create table error, %s, SQL: %s' % (err, SQL))
1239282
private TableAlias createTableAlias(String table, String path)
    {
        TableAlias alias;

        if (table == null)
        {
            getLogger().warn("Creating TableAlias without table for path: " + path);
        }

        String aliasName = String.valueOf(getAliasChar()) + m_aliasCount++; // + m_pathToAlias.size();
        alias = new TableAlias(table, aliasName);
        setTableAliasForPath(path, null, alias);        
        m_logger.debug("createTableAlias2: path: " + path + " tableAlias: " + alias);

        return alias;
    }
1332129
def create_url(self, db="", user="genome", host="genome-mysql.cse.ucsc.edu",
        password="", dialect="mysqldb"):
        
        if os.path.exists(db):
            db = "sqlite:///" + db

        # Is this a DB URL? If so, use it directly
        if self.db_regex.match(db):
            self.db = self.url = db
            self.dburl = db
            self.user = self.host = self.password = ""
        else:
            self.db = db
            if user == "genome" and host != "genome-mysql.cse.ucsc.edu":
                import getpass
                user = getpass.getuser()
            self.host = host
            self.user = user
            self.password = (":" + password) if password else ""
            self.dburl = self.url.format(db=self.db, user=self.user,
                host=self.host, password=self.password, dialect=dialect)
1118149
def create_table(clas,pool_or_cursor):
    ""
    def mkfield((name,tp)): return name,(tp if isinstance(tp,basestring) else 'jsonb')
    fields = ','.join(map(' '.join,map(mkfield,clas.FIELDS)))
    base = 'create table if not exists %s (%s'%(clas.TABLE,fields)
    if clas.PKEY: base += ',primary key (%s)'%clas.PKEY
    base += ')'
    commit_or_execute(pool_or_cursor,base)
    clas.create_indexes(pool_or_cursor)
315699
def _create_table(self, packet_defn):
        ''' 
        '''
        cols = ('%s %s' % (defn.name, self._getTypename(defn)) for defn in packet_defn.fields)
        sql  = 'CREATE TABLE IF NOT EXISTS %s (%s)' % (packet_defn.name, ', '.join(cols))

        self._conn.execute(sql)
        self._conn.commit()
1009597
def main() -> None:
    
    main_only_quicksetup_rootlogger()
    wdcd_suffix = "_with_drop_create_database"
    timeformat = "%Y%m%dT%H%M%S"
    parser = argparse.ArgumentParser(
        description="""
        Back up a specific MySQL database. The resulting filename has the
        format '<DATABASENAME>_<DATETIME><SUFFIX>.sql', where <DATETIME> is of
        the ISO-8601 format {timeformat!r} and <SUFFIX> is either blank or
        {suffix!r}. A typical filename is therefore 'mydb_20190415T205524.sql'.
        """.format(timeformat=timeformat, suffix=wdcd_suffix),
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument(
        "databases", nargs="+",
        help="Database(s) to back up")
    parser.add_argument(
        "--max_allowed_packet", default="1GB",
        help="Maximum size of buffer")
    parser.add_argument(
        "--mysqldump", default="mysqldump",
        help="mysqldump executable")
    parser.add_argument(
        "--username", default="root",
        help="MySQL user")
    parser.add_argument(
        "--password",
        help="MySQL password (AVOID THIS OPTION IF POSSIBLE; VERY INSECURE; "
             "VISIBLE TO OTHER PROCESSES; if you don't use it, you'll be "
             "prompted for the password)")
    parser.add_argument(
        "--with_drop_create_database", action="store_true",
        help="Include DROP DATABASE and CREATE DATABASE commands, and append "
             "a suffix to the output filename as above")
    parser.add_argument(
        "--output_dir", type=str,
        help="Output directory (if not specified, current directory will be "
             "used)")
    parser.add_argument(
        "--verbose", action="store_true",
        help="Verbose output")
    args = parser.parse_args()

    output_dir = args.output_dir or os.getcwd()
    os.chdir(output_dir)

    password = args.password or getpass.getpass(
        prompt="MySQL password for user {}: ".format(args.username))

    output_files = []  # type: List[str]
    if args.with_drop_create_database:
        log.info("Note that the DROP DATABASE commands will look like they're "
                 "commented out, but they're not: "
                 "https://dba.stackexchange.com/questions/59294/")
        suffix = wdcd_suffix
    else:
        suffix = ""
    for db in args.databases:
        now = datetime.datetime.now().strftime(timeformat)
        outfilename = "{db}_{now}{suffix}.sql".format(db=db, now=now,
                                                      suffix=suffix)
        display_args = cmdargs(
            mysqldump=args.mysqldump,
            username=args.username,
            password=password,
            database=db,
            verbose=args.verbose,
            with_drop_create_database=args.with_drop_create_database,
            max_allowed_packet=args.max_allowed_packet,
            hide_password=True
        )
        actual_args = cmdargs(
            mysqldump=args.mysqldump,
            username=args.username,
            password=password,
            database=db,
            verbose=args.verbose,
            with_drop_create_database=args.with_drop_create_database,
            max_allowed_packet=args.max_allowed_packet,
            hide_password=False
        )
        log.info("Executing: " + repr(display_args))
        log.info("Output file: " + repr(outfilename))
        try:
            with open(outfilename, "w") as f:
                subprocess.check_call(actual_args, stdout=f)
        except subprocess.CalledProcessError:
            os.remove(outfilename)
            log.critical("Failed!")
            sys.exit(1)
        output_files.append(outfilename)
    log.info("Done. See:\n" + "\n".join("    " + x for x in output_files))
    if args.with_drop_create_database:
        log.info("To restore: mysql -u USER -p < BACKUP.sql")
    else:
        log.info("To restore: mysql -u USER -p DATABASE < BACKUP.sql")