Build DB-API compatible connection arguments.

        Overrides interface
        :meth:`~sqlalchemy.engine.interfaces.Dialect.create_connect_args`.
494080
def create_connect_args(self, *args, **kwargs):
        
        default_args = {
            'sslmode': 'verify-full',
            'sslrootcert': pkg_resources.resource_filename(
                __name__,
                'redshift-ca-bundle.crt'
            ),
        }
        cargs, cparams = super(RedshiftDialect, self).create_connect_args(
            *args, **kwargs
        )
        default_args.update(cparams)
        return cargs, default_args
97459
def connectDb(engine   = dbeng,
              user     = dbuser,
              password = dbpwd,
              host     = dbhost,
              port     = dbport,
              database = dbname,
              params   = "?charset=utf8&use_unicode=1",
              echoopt  = False):
    
    return create_engine('%s://%s:%s@%s:%s/%s%s' % (engine, user, password, host, port, database, params), echo=echoopt)
256154
def create_db(url=None):
    
    if url is None:
        url = os.environ.get("DATABASE_URL")
    parsed_url = urlparse(url)
    db_name = parsed_url.path
    db_name = db_name.strip("/")
    db = connect("postgresql://" + parsed_url.netloc)
    # check that db does not exist
    q = """SELECT 1 as exists
           FROM pg_database
           WHERE datname = '{db_name}'""".format(
        db_name=db_name
    )
    if not db.query(q).fetchone():
        # CREATE DATABASE must be run outside of a transaction
        # https://stackoverflow.com/questions/6506578/how-to-create-a-new-database-using-sqlalchemy
        conn = db.engine.connect()
        conn.execute("commit")
        conn.execute("CREATE DATABASE " + db_name)
        conn.close()
766763
def connect(self, **kwargs):
        ''' 
        '''
        if 'database' not in kwargs:
            kwargs['database'] = 'ait'

        self._conn = self._backend.connect(kwargs['database'])
649857
def make_argparser():
    """"""

    if PY2:
        def unicode_arg(val):
            return val.decode(sys.getfilesystemencoding() or 'utf8')
    else:
        unicode_arg = str

    # Generic options
    p_main = ArgumentParser()
    generic = p_main.add_argument_group("generic arguments")
    generic.add_argument("-q", "--quiet",
                         action='store_true', dest='quiet', default=False,
                         help="silence information messages")
    generic.add_argument("-f", "--force",
                         action='store_true', dest='force', default=False,
                         help="Kill connections automatically if they prevent a command from executing. "
                              "Rename existing databases that are in the way.")
    generic.add_argument("--traceback", action='store_true', default=False,
                         help="print traceback when an error occurs")
    generic.add_argument("--host", metavar="HOST",
                         help="hostname of database server")
    generic.add_argument("-p", "--port", metavar="PORT", type=int,
                         help="port number of database server")

    sub = p_main.add_subparsers(metavar="COMMAND", dest='cmd')

    p_cp = sub.add_parser('cp', description=cmd_copy.__doc__,
                          help="Create a copy of a database within a server")
    p_mv = sub.add_parser('mv', description=cmd_move.__doc__,
                          help="Rename a database within a server")

    for p_cmd in (p_cp, p_mv):
        p_cmd.add_argument('src', metavar="SOURCE", type=unicode_arg,
                           help="source database name")
        p_cmd.add_argument('dest', metavar="DEST", type=unicode_arg,
                           help="destination database name")
        p_cmd.add_argument("--no-backup",
                           action='store_true', dest='no_backup', default=False,
                           help="drop existing DEST database if it exists")

    p_kill = sub.add_parser('kill', description=cmd_kill.__doc__,
                            help="Terminate active connections to a database")
    p_kill.add_argument('databases', metavar="DBNAME", type=unicode_arg, nargs='+',
                        help="kill connections on this database")

    p_reindex = sub.add_parser('reindex', description=cmd_reindex.__doc__,
                               help="Gracefully recreate an index")
    p_reindex.add_argument('-d', '--database', metavar="DB", type=unicode_arg,
                           help="apply reindex in this database")
    p_reindex.add_argument('indexes', metavar="IDXNAME", type=unicode_arg, nargs='+',
                           help="reindex these indexes")

    return p_main
651342
def wrap_connection(func_, *args, **kwargs):
    
    if not args[-1]:
        new_args = list(args)
        new_args[-1] = connect()
        args = tuple(new_args)
    return func_(*args, **kwargs)
715617
def get_mysql_args(db_config):
    
    db = db_config['NAME']

    mapping = [('--user={0}', db_config.get('USER')),
               ('--password={0}', db_config.get('PASSWORD')),
               ('--host={0}', db_config.get('HOST')),
               ('--port={0}', db_config.get('PORT'))]
    args = apply_arg_values(mapping)
    args.append(db)

    return args
692567
def create(self, **kwargs):
        
        raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource')
377456
def build(self, connection, grammar):
        
        for statement in self.to_sql(connection, grammar):
            connection.statement(statement)
171283
def create(cls, arg):
        
        obj = cls()
        obj._connection = arg.connection
        obj._heading = arg.heading.make_subquery_heading()
        obj._arg = arg
        return obj
143245
def _connect(self):
        
        # Attempt to get a cached connection from the connection pool
        try:
            connection = self._pool_manager.get(self.pid, self)
            LOGGER.debug("Re-using connection for %s", self.pid)
        except pool.NoIdleConnectionsError:
            if self._pool_manager.is_full(self.pid):
                raise

            # Create a new PostgreSQL connection
            kwargs = utils.uri_to_kwargs(self._uri)
            LOGGER.debug("Creating a new connection for %s", self.pid)
            connection = self._psycopg2_connect(kwargs)

            self._pool_manager.add(self.pid, connection)
            self._pool_manager.lock(self.pid, connection, self)

            # Added in because psycopg2ct connects and leaves the connection in
            # a weird state: consts.STATUS_DATESTYLE, returning from
            # Connection._setup without setting the state as const.STATUS_OK
            if utils.PYPY:
                connection.reset()

            # Register the custom data types
            self._register_unicode(connection)
            self._register_uuid(connection)

        return connection
1030133
def get_postgresql_args(db_config, extra_args=None):
    
    db = db_config['NAME']

    mapping = [('--username={0}', db_config.get('USER')),
               ('--host={0}', db_config.get('HOST')),
               ('--port={0}', db_config.get('PORT'))]
    args = apply_arg_values(mapping)

    if extra_args is not None:
        args.extend(shlex.split(extra_args))
    args.append(db)

    return args
887412
def _prepare_connection(**kwargs):
    '''
    
    '''
    init_args = {}
    fun_kwargs = {}
    netmiko_kwargs = __salt__['config.get']('netmiko', {})
    netmiko_kwargs.update(kwargs)  # merge the CLI args with the opts/pillar
    netmiko_init_args, _, _, netmiko_defaults = inspect.getargspec(BaseConnection.__init__)
    check_self = netmiko_init_args.pop(0)
    for karg, warg in six.iteritems(netmiko_kwargs):
        if karg not in netmiko_init_args:
            if warg is not None:
                fun_kwargs[karg] = warg
            continue
        if warg is not None:
            init_args[karg] = warg
    conn = ConnectHandler(**init_args)
    return conn, fun_kwargs
945372
def _get_connect_kwargs(self, host, port, user, password, database_url):
        
        if database_url:
            return {'dsn': database_url}

        if not host:
            raise CheckException("Please specify a PgBouncer host to connect to.")

        if not user:
            raise CheckException("Please specify a user to connect to PgBouncer as.")

        if host in ('localhost', '127.0.0.1') and password == '':
            # Use ident method
            return {'dsn': "user={} dbname={}".format(user, self.DB_NAME)}

        if port:
            return {'host': host, 'user': user, 'password': password, 'database': self.DB_NAME, 'port': port}

        return {'host': host, 'user': user, 'password': password, 'database': self.DB_NAME}
184186
def _connect(dbapi_connection, connection_record):
    """"""

    # If back end is sqlite
    if type(dbapi_connection) is sqlite3.Connection:

        # Respect foreign key constraints by default
        cursor = dbapi_connection.cursor()
        cursor.execute("PRAGMA foreign_keys=ON")
        cursor.close()
501355
def generate(args=None, namespace=None, file=None):
    
    if hasattr(args, 'split'):
        args = args.split()
    args = parser.parse_args(args, namespace)
    set_logging(args)
    logging.info(str(args))
    if args.dialect in ('pg', 'pgsql', 'postgres'):
        args.dialect = 'postgresql'
    if args.dialect.startswith('dj'):
        args.dialect = 'django'
    elif args.dialect.startswith('sqla'):
        args.dialect = 'sqlalchemy'

    if args.dialect not in dialect_names:
        raise NotImplementedError('First arg must be one of: %s' % ", ".join(dialect_names))
    if args.dialect == 'sqlalchemy':
        print(sqla_head, file=file)
    for datafile in args.datafile:
        if is_sqlalchemy_url.search(datafile):
            table_names_for_insert = []
            for tbl in sqlalchemy_table_sources(datafile):
                t = generate_one(tbl, args, table_name=tbl.generator.name, file=file)
                if t.data:
                    table_names_for_insert.append(tbl.generator.name)
            if args.inserts and args.dialect == 'sqlalchemy':
                print(sqla_inserter_call(table_names_for_insert), file=file)
            if t and args.inserts:
                for seq_update in emit_db_sequence_updates(t.source.db_engine):
                    if args.dialect == 'sqlalchemy':
                        print('    conn.execute("%s")' % seq_update, file=file)
                    elif args.dialect == 'postgresql':
                        print(seq_update, file=file)
        else:
            generate_one(datafile, args, file=file)
1244768
def do_sqlite_connect(dbapi_connection, connection_record):
    
    # Enable foreign key constraint checking
    cursor = dbapi_connection.cursor()
    cursor.execute('PRAGMA foreign_keys=ON')
    cursor.close()