def get_odbc_connection_string(conn, password):
    conn_params = get_connection_parameters(conn)
    if password is not None:
        conn_params['password'] = password  # TODO: Check password handling policy: When should we take this or the one in the parameters?
    connection_string_template = conn.driver.connectionStringTemplate or 'DRIVER={%driver%};SERVER=%hostName%;PORT=%port%;DATABASE={%schema%};UID=%userName%;PWD={%password%}'
    connection_string = replace_string_parameters(connection_string_template, conn_params)
    return connection_string
def odbc_conn_string(conn, strip_password = False):
    conn_params = dict(conn.parameterValues)
    conn_params.update(get_connection_parameters(conn))

    connection_string_template = conn.driver.connectionStringTemplate or 'DRIVER={%driver%};SERVER=%host%;PORT=%port%;DATABASE={%database%};UID=%username%;PWD={%password%}'
    connstring = replace_string_parameters(connection_string_template, conn_params)
    if strip_password:
        connstring = re.sub("(PWD={[^;]}*|PWD=[^;]*)", "", connstring).rstrip(";")
    return connstring
def odbc_conn_string(conn, strip_password = False):
    conn_params = dict(conn.parameterValues)
    conn_params.update(get_connection_parameters(conn))

    connection_string_template = conn.driver.connectionStringTemplate or 'DRIVER={%driver%};SERVER=%host%;PORT=%port%;DATABASE={%database%};UID=%username%;PWD={%password%}'
    connstring = replace_string_parameters(connection_string_template, conn_params)
    if strip_password:
        connstring = re.sub("(PWD={[^;]}*|PWD=[^;]*)", "", connstring).rstrip(";")
    return connstring
Beispiel #4
0
def get_odbc_connection_string(conn, password):
    conn_params = get_connection_parameters(conn)
    if password is not None:
        conn_params[
            'password'] = password  # TODO: Check password handling policy: When should we take this or the one in the parameters?
    connection_string_template = conn.driver.connectionStringTemplate or 'DRIVER={%driver%};SERVER=%hostName%;PORT=%port%;DATABASE={%schema%};UID=%userName%;PWD={%password%}'
    connection_string = replace_string_parameters(connection_string_template,
                                                  conn_params)
    return connection_string
Beispiel #5
0
    def connect(cls, connection, password):
        '''Establishes a connection to the server and stores the connection object in the connections pool.

        It first looks for a connection with the given connection parameters in the connections pool to
        reuse existent connections. If such connection is found it queries the server to ensure that the
        connection is alive and reestablishes it if is dead. If no suitable connection is found in the
        connections pool, a new one is created and stored in the pool.

        Parameters:
        ===========
            connection:  an object of the class db_mgmt_Connection storing the parameters
                         for the connection.
            password:    a string with the password to use for the connection (ignored for SQLite).
        '''
        con = None
        try:
            con = cls.get_connection(connection)
            try:
                if not con.cursor().execute('SELECT 1'):
                    raise Exception('connection error')
            except Exception, exc:
                grt.send_info(
                    'Connection to %s apparently lost, reconnecting...' %
                    connection.hostIdentifier)
                raise NotConnectedError('Connection error')
        except NotConnectedError, exc:
            grt.send_info('Connecting to %s...' % connection.hostIdentifier)
            if connection.driver.driverLibraryName == 'sqlanydb':
                import sqlanydbwrapper as sqlanydb  # Replace this to a direct sqlanydb import when it complies with PEP 249
                connstr = replace_string_parameters(
                    connection.driver.connectionStringTemplate,
                    dict(connection.parameterValues))
                import ast
                try:
                    all_params_dict = ast.literal_eval(connstr)
                except Exception, exc:
                    grt.send_error(
                        'The given connection string is not a valid python dict: %s'
                        % connstr)
                    raise
                # Remove unreplaced parameters:
                params = dict(
                    (key, value) for key, value in all_params_dict.iteritems()
                    if not (value.startswith('%') and value.endswith('%')))
                params['password'] = password
                conn_params = dict(params)
                conn_params['password'] = '******'
                connection.parameterValues[
                    'wbcopytables_connection_string'] = repr(conn_params)

                con = sqlanydb.connect(**params)
    def connect(cls, connection, password):
        """Establishes a connection to the server and stores the connection object in the connections pool.

        It first looks for a connection with the given connection parameters in the connections pool to
        reuse existent connections. If such connection is found it queries the server to ensure that the
        connection is alive and reestablishes it if is dead. If no suitable connection is found in the
        connections pool, a new one is created and stored in the pool.

        Parameters:
        ===========
            connection:  an object of the class db_mgmt_Connection storing the parameters
                         for the connection.
            password:    a string with the password to use for the connection (ignored for SQLite).
        """
        con = None
        try:
            con = cls.get_connection(connection)
            try:
                if not con.cursor().execute("SELECT 1"):
                    raise Exception("connection error")
            except Exception, exc:
                grt.send_info("Connection to %s apparently lost, reconnecting..." % connection.hostIdentifier)
                raise NotConnectedError("Connection error")
        except NotConnectedError, exc:
            grt.send_info("Connecting to %s..." % connection.hostIdentifier)
            if connection.driver.driverLibraryName == "sqlanydb":
                import sqlanydbwrapper as sqlanydb  # Replace this to a direct sqlanydb import when it complies with PEP 249

                connstr = replace_string_parameters(
                    connection.driver.connectionStringTemplate, dict(connection.parameterValues)
                )
                import ast

                try:
                    all_params_dict = ast.literal_eval(connstr)
                except Exception, exc:
                    grt.send_error("The given connection string is not a valid python dict: %s" % connstr)
                    raise
                # Remove unreplaced parameters:
                params = dict(
                    (key, value)
                    for key, value in all_params_dict.iteritems()
                    if not (value.startswith("%") and value.endswith("%"))
                )
                params["password"] = password
                conn_params = dict(params)
                conn_params["password"] = "******"
                connection.parameterValues["wbcopytables_connection_string"] = repr(conn_params)

                con = sqlanydb.connect(**params)
def request_password(connection, forget_old = False):
    # Get the password:
    for param in connection.driver.parameters:
        if param.paramType in ('keychain', 'password'):
            if param.paramType == 'keychain':
                connection_params = get_connection_parameters(connection, do_not_transform=True)
                storage_key_format = param.paramTypeDetails['storageKeyFormat']
                username, storage_string = replace_string_parameters(storage_key_format, connection_params).split('::', 1)
                accepted, passwd = mforms.Utilities.find_or_ask_for_password('Enter password for user ' + username, storage_string, username, forget_old)
                if accepted:
                    return passwd
            else: # Plain password field
                return connection.parameterValues['password']
            break
    return None
def request_password(connection, forget_old = False):
    # Get the password:
    for param in connection.driver.parameters:
        if param.paramType in ('keychain', 'password'):
            if param.paramType == 'keychain':
                connection_params = get_connection_parameters(connection, do_not_transform=True)
                storage_key_format = param.paramTypeDetails['storageKeyFormat']
                username, storage_string = replace_string_parameters(storage_key_format, connection_params).split('::', 1)
                accepted, passwd = mforms.Utilities.find_or_ask_for_password('Enter password for user ' + username, storage_string, username, forget_old)
                if accepted:
                    return passwd
            else: # Plain password field
                return connection.parameterValues['password']
            break
    return None
Beispiel #9
0
    def connect(cls, connection, password):
        '''Establishes a connection to the server and stores the connection object in the connections pool.

        It first looks for a connection with the given connection parameters in the connections pool to
        reuse existent connections. If such connection is found it queries the server to ensure that the
        connection is alive and reestablishes it if is dead. If no suitable connection is found in the
        connections pool, a new one is created and stored in the pool.

        Parameters:
        ===========
            connection:  an object of the class db_mgmt_Connection storing the parameters
                         for the connection.
            password:    a string with the password to use for the connection (ignored for SQLite).
        '''
        con = None
        try:
            con = cls.get_connection(connection)
            try:
                if not con.cursor().execute('SELECT 1'):
                    raise Exception('connection error')
            except Exception as exc:
                grt.send_info(
                    'Connection to %s apparently lost, reconnecting...' %
                    connection.hostIdentifier)
                raise NotConnectedError('Connection error')
        except NotConnectedError as exc:
            grt.send_info('Connecting to %s...' % connection.hostIdentifier)
            if connection.driver.driverLibraryName == 'sqlanydb':
                import sqlanydbwrapper as sqlanydb  # Replace this to a direct sqlanydb import when it complies with PEP 249
                connstr = replace_string_parameters(
                    connection.driver.connectionStringTemplate,
                    dict(connection.parameterValues))
                import ast
                try:
                    all_params_dict = ast.literal_eval(connstr)
                except Exception as exc:
                    grt.send_error(
                        'The given connection string is not a valid python dict: %s'
                        % connstr)
                    raise
                # Remove unreplaced parameters:
                params = dict(
                    (key, value)
                    for key, value in list(all_params_dict.items())
                    if not (value.startswith('%') and value.endswith('%')))
                params['password'] = password
                conn_params = dict(params)
                conn_params['password'] = '******'
                connection.parameterValues[
                    'wbcopytables_connection_string'] = repr(conn_params)

                con = sqlanydb.connect(**params)
            else:
                con = db_driver.connect(connection, password)
            if not con:
                grt.send_error('Connection failed', str(exc))
                raise
            grt.send_info('Connected')
            cls._connections[connection.__id__] = {'connection': con}
        if con:
            ver = cls.execute_query(connection,
                                    "SELECT @@version").fetchone()[0]
            grt.log_info("SQLAnywhere RE",
                         "Connected to %s, %s\n" % (connection.name, ver))
            ver_parts = server_version_str2tuple(ver) + (0, 0, 0, 0)
            version = grt.classes.GrtVersion()
            version.majorNumber, version.minorNumber, version.releaseNumber, version.buildNumber = ver_parts[:
                                                                                                             4]
            cls._connections[connection.__id__]["version"] = version

        return 1