def quote_identifier(identifier):
    """Quote an identifier, such as a table or role name.

    In SQL, identifiers are quoted using " rather than ' (which is reserved
    for strings).

    >>> print(quote_identifier('hello'))
    "hello"

    Quotes and Unicode are handled if you make use of them in your
    identifiers.

    >>> print(quote_identifier("'"))
    "'"
    >>> print(quote_identifier('"'))
    ""\""
    >>> print(quote_identifier("\\\\"))
    "\\"
    >>> print(quote_identifier('\\\\"'))
    "\\""\"
    >>> print(quote_identifier('\\\\ aargh \\u0441\\u043b\\u043e\\u043d'))
    U&"\\\\ aargh \\0441\\043b\\043e\\043d"
    """
    try:
        identifier_bytes = identifier.encode('ascii')
        return '"%s"' % identifier_bytes.replace(b'"', b'""').decode('ascii')
    except UnicodeEncodeError:
        escaped = []
        for c in identifier:
            if c == '\\':
                escaped.append(b'\\\\')
            elif c == '"':
                escaped.append(b'""')
            else:
                c = c.encode('ascii', 'backslashreplace')
                if c.startswith(b'\\u'):
                    c = b'\\' + c[2:]
                escaped.append(c)
        return 'U&"%s"' % b''.join(escaped).decode('ascii')
