[
  {
    "path": ".gitattributes",
    "content": "pg8000/_version.py export-subst\n"
  },
  {
    "path": ".gitignore",
    "content": "*.py[co]\n*.swp\n*.orig\n*.class\nbuild\npg8000.egg-info\ntmp\ndist\n.tox\nMANIFEST\nvenv\n.cache\n"
  },
  {
    "path": ".travis.yml",
    "content": "sudo: required\nlanguage: python\npython:\n  - \"2.7\"\n  - \"3.5\"\n  - \"3.6\"\n  - \"pypy3.5\"\n\nenv:\n  - DB=\"9.5\"\n  - DB=\"9.6\"\n\nservices:\n  - postgresql\naddons:\n  postgresql: \"9.5\"\n  postgresql: \"9.6\"\n\nbefore_install:\n  - sudo service postgresql stop\n  - cd /etc/postgresql/$DB/main\n  - sudo chmod ugo+rw pg_hba.conf\n  - sudo cp pg_hba.conf old_pg_hba.conf\n  - sudo echo \"host pg8000_md5 all 127.0.0.1/32 md5\" > pg_hba.conf\n  - sudo echo \"host pg8000_gss all 127.0.0.1/32 gss\" >> pg_hba.conf\n  - sudo echo \"host pg8000_password all 127.0.0.1/32 password\" >> pg_hba.conf\n  - cat old_pg_hba.conf >> pg_hba.conf\n  - sudo service postgresql start $DB\n  - psql -U postgres -tc 'create extension hstore;'\n  - psql -U postgres -tc 'show server_version;'\n  - psql -U postgres -tc \"alter user postgres with password 'pw';\"\n  - psql -U postgres -tc \"alter system set client_min_messages = notice;\"\n  - sudo service postgresql reload $DB\n  - psql -U postgres -tc 'show client_min_messages;'\n  - cd $TRAVIS_BUILD_DIR\n\ninstall:\n  - pip install nose\n  - pip install pytz\n\nscript:\n  - nosetests\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2007-2009, Mathieu Fenniak\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n* Redistributions of source code must retain the above copyright notice,\nthis list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand/or other materials provided with the distribution.\n* The name of the author may not be used to endorse or promote products\nderived from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "include README.creole\ninclude versioneer.py\ninclude pg8000/_version.py\ninclude LICENSE\ninclude doc/*\n"
  },
  {
    "path": "README.adoc",
    "content": "= pg8000\n\nHello, the pg8000 repository has moved to https://github.com/tlocke/pg8000.\n"
  },
  {
    "path": "multi",
    "content": "#!/bin/bash\n\n# set postgres share memory to minimum to trigger unpinned buffer errors.\n\nfor i in {1..100}\ndo\n\tpython -m pg8000.tests.stress &\ndone\nwait\necho \"All processes done!\"\n"
  },
  {
    "path": "pg8000/__init__.py",
    "content": "from pg8000.core import (\n    Warning, Bytea, DataError, DatabaseError, InterfaceError, ProgrammingError,\n    Error, OperationalError, IntegrityError, InternalError, NotSupportedError,\n    ArrayContentNotHomogenousError, ArrayDimensionsNotConsistentError,\n    ArrayContentNotSupportedError, utc, Connection, Cursor, Binary, Date,\n    DateFromTicks, Time, TimeFromTicks, Timestamp, TimestampFromTicks, BINARY,\n    Interval, PGEnum, PGJson, PGJsonb, PGTsvector, PGText, PGVarchar)\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n\n# Copyright (c) 2007-2009, Mathieu Fenniak\n# Copyright (c) The Contributors\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * The name of the author may not be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n__author__ = \"Mathieu Fenniak\"\n\n\ndef connect(\n        user, host='localhost', unix_sock=None, port=5432, database=None,\n        password=None, ssl=False, timeout=None, application_name=None,\n        max_prepared_statements=1000):\n    \"\"\"Creates a connection to a PostgreSQL database.\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_; however, the arguments of the\n    function are not defined by the specification.\n\n    :param user:\n        The username to connect to the PostgreSQL server with.\n\n        If your server character encoding is not ``ascii`` or ``utf8``, then\n        you need to provide ``user`` as bytes, eg.\n        ``\"my_name\".encode('EUC-JP')``.\n\n    :keyword host:\n        The hostname of the PostgreSQL server to connect with.  Providing this\n        parameter is necessary for TCP/IP connections.  One of either ``host``\n        or ``unix_sock`` must be provided. The default is ``localhost``.\n\n    :keyword unix_sock:\n        The path to the UNIX socket to access the database through, for\n        example, ``'/tmp/.s.PGSQL.5432'``.  One of either ``host`` or\n        ``unix_sock`` must be provided.\n\n    :keyword port:\n        The TCP/IP port of the PostgreSQL server instance.  This parameter\n        defaults to ``5432``, the registered common port of PostgreSQL TCP/IP\n        servers.\n\n    :keyword database:\n        The name of the database instance to connect with.  This parameter is\n        optional; if omitted, the PostgreSQL server will assume the database\n        name is the same as the username.\n\n        If your server character encoding is not ``ascii`` or ``utf8``, then\n        you need to provide ``database`` as bytes, eg.\n        ``\"my_db\".encode('EUC-JP')``.\n\n    :keyword password:\n        The user password to connect to the server with.  This parameter is\n        optional; if omitted and the database server requests password-based\n        authentication, the connection will fail to open.  If this parameter\n        is provided but not requested by the server, no error will occur.\n\n        If your server character encoding is not ``ascii`` or ``utf8``, then\n        you need to provide ``user`` as bytes, eg.\n        ``\"my_password\".encode('EUC-JP')``.\n\n    :keyword application_name:\n        The name will be displayed in the pg_stat_activity view.\n        This parameter is optional.\n\n    :keyword ssl:\n        Use SSL encryption for TCP/IP sockets if ``True``.  Defaults to\n        ``False``.\n\n    :keyword timeout:\n        Only used with Python 3, this is the time in seconds before the\n        connection to the database will time out. The default is ``None`` which\n        means no timeout.\n\n    :rtype:\n        A :class:`Connection` object.\n    \"\"\"\n    return Connection(\n        user, host, unix_sock, port, database, password, ssl, timeout,\n        application_name, max_prepared_statements)\n\n\napilevel = \"2.0\"\n\"\"\"The DBAPI level supported, currently \"2.0\".\n\nThis property is part of the `DBAPI 2.0 specification\n<http://www.python.org/dev/peps/pep-0249/>`_.\n\"\"\"\n\nthreadsafety = 1\n\"\"\"Integer constant stating the level of thread safety the DBAPI interface\nsupports. This DBAPI module supports sharing of the module only. Connections\nand cursors my not be shared between threads. This gives pg8000 a threadsafety\nvalue of 1.\n\nThis property is part of the `DBAPI 2.0 specification\n<http://www.python.org/dev/peps/pep-0249/>`_.\n\"\"\"\n\nparamstyle = 'format'\n\nmax_prepared_statements = 1000\n\n# I have no idea what this would be used for by a client app.  Should it be\n# TEXT, VARCHAR, CHAR?  It will only compare against row_description's\n# type_code if it is this one type.  It is the varchar type oid for now, this\n# appears to match expectations in the DB API 2.0 compliance test suite.\n\nSTRING = 1043\n\"\"\"String type oid.\"\"\"\n\n\nNUMBER = 1700\n\"\"\"Numeric type oid\"\"\"\n\nDATETIME = 1114\n\"\"\"Timestamp type oid\"\"\"\n\nROWID = 26\n\"\"\"ROWID type oid\"\"\"\n\n__all__ = [\n    Warning, Bytea, DataError, DatabaseError, connect, InterfaceError,\n    ProgrammingError, Error, OperationalError, IntegrityError, InternalError,\n    NotSupportedError, ArrayContentNotHomogenousError,\n    ArrayDimensionsNotConsistentError, ArrayContentNotSupportedError, utc,\n    Connection, Cursor, Binary, Date, DateFromTicks, Time, TimeFromTicks,\n    Timestamp, TimestampFromTicks, BINARY, Interval, PGEnum, PGJson, PGJsonb,\n    PGTsvector, PGText, PGVarchar]\n\n\"\"\"Version string for pg8000.\n\n    .. versionadded:: 1.9.11\n\"\"\"\n"
  },
  {
    "path": "pg8000/_version.py",
    "content": "\n# This file helps to compute a version number in source trees obtained from\n# git-archive tarball (such as those provided by githubs download-from-tag\n# feature). Distribution tarballs (built by setup.py sdist) and build\n# directories (produced by setup.py build) will contain a much shorter file\n# that just contains the computed version number.\n\n# This file is released into the public domain. Generated by\n# versioneer-0.15 (https://github.com/warner/python-versioneer)\n\nimport errno\nimport os\nimport re\nimport subprocess\nimport sys\n\n\ndef get_keywords():\n    # these strings will be replaced by git during git-archive.\n    # setup.py/versioneer.py will grep for the variable names, so they must\n    # each be defined on a line of their own. _version.py will just call\n    # get_keywords().\n    git_refnames = \"$Format:%d$\"\n    git_full = \"$Format:%H$\"\n    keywords = {\"refnames\": git_refnames, \"full\": git_full}\n    return keywords\n\n\nclass VersioneerConfig:\n    pass\n\n\ndef get_config():\n    # these strings are filled in when 'setup.py versioneer' creates\n    # _version.py\n    cfg = VersioneerConfig()\n    cfg.VCS = \"git\"\n    cfg.style = \"pep440\"\n    cfg.tag_prefix = \"\"\n    cfg.parentdir_prefix = \"pg8000-\"\n    cfg.versionfile_source = \"pg8000/_version.py\"\n    cfg.verbose = False\n    return cfg\n\n\nclass NotThisMethod(Exception):\n    pass\n\n\nLONG_VERSION_PY = {}\nHANDLERS = {}\n\n\ndef register_vcs_handler(vcs, method):  # decorator\n    def decorate(f):\n        if vcs not in HANDLERS:\n            HANDLERS[vcs] = {}\n        HANDLERS[vcs][method] = f\n        return f\n    return decorate\n\n\ndef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):\n    assert isinstance(commands, list)\n    p = None\n    for c in commands:\n        try:\n            dispcmd = str([c] + args)\n            # remember shell=False, so use git.cmd on windows, not just git\n            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,\n                                 stderr=(subprocess.PIPE if hide_stderr\n                                         else None))\n            break\n        except EnvironmentError:\n            e = sys.exc_info()[1]\n            if e.errno == errno.ENOENT:\n                continue\n            if verbose:\n                print(\"unable to run %s\" % dispcmd)\n                print(e)\n            return None\n    else:\n        if verbose:\n            print(\"unable to find command, tried %s\" % (commands,))\n        return None\n    stdout = p.communicate()[0].strip()\n    if sys.version_info[0] >= 3:\n        stdout = stdout.decode()\n    if p.returncode != 0:\n        if verbose:\n            print(\"unable to run %s (error)\" % dispcmd)\n        return None\n    return stdout\n\n\ndef versions_from_parentdir(parentdir_prefix, root, verbose):\n    # Source tarballs conventionally unpack into a directory that includes\n    # both the project name and a version string.\n    dirname = os.path.basename(root)\n    if not dirname.startswith(parentdir_prefix):\n        if verbose:\n            print(\"guessing rootdir is '%s', but '%s' doesn't start with \"\n                  \"prefix '%s'\" % (root, dirname, parentdir_prefix))\n        raise NotThisMethod(\"rootdir doesn't start with parentdir_prefix\")\n    return {\"version\": dirname[len(parentdir_prefix):],\n            \"full-revisionid\": None,\n            \"dirty\": False, \"error\": None}\n\n\n@register_vcs_handler(\"git\", \"get_keywords\")\ndef git_get_keywords(versionfile_abs):\n    # the code embedded in _version.py can just fetch the value of these\n    # keywords. When used from setup.py, we don't want to import _version.py,\n    # so we do it with a regexp instead. This function is not used from\n    # _version.py.\n    keywords = {}\n    try:\n        f = open(versionfile_abs, \"r\")\n        for line in f.readlines():\n            if line.strip().startswith(\"git_refnames =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"refnames\"] = mo.group(1)\n            if line.strip().startswith(\"git_full =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"full\"] = mo.group(1)\n        f.close()\n    except EnvironmentError:\n        pass\n    return keywords\n\n\n@register_vcs_handler(\"git\", \"keywords\")\ndef git_versions_from_keywords(keywords, tag_prefix, verbose):\n    if not keywords:\n        raise NotThisMethod(\"no keywords at all, weird\")\n    refnames = keywords[\"refnames\"].strip()\n    if refnames.startswith(\"$Format\"):\n        if verbose:\n            print(\"keywords are unexpanded, not using\")\n        raise NotThisMethod(\"unexpanded keywords, not a git-archive tarball\")\n    refs = set([r.strip() for r in refnames.strip(\"()\").split(\",\")])\n    # starting in git-1.8.3, tags are listed as \"tag: foo-1.0\" instead of\n    # just \"foo-1.0\". If we see a \"tag: \" prefix, prefer those.\n    TAG = \"tag: \"\n    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])\n    if not tags:\n        # Either we're using git < 1.8.3, or there really are no tags. We use\n        # a heuristic: assume all version tags have a digit. The old git %d\n        # expansion behaves like git log --decorate=short and strips out the\n        # refs/heads/ and refs/tags/ prefixes that would let us distinguish\n        # between branches and tags. By ignoring refnames without digits, we\n        # filter out many common branch names like \"release\" and\n        # \"stabilization\", as well as \"HEAD\" and \"master\".\n        tags = set([r for r in refs if re.search(r'\\d', r)])\n        if verbose:\n            print(\"discarding '%s', no digits\" % \",\".join(refs-tags))\n    if verbose:\n        print(\"likely tags: %s\" % \",\".join(sorted(tags)))\n    for ref in sorted(tags):\n        # sorting will prefer e.g. \"2.0\" over \"2.0rc1\"\n        if ref.startswith(tag_prefix):\n            r = ref[len(tag_prefix):]\n            if verbose:\n                print(\"picking %s\" % r)\n            return {\"version\": r,\n                    \"full-revisionid\": keywords[\"full\"].strip(),\n                    \"dirty\": False, \"error\": None\n                    }\n    # no suitable tags, so version is \"0+unknown\", but full hex is still there\n    if verbose:\n        print(\"no suitable tags, using unknown + full revision id\")\n    return {\"version\": \"0+unknown\",\n            \"full-revisionid\": keywords[\"full\"].strip(),\n            \"dirty\": False, \"error\": \"no suitable tags\"}\n\n\n@register_vcs_handler(\"git\", \"pieces_from_vcs\")\ndef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n    # this runs 'git' from the root of the source tree. This only gets called\n    # if the git-archive 'subst' keywords were *not* expanded, and\n    # _version.py hasn't already been rewritten with a short version string,\n    # meaning we're inside a checked out source tree.\n\n    if not os.path.exists(os.path.join(root, \".git\")):\n        if verbose:\n            print(\"no .git in %s\" % root)\n        raise NotThisMethod(\"no .git directory\")\n\n    GITS = [\"git\"]\n    if sys.platform == \"win32\":\n        GITS = [\"git.cmd\", \"git.exe\"]\n    # if there is a tag, this yields TAG-NUM-gHEX[-dirty]\n    # if there are no tags, this yields HEX[-dirty] (no NUM)\n    describe_out = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n                                      \"--always\", \"--long\"],\n                               cwd=root)\n    # --long was added in git-1.5.5\n    if describe_out is None:\n        raise NotThisMethod(\"'git describe' failed\")\n    describe_out = describe_out.strip()\n    full_out = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n    if full_out is None:\n        raise NotThisMethod(\"'git rev-parse' failed\")\n    full_out = full_out.strip()\n\n    pieces = {}\n    pieces[\"long\"] = full_out\n    pieces[\"short\"] = full_out[:7]  # maybe improved later\n    pieces[\"error\"] = None\n\n    # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]\n    # TAG might have hyphens.\n    git_describe = describe_out\n\n    # look for -dirty suffix\n    dirty = git_describe.endswith(\"-dirty\")\n    pieces[\"dirty\"] = dirty\n    if dirty:\n        git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n    # now we have TAG-NUM-gHEX or HEX\n\n    if \"-\" in git_describe:\n        # TAG-NUM-gHEX\n        mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n        if not mo:\n            # unparseable. Maybe git-describe is misbehaving?\n            pieces[\"error\"] = (\"unable to parse git-describe output: '%s'\"\n                               % describe_out)\n            return pieces\n\n        # tag\n        full_tag = mo.group(1)\n        if not full_tag.startswith(tag_prefix):\n            if verbose:\n                fmt = \"tag '%s' doesn't start with prefix '%s'\"\n                print(fmt % (full_tag, tag_prefix))\n            pieces[\"error\"] = (\"tag '%s' doesn't start with prefix '%s'\"\n                               % (full_tag, tag_prefix))\n            return pieces\n        pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n        # distance: number of commits since tag\n        pieces[\"distance\"] = int(mo.group(2))\n\n        # commit: short hex revision ID\n        pieces[\"short\"] = mo.group(3)\n\n    else:\n        # HEX: no tags\n        pieces[\"closest-tag\"] = None\n        count_out = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n                                cwd=root)\n        pieces[\"distance\"] = int(count_out)  # total number of commits\n\n    return pieces\n\n\ndef plus_or_dot(pieces):\n    if \"+\" in pieces.get(\"closest-tag\", \"\"):\n        return \".\"\n    return \"+\"\n\n\ndef render_pep440(pieces):\n    # now build up version string, with post-release \"local version\n    # identifier\". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you\n    # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty\n\n    # exceptions:\n    # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += plus_or_dot(pieces)\n            rendered += \"%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n            if pieces[\"dirty\"]:\n                rendered += \".dirty\"\n    else:\n        # exception #1\n        rendered = \"0+untagged.%d.g%s\" % (pieces[\"distance\"],\n                                          pieces[\"short\"])\n        if pieces[\"dirty\"]:\n            rendered += \".dirty\"\n    return rendered\n\n\ndef render_pep440_pre(pieces):\n    # TAG[.post.devDISTANCE] . No -dirty\n\n    # exceptions:\n    # 1: no tags. 0.post.devDISTANCE\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \".post.dev%d\" % pieces[\"distance\"]\n    else:\n        # exception #1\n        rendered = \"0.post.dev%d\" % pieces[\"distance\"]\n    return rendered\n\n\ndef render_pep440_post(pieces):\n    # TAG[.postDISTANCE[.dev0]+gHEX] . The \".dev0\" means dirty. Note that\n    # .dev0 sorts backwards (a dirty tree will appear \"older\" than the\n    # corresponding clean one), but you shouldn't be releasing software with\n    # -dirty anyways.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%d\" % pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n            rendered += plus_or_dot(pieces)\n            rendered += \"g%s\" % pieces[\"short\"]\n    else:\n        # exception #1\n        rendered = \"0.post%d\" % pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n        rendered += \"+g%s\" % pieces[\"short\"]\n    return rendered\n\n\ndef render_pep440_old(pieces):\n    # TAG[.postDISTANCE[.dev0]] . The \".dev0\" means dirty.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%d\" % pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n    else:\n        # exception #1\n        rendered = \"0.post%d\" % pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n    return rendered\n\n\ndef render_git_describe(pieces):\n    # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty\n    # --always'\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render_git_describe_long(pieces):\n    # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty\n    # --always -long'. The distance/hash is unconditional.\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render(pieces, style):\n    if pieces[\"error\"]:\n        return {\"version\": \"unknown\",\n                \"full-revisionid\": pieces.get(\"long\"),\n                \"dirty\": None,\n                \"error\": pieces[\"error\"]}\n\n    if not style or style == \"default\":\n        style = \"pep440\"  # the default\n\n    if style == \"pep440\":\n        rendered = render_pep440(pieces)\n    elif style == \"pep440-pre\":\n        rendered = render_pep440_pre(pieces)\n    elif style == \"pep440-post\":\n        rendered = render_pep440_post(pieces)\n    elif style == \"pep440-old\":\n        rendered = render_pep440_old(pieces)\n    elif style == \"git-describe\":\n        rendered = render_git_describe(pieces)\n    elif style == \"git-describe-long\":\n        rendered = render_git_describe_long(pieces)\n    else:\n        raise ValueError(\"unknown style '%s'\" % style)\n\n    return {\"version\": rendered, \"full-revisionid\": pieces[\"long\"],\n            \"dirty\": pieces[\"dirty\"], \"error\": None}\n\n\ndef get_versions():\n    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have\n    # __file__, we can work backwards from there to the root. Some\n    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which\n    # case we can only use expanded keywords.\n\n    cfg = get_config()\n    verbose = cfg.verbose\n\n    try:\n        return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,\n                                          verbose)\n    except NotThisMethod:\n        pass\n\n    try:\n        root = os.path.realpath(__file__)\n        # versionfile_source is the relative path from the top of the source\n        # tree (where the .git directory might live) to this file. Invert\n        # this to find the root from __file__.\n        for i in cfg.versionfile_source.split('/'):\n            root = os.path.dirname(root)\n    except NameError:\n        return {\"version\": \"0+unknown\", \"full-revisionid\": None,\n                \"dirty\": None,\n                \"error\": \"unable to find root of source tree\"}\n\n    try:\n        pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)\n        return render(pieces, cfg.style)\n    except NotThisMethod:\n        pass\n\n    try:\n        if cfg.parentdir_prefix:\n            return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)\n    except NotThisMethod:\n        pass\n\n    return {\"version\": \"0+unknown\", \"full-revisionid\": None,\n            \"dirty\": None,\n            \"error\": \"unable to compute version\"}\n"
  },
  {
    "path": "pg8000/core.py",
    "content": "from datetime import (\n    timedelta as Timedelta, datetime as Datetime, tzinfo, date, time)\nfrom warnings import warn\nimport socket\nfrom struct import pack\nfrom hashlib import md5\nfrom decimal import Decimal\nfrom collections import deque, defaultdict\nfrom itertools import count, islice\nfrom six.moves import map\nfrom six import (\n    b, PY2, integer_types, next, text_type, u, binary_type, itervalues,\n    iteritems)\nfrom uuid import UUID\nfrom copy import deepcopy\nfrom calendar import timegm\nfrom distutils.version import LooseVersion\nfrom struct import Struct\nfrom time import localtime\nimport pg8000\nfrom json import loads, dumps\nfrom os import getpid\n\n\n# Copyright (c) 2007-2009, Mathieu Fenniak\n# Copyright (c) The Contributors\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * The name of the author may not be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\n__author__ = \"Mathieu Fenniak\"\n\n\nZERO = Timedelta(0)\n\n\nclass UTC(tzinfo):\n\n    def utcoffset(self, dt):\n        return ZERO\n\n    def tzname(self, dt):\n        return \"UTC\"\n\n    def dst(self, dt):\n        return ZERO\n\n\nutc = UTC()\n\n\nclass Interval(object):\n    \"\"\"An Interval represents a measurement of time.  In PostgreSQL, an\n    interval is defined in the measure of months, days, and microseconds; as\n    such, the pg8000 interval type represents the same information.\n\n    Note that values of the :attr:`microseconds`, :attr:`days` and\n    :attr:`months` properties are independently measured and cannot be\n    converted to each other.  A month may be 28, 29, 30, or 31 days, and a day\n    may occasionally be lengthened slightly by a leap second.\n\n    .. attribute:: microseconds\n\n        Measure of microseconds in the interval.\n\n        The microseconds value is constrained to fit into a signed 64-bit\n        integer.  Any attempt to set a value too large or too small will result\n        in an OverflowError being raised.\n\n    .. attribute:: days\n\n        Measure of days in the interval.\n\n        The days value is constrained to fit into a signed 32-bit integer.\n        Any attempt to set a value too large or too small will result in an\n        OverflowError being raised.\n\n    .. attribute:: months\n\n        Measure of months in the interval.\n\n        The months value is constrained to fit into a signed 32-bit integer.\n        Any attempt to set a value too large or too small will result in an\n        OverflowError being raised.\n    \"\"\"\n\n    def __init__(self, microseconds=0, days=0, months=0):\n        self.microseconds = microseconds\n        self.days = days\n        self.months = months\n\n    def _setMicroseconds(self, value):\n        if not isinstance(value, integer_types):\n            raise TypeError(\"microseconds must be an integer type\")\n        elif not (min_int8 < value < max_int8):\n            raise OverflowError(\n                \"microseconds must be representable as a 64-bit integer\")\n        else:\n            self._microseconds = value\n\n    def _setDays(self, value):\n        if not isinstance(value, integer_types):\n            raise TypeError(\"days must be an integer type\")\n        elif not (min_int4 < value < max_int4):\n            raise OverflowError(\n                \"days must be representable as a 32-bit integer\")\n        else:\n            self._days = value\n\n    def _setMonths(self, value):\n        if not isinstance(value, integer_types):\n            raise TypeError(\"months must be an integer type\")\n        elif not (min_int4 < value < max_int4):\n            raise OverflowError(\n                \"months must be representable as a 32-bit integer\")\n        else:\n            self._months = value\n\n    microseconds = property(lambda self: self._microseconds, _setMicroseconds)\n    days = property(lambda self: self._days, _setDays)\n    months = property(lambda self: self._months, _setMonths)\n\n    def __repr__(self):\n        return \"<Interval %s months %s days %s microseconds>\" % (\n            self.months, self.days, self.microseconds)\n\n    def __eq__(self, other):\n        return other is not None and isinstance(other, Interval) and \\\n            self.months == other.months and self.days == other.days and \\\n            self.microseconds == other.microseconds\n\n    def __neq__(self, other):\n        return not self.__eq__(other)\n\n\nclass PGType(object):\n    def __init__(self, value):\n        self.value = value\n\n    def encode(self, encoding):\n        return str(self.value).encode(encoding)\n\n\nclass PGEnum(PGType):\n    def __init__(self, value):\n        if isinstance(value, str):\n            self.value = value\n        else:\n            self.value = value.value\n\n\nclass PGJson(PGType):\n    def encode(self, encoding):\n        return dumps(self.value).encode(encoding)\n\n\nclass PGJsonb(PGType):\n    def encode(self, encoding):\n        return dumps(self.value).encode(encoding)\n\n\nclass PGTsvector(PGType):\n    pass\n\n\nclass PGVarchar(str):\n    pass\n\n\nclass PGText(str):\n    pass\n\n\ndef pack_funcs(fmt):\n    struc = Struct('!' + fmt)\n    return struc.pack, struc.unpack_from\n\n\ni_pack, i_unpack = pack_funcs('i')\nh_pack, h_unpack = pack_funcs('h')\nq_pack, q_unpack = pack_funcs('q')\nd_pack, d_unpack = pack_funcs('d')\nf_pack, f_unpack = pack_funcs('f')\niii_pack, iii_unpack = pack_funcs('iii')\nii_pack, ii_unpack = pack_funcs('ii')\nqii_pack, qii_unpack = pack_funcs('qii')\ndii_pack, dii_unpack = pack_funcs('dii')\nihihih_pack, ihihih_unpack = pack_funcs('ihihih')\nci_pack, ci_unpack = pack_funcs('ci')\nbh_pack, bh_unpack = pack_funcs('bh')\ncccc_pack, cccc_unpack = pack_funcs('cccc')\n\n\nmin_int2, max_int2 = -2 ** 15, 2 ** 15\nmin_int4, max_int4 = -2 ** 31, 2 ** 31\nmin_int8, max_int8 = -2 ** 63, 2 ** 63\n\n\nclass Warning(Exception):\n    \"\"\"Generic exception raised for important database warnings like data\n    truncations.  This exception is not currently used by pg8000.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass Error(Exception):\n    \"\"\"Generic exception that is the base exception of all other error\n    exceptions.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass InterfaceError(Error):\n    \"\"\"Generic exception raised for errors that are related to the database\n    interface rather than the database itself.  For example, if the interface\n    attempts to use an SSL connection but the server refuses, an InterfaceError\n    will be raised.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass DatabaseError(Error):\n    \"\"\"Generic exception raised for errors that are related to the database.\n    This exception is currently never raised by pg8000.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass DataError(DatabaseError):\n    \"\"\"Generic exception raised for errors that are due to problems with the\n    processed data.  This exception is not currently raised by pg8000.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass OperationalError(DatabaseError):\n    \"\"\"\n    Generic exception raised for errors that are related to the database's\n    operation and not necessarily under the control of the programmer. This\n    exception is currently never raised by pg8000.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass IntegrityError(DatabaseError):\n    \"\"\"\n    Generic exception raised when the relational integrity of the database is\n    affected.  This exception is not currently raised by pg8000.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass InternalError(DatabaseError):\n    \"\"\"Generic exception raised when the database encounters an internal error.\n    This is currently only raised when unexpected state occurs in the pg8000\n    interface itself, and is typically the result of a interface bug.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass ProgrammingError(DatabaseError):\n    \"\"\"Generic exception raised for programming errors.  For example, this\n    exception is raised if more parameter fields are in a query string than\n    there are available parameters.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass NotSupportedError(DatabaseError):\n    \"\"\"Generic exception raised in case a method or database API was used which\n    is not supported by the database.\n\n    This exception is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n    pass\n\n\nclass ArrayContentNotSupportedError(NotSupportedError):\n    \"\"\"\n    Raised when attempting to transmit an array where the base type is not\n    supported for binary data transfer by the interface.\n    \"\"\"\n    pass\n\n\nclass ArrayContentNotHomogenousError(ProgrammingError):\n    \"\"\"\n    Raised when attempting to transmit an array that doesn't contain only a\n    single type of object.\n    \"\"\"\n    pass\n\n\nclass ArrayDimensionsNotConsistentError(ProgrammingError):\n    \"\"\"\n    Raised when attempting to transmit an array that has inconsistent\n    multi-dimension sizes.\n    \"\"\"\n    pass\n\n\nclass Bytea(binary_type):\n    \"\"\"Bytea is a str-derived class that is mapped to a PostgreSQL byte array.\n    This class is only used in Python 2, the built-in ``bytes`` type is used in\n    Python 3.\n    \"\"\"\n    pass\n\n\ndef Date(year, month, day):\n    \"\"\"Constuct an object holding a date value.\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.date`\n    \"\"\"\n    return date(year, month, day)\n\n\ndef Time(hour, minute, second):\n    \"\"\"Construct an object holding a time value.\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.time`\n    \"\"\"\n    return time(hour, minute, second)\n\n\ndef Timestamp(year, month, day, hour, minute, second):\n    \"\"\"Construct an object holding a timestamp value.\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.datetime`\n    \"\"\"\n    return Datetime(year, month, day, hour, minute, second)\n\n\ndef DateFromTicks(ticks):\n    \"\"\"Construct an object holding a date value from the given ticks value\n    (number of seconds since the epoch).\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.date`\n    \"\"\"\n    return Date(*localtime(ticks)[:3])\n\n\ndef TimeFromTicks(ticks):\n    \"\"\"Construct an objet holding a time value from the given ticks value\n    (number of seconds since the epoch).\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.time`\n    \"\"\"\n    return Time(*localtime(ticks)[3:6])\n\n\ndef TimestampFromTicks(ticks):\n    \"\"\"Construct an object holding a timestamp value from the given ticks value\n    (number of seconds since the epoch).\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`datetime.datetime`\n    \"\"\"\n    return Timestamp(*localtime(ticks)[:6])\n\n\ndef Binary(value):\n    \"\"\"Construct an object holding binary data.\n\n    This function is part of the `DBAPI 2.0 specification\n    <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    :rtype: :class:`pg8000.types.Bytea` for Python 2, otherwise :class:`bytes`\n    \"\"\"\n    if PY2:\n        return Bytea(value)\n    else:\n        return value\n\n\nif PY2:\n    BINARY = Bytea\nelse:\n    BINARY = bytes\n\nFC_TEXT = 0\nFC_BINARY = 1\n\nBINARY_SPACE = b(\" \")\nDDL_COMMANDS = b(\"ALTER\"), b(\"CREATE\")\n\n\ndef convert_paramstyle(style, query):\n    # I don't see any way to avoid scanning the query string char by char,\n    # so we might as well take that careful approach and create a\n    # state-based scanner.  We'll use int variables for the state.\n    OUTSIDE = 0    # outside quoted string\n    INSIDE_SQ = 1  # inside single-quote string '...'\n    INSIDE_QI = 2  # inside quoted identifier   \"...\"\n    INSIDE_ES = 3  # inside escaped single-quote string, E'...'\n    INSIDE_PN = 4  # inside parameter name eg. :name\n    INSIDE_CO = 5  # inside inline comment eg. --\n\n    in_quote_escape = False\n    in_param_escape = False\n    placeholders = []\n    output_query = []\n    param_idx = map(lambda x: \"$\" + str(x), count(1))\n    state = OUTSIDE\n    prev_c = None\n    for i, c in enumerate(query):\n        if i + 1 < len(query):\n            next_c = query[i + 1]\n        else:\n            next_c = None\n\n        if state == OUTSIDE:\n            if c == \"'\":\n                output_query.append(c)\n                if prev_c == 'E':\n                    state = INSIDE_ES\n                else:\n                    state = INSIDE_SQ\n            elif c == '\"':\n                output_query.append(c)\n                state = INSIDE_QI\n            elif c == '-':\n                output_query.append(c)\n                if prev_c == '-':\n                    state = INSIDE_CO\n            elif style == \"qmark\" and c == \"?\":\n                output_query.append(next(param_idx))\n            elif style == \"numeric\" and c == \":\":\n                output_query.append(\"$\")\n            elif style == \"named\" and c == \":\":\n                state = INSIDE_PN\n                placeholders.append('')\n            elif style == \"pyformat\" and c == '%' and next_c == \"(\":\n                state = INSIDE_PN\n                placeholders.append('')\n            elif style in (\"format\", \"pyformat\") and c == \"%\":\n                style = \"format\"\n                if in_param_escape:\n                    in_param_escape = False\n                    output_query.append(c)\n                else:\n                    if next_c == \"%\":\n                        in_param_escape = True\n                    elif next_c == \"s\":\n                        state = INSIDE_PN\n                        output_query.append(next(param_idx))\n                    else:\n                        raise InterfaceError(\n                            \"Only %s and %% are supported in the query.\")\n            else:\n                output_query.append(c)\n\n        elif state == INSIDE_SQ:\n            if c == \"'\":\n                if in_quote_escape:\n                    in_quote_escape = False\n                else:\n                    if next_c == \"'\":\n                        in_quote_escape = True\n                    else:\n                        state = OUTSIDE\n            output_query.append(c)\n\n        elif state == INSIDE_QI:\n            if c == '\"':\n                state = OUTSIDE\n            output_query.append(c)\n\n        elif state == INSIDE_ES:\n            if c == \"'\" and prev_c != \"\\\\\":\n                # check for escaped single-quote\n                state = OUTSIDE\n            output_query.append(c)\n\n        elif state == INSIDE_PN:\n            if style == 'named':\n                placeholders[-1] += c\n                if next_c is None or (not next_c.isalnum() and next_c != '_'):\n                    state = OUTSIDE\n                    try:\n                        pidx = placeholders.index(placeholders[-1], 0, -1)\n                        output_query.append(\"$\" + str(pidx + 1))\n                        del placeholders[-1]\n                    except ValueError:\n                        output_query.append(\"$\" + str(len(placeholders)))\n            elif style == 'pyformat':\n                if prev_c == ')' and c == \"s\":\n                    state = OUTSIDE\n                    try:\n                        pidx = placeholders.index(placeholders[-1], 0, -1)\n                        output_query.append(\"$\" + str(pidx + 1))\n                        del placeholders[-1]\n                    except ValueError:\n                        output_query.append(\"$\" + str(len(placeholders)))\n                elif c in \"()\":\n                    pass\n                else:\n                    placeholders[-1] += c\n            elif style == 'format':\n                state = OUTSIDE\n\n        elif state == INSIDE_CO:\n            output_query.append(c)\n            if c == '\\n':\n                state = OUTSIDE\n\n        prev_c = c\n\n    if style in ('numeric', 'qmark', 'format'):\n        def make_args(vals):\n            return vals\n    else:\n        def make_args(vals):\n            return tuple(vals[p] for p in placeholders)\n\n    return ''.join(output_query), make_args\n\n\nEPOCH = Datetime(2000, 1, 1)\nEPOCH_TZ = EPOCH.replace(tzinfo=utc)\nEPOCH_SECONDS = timegm(EPOCH.timetuple())\nINFINITY_MICROSECONDS = 2 ** 63 - 1\nMINUS_INFINITY_MICROSECONDS = -1 * INFINITY_MICROSECONDS - 1\n\n\n# data is 64-bit integer representing microseconds since 2000-01-01\ndef timestamp_recv_integer(data, offset, length):\n    micros = q_unpack(data, offset)[0]\n    try:\n        return EPOCH + Timedelta(microseconds=micros)\n    except OverflowError:\n        if micros == INFINITY_MICROSECONDS:\n            return 'infinity'\n        elif micros == MINUS_INFINITY_MICROSECONDS:\n            return '-infinity'\n        else:\n            return micros\n\n\n# data is double-precision float representing seconds since 2000-01-01\ndef timestamp_recv_float(data, offset, length):\n    return Datetime.utcfromtimestamp(EPOCH_SECONDS + d_unpack(data, offset)[0])\n\n\n# data is 64-bit integer representing microseconds since 2000-01-01\ndef timestamp_send_integer(v):\n    return q_pack(\n        int((timegm(v.timetuple()) - EPOCH_SECONDS) * 1e6) + v.microsecond)\n\n\n# data is double-precision float representing seconds since 2000-01-01\ndef timestamp_send_float(v):\n    return d_pack(timegm(v.timetuple()) + v.microsecond / 1e6 - EPOCH_SECONDS)\n\n\ndef timestamptz_send_integer(v):\n    # timestamps should be sent as UTC.  If they have zone info,\n    # convert them.\n    return timestamp_send_integer(v.astimezone(utc).replace(tzinfo=None))\n\n\ndef timestamptz_send_float(v):\n    # timestamps should be sent as UTC.  If they have zone info,\n    # convert them.\n    return timestamp_send_float(v.astimezone(utc).replace(tzinfo=None))\n\n\n# return a timezone-aware datetime instance if we're reading from a\n# \"timestamp with timezone\" type.  The timezone returned will always be\n# UTC, but providing that additional information can permit conversion\n# to local.\ndef timestamptz_recv_integer(data, offset, length):\n    micros = q_unpack(data, offset)[0]\n    try:\n        return EPOCH_TZ + Timedelta(microseconds=micros)\n    except OverflowError:\n        if micros == INFINITY_MICROSECONDS:\n            return 'infinity'\n        elif micros == MINUS_INFINITY_MICROSECONDS:\n            return '-infinity'\n        else:\n            return micros\n\n\ndef timestamptz_recv_float(data, offset, length):\n    return timestamp_recv_float(data, offset, length).replace(tzinfo=utc)\n\n\ndef interval_send_integer(v):\n    microseconds = v.microseconds\n    try:\n        microseconds += int(v.seconds * 1e6)\n    except AttributeError:\n        pass\n\n    try:\n        months = v.months\n    except AttributeError:\n        months = 0\n\n    return qii_pack(microseconds, v.days, months)\n\n\ndef interval_send_float(v):\n    seconds = v.microseconds / 1000.0 / 1000.0\n    try:\n        seconds += v.seconds\n    except AttributeError:\n        pass\n\n    try:\n        months = v.months\n    except AttributeError:\n        months = 0\n\n    return dii_pack(seconds, v.days, months)\n\n\ndef interval_recv_integer(data, offset, length):\n    microseconds, days, months = qii_unpack(data, offset)\n    if months == 0:\n        seconds, micros = divmod(microseconds, 1e6)\n        return Timedelta(days, seconds, micros)\n    else:\n        return Interval(microseconds, days, months)\n\n\ndef interval_recv_float(data, offset, length):\n    seconds, days, months = dii_unpack(data, offset)\n    if months == 0:\n        secs, microseconds = divmod(seconds, 1e6)\n        return Timedelta(days, secs, microseconds)\n    else:\n        return Interval(int(seconds * 1000 * 1000), days, months)\n\n\ndef int8_recv(data, offset, length):\n    return q_unpack(data, offset)[0]\n\n\ndef int2_recv(data, offset, length):\n    return h_unpack(data, offset)[0]\n\n\ndef int4_recv(data, offset, length):\n    return i_unpack(data, offset)[0]\n\n\ndef float4_recv(data, offset, length):\n    return f_unpack(data, offset)[0]\n\n\ndef float8_recv(data, offset, length):\n    return d_unpack(data, offset)[0]\n\n\ndef bytea_send(v):\n    return v\n\n\n# bytea\nif PY2:\n    def bytea_recv(data, offset, length):\n        return Bytea(data[offset:offset + length])\nelse:\n    def bytea_recv(data, offset, length):\n        return data[offset:offset + length]\n\n\ndef uuid_send(v):\n    return v.bytes\n\n\ndef uuid_recv(data, offset, length):\n    return UUID(bytes=data[offset:offset+length])\n\n\nTRUE = b(\"\\x01\")\nFALSE = b(\"\\x00\")\n\n\ndef bool_send(v):\n    return TRUE if v else FALSE\n\n\nNULL = i_pack(-1)\n\nNULL_BYTE = b('\\x00')\n\n\ndef null_send(v):\n    return NULL\n\n\ndef int_in(data, offset, length):\n    return int(data[offset: offset + length])\n\n\nclass Cursor():\n    \"\"\"A cursor object is returned by the :meth:`~Connection.cursor` method of\n    a connection. It has the following attributes and methods:\n\n    .. attribute:: arraysize\n\n        This read/write attribute specifies the number of rows to fetch at a\n        time with :meth:`fetchmany`.  It defaults to 1.\n\n    .. attribute:: connection\n\n        This read-only attribute contains a reference to the connection object\n        (an instance of :class:`Connection`) on which the cursor was\n        created.\n\n        This attribute is part of a DBAPI 2.0 extension.  Accessing this\n        attribute will generate the following warning: ``DB-API extension\n        cursor.connection used``.\n\n    .. attribute:: rowcount\n\n        This read-only attribute contains the number of rows that the last\n        ``execute()`` or ``executemany()`` method produced (for query\n        statements like ``SELECT``) or affected (for modification statements\n        like ``UPDATE``).\n\n        The value is -1 if:\n\n        - No ``execute()`` or ``executemany()`` method has been performed yet\n          on the cursor.\n        - There was no rowcount associated with the last ``execute()``.\n        - At least one of the statements executed as part of an\n          ``executemany()`` had no row count associated with it.\n        - Using a ``SELECT`` query statement on PostgreSQL server older than\n          version 9.\n        - Using a ``COPY`` query statement on PostgreSQL server version 8.1 or\n          older.\n\n        This attribute is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n    .. attribute:: description\n\n        This read-only attribute is a sequence of 7-item sequences.  Each value\n        contains information describing one result column.  The 7 items\n        returned for each column are (name, type_code, display_size,\n        internal_size, precision, scale, null_ok).  Only the first two values\n        are provided by the current implementation.\n\n        This attribute is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n    \"\"\"\n\n    def __init__(self, connection):\n        self._c = connection\n        self.arraysize = 1\n        self.ps = None\n        self._row_count = -1\n        self._cached_rows = deque()\n\n    def __enter__(self):\n        return self\n\n    def __exit__(self, exc_type, exc_value, traceback):\n        self.close()\n\n    @property\n    def connection(self):\n        warn(\"DB-API extension cursor.connection used\", stacklevel=3)\n        return self._c\n\n    @property\n    def rowcount(self):\n        return self._row_count\n\n    description = property(lambda self: self._getDescription())\n\n    def _getDescription(self):\n        if self.ps is None:\n            return None\n        row_desc = self.ps['row_desc']\n        if len(row_desc) == 0:\n            return None\n        columns = []\n        for col in row_desc:\n            columns.append(\n                (col[\"name\"], col[\"type_oid\"], None, None, None, None, None))\n        return columns\n\n    ##\n    # Executes a database operation.  Parameters may be provided as a sequence\n    # or mapping and will be bound to variables in the operation.\n    # <p>\n    # Stability: Part of the DBAPI 2.0 specification.\n    def execute(self, operation, args=None, stream=None):\n        \"\"\"Executes a database operation.  Parameters may be provided as a\n        sequence, or as a mapping, depending upon the value of\n        :data:`pg8000.paramstyle`.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n        :param operation:\n            The SQL statement to execute.\n\n        :param args:\n            If :data:`paramstyle` is ``qmark``, ``numeric``, or ``format``,\n            this argument should be an array of parameters to bind into the\n            statement.  If :data:`paramstyle` is ``named``, the argument should\n            be a dict mapping of parameters.  If the :data:`paramstyle` is\n            ``pyformat``, the argument value may be either an array or a\n            mapping.\n\n        :param stream: This is a pg8000 extension for use with the PostgreSQL\n            `COPY\n            <http://www.postgresql.org/docs/current/static/sql-copy.html>`_\n            command. For a COPY FROM the parameter must be a readable file-like\n            object, and for COPY TO it must be writable.\n\n            .. versionadded:: 1.9.11\n        \"\"\"\n        try:\n            self.stream = stream\n\n            if not self._c.in_transaction and not self._c.autocommit:\n                self._c.execute(self, \"begin transaction\", None)\n            self._c.execute(self, operation, args)\n        except AttributeError as e:\n            if self._c is None:\n                raise InterfaceError(\"Cursor closed\")\n            elif self._c._sock is None:\n                raise InterfaceError(\"connection is closed\")\n            else:\n                raise e\n\n    def executemany(self, operation, param_sets):\n        \"\"\"Prepare a database operation, and then execute it against all\n        parameter sequences or mappings provided.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n        :param operation:\n            The SQL statement to execute\n        :param parameter_sets:\n            A sequence of parameters to execute the statement with. The values\n            in the sequence should be sequences or mappings of parameters, the\n            same as the args argument of the :meth:`execute` method.\n        \"\"\"\n        rowcounts = []\n        for parameters in param_sets:\n            self.execute(operation, parameters)\n            rowcounts.append(self._row_count)\n\n        self._row_count = -1 if -1 in rowcounts else sum(rowcounts)\n\n    def fetchone(self):\n        \"\"\"Fetch the next row of a query result set.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n        :returns:\n            A row as a sequence of field values, or ``None`` if no more rows\n            are available.\n        \"\"\"\n        try:\n            return next(self)\n        except StopIteration:\n            return None\n        except TypeError:\n            raise ProgrammingError(\"attempting to use unexecuted cursor\")\n        except AttributeError:\n            raise ProgrammingError(\"attempting to use unexecuted cursor\")\n\n    def fetchmany(self, num=None):\n        \"\"\"Fetches the next set of rows of a query result.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n        :param size:\n\n            The number of rows to fetch when called.  If not provided, the\n            :attr:`arraysize` attribute value is used instead.\n\n        :returns:\n\n            A sequence, each entry of which is a sequence of field values\n            making up a row.  If no more rows are available, an empty sequence\n            will be returned.\n        \"\"\"\n        try:\n            return tuple(\n                islice(self, self.arraysize if num is None else num))\n        except TypeError:\n            raise ProgrammingError(\"attempting to use unexecuted cursor\")\n\n    def fetchall(self):\n        \"\"\"Fetches all remaining rows of a query result.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n\n        :returns:\n\n            A sequence, each entry of which is a sequence of field values\n            making up a row.\n        \"\"\"\n        try:\n            return tuple(self)\n        except TypeError:\n            raise ProgrammingError(\"attempting to use unexecuted cursor\")\n\n    def close(self):\n        \"\"\"Closes the cursor.\n\n        This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        self._c = None\n\n    def __iter__(self):\n        \"\"\"A cursor object is iterable to retrieve the rows from a query.\n\n        This is a DBAPI 2.0 extension.\n        \"\"\"\n        return self\n\n    def setinputsizes(self, sizes):\n        \"\"\"This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_, however, it is not\n        implemented by pg8000.\n        \"\"\"\n        pass\n\n    def setoutputsize(self, size, column=None):\n        \"\"\"This method is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_, however, it is not\n        implemented by pg8000.\n        \"\"\"\n        pass\n\n    def __next__(self):\n        try:\n            return self._cached_rows.popleft()\n        except IndexError:\n            if self.ps is None:\n                raise ProgrammingError(\"A query hasn't been issued.\")\n            elif len(self.ps['row_desc']) == 0:\n                raise ProgrammingError(\"no result set\")\n            else:\n                raise StopIteration()\n\n\nif PY2:\n    Cursor.next = Cursor.__next__\n\n# Message codes\nNOTICE_RESPONSE = b(\"N\")\nAUTHENTICATION_REQUEST = b(\"R\")\nPARAMETER_STATUS = b(\"S\")\nBACKEND_KEY_DATA = b(\"K\")\nREADY_FOR_QUERY = b(\"Z\")\nROW_DESCRIPTION = b(\"T\")\nERROR_RESPONSE = b(\"E\")\nDATA_ROW = b(\"D\")\nCOMMAND_COMPLETE = b(\"C\")\nPARSE_COMPLETE = b(\"1\")\nBIND_COMPLETE = b(\"2\")\nCLOSE_COMPLETE = b(\"3\")\nPORTAL_SUSPENDED = b(\"s\")\nNO_DATA = b(\"n\")\nPARAMETER_DESCRIPTION = b(\"t\")\nNOTIFICATION_RESPONSE = b(\"A\")\nCOPY_DONE = b(\"c\")\nCOPY_DATA = b(\"d\")\nCOPY_IN_RESPONSE = b(\"G\")\nCOPY_OUT_RESPONSE = b(\"H\")\nEMPTY_QUERY_RESPONSE = b(\"I\")\n\nBIND = b(\"B\")\nPARSE = b(\"P\")\nEXECUTE = b(\"E\")\nFLUSH = b('H')\nSYNC = b('S')\nPASSWORD = b('p')\nDESCRIBE = b('D')\nTERMINATE = b('X')\nCLOSE = b('C')\n\n\ndef create_message(code, data=b('')):\n    return code + i_pack(len(data) + 4) + data\n\n\nFLUSH_MSG = create_message(FLUSH)\nSYNC_MSG = create_message(SYNC)\nTERMINATE_MSG = create_message(TERMINATE)\nCOPY_DONE_MSG = create_message(COPY_DONE)\nEXECUTE_MSG = create_message(EXECUTE, NULL_BYTE + i_pack(0))\n\n# DESCRIBE constants\nSTATEMENT = b('S')\nPORTAL = b('P')\n\n# ErrorResponse codes\nRESPONSE_SEVERITY = \"S\"  # always present\nRESPONSE_SEVERITY = \"V\"  # always present\nRESPONSE_CODE = \"C\"  # always present\nRESPONSE_MSG = \"M\"  # always present\nRESPONSE_DETAIL = \"D\"\nRESPONSE_HINT = \"H\"\nRESPONSE_POSITION = \"P\"\nRESPONSE__POSITION = \"p\"\nRESPONSE__QUERY = \"q\"\nRESPONSE_WHERE = \"W\"\nRESPONSE_FILE = \"F\"\nRESPONSE_LINE = \"L\"\nRESPONSE_ROUTINE = \"R\"\n\nIDLE = b(\"I\")\nIDLE_IN_TRANSACTION = b(\"T\")\nIDLE_IN_FAILED_TRANSACTION = b(\"E\")\n\n\narr_trans = dict(zip(map(ord, u(\"[] 'u\")), list(u('{}')) + [None] * 3))\n\n\nclass Connection(object):\n\n    # DBAPI Extension: supply exceptions as attributes on the connection\n    Warning = property(lambda self: self._getError(Warning))\n    Error = property(lambda self: self._getError(Error))\n    InterfaceError = property(lambda self: self._getError(InterfaceError))\n    DatabaseError = property(lambda self: self._getError(DatabaseError))\n    OperationalError = property(lambda self: self._getError(OperationalError))\n    IntegrityError = property(lambda self: self._getError(IntegrityError))\n    InternalError = property(lambda self: self._getError(InternalError))\n    ProgrammingError = property(lambda self: self._getError(ProgrammingError))\n    NotSupportedError = property(\n        lambda self: self._getError(NotSupportedError))\n\n    def _getError(self, error):\n        warn(\n            \"DB-API extension connection.%s used\" %\n            error.__name__, stacklevel=3)\n        return error\n\n    def __init__(\n            self, user, host, unix_sock, port, database, password, ssl,\n            timeout, application_name, max_prepared_statements):\n        self._client_encoding = \"utf8\"\n        self._commands_with_count = (\n            b(\"INSERT\"), b(\"DELETE\"), b(\"UPDATE\"), b(\"MOVE\"),\n            b(\"FETCH\"), b(\"COPY\"), b(\"SELECT\"))\n        self.notifications = deque(maxlen=100)\n        self.notices = deque(maxlen=100)\n        self.parameter_statuses = deque(maxlen=100)\n        self.max_prepared_statements = int(max_prepared_statements)\n\n        if user is None:\n            raise InterfaceError(\n                \"The 'user' connection parameter cannot be None\")\n\n        if isinstance(user, text_type):\n            self.user = user.encode('utf8')\n        else:\n            self.user = user\n\n        if isinstance(password, text_type):\n            self.password = password.encode('utf8')\n        else:\n            self.password = password\n\n        self.autocommit = False\n        self._xid = None\n\n        self._caches = {}\n\n        try:\n            if unix_sock is None and host is not None:\n                self._usock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n            elif unix_sock is not None:\n                if not hasattr(socket, \"AF_UNIX\"):\n                    raise InterfaceError(\n                        \"attempt to connect to unix socket on unsupported \"\n                        \"platform\")\n                self._usock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)\n            else:\n                raise ProgrammingError(\n                    \"one of host or unix_sock must be provided\")\n            if not PY2 and timeout is not None:\n                self._usock.settimeout(timeout)\n\n            if unix_sock is None and host is not None:\n                self._usock.connect((host, port))\n            elif unix_sock is not None:\n                self._usock.connect(unix_sock)\n\n            if ssl:\n                try:\n                    import ssl as sslmodule\n                    # Int32(8) - Message length, including self.\n                    # Int32(80877103) - The SSL request code.\n                    self._usock.sendall(ii_pack(8, 80877103))\n                    resp = self._usock.recv(1)\n                    if resp == b('S'):\n                        self._usock = sslmodule.wrap_socket(self._usock)\n                    else:\n                        raise InterfaceError(\"Server refuses SSL\")\n                except ImportError:\n                    raise InterfaceError(\n                        \"SSL required but ssl module not available in \"\n                        \"this python installation\")\n\n            self._sock = self._usock.makefile(mode=\"rwb\")\n        except socket.error as e:\n            self._usock.close()\n            raise InterfaceError(\"communication error\", e)\n        self._flush = self._sock.flush\n        self._read = self._sock.read\n        self._write = self._sock.write\n        self._backend_key_data = None\n\n        def text_out(v):\n            return v.encode(self._client_encoding)\n\n        def enum_out(v):\n            return str(v.value).encode(self._client_encoding)\n\n        def time_out(v):\n            return v.isoformat().encode(self._client_encoding)\n\n        def date_out(v):\n            return v.isoformat().encode(self._client_encoding)\n\n        def unknown_out(v):\n            return str(v).encode(self._client_encoding)\n\n        trans_tab = dict(zip(map(ord, u('{}')), u('[]')))\n        glbls = {'Decimal': Decimal}\n\n        def array_in(data, idx, length):\n            arr = []\n            prev_c = None\n            for c in data[idx:idx+length].decode(\n                    self._client_encoding).translate(\n                    trans_tab).replace(u('NULL'), u('None')):\n                if c not in ('[', ']', ',', 'N') and prev_c in ('[', ','):\n                    arr.extend(\"Decimal('\")\n                elif c in (']', ',') and prev_c not in ('[', ']', ',', 'e'):\n                    arr.extend(\"')\")\n\n                arr.append(c)\n                prev_c = c\n            return eval(''.join(arr), glbls)\n\n        def array_recv(data, idx, length):\n            final_idx = idx + length\n            dim, hasnull, typeoid = iii_unpack(data, idx)\n            idx += 12\n\n            # get type conversion method for typeoid\n            conversion = self.pg_types[typeoid][1]\n\n            # Read dimension info\n            dim_lengths = []\n            for i in range(dim):\n                dim_lengths.append(ii_unpack(data, idx)[0])\n                idx += 8\n\n            # Read all array values\n            values = []\n            while idx < final_idx:\n                element_len, = i_unpack(data, idx)\n                idx += 4\n                if element_len == -1:\n                    values.append(None)\n                else:\n                    values.append(conversion(data, idx, element_len))\n                    idx += element_len\n\n            # at this point, {{1,2,3},{4,5,6}}::int[][] looks like\n            # [1,2,3,4,5,6]. go through the dimensions and fix up the array\n            # contents to match expected dimensions\n            for length in reversed(dim_lengths[1:]):\n                values = list(map(list, zip(*[iter(values)] * length)))\n            return values\n\n        def vector_in(data, idx, length):\n            return eval('[' + data[idx:idx+length].decode(\n                self._client_encoding).replace(' ', ',') + ']')\n\n        if PY2:\n            def text_recv(data, offset, length):\n                return unicode(  # noqa\n                    data[offset: offset + length], self._client_encoding)\n\n            def bool_recv(d, o, l):\n                return d[o] == \"\\x01\"\n\n            def json_in(data, offset, length):\n                return loads(unicode(  # noqa\n                    data[offset: offset + length], self._client_encoding))\n\n        else:\n            def text_recv(data, offset, length):\n                return str(\n                    data[offset: offset + length], self._client_encoding)\n\n            def bool_recv(data, offset, length):\n                return data[offset] == 1\n\n            def json_in(data, offset, length):\n                return loads(\n                    str(data[offset: offset + length], self._client_encoding))\n\n        def time_in(data, offset, length):\n            hour = int(data[offset:offset + 2])\n            minute = int(data[offset + 3:offset + 5])\n            sec = Decimal(\n                data[offset + 6:offset + length].decode(self._client_encoding))\n            return time(\n                hour, minute, int(sec), int((sec - int(sec)) * 1000000))\n\n        def date_in(data, offset, length):\n            d = data[offset:offset+length].decode(self._client_encoding)\n            try:\n                return date(int(d[:4]), int(d[5:7]), int(d[8:10]))\n            except ValueError:\n                return d\n\n        def numeric_in(data, offset, length):\n            return Decimal(\n                data[offset: offset + length].decode(self._client_encoding))\n\n        def numeric_out(d):\n            return str(d).encode(self._client_encoding)\n\n        self.pg_types = defaultdict(\n            lambda: (FC_TEXT, text_recv), {\n                16: (FC_BINARY, bool_recv),  # boolean\n                17: (FC_BINARY, bytea_recv),  # bytea\n                19: (FC_BINARY, text_recv),  # name type\n                20: (FC_BINARY, int8_recv),  # int8\n                21: (FC_BINARY, int2_recv),  # int2\n                22: (FC_TEXT, vector_in),  # int2vector\n                23: (FC_BINARY, int4_recv),  # int4\n                25: (FC_BINARY, text_recv),  # TEXT type\n                26: (FC_TEXT, int_in),  # oid\n                28: (FC_TEXT, int_in),  # xid\n                114: (FC_TEXT, json_in),  # json\n                700: (FC_BINARY, float4_recv),  # float4\n                701: (FC_BINARY, float8_recv),  # float8\n                705: (FC_BINARY, text_recv),  # unknown\n                829: (FC_TEXT, text_recv),  # MACADDR type\n                1000: (FC_BINARY, array_recv),  # BOOL[]\n                1003: (FC_BINARY, array_recv),  # NAME[]\n                1005: (FC_BINARY, array_recv),  # INT2[]\n                1007: (FC_BINARY, array_recv),  # INT4[]\n                1009: (FC_BINARY, array_recv),  # TEXT[]\n                1014: (FC_BINARY, array_recv),  # CHAR[]\n                1015: (FC_BINARY, array_recv),  # VARCHAR[]\n                1016: (FC_BINARY, array_recv),  # INT8[]\n                1021: (FC_BINARY, array_recv),  # FLOAT4[]\n                1022: (FC_BINARY, array_recv),  # FLOAT8[]\n                1042: (FC_BINARY, text_recv),  # CHAR type\n                1043: (FC_BINARY, text_recv),  # VARCHAR type\n                1082: (FC_TEXT, date_in),  # date\n                1083: (FC_TEXT, time_in),\n                1114: (FC_BINARY, timestamp_recv_float),  # timestamp w/ tz\n                1184: (FC_BINARY, timestamptz_recv_float),\n                1186: (FC_BINARY, interval_recv_integer),\n                1231: (FC_TEXT, array_in),  # NUMERIC[]\n                1263: (FC_BINARY, array_recv),  # cstring[]\n                1700: (FC_TEXT, numeric_in),  # NUMERIC\n                2275: (FC_BINARY, text_recv),  # cstring\n                2950: (FC_BINARY, uuid_recv),  # uuid\n                3802: (FC_TEXT, json_in),  # jsonb\n            })\n\n        self.py_types = {\n            type(None): (-1, FC_BINARY, null_send),  # null\n            bool: (16, FC_BINARY, bool_send),\n            bytearray: (17, FC_BINARY, bytea_send),  # bytea\n            20: (20, FC_BINARY, q_pack),  # int8\n            21: (21, FC_BINARY, h_pack),  # int2\n            23: (23, FC_BINARY, i_pack),  # int4\n            PGText: (25, FC_TEXT, text_out),  # text\n            float: (701, FC_BINARY, d_pack),  # float8\n            PGEnum: (705, FC_TEXT, enum_out),\n            date: (1082, FC_TEXT, date_out),  # date\n            time: (1083, FC_TEXT, time_out),  # time\n            1114: (1114, FC_BINARY, timestamp_send_integer),  # timestamp\n            # timestamp w/ tz\n            PGVarchar: (1043, FC_TEXT, text_out),  # varchar\n            1184: (1184, FC_BINARY, timestamptz_send_integer),\n            PGJson: (114, FC_TEXT, text_out),\n            PGJsonb: (3802, FC_TEXT, text_out),\n            Timedelta: (1186, FC_BINARY, interval_send_integer),\n            Interval: (1186, FC_BINARY, interval_send_integer),\n            Decimal: (1700, FC_TEXT, numeric_out),  # Decimal\n            PGTsvector: (3614, FC_TEXT, text_out),\n            UUID: (2950, FC_BINARY, uuid_send)}  # uuid\n\n        self.inspect_funcs = {\n            Datetime: self.inspect_datetime,\n            list: self.array_inspect,\n            tuple: self.array_inspect,\n            int: self.inspect_int}\n\n        if PY2:\n            self.py_types[Bytea] = (17, FC_BINARY, bytea_send)  # bytea\n            self.py_types[text_type] = (705, FC_TEXT, text_out)  # unknown\n            self.py_types[str] = (705, FC_TEXT, bytea_send)  # unknown\n\n            self.inspect_funcs[long] = self.inspect_int  # noqa\n        else:\n            self.py_types[bytes] = (17, FC_BINARY, bytea_send)  # bytea\n            self.py_types[str] = (705, FC_TEXT, text_out)  # unknown\n\n        try:\n            import enum\n\n            self.py_types[enum.Enum] = (705, FC_TEXT, enum_out)\n        except ImportError:\n            pass\n\n        try:\n            from ipaddress import (\n                ip_address, IPv4Address, IPv6Address, ip_network, IPv4Network,\n                IPv6Network)\n\n            def inet_out(v):\n                return str(v).encode(self._client_encoding)\n\n            def inet_in(data, offset, length):\n                inet_str = data[offset: offset + length].decode(\n                    self._client_encoding)\n                if '/' in inet_str:\n                    return ip_network(inet_str, False)\n                else:\n                    return ip_address(inet_str)\n\n            self.py_types[IPv4Address] = (869, FC_TEXT, inet_out)  # inet\n            self.py_types[IPv6Address] = (869, FC_TEXT, inet_out)  # inet\n            self.py_types[IPv4Network] = (869, FC_TEXT, inet_out)  # inet\n            self.py_types[IPv6Network] = (869, FC_TEXT, inet_out)  # inet\n            self.pg_types[869] = (FC_TEXT, inet_in)  # inet\n        except ImportError:\n            pass\n\n        self.message_types = {\n            NOTICE_RESPONSE: self.handle_NOTICE_RESPONSE,\n            AUTHENTICATION_REQUEST: self.handle_AUTHENTICATION_REQUEST,\n            PARAMETER_STATUS: self.handle_PARAMETER_STATUS,\n            BACKEND_KEY_DATA: self.handle_BACKEND_KEY_DATA,\n            READY_FOR_QUERY: self.handle_READY_FOR_QUERY,\n            ROW_DESCRIPTION: self.handle_ROW_DESCRIPTION,\n            ERROR_RESPONSE: self.handle_ERROR_RESPONSE,\n            EMPTY_QUERY_RESPONSE: self.handle_EMPTY_QUERY_RESPONSE,\n            DATA_ROW: self.handle_DATA_ROW,\n            COMMAND_COMPLETE: self.handle_COMMAND_COMPLETE,\n            PARSE_COMPLETE: self.handle_PARSE_COMPLETE,\n            BIND_COMPLETE: self.handle_BIND_COMPLETE,\n            CLOSE_COMPLETE: self.handle_CLOSE_COMPLETE,\n            PORTAL_SUSPENDED: self.handle_PORTAL_SUSPENDED,\n            NO_DATA: self.handle_NO_DATA,\n            PARAMETER_DESCRIPTION: self.handle_PARAMETER_DESCRIPTION,\n            NOTIFICATION_RESPONSE: self.handle_NOTIFICATION_RESPONSE,\n            COPY_DONE: self.handle_COPY_DONE,\n            COPY_DATA: self.handle_COPY_DATA,\n            COPY_IN_RESPONSE: self.handle_COPY_IN_RESPONSE,\n            COPY_OUT_RESPONSE: self.handle_COPY_OUT_RESPONSE}\n\n        # Int32 - Message length, including self.\n        # Int32(196608) - Protocol version number.  Version 3.0.\n        # Any number of key/value pairs, terminated by a zero byte:\n        #   String - A parameter name (user, database, or options)\n        #   String - Parameter value\n        protocol = 196608\n        val = bytearray(\n            i_pack(protocol) + b(\"user\\x00\") + self.user + NULL_BYTE)\n        if database is not None:\n            if isinstance(database, text_type):\n                database = database.encode('utf8')\n            val.extend(b(\"database\\x00\") + database + NULL_BYTE)\n        if application_name is not None:\n            if isinstance(application_name, text_type):\n                application_name = application_name.encode('utf8')\n            val.extend(\n                b(\"application_name\\x00\") + application_name + NULL_BYTE)\n        val.append(0)\n        self._write(i_pack(len(val) + 4))\n        self._write(val)\n        self._flush()\n\n        self._cursor = self.cursor()\n        code = self.error = None\n        while code not in (READY_FOR_QUERY, ERROR_RESPONSE):\n            code, data_len = ci_unpack(self._read(5))\n            self.message_types[code](self._read(data_len - 4), None)\n        if self.error is not None:\n            raise self.error\n\n        self.in_transaction = False\n\n    def handle_ERROR_RESPONSE(self, data, ps):\n        msg = dict(\n            (\n                s[:1].decode(self._client_encoding),\n                s[1:].decode(self._client_encoding)) for s in\n            data.split(NULL_BYTE) if s != b(''))\n\n        response_code = msg[RESPONSE_CODE]\n        if response_code == '28000':\n            cls = InterfaceError\n        elif response_code == '23505':\n            cls = IntegrityError\n        else:\n            cls = ProgrammingError\n\n        self.error = cls(msg)\n\n    def handle_EMPTY_QUERY_RESPONSE(self, data, ps):\n        self.error = ProgrammingError(\"query was empty\")\n\n    def handle_CLOSE_COMPLETE(self, data, ps):\n        pass\n\n    def handle_PARSE_COMPLETE(self, data, ps):\n        # Byte1('1') - Identifier.\n        # Int32(4) - Message length, including self.\n        pass\n\n    def handle_BIND_COMPLETE(self, data, ps):\n        pass\n\n    def handle_PORTAL_SUSPENDED(self, data, cursor):\n        pass\n\n    def handle_PARAMETER_DESCRIPTION(self, data, ps):\n        # Well, we don't really care -- we're going to send whatever we\n        # want and let the database deal with it.  But thanks anyways!\n\n        # count = h_unpack(data)[0]\n        # type_oids = unpack_from(\"!\" + \"i\" * count, data, 2)\n        pass\n\n    def handle_COPY_DONE(self, data, ps):\n        self._copy_done = True\n\n    def handle_COPY_OUT_RESPONSE(self, data, ps):\n        # Int8(1) - 0 textual, 1 binary\n        # Int16(2) - Number of columns\n        # Int16(N) - Format codes for each column (0 text, 1 binary)\n\n        is_binary, num_cols = bh_unpack(data)\n        # column_formats = unpack_from('!' + 'h' * num_cols, data, 3)\n        if ps.stream is None:\n            raise InterfaceError(\n                \"An output stream is required for the COPY OUT response.\")\n\n    def handle_COPY_DATA(self, data, ps):\n        ps.stream.write(data)\n\n    def handle_COPY_IN_RESPONSE(self, data, ps):\n        # Int16(2) - Number of columns\n        # Int16(N) - Format codes for each column (0 text, 1 binary)\n        is_binary, num_cols = bh_unpack(data)\n        # column_formats = unpack_from('!' + 'h' * num_cols, data, 3)\n        if ps.stream is None:\n            raise InterfaceError(\n                \"An input stream is required for the COPY IN response.\")\n\n        if PY2:\n            while True:\n                data = ps.stream.read(8192)\n                if not data:\n                    break\n                self._write(COPY_DATA + i_pack(len(data) + 4))\n                self._write(data)\n                self._flush()\n        else:\n            bffr = bytearray(8192)\n            while True:\n                bytes_read = ps.stream.readinto(bffr)\n                if bytes_read == 0:\n                    break\n                self._write(COPY_DATA + i_pack(bytes_read + 4))\n                self._write(bffr[:bytes_read])\n                self._flush()\n\n        # Send CopyDone\n        # Byte1('c') - Identifier.\n        # Int32(4) - Message length, including self.\n        self._write(COPY_DONE_MSG)\n        self._write(SYNC_MSG)\n        self._flush()\n\n    def handle_NOTIFICATION_RESPONSE(self, data, ps):\n        ##\n        # A message sent if this connection receives a NOTIFY that it was\n        # LISTENing for.\n        # <p>\n        # Stability: Added in pg8000 v1.03.  When limited to accessing\n        # properties from a notification event dispatch, stability is\n        # guaranteed for v1.xx.\n        backend_pid = i_unpack(data)[0]\n        idx = 4\n        null = data.find(NULL_BYTE, idx) - idx\n        condition = data[idx:idx + null].decode(\"ascii\")\n        idx += null + 1\n        null = data.find(NULL_BYTE, idx) - idx\n        # additional_info = data[idx:idx + null]\n\n        self.notifications.append((backend_pid, condition))\n\n    def cursor(self):\n        \"\"\"Creates a :class:`Cursor` object bound to this\n        connection.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        return Cursor(self)\n\n    def commit(self):\n        \"\"\"Commits the current database transaction.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        self.execute(self._cursor, \"commit\", None)\n\n    def rollback(self):\n        \"\"\"Rolls back the current database transaction.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        if not self.in_transaction:\n            return\n        self.execute(self._cursor, \"rollback\", None)\n\n    def close(self):\n        \"\"\"Closes the database connection.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        try:\n            # Byte1('X') - Identifies the message as a terminate message.\n            # Int32(4) - Message length, including self.\n            self._write(TERMINATE_MSG)\n            self._flush()\n            self._sock.close()\n        except AttributeError:\n            raise InterfaceError(\"connection is closed\")\n        except ValueError:\n            raise InterfaceError(\"connection is closed\")\n        except socket.error:\n            pass\n        finally:\n            self._usock.close()\n            self._sock = None\n\n    def handle_AUTHENTICATION_REQUEST(self, data, cursor):\n        # Int32 -   An authentication code that represents different\n        #           authentication messages:\n        #               0 = AuthenticationOk\n        #               5 = MD5 pwd\n        #               2 = Kerberos v5 (not supported by pg8000)\n        #               3 = Cleartext pwd\n        #               4 = crypt() pwd (not supported by pg8000)\n        #               6 = SCM credential (not supported by pg8000)\n        #               7 = GSSAPI (not supported by pg8000)\n        #               8 = GSSAPI data (not supported by pg8000)\n        #               9 = SSPI (not supported by pg8000)\n        # Some authentication messages have additional data following the\n        # authentication code.  That data is documented in the appropriate\n        # class.\n        auth_code = i_unpack(data)[0]\n        if auth_code == 0:\n            pass\n        elif auth_code == 3:\n            if self.password is None:\n                raise InterfaceError(\n                    \"server requesting password authentication, but no \"\n                    \"password was provided\")\n            self._send_message(PASSWORD, self.password + NULL_BYTE)\n            self._flush()\n        elif auth_code == 5:\n            ##\n            # A message representing the backend requesting an MD5 hashed\n            # password response.  The response will be sent as\n            # md5(md5(pwd + login) + salt).\n\n            # Additional message data:\n            #  Byte4 - Hash salt.\n            salt = b(\"\").join(cccc_unpack(data, 4))\n            if self.password is None:\n                raise InterfaceError(\n                    \"server requesting MD5 password authentication, but no \"\n                    \"password was provided\")\n            pwd = b(\"md5\") + md5(\n                md5(self.password + self.user).hexdigest().encode(\"ascii\") +\n                salt).hexdigest().encode(\"ascii\")\n            # Byte1('p') - Identifies the message as a password message.\n            # Int32 - Message length including self.\n            # String - The password.  Password may be encrypted.\n            self._send_message(PASSWORD, pwd + NULL_BYTE)\n            self._flush()\n\n        elif auth_code in (2, 4, 6, 7, 8, 9):\n            raise InterfaceError(\n                \"Authentication method \" + str(auth_code) +\n                \" not supported by pg8000.\")\n        else:\n            raise InterfaceError(\n                \"Authentication method \" + str(auth_code) +\n                \" not recognized by pg8000.\")\n\n    def handle_READY_FOR_QUERY(self, data, ps):\n        # Byte1 -   Status indicator.\n        self.in_transaction = data != IDLE\n\n    def handle_BACKEND_KEY_DATA(self, data, ps):\n        self._backend_key_data = data\n\n    def inspect_datetime(self, value):\n        if value.tzinfo is None:\n            return self.py_types[1114]  # timestamp\n        else:\n            return self.py_types[1184]  # send as timestamptz\n\n    def inspect_int(self, value):\n        if min_int2 < value < max_int2:\n            return self.py_types[21]\n        if min_int4 < value < max_int4:\n            return self.py_types[23]\n        if min_int8 < value < max_int8:\n            return self.py_types[20]\n\n    def make_params(self, values):\n        params = []\n        for value in values:\n            typ = type(value)\n            try:\n                params.append(self.py_types[typ])\n            except KeyError:\n                try:\n                    params.append(self.inspect_funcs[typ](value))\n                except KeyError as e:\n                    param = None\n                    for k, v in iteritems(self.py_types):\n                        try:\n                            if isinstance(value, k):\n                                param = v\n                                break\n                        except TypeError:\n                            pass\n\n                    if param is None:\n                        for k, v in iteritems(self.inspect_funcs):\n                            try:\n                                if isinstance(value, k):\n                                    param = v(value)\n                                    break\n                            except TypeError:\n                                pass\n                            except KeyError:\n                                pass\n\n                    if param is None:\n                        raise NotSupportedError(\n                            \"type \" + str(e) + \" not mapped to pg type\")\n                    else:\n                        params.append(param)\n\n        return tuple(params)\n\n    def handle_ROW_DESCRIPTION(self, data, cursor):\n        count = h_unpack(data)[0]\n        idx = 2\n        for i in range(count):\n            name = data[idx:data.find(NULL_BYTE, idx)]\n            idx += len(name) + 1\n            field = dict(\n                zip((\n                    \"table_oid\", \"column_attrnum\", \"type_oid\", \"type_size\",\n                    \"type_modifier\", \"format\"), ihihih_unpack(data, idx)))\n            field['name'] = name\n            idx += 18\n            cursor.ps['row_desc'].append(field)\n            field['pg8000_fc'], field['func'] = \\\n                self.pg_types[field['type_oid']]\n\n    def execute(self, cursor, operation, vals):\n        if vals is None:\n            vals = ()\n\n        paramstyle = pg8000.paramstyle\n        pid = getpid()\n        try:\n            cache = self._caches[paramstyle][pid]\n        except KeyError:\n            try:\n                param_cache = self._caches[paramstyle]\n            except KeyError:\n                param_cache = self._caches[paramstyle] = {}\n\n            try:\n                cache = param_cache[pid]\n            except KeyError:\n                cache = param_cache[pid] = {'statement': {}, 'ps': {}}\n\n        try:\n            statement, make_args = cache['statement'][operation]\n        except KeyError:\n            statement, make_args = cache['statement'][operation] = \\\n                convert_paramstyle(paramstyle, operation)\n\n        args = make_args(vals)\n        params = self.make_params(args)\n        key = operation, params\n\n        try:\n            ps = cache['ps'][key]\n            cursor.ps = ps\n        except KeyError:\n            statement_nums = [0]\n            for style_cache in itervalues(self._caches):\n                try:\n                    pid_cache = style_cache[pid]\n                    for csh in itervalues(pid_cache['ps']):\n                        statement_nums.append(csh['statement_num'])\n                except KeyError:\n                    pass\n\n            statement_num = sorted(statement_nums)[-1] + 1\n            statement_name = '_'.join(\n                (\"pg8000\", \"statement\", str(pid), str(statement_num)))\n            statement_name_bin = statement_name.encode('ascii') + NULL_BYTE\n            ps = {\n                'statement_name_bin': statement_name_bin,\n                'pid': pid,\n                'statement_num': statement_num,\n                'row_desc': [],\n                'param_funcs': tuple(x[2] for x in params)}\n            cursor.ps = ps\n\n            param_fcs = tuple(x[1] for x in params)\n\n            # Byte1('P') - Identifies the message as a Parse command.\n            # Int32 -   Message length, including self.\n            # String -  Prepared statement name. An empty string selects the\n            #           unnamed prepared statement.\n            # String -  The query string.\n            # Int16 -   Number of parameter data types specified (can be zero).\n            # For each parameter:\n            #   Int32 - The OID of the parameter data type.\n            val = bytearray(statement_name_bin)\n            val.extend(statement.encode(self._client_encoding) + NULL_BYTE)\n            val.extend(h_pack(len(params)))\n            for oid, fc, send_func in params:\n                # Parse message doesn't seem to handle the -1 type_oid for NULL\n                # values that other messages handle.  So we'll provide type_oid\n                # 705, the PG \"unknown\" type.\n                val.extend(i_pack(705 if oid == -1 else oid))\n\n            # Byte1('D') - Identifies the message as a describe command.\n            # Int32 - Message length, including self.\n            # Byte1 - 'S' for prepared statement, 'P' for portal.\n            # String - The name of the item to describe.\n            self._send_message(PARSE, val)\n            self._send_message(DESCRIBE, STATEMENT + statement_name_bin)\n            self._write(SYNC_MSG)\n\n            try:\n                self._flush()\n            except AttributeError as e:\n                if self._sock is None:\n                    raise InterfaceError(\"connection is closed\")\n                else:\n                    raise e\n\n            self.handle_messages(cursor)\n\n            # We've got row_desc that allows us to identify what we're\n            # going to get back from this statement.\n            output_fc = tuple(\n                self.pg_types[f['type_oid']][0] for f in ps['row_desc'])\n\n            ps['input_funcs'] = tuple(f['func'] for f in ps['row_desc'])\n            # Byte1('B') - Identifies the Bind command.\n            # Int32 - Message length, including self.\n            # String - Name of the destination portal.\n            # String - Name of the source prepared statement.\n            # Int16 - Number of parameter format codes.\n            # For each parameter format code:\n            #   Int16 - The parameter format code.\n            # Int16 - Number of parameter values.\n            # For each parameter value:\n            #   Int32 - The length of the parameter value, in bytes, not\n            #           including this length.  -1 indicates a NULL parameter\n            #           value, in which no value bytes follow.\n            #   Byte[n] - Value of the parameter.\n            # Int16 - The number of result-column format codes.\n            # For each result-column format code:\n            #   Int16 - The format code.\n            ps['bind_1'] = NULL_BYTE + statement_name_bin + \\\n                h_pack(len(params)) + \\\n                pack(\"!\" + \"h\" * len(param_fcs), *param_fcs) + \\\n                h_pack(len(params))\n\n            ps['bind_2'] = h_pack(len(output_fc)) + \\\n                pack(\"!\" + \"h\" * len(output_fc), *output_fc)\n\n            if len(cache['ps']) > self.max_prepared_statements:\n                for p in itervalues(cache['ps']):\n                    self.close_prepared_statement(p['statement_name_bin'])\n                cache['ps'].clear()\n\n            cache['ps'][key] = ps\n\n        cursor._cached_rows.clear()\n        cursor._row_count = -1\n\n        # Byte1('B') - Identifies the Bind command.\n        # Int32 - Message length, including self.\n        # String - Name of the destination portal.\n        # String - Name of the source prepared statement.\n        # Int16 - Number of parameter format codes.\n        # For each parameter format code:\n        #   Int16 - The parameter format code.\n        # Int16 - Number of parameter values.\n        # For each parameter value:\n        #   Int32 - The length of the parameter value, in bytes, not\n        #           including this length.  -1 indicates a NULL parameter\n        #           value, in which no value bytes follow.\n        #   Byte[n] - Value of the parameter.\n        # Int16 - The number of result-column format codes.\n        # For each result-column format code:\n        #   Int16 - The format code.\n        retval = bytearray(ps['bind_1'])\n        for value, send_func in zip(args, ps['param_funcs']):\n            if value is None:\n                val = NULL\n            else:\n                val = send_func(value)\n                retval.extend(i_pack(len(val)))\n            retval.extend(val)\n        retval.extend(ps['bind_2'])\n\n        self._send_message(BIND, retval)\n        self.send_EXECUTE(cursor)\n        self._write(SYNC_MSG)\n        self._flush()\n        self.handle_messages(cursor)\n\n    def _send_message(self, code, data):\n        try:\n            self._write(code)\n            self._write(i_pack(len(data) + 4))\n            self._write(data)\n            self._write(FLUSH_MSG)\n        except ValueError as e:\n            if str(e) == \"write to closed file\":\n                raise InterfaceError(\"connection is closed\")\n            else:\n                raise e\n        except AttributeError:\n            raise InterfaceError(\"connection is closed\")\n\n    def send_EXECUTE(self, cursor):\n        # Byte1('E') - Identifies the message as an execute message.\n        # Int32 -   Message length, including self.\n        # String -  The name of the portal to execute.\n        # Int32 -   Maximum number of rows to return, if portal\n        #           contains a query # that returns rows.\n        #           0 = no limit.\n        self._write(EXECUTE_MSG)\n        self._write(FLUSH_MSG)\n\n    def handle_NO_DATA(self, msg, ps):\n        pass\n\n    def handle_COMMAND_COMPLETE(self, data, cursor):\n        values = data[:-1].split(BINARY_SPACE)\n        command = values[0]\n        if command in self._commands_with_count:\n            row_count = int(values[-1])\n            if cursor._row_count == -1:\n                cursor._row_count = row_count\n            else:\n                cursor._row_count += row_count\n\n        if command in DDL_COMMANDS:\n            for scache in itervalues(self._caches):\n                for pcache in itervalues(scache):\n                    for ps in itervalues(pcache['ps']):\n                        self.close_prepared_statement(ps['statement_name_bin'])\n                    pcache['ps'].clear()\n\n    def handle_DATA_ROW(self, data, cursor):\n        data_idx = 2\n        row = []\n        for func in cursor.ps['input_funcs']:\n            vlen = i_unpack(data, data_idx)[0]\n            data_idx += 4\n            if vlen == -1:\n                row.append(None)\n            else:\n                row.append(func(data, data_idx, vlen))\n                data_idx += vlen\n        cursor._cached_rows.append(row)\n\n    def handle_messages(self, cursor):\n        code = self.error = None\n\n        while code != READY_FOR_QUERY:\n            code, data_len = ci_unpack(self._read(5))\n            self.message_types[code](self._read(data_len - 4), cursor)\n\n        if self.error is not None:\n            raise self.error\n\n    # Byte1('C') - Identifies the message as a close command.\n    # Int32 - Message length, including self.\n    # Byte1 - 'S' for prepared statement, 'P' for portal.\n    # String - The name of the item to close.\n    def close_prepared_statement(self, statement_name_bin):\n        self._send_message(CLOSE, STATEMENT + statement_name_bin)\n        self._write(SYNC_MSG)\n        self._flush()\n        self.handle_messages(self._cursor)\n\n    # Byte1('N') - Identifier\n    # Int32 - Message length\n    # Any number of these, followed by a zero byte:\n    #   Byte1 - code identifying the field type (see responseKeys)\n    #   String - field value\n    def handle_NOTICE_RESPONSE(self, data, ps):\n        self.notices.append(\n            dict((s[0:1], s[1:]) for s in data.split(NULL_BYTE)))\n\n    def handle_PARAMETER_STATUS(self, data, ps):\n        pos = data.find(NULL_BYTE)\n        key, value = data[:pos], data[pos + 1:-1]\n        self.parameter_statuses.append((key, value))\n        if key == b(\"client_encoding\"):\n            encoding = value.decode(\"ascii\").lower()\n            self._client_encoding = pg_to_py_encodings.get(encoding, encoding)\n\n        elif key == b(\"integer_datetimes\"):\n            if value == b('on'):\n\n                self.py_types[1114] = (1114, FC_BINARY, timestamp_send_integer)\n                self.pg_types[1114] = (FC_BINARY, timestamp_recv_integer)\n\n                self.py_types[1184] = (\n                    1184, FC_BINARY, timestamptz_send_integer)\n                self.pg_types[1184] = (FC_BINARY, timestamptz_recv_integer)\n\n                self.py_types[Interval] = (\n                    1186, FC_BINARY, interval_send_integer)\n                self.py_types[Timedelta] = (\n                    1186, FC_BINARY, interval_send_integer)\n                self.pg_types[1186] = (FC_BINARY, interval_recv_integer)\n            else:\n                self.py_types[1114] = (1114, FC_BINARY, timestamp_send_float)\n                self.pg_types[1114] = (FC_BINARY, timestamp_recv_float)\n                self.py_types[1184] = (1184, FC_BINARY, timestamptz_send_float)\n                self.pg_types[1184] = (FC_BINARY, timestamptz_recv_float)\n\n                self.py_types[Interval] = (\n                    1186, FC_BINARY, interval_send_float)\n                self.py_types[Timedelta] = (\n                    1186, FC_BINARY, interval_send_float)\n                self.pg_types[1186] = (FC_BINARY, interval_recv_float)\n\n        elif key == b(\"server_version\"):\n            self._server_version = LooseVersion(value.decode('ascii'))\n            if self._server_version < LooseVersion('8.2.0'):\n                self._commands_with_count = (\n                    b(\"INSERT\"), b(\"DELETE\"), b(\"UPDATE\"), b(\"MOVE\"),\n                    b(\"FETCH\"))\n            elif self._server_version < LooseVersion('9.0.0'):\n                self._commands_with_count = (\n                    b(\"INSERT\"), b(\"DELETE\"), b(\"UPDATE\"), b(\"MOVE\"),\n                    b(\"FETCH\"), b(\"COPY\"))\n\n    def array_inspect(self, value):\n        # Check if array has any values. If empty, we can just assume it's an\n        # array of strings\n        first_element = array_find_first_element(value)\n        if first_element is None:\n            oid = 25\n            # Use binary ARRAY format to avoid having to properly\n            # escape text in the array literals\n            fc = FC_BINARY\n            array_oid = pg_array_types[oid]\n        else:\n            # supported array output\n            typ = type(first_element)\n\n            if issubclass(typ, integer_types):\n                # special int array support -- send as smallest possible array\n                # type\n                typ = integer_types\n                int2_ok, int4_ok, int8_ok = True, True, True\n                for v in array_flatten(value):\n                    if v is None:\n                        continue\n                    if min_int2 < v < max_int2:\n                        continue\n                    int2_ok = False\n                    if min_int4 < v < max_int4:\n                        continue\n                    int4_ok = False\n                    if min_int8 < v < max_int8:\n                        continue\n                    int8_ok = False\n                if int2_ok:\n                    array_oid = 1005  # INT2[]\n                    oid, fc, send_func = (21, FC_BINARY, h_pack)\n                elif int4_ok:\n                    array_oid = 1007  # INT4[]\n                    oid, fc, send_func = (23, FC_BINARY, i_pack)\n                elif int8_ok:\n                    array_oid = 1016  # INT8[]\n                    oid, fc, send_func = (20, FC_BINARY, q_pack)\n                else:\n                    raise ArrayContentNotSupportedError(\n                        \"numeric not supported as array contents\")\n            else:\n                try:\n                    oid, fc, send_func = self.make_params((first_element,))[0]\n\n                    # If unknown or string, assume it's a string array\n                    if oid in (705, 1043, 25):\n                        oid = 25\n                        # Use binary ARRAY format to avoid having to properly\n                        # escape text in the array literals\n                        fc = FC_BINARY\n                    array_oid = pg_array_types[oid]\n                except KeyError:\n                    raise ArrayContentNotSupportedError(\n                        \"oid \" + str(oid) + \" not supported as array contents\")\n                except NotSupportedError:\n                    raise ArrayContentNotSupportedError(\n                        \"type \" + str(typ) +\n                        \" not supported as array contents\")\n        if fc == FC_BINARY:\n            def send_array(arr):\n                # check that all array dimensions are consistent\n                array_check_dimensions(arr)\n\n                has_null = array_has_null(arr)\n                dim_lengths = array_dim_lengths(arr)\n                data = bytearray(iii_pack(len(dim_lengths), has_null, oid))\n                for i in dim_lengths:\n                    data.extend(ii_pack(i, 1))\n                for v in array_flatten(arr):\n                    if v is None:\n                        data += i_pack(-1)\n                    elif isinstance(v, typ):\n                        inner_data = send_func(v)\n                        data += i_pack(len(inner_data))\n                        data += inner_data\n                    else:\n                        raise ArrayContentNotHomogenousError(\n                            \"not all array elements are of type \" + str(typ))\n                return data\n        else:\n            def send_array(arr):\n                array_check_dimensions(arr)\n                ar = deepcopy(arr)\n                for a, i, v in walk_array(ar):\n                    if v is None:\n                        a[i] = 'NULL'\n                    elif isinstance(v, typ):\n                        a[i] = send_func(v).decode('ascii')\n                    else:\n                        raise ArrayContentNotHomogenousError(\n                            \"not all array elements are of type \" + str(typ))\n                return u(str(ar)).translate(arr_trans).encode('ascii')\n\n        return (array_oid, fc, send_array)\n\n    def xid(self, format_id, global_transaction_id, branch_qualifier):\n        \"\"\"Create a Transaction IDs (only global_transaction_id is used in pg)\n        format_id and branch_qualifier are not used in postgres\n        global_transaction_id may be any string identifier supported by\n        postgres returns a tuple\n        (format_id, global_transaction_id, branch_qualifier)\"\"\"\n        return (format_id, global_transaction_id, branch_qualifier)\n\n    def tpc_begin(self, xid):\n        \"\"\"Begins a TPC transaction with the given transaction ID xid.\n\n        This method should be called outside of a transaction (i.e. nothing may\n        have executed since the last .commit() or .rollback()).\n\n        Furthermore, it is an error to call .commit() or .rollback() within the\n        TPC transaction. A ProgrammingError is raised, if the application calls\n        .commit() or .rollback() during an active TPC transaction.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        self._xid = xid\n        if self.autocommit:\n            self.execute(self._cursor, \"begin transaction\", None)\n\n    def tpc_prepare(self):\n        \"\"\"Performs the first phase of a transaction started with .tpc_begin().\n        A ProgrammingError is be raised if this method is called outside of a\n        TPC transaction.\n\n        After calling .tpc_prepare(), no statements can be executed until\n        .tpc_commit() or .tpc_rollback() have been called.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        q = \"PREPARE TRANSACTION '%s';\" % (self._xid[1],)\n        self.execute(self._cursor, q, None)\n\n    def tpc_commit(self, xid=None):\n        \"\"\"When called with no arguments, .tpc_commit() commits a TPC\n        transaction previously prepared with .tpc_prepare().\n\n        If .tpc_commit() is called prior to .tpc_prepare(), a single phase\n        commit is performed. A transaction manager may choose to do this if\n        only a single resource is participating in the global transaction.\n\n        When called with a transaction ID xid, the database commits the given\n        transaction. If an invalid transaction ID is provided, a\n        ProgrammingError will be raised. This form should be called outside of\n        a transaction, and is intended for use in recovery.\n\n        On return, the TPC transaction is ended.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        if xid is None:\n            xid = self._xid\n\n        if xid is None:\n            raise ProgrammingError(\n                \"Cannot tpc_commit() without a TPC transaction!\")\n\n        try:\n            previous_autocommit_mode = self.autocommit\n            self.autocommit = True\n            if xid in self.tpc_recover():\n                self.execute(\n                    self._cursor, \"COMMIT PREPARED '%s';\" % (xid[1], ),\n                    None)\n            else:\n                # a single-phase commit\n                self.commit()\n        finally:\n            self.autocommit = previous_autocommit_mode\n        self._xid = None\n\n    def tpc_rollback(self, xid=None):\n        \"\"\"When called with no arguments, .tpc_rollback() rolls back a TPC\n        transaction. It may be called before or after .tpc_prepare().\n\n        When called with a transaction ID xid, it rolls back the given\n        transaction. If an invalid transaction ID is provided, a\n        ProgrammingError is raised. This form should be called outside of a\n        transaction, and is intended for use in recovery.\n\n        On return, the TPC transaction is ended.\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        if xid is None:\n            xid = self._xid\n\n        if xid is None:\n            raise ProgrammingError(\n                \"Cannot tpc_rollback() without a TPC prepared transaction!\")\n\n        try:\n            previous_autocommit_mode = self.autocommit\n            self.autocommit = True\n            if xid in self.tpc_recover():\n                # a two-phase rollback\n                self.execute(\n                    self._cursor, \"ROLLBACK PREPARED '%s';\" % (xid[1],),\n                    None)\n            else:\n                # a single-phase rollback\n                self.rollback()\n        finally:\n            self.autocommit = previous_autocommit_mode\n        self._xid = None\n\n    def tpc_recover(self):\n        \"\"\"Returns a list of pending transaction IDs suitable for use with\n        .tpc_commit(xid) or .tpc_rollback(xid).\n\n        This function is part of the `DBAPI 2.0 specification\n        <http://www.python.org/dev/peps/pep-0249/>`_.\n        \"\"\"\n        try:\n            previous_autocommit_mode = self.autocommit\n            self.autocommit = True\n            curs = self.cursor()\n            curs.execute(\"select gid FROM pg_prepared_xacts\")\n            return [self.xid(0, row[0], '') for row in curs]\n        finally:\n            self.autocommit = previous_autocommit_mode\n\n\n# pg element oid -> pg array typeoid\npg_array_types = {\n    16: 1000,\n    25: 1009,    # TEXT[]\n    701: 1022,\n    1043: 1009,\n    1700: 1231,  # NUMERIC[]\n}\n\n\n# PostgreSQL encodings:\n#   http://www.postgresql.org/docs/8.3/interactive/multibyte.html\n# Python encodings:\n#   http://www.python.org/doc/2.4/lib/standard-encodings.html\n#\n# Commented out encodings don't require a name change between PostgreSQL and\n# Python.  If the py side is None, then the encoding isn't supported.\npg_to_py_encodings = {\n    # Not supported:\n    \"mule_internal\": None,\n    \"euc_tw\": None,\n\n    # Name fine as-is:\n    # \"euc_jp\",\n    # \"euc_jis_2004\",\n    # \"euc_kr\",\n    # \"gb18030\",\n    # \"gbk\",\n    # \"johab\",\n    # \"sjis\",\n    # \"shift_jis_2004\",\n    # \"uhc\",\n    # \"utf8\",\n\n    # Different name:\n    \"euc_cn\": \"gb2312\",\n    \"iso_8859_5\": \"is8859_5\",\n    \"iso_8859_6\": \"is8859_6\",\n    \"iso_8859_7\": \"is8859_7\",\n    \"iso_8859_8\": \"is8859_8\",\n    \"koi8\": \"koi8_r\",\n    \"latin1\": \"iso8859-1\",\n    \"latin2\": \"iso8859_2\",\n    \"latin3\": \"iso8859_3\",\n    \"latin4\": \"iso8859_4\",\n    \"latin5\": \"iso8859_9\",\n    \"latin6\": \"iso8859_10\",\n    \"latin7\": \"iso8859_13\",\n    \"latin8\": \"iso8859_14\",\n    \"latin9\": \"iso8859_15\",\n    \"sql_ascii\": \"ascii\",\n    \"win866\": \"cp886\",\n    \"win874\": \"cp874\",\n    \"win1250\": \"cp1250\",\n    \"win1251\": \"cp1251\",\n    \"win1252\": \"cp1252\",\n    \"win1253\": \"cp1253\",\n    \"win1254\": \"cp1254\",\n    \"win1255\": \"cp1255\",\n    \"win1256\": \"cp1256\",\n    \"win1257\": \"cp1257\",\n    \"win1258\": \"cp1258\",\n    \"unicode\": \"utf-8\",  # Needed for Amazon Redshift\n}\n\n\ndef walk_array(arr):\n    for i, v in enumerate(arr):\n        if isinstance(v, list):\n            for a, i2, v2 in walk_array(v):\n                yield a, i2, v2\n        else:\n            yield arr, i, v\n\n\ndef array_find_first_element(arr):\n    for v in array_flatten(arr):\n        if v is not None:\n            return v\n    return None\n\n\ndef array_flatten(arr):\n    for v in arr:\n        if isinstance(v, list):\n            for v2 in array_flatten(v):\n                yield v2\n        else:\n            yield v\n\n\ndef array_check_dimensions(arr):\n    if len(arr) > 0:\n        v0 = arr[0]\n        if isinstance(v0, list):\n            req_len = len(v0)\n            req_inner_lengths = array_check_dimensions(v0)\n            for v in arr:\n                inner_lengths = array_check_dimensions(v)\n                if len(v) != req_len or inner_lengths != req_inner_lengths:\n                    raise ArrayDimensionsNotConsistentError(\n                        \"array dimensions not consistent\")\n            retval = [req_len]\n            retval.extend(req_inner_lengths)\n            return retval\n        else:\n            # make sure nothing else at this level is a list\n            for v in arr:\n                if isinstance(v, list):\n                    raise ArrayDimensionsNotConsistentError(\n                        \"array dimensions not consistent\")\n    return []\n\n\ndef array_has_null(arr):\n    for v in array_flatten(arr):\n        if v is None:\n            return True\n    return False\n\n\ndef array_dim_lengths(arr):\n    len_arr = len(arr)\n    if len_arr > 0:\n        v0 = arr[0]\n        if isinstance(v0, list):\n            retval = [len(v0)]\n            retval.extend(array_dim_lengths(v0))\n            return retval\n    return [len_arr]\n"
  },
  {
    "path": "setup.cfg",
    "content": "[upload_docs]\nupload-dir = build/sphinx/html\n\n[bdist_wheel]\nuniversal=1\n\n[versioneer]\nVCS = git\nstyle = pep440\nversionfile_source = pg8000/_version.py\nversionfile_build = pg8000/_version.py\ntag_prefix =\nparentdir_prefix = pg8000-\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n\nimport versioneer\nfrom setuptools import setup\n\nlong_description = \"\"\"\\\n\npg8000\n------\n\npg8000 is a Pure-Python interface to the PostgreSQL database engine.  It is \\\none of many PostgreSQL interfaces for the Python programming language. pg8000 \\\nis somewhat distinctive in that it is written entirely in Python and does not \\\nrely on any external libraries (such as a compiled python module, or \\\nPostgreSQL's libpq library). pg8000 supports the standard Python DB-API \\\nversion 2.0.\n\npg8000's name comes from the belief that it is probably about the 8000th \\\nPostgreSQL interface for Python.\"\"\"\n\ncmdclass = dict(versioneer.get_cmdclass())\nversion = versioneer.get_version()\n\nsetup(\n    name=\"pg8000\",\n    version=version,\n    cmdclass=cmdclass,\n    description=\"PostgreSQL interface library\",\n    long_description=long_description,\n    author=\"Mathieu Fenniak\",\n    author_email=\"biziqe@mathieu.fenniak.net\",\n    url=\"https://github.com/mfenniak/pg8000\",\n    license=\"BSD\",\n    install_requires=[\n        \"six>=1.10.0\",\n    ],\n    classifiers=[\n        \"Development Status :: 4 - Beta\",\n        \"Intended Audience :: Developers\",\n        \"License :: OSI Approved :: BSD License\",\n        \"Programming Language :: Python\",\n        \"Programming Language :: Python :: 2\",\n        \"Programming Language :: Python :: 2.7\",\n        \"Programming Language :: Python :: 3\",\n        \"Programming Language :: Python :: 3.3\",\n        \"Programming Language :: Python :: 3.4\",\n        \"Programming Language :: Python :: 3.5\",\n        \"Programming Language :: Python :: Implementation\",\n        \"Programming Language :: Python :: Implementation :: CPython\",\n        \"Programming Language :: Python :: Implementation :: Jython\",\n        \"Programming Language :: Python :: Implementation :: PyPy\",\n        \"Operating System :: OS Independent\",\n        \"Topic :: Database :: Front-Ends\",\n        \"Topic :: Software Development :: Libraries :: Python Modules\",\n    ],\n    keywords=\"postgresql dbapi\",\n    packages=(\"pg8000\",),\n    command_options={\n        'build_sphinx': {\n            'version': ('setup.py', version),\n            'release': ('setup.py', version)}},\n)\n"
  },
  {
    "path": "tests/connection_settings.py",
    "content": "db_connect = {\n    'user': 'postgres',\n    'password': 'pw',\n    'port': 5432}\n"
  },
  {
    "path": "tests/dbapi20.py",
    "content": "#!/usr/bin/env python\nimport unittest\nimport time\nimport warnings\nfrom six import b\n''' Python DB API 2.0 driver compliance unit test suite.\n\n    This software is Public Domain and may be used without restrictions.\n\n \"Now we have booze and barflies entering the discussion, plus rumours of\n  DBAs on drugs... and I won't tell you what flashes through my mind each\n  time I read the subject line with 'Anal Compliance' in it.  All around\n  this is turning out to be a thoroughly unwholesome unit test.\"\n\n    -- Ian Bicking\n'''\n\n__rcs_id__ = '$Id: dbapi20.py,v 1.10 2003/10/09 03:14:14 zenzen Exp $'\n__version__ = '$Revision: 1.10 $'[11:-2]\n__author__ = 'Stuart Bishop <zen@shangri-la.dropbear.id.au>'\n\n\n# $Log: dbapi20.py,v $\n# Revision 1.10  2003/10/09 03:14:14  zenzen\n# Add test for DB API 2.0 optional extension, where database exceptions\n# are exposed as attributes on the Connection object.\n#\n# Revision 1.9  2003/08/13 01:16:36  zenzen\n# Minor tweak from Stefan Fleiter\n#\n# Revision 1.8  2003/04/10 00:13:25  zenzen\n# Changes, as per suggestions by M.-A. Lemburg\n# - Add a table prefix, to ensure namespace collisions can always be avoided\n#\n# Revision 1.7  2003/02/26 23:33:37  zenzen\n# Break out DDL into helper functions, as per request by David Rushby\n#\n# Revision 1.6  2003/02/21 03:04:33  zenzen\n# Stuff from Henrik Ekelund:\n#     added test_None\n#     added test_nextset & hooks\n#\n# Revision 1.5  2003/02/17 22:08:43  zenzen\n# Implement suggestions and code from Henrik Eklund - test that\n# cursor.arraysize defaults to 1 & generic cursor.callproc test added\n#\n# Revision 1.4  2003/02/15 00:16:33  zenzen\n# Changes, as per suggestions and bug reports by M.-A. Lemburg,\n# Matthew T. Kromer, Federico Di Gregorio and Daniel Dittmar\n# - Class renamed\n# - Now a subclass of TestCase, to avoid requiring the driver stub\n#   to use multiple inheritance\n# - Reversed the polarity of buggy test in test_description\n# - Test exception heirarchy correctly\n# - self.populate is now self._populate(), so if a driver stub\n#   overrides self.ddl1 this change propogates\n# - VARCHAR columns now have a width, which will hopefully make the\n#   DDL even more portible (this will be reversed if it causes more problems)\n# - cursor.rowcount being checked after various execute and fetchXXX methods\n# - Check for fetchall and fetchmany returning empty lists after results\n#   are exhausted (already checking for empty lists if select retrieved\n#   nothing\n# - Fix bugs in test_setoutputsize_basic and test_setinputsizes\n#\n\n\nclass DatabaseAPI20Test(unittest.TestCase):\n    ''' Test a database self.driver for DB API 2.0 compatibility.\n        This implementation tests Gadfly, but the TestCase\n        is structured so that other self.drivers can subclass this\n        test case to ensure compiliance with the DB-API. It is\n        expected that this TestCase may be expanded in the future\n        if ambiguities or edge conditions are discovered.\n\n        The 'Optional Extensions' are not yet being tested.\n\n        self.drivers should subclass this test, overriding setUp, tearDown,\n        self.driver, connect_args and connect_kw_args. Class specification\n        should be as follows:\n\n        import dbapi20\n        class mytest(dbapi20.DatabaseAPI20Test):\n           [...]\n\n        Don't 'import DatabaseAPI20Test from dbapi20', or you will\n        confuse the unit tester - just 'import dbapi20'.\n    '''\n\n    # The self.driver module. This should be the module where the 'connect'\n    # method is to be found\n    driver = None\n    connect_args = ()  # List of arguments to pass to connect\n    connect_kw_args = {}  # Keyword arguments for connect\n    table_prefix = 'dbapi20test_'  # If you need to specify a prefix for tables\n\n    ddl1 = 'create table %sbooze (name varchar(20))' % table_prefix\n    ddl2 = 'create table %sbarflys (name varchar(20))' % table_prefix\n    xddl1 = 'drop table %sbooze' % table_prefix\n    xddl2 = 'drop table %sbarflys' % table_prefix\n\n    # Name of stored procedure to convert\n    # string->lowercase\n    lowerfunc = 'lower'\n\n    # Some drivers may need to override these helpers, for example adding\n    # a 'commit' after the execute.\n    def executeDDL1(self, cursor):\n        cursor.execute(self.ddl1)\n\n    def executeDDL2(self, cursor):\n        cursor.execute(self.ddl2)\n\n    def setUp(self):\n        ''' self.drivers should override this method to perform required setup\n            if any is necessary, such as creating the database.\n        '''\n        pass\n\n    def tearDown(self):\n        ''' self.drivers should override this method to perform required\n            cleanup if any is necessary, such as deleting the test database.\n            The default drops the tables that may be created.\n        '''\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            for ddl in (self.xddl1, self.xddl2):\n                try:\n                    cur.execute(ddl)\n                    con.commit()\n                except self.driver.Error:\n                    # Assume table didn't exist. Other tests will check if\n                    # execute is busted.\n                    pass\n        finally:\n            con.close()\n\n    def _connect(self):\n        try:\n            return self.driver.connect(\n                *self.connect_args, **self.connect_kw_args)\n        except AttributeError:\n            self.fail(\"No connect method found in self.driver module\")\n\n    def test_connect(self):\n        con = self._connect()\n        con.close()\n\n    def test_apilevel(self):\n        try:\n            # Must exist\n            apilevel = self.driver.apilevel\n            # Must equal 2.0\n            self.assertEqual(apilevel, '2.0')\n        except AttributeError:\n            self.fail(\"Driver doesn't define apilevel\")\n\n    def test_threadsafety(self):\n        try:\n            # Must exist\n            threadsafety = self.driver.threadsafety\n            # Must be a valid value\n            self.assertEqual(threadsafety in (0, 1, 2, 3), True)\n        except AttributeError:\n            self.fail(\"Driver doesn't define threadsafety\")\n\n    def test_paramstyle(self):\n        try:\n            # Must exist\n            paramstyle = self.driver.paramstyle\n            # Must be a valid value\n            self.assertEqual(\n                paramstyle in (\n                    'qmark', 'numeric', 'named', 'format', 'pyformat'), True)\n        except AttributeError:\n            self.fail(\"Driver doesn't define paramstyle\")\n\n    def test_Exceptions(self):\n        # Make sure required exceptions exist, and are in the\n        # defined heirarchy.\n        self.assertEqual(issubclass(self.driver.Warning, Exception), True)\n        self.assertEqual(issubclass(self.driver.Error, Exception), True)\n        self.assertEqual(\n            issubclass(self.driver.InterfaceError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.DatabaseError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.OperationalError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.IntegrityError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.InternalError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.ProgrammingError, self.driver.Error), True)\n        self.assertEqual(\n            issubclass(self.driver.NotSupportedError, self.driver.Error), True)\n\n    def test_ExceptionsAsConnectionAttributes(self):\n        # OPTIONAL EXTENSION\n        # Test for the optional DB API 2.0 extension, where the exceptions\n        # are exposed as attributes on the Connection object\n        # I figure this optional extension will be implemented by any\n        # driver author who is using this test suite, so it is enabled\n        # by default.\n        warnings.simplefilter(\"ignore\")\n        con = self._connect()\n        drv = self.driver\n        self.assertEqual(con.Warning is drv.Warning, True)\n        self.assertEqual(con.Error is drv.Error, True)\n        self.assertEqual(con.InterfaceError is drv.InterfaceError, True)\n        self.assertEqual(con.DatabaseError is drv.DatabaseError, True)\n        self.assertEqual(con.OperationalError is drv.OperationalError, True)\n        self.assertEqual(con.IntegrityError is drv.IntegrityError, True)\n        self.assertEqual(con.InternalError is drv.InternalError, True)\n        self.assertEqual(con.ProgrammingError is drv.ProgrammingError, True)\n        self.assertEqual(con.NotSupportedError is drv.NotSupportedError, True)\n        warnings.resetwarnings()\n        con.close()\n\n    def test_commit(self):\n        con = self._connect()\n        try:\n            # Commit must work, even if it doesn't do anything\n            con.commit()\n        finally:\n            con.close()\n\n    def test_rollback(self):\n        con = self._connect()\n        # If rollback is defined, it should either work or throw\n        # the documented exception\n        if hasattr(con, 'rollback'):\n            try:\n                con.rollback()\n            except self.driver.NotSupportedError:\n                pass\n        con.close()\n\n    def test_cursor(self):\n        con = self._connect()\n        try:\n            con.cursor()\n        finally:\n            con.close()\n\n    def test_cursor_isolation(self):\n        con = self._connect()\n        try:\n            # Make sure cursors created from the same connection have\n            # the documented transaction isolation level\n            cur1 = con.cursor()\n            cur2 = con.cursor()\n            self.executeDDL1(cur1)\n            cur1.execute(\n                \"insert into %sbooze values ('Victoria Bitter')\" % (\n                    self.table_prefix))\n            cur2.execute(\"select name from %sbooze\" % self.table_prefix)\n            booze = cur2.fetchall()\n            self.assertEqual(len(booze), 1)\n            self.assertEqual(len(booze[0]), 1)\n            self.assertEqual(booze[0][0], 'Victoria Bitter')\n        finally:\n            con.close()\n\n    def test_description(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.executeDDL1(cur)\n            self.assertEqual(\n                cur.description, None,\n                'cursor.description should be none after executing a '\n                'statement that can return no rows (such as DDL)')\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            self.assertEqual(\n                len(cur.description), 1,\n                'cursor.description describes too many columns')\n            self.assertEqual(\n                len(cur.description[0]), 7,\n                'cursor.description[x] tuples must have 7 elements')\n            self.assertEqual(\n                cur.description[0][0].lower(), b('name'),\n                'cursor.description[x][0] must return column name')\n            self.assertEqual(\n                cur.description[0][1], self.driver.STRING,\n                'cursor.description[x][1] must return column type. Got %r'\n                % cur.description[0][1])\n\n            # Make sure self.description gets reset\n            self.executeDDL2(cur)\n            self.assertEqual(\n                cur.description, None,\n                'cursor.description not being set to None when executing '\n                'no-result statements (eg. DDL)')\n        finally:\n            con.close()\n\n    def test_rowcount(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.executeDDL1(cur)\n            self.assertEqual(\n                cur.rowcount, -1,\n                'cursor.rowcount should be -1 after executing no-result '\n                'statements')\n            cur.execute(\n                \"insert into %sbooze values ('Victoria Bitter')\" % (\n                    self.table_prefix))\n            self.assertEqual(\n                cur.rowcount in (-1, 1), True,\n                'cursor.rowcount should == number or rows inserted, or '\n                'set to -1 after executing an insert statement')\n            cur.execute(\"select name from %sbooze\" % self.table_prefix)\n            self.assertEqual(\n                cur.rowcount in (-1, 1), True,\n                'cursor.rowcount should == number of rows returned, or '\n                'set to -1 after executing a select statement')\n            self.executeDDL2(cur)\n            self.assertEqual(\n                cur.rowcount, -1,\n                'cursor.rowcount not being reset to -1 after executing '\n                'no-result statements')\n        finally:\n            con.close()\n\n    lower_func = 'lower'\n\n    def test_callproc(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            if self.lower_func and hasattr(cur, 'callproc'):\n                r = cur.callproc(self.lower_func, ('FOO',))\n                self.assertEqual(len(r), 1)\n                self.assertEqual(r[0], 'FOO')\n                r = cur.fetchall()\n                self.assertEqual(len(r), 1, 'callproc produced no result set')\n                self.assertEqual(\n                    len(r[0]), 1, 'callproc produced invalid result set')\n                self.assertEqual(\n                    r[0][0], 'foo', 'callproc produced invalid results')\n        finally:\n            con.close()\n\n    def test_close(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n        finally:\n            con.close()\n\n        # cursor.execute should raise an Error if called after connection\n        # closed\n        self.assertRaises(self.driver.Error, self.executeDDL1, cur)\n\n        # connection.commit should raise an Error if called after connection'\n        # closed.'\n        self.assertRaises(self.driver.Error, con.commit)\n\n        # connection.close should raise an Error if called more than once\n        self.assertRaises(self.driver.Error, con.close)\n\n    def test_execute(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self._paraminsert(cur)\n        finally:\n            con.close()\n\n    def _paraminsert(self, cur):\n        self.executeDDL1(cur)\n        cur.execute(\"insert into %sbooze values ('Victoria Bitter')\" % (\n            self.table_prefix))\n        self.assertEqual(cur.rowcount in (-1, 1), True)\n\n        if self.driver.paramstyle == 'qmark':\n            cur.execute(\n                'insert into %sbooze values (?)' % self.table_prefix,\n                (\"Cooper's\",))\n        elif self.driver.paramstyle == 'numeric':\n            cur.execute(\n                'insert into %sbooze values (:1)' % self.table_prefix,\n                (\"Cooper's\",))\n        elif self.driver.paramstyle == 'named':\n            cur.execute(\n                'insert into %sbooze values (:beer)' % self.table_prefix,\n                {'beer': \"Cooper's\"})\n        elif self.driver.paramstyle == 'format':\n            cur.execute(\n                'insert into %sbooze values (%%s)' % self.table_prefix,\n                (\"Cooper's\",))\n        elif self.driver.paramstyle == 'pyformat':\n            cur.execute(\n                'insert into %sbooze values (%%(beer)s)' % self.table_prefix,\n                {'beer': \"Cooper's\"})\n        else:\n            self.fail('Invalid paramstyle')\n        self.assertEqual(cur.rowcount in (-1, 1), True)\n\n        cur.execute('select name from %sbooze' % self.table_prefix)\n        res = cur.fetchall()\n        self.assertEqual(\n            len(res), 2, 'cursor.fetchall returned too few rows')\n        beers = [res[0][0], res[1][0]]\n        beers.sort()\n        self.assertEqual(\n            beers[0], \"Cooper's\",\n            'cursor.fetchall retrieved incorrect data, or data inserted '\n            'incorrectly')\n        self.assertEqual(\n            beers[1], \"Victoria Bitter\",\n            'cursor.fetchall retrieved incorrect data, or data inserted '\n            'incorrectly')\n\n    def test_executemany(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.executeDDL1(cur)\n            largs = [(\"Cooper's\",), (\"Boag's\",)]\n            margs = [{'beer': \"Cooper's\"}, {'beer': \"Boag's\"}]\n            if self.driver.paramstyle == 'qmark':\n                cur.executemany(\n                    'insert into %sbooze values (?)' % self.table_prefix,\n                    largs\n                    )\n            elif self.driver.paramstyle == 'numeric':\n                cur.executemany(\n                    'insert into %sbooze values (:1)' % self.table_prefix,\n                    largs\n                    )\n            elif self.driver.paramstyle == 'named':\n                cur.executemany(\n                    'insert into %sbooze values (:beer)' % self.table_prefix,\n                    margs\n                    )\n            elif self.driver.paramstyle == 'format':\n                cur.executemany(\n                    'insert into %sbooze values (%%s)' % self.table_prefix,\n                    largs\n                    )\n            elif self.driver.paramstyle == 'pyformat':\n                cur.executemany(\n                    'insert into %sbooze values (%%(beer)s)' % (\n                        self.table_prefix), margs)\n            else:\n                self.fail('Unknown paramstyle')\n            self.assertEqual(\n                cur.rowcount in (-1, 2), True,\n                'insert using cursor.executemany set cursor.rowcount to '\n                'incorrect value %r' % cur.rowcount)\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            res = cur.fetchall()\n            self.assertEqual(\n                len(res), 2,\n                'cursor.fetchall retrieved incorrect number of rows')\n            beers = [res[0][0], res[1][0]]\n            beers.sort()\n            self.assertEqual(beers[0], \"Boag's\", 'incorrect data retrieved')\n            self.assertEqual(beers[1], \"Cooper's\", 'incorrect data retrieved')\n        finally:\n            con.close()\n\n    def test_fetchone(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n\n            # cursor.fetchone should raise an Error if called before\n            # executing a select-type query\n            self.assertRaises(self.driver.Error, cur.fetchone)\n\n            # cursor.fetchone should raise an Error if called after\n            # executing a query that cannnot return rows\n            self.executeDDL1(cur)\n            self.assertRaises(self.driver.Error, cur.fetchone)\n\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            self.assertEqual(\n                cur.fetchone(), None,\n                'cursor.fetchone should return None if a query retrieves '\n                'no rows')\n            self.assertEqual(cur.rowcount in (-1, 0), True)\n\n            # cursor.fetchone should raise an Error if called after\n            # executing a query that cannnot return rows\n            cur.execute(\n                \"insert into %sbooze values ('Victoria Bitter')\" % (\n                    self.table_prefix))\n            self.assertRaises(self.driver.Error, cur.fetchone)\n\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            r = cur.fetchone()\n            self.assertEqual(\n                len(r), 1,\n                'cursor.fetchone should have retrieved a single row')\n            self.assertEqual(\n                r[0], 'Victoria Bitter',\n                'cursor.fetchone retrieved incorrect data')\n            self.assertEqual(\n                cur.fetchone(), None,\n                'cursor.fetchone should return None if no more rows available')\n            self.assertEqual(cur.rowcount in (-1, 1), True)\n        finally:\n            con.close()\n\n    samples = [\n        'Carlton Cold',\n        'Carlton Draft',\n        'Mountain Goat',\n        'Redback',\n        'Victoria Bitter',\n        'XXXX'\n        ]\n\n    def _populate(self):\n        ''' Return a list of sql commands to setup the DB for the fetch\n            tests.\n        '''\n        populate = [\n            \"insert into %sbooze values ('%s')\" % (self.table_prefix, s)\n            for s in self.samples]\n        return populate\n\n    def test_fetchmany(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n\n            # cursor.fetchmany should raise an Error if called without\n            # issuing a query\n            self.assertRaises(self.driver.Error, cur.fetchmany, 4)\n\n            self.executeDDL1(cur)\n            for sql in self._populate():\n                cur.execute(sql)\n\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            r = cur.fetchmany()\n            self.assertEqual(\n                len(r), 1,\n                'cursor.fetchmany retrieved incorrect number of rows, '\n                'default of arraysize is one.')\n            cur.arraysize = 10\n            r = cur.fetchmany(3)  # Should get 3 rows\n            self.assertEqual(\n                len(r), 3,\n                'cursor.fetchmany retrieved incorrect number of rows')\n            r = cur.fetchmany(4)  # Should get 2 more\n            self.assertEqual(\n                len(r), 2,\n                'cursor.fetchmany retrieved incorrect number of rows')\n            r = cur.fetchmany(4)  # Should be an empty sequence\n            self.assertEqual(\n                len(r), 0,\n                'cursor.fetchmany should return an empty sequence after '\n                'results are exhausted')\n            self.assertEqual(cur.rowcount in (-1, 6), True)\n\n            # Same as above, using cursor.arraysize\n            cur.arraysize = 4\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            r = cur.fetchmany()  # Should get 4 rows\n            self.assertEqual(\n                len(r), 4,\n                'cursor.arraysize not being honoured by fetchmany')\n            r = cur.fetchmany()  # Should get 2 more\n            self.assertEqual(len(r), 2)\n            r = cur.fetchmany()  # Should be an empty sequence\n            self.assertEqual(len(r), 0)\n            self.assertEqual(cur.rowcount in (-1, 6), True)\n\n            cur.arraysize = 6\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            rows = cur.fetchmany()  # Should get all rows\n            self.assertEqual(cur.rowcount in (-1, 6), True)\n            self.assertEqual(len(rows), 6)\n            self.assertEqual(len(rows), 6)\n            rows = [row[0] for row in rows]\n            rows.sort()\n\n            # Make sure we get the right data back out\n            for i in range(0, 6):\n                self.assertEqual(\n                    rows[i], self.samples[i],\n                    'incorrect data retrieved by cursor.fetchmany')\n\n            rows = cur.fetchmany()  # Should return an empty list\n            self.assertEqual(\n                len(rows), 0,\n                'cursor.fetchmany should return an empty sequence if '\n                'called after the whole result set has been fetched')\n            self.assertEqual(cur.rowcount in (-1, 6), True)\n\n            self.executeDDL2(cur)\n            cur.execute('select name from %sbarflys' % self.table_prefix)\n            r = cur.fetchmany()  # Should get empty sequence\n            self.assertEqual(\n                len(r), 0,\n                'cursor.fetchmany should return an empty sequence if '\n                'query retrieved no rows')\n            self.assertEqual(cur.rowcount in (-1, 0), True)\n\n        finally:\n            con.close()\n\n    def test_fetchall(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            # cursor.fetchall should raise an Error if called\n            # without executing a query that may return rows (such\n            # as a select)\n            self.assertRaises(self.driver.Error, cur.fetchall)\n\n            self.executeDDL1(cur)\n            for sql in self._populate():\n                cur.execute(sql)\n\n            # cursor.fetchall should raise an Error if called\n            # after executing a a statement that cannot return rows\n            self.assertRaises(self.driver.Error, cur.fetchall)\n\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            rows = cur.fetchall()\n            self.assertEqual(cur.rowcount in (-1, len(self.samples)), True)\n            self.assertEqual(\n                len(rows), len(self.samples),\n                'cursor.fetchall did not retrieve all rows')\n            rows = [r[0] for r in rows]\n            rows.sort()\n            for i in range(0, len(self.samples)):\n                self.assertEqual(\n                    rows[i], self.samples[i],\n                    'cursor.fetchall retrieved incorrect rows')\n            rows = cur.fetchall()\n            self.assertEqual(\n                len(rows), 0,\n                'cursor.fetchall should return an empty list if called '\n                'after the whole result set has been fetched')\n            self.assertEqual(cur.rowcount in (-1, len(self.samples)), True)\n\n            self.executeDDL2(cur)\n            cur.execute('select name from %sbarflys' % self.table_prefix)\n            rows = cur.fetchall()\n            self.assertEqual(cur.rowcount in (-1, 0), True)\n            self.assertEqual(\n                len(rows), 0,\n                'cursor.fetchall should return an empty list if '\n                'a select query returns no rows')\n\n        finally:\n            con.close()\n\n    def test_mixedfetch(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.executeDDL1(cur)\n            for sql in self._populate():\n                cur.execute(sql)\n\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            rows1 = cur.fetchone()\n            rows23 = cur.fetchmany(2)\n            rows4 = cur.fetchone()\n            rows56 = cur.fetchall()\n            self.assertEqual(cur.rowcount in (-1, 6), True)\n            self.assertEqual(\n                len(rows23), 2, 'fetchmany returned incorrect number of rows')\n            self.assertEqual(\n                len(rows56), 2, 'fetchall returned incorrect number of rows')\n\n            rows = [rows1[0]]\n            rows.extend([rows23[0][0], rows23[1][0]])\n            rows.append(rows4[0])\n            rows.extend([rows56[0][0], rows56[1][0]])\n            rows.sort()\n            for i in range(0, len(self.samples)):\n                self.assertEqual(\n                    rows[i], self.samples[i],\n                    'incorrect data retrieved or inserted')\n        finally:\n            con.close()\n\n    def help_nextset_setUp(self, cur):\n        ''' Should create a procedure called deleteme\n            that returns two result sets, first the\n            number of rows in booze then \"name from booze\"\n        '''\n        raise NotImplementedError('Helper not implemented')\n\n    def help_nextset_tearDown(self, cur):\n        'If cleaning up is needed after nextSetTest'\n        raise NotImplementedError('Helper not implemented')\n\n    def test_nextset(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            if not hasattr(cur, 'nextset'):\n                return\n\n            try:\n                self.executeDDL1(cur)\n                sql = self._populate()\n                for sql in self._populate():\n                    cur.execute(sql)\n\n                self.help_nextset_setUp(cur)\n\n                cur.callproc('deleteme')\n                numberofrows = cur.fetchone()\n                assert numberofrows[0] == len(self.samples)\n                assert cur.nextset()\n                names = cur.fetchall()\n                assert len(names) == len(self.samples)\n                s = cur.nextset()\n                assert s is None, 'No more return sets, should return None'\n            finally:\n                self.help_nextset_tearDown(cur)\n\n        finally:\n            con.close()\n\n    '''\n    def test_nextset(self):\n        raise NotImplementedError('Drivers need to override this test')\n    '''\n\n    def test_arraysize(self):\n        # Not much here - rest of the tests for this are in test_fetchmany\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.assertEqual(\n                hasattr(cur, 'arraysize'), True,\n                'cursor.arraysize must be defined')\n        finally:\n            con.close()\n\n    def test_setinputsizes(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            cur.setinputsizes((25,))\n            self._paraminsert(cur)  # Make sure cursor still works\n        finally:\n            con.close()\n\n    def test_setoutputsize_basic(self):\n        # Basic test is to make sure setoutputsize doesn't blow up\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            cur.setoutputsize(1000)\n            cur.setoutputsize(2000, 0)\n            self._paraminsert(cur)  # Make sure the cursor still works\n        finally:\n            con.close()\n\n    def test_setoutputsize(self):\n        # Real test for setoutputsize is driver dependant\n        raise NotImplementedError('Driver need to override this test')\n\n    def test_None(self):\n        con = self._connect()\n        try:\n            cur = con.cursor()\n            self.executeDDL1(cur)\n            cur.execute(\n                'insert into %sbooze values (NULL)' % self.table_prefix)\n            cur.execute('select name from %sbooze' % self.table_prefix)\n            r = cur.fetchall()\n            self.assertEqual(len(r), 1)\n            self.assertEqual(len(r[0]), 1)\n            self.assertEqual(r[0][0], None, 'NULL value not returned as None')\n        finally:\n            con.close()\n\n    def test_Date(self):\n        self.driver.Date(2002, 12, 25)\n        self.driver.DateFromTicks(\n            time.mktime((2002, 12, 25, 0, 0, 0, 0, 0, 0)))\n        # Can we assume this? API doesn't specify, but it seems implied\n        # self.assertEqual(str(d1),str(d2))\n\n    def test_Time(self):\n        self.driver.Time(13, 45, 30)\n        self.driver.TimeFromTicks(\n            time.mktime((2001, 1, 1, 13, 45, 30, 0, 0, 0)))\n        # Can we assume this? API doesn't specify, but it seems implied\n        # self.assertEqual(str(t1),str(t2))\n\n    def test_Timestamp(self):\n        self.driver.Timestamp(2002, 12, 25, 13, 45, 30)\n        self.driver.TimestampFromTicks(\n            time.mktime((2002, 12, 25, 13, 45, 30, 0, 0, 0)))\n        # Can we assume this? API doesn't specify, but it seems implied\n        # self.assertEqual(str(t1),str(t2))\n\n    def test_Binary(self):\n        self.driver.Binary(b('Something'))\n        self.driver.Binary(b(''))\n\n    def test_STRING(self):\n        self.assertEqual(\n            hasattr(self.driver, 'STRING'), True,\n            'module.STRING must be defined')\n\n    def test_BINARY(self):\n        self.assertEqual(\n            hasattr(self.driver, 'BINARY'), True,\n            'module.BINARY must be defined.')\n\n    def test_NUMBER(self):\n        self.assertTrue(\n            hasattr(self.driver, 'NUMBER'), 'module.NUMBER must be defined.')\n\n    def test_DATETIME(self):\n        self.assertEqual(\n            hasattr(self.driver, 'DATETIME'), True,\n            'module.DATETIME must be defined.')\n\n    def test_ROWID(self):\n        self.assertEqual(\n            hasattr(self.driver, 'ROWID'), True,\n            'module.ROWID must be defined.')\n"
  },
  {
    "path": "tests/performance.py",
    "content": "import pg8000\nfrom pg8000.tests.connection_settings import db_connect\nimport time\nimport warnings\nfrom contextlib import closing\nfrom decimal import Decimal\n\n\nwhole_begin_time = time.time()\n\ntests = (\n        (\"cast(id / 100 as int2)\", 'int2'),\n        (\"cast(id as int4)\", 'int4'),\n        (\"cast(id * 100 as int8)\", 'int8'),\n        (\"(id %% 2) = 0\", 'bool'),\n        (\"N'Static text string'\", 'txt'),\n        (\"cast(id / 100 as float4)\", 'float4'),\n        (\"cast(id / 100 as float8)\", 'float8'),\n        (\"cast(id / 100 as numeric)\", 'numeric'),\n        (\"timestamp '2001-09-28' + id * interval '1 second'\", 'timestamp'),\n)\n\nwith warnings.catch_warnings(), closing(pg8000.connect(**db_connect)) as db:\n    for txt, name in tests:\n        query = \"\"\"SELECT {0} AS column1, {0} AS column2, {0} AS column3,\n            {0} AS column4, {0} AS column5, {0} AS column6, {0} AS column7\n            FROM (SELECT generate_series(1, 10000) AS id) AS tbl\"\"\".format(txt)\n        cursor = db.cursor()\n        print(\"Beginning %s test...\" % name)\n        for i in range(1, 5):\n            begin_time = time.time()\n            cursor.execute(query)\n            for row in cursor:\n                pass\n            end_time = time.time()\n            print(\"Attempt %s - %s seconds.\" % (i, end_time - begin_time))\n    db.commit()\n    cursor = db.cursor()\n    cursor.execute(\n        \"CREATE TEMPORARY TABLE t1 (f1 serial primary key, \"\n        \"f2 bigint not null, f3 varchar(50) null, f4 bool)\")\n    db.commit()\n    params = [(Decimal('7.4009'), 'season of mists...', True)] * 1000\n    print(\"Beginning executemany test...\")\n    for i in range(1, 5):\n        begin_time = time.time()\n        cursor.executemany(\n            \"insert into t1 (f2, f3, f4) values (%s, %s, %s)\", params)\n        db.commit()\n        end_time = time.time()\n        print(\"Attempt {0} took {1} seconds.\".format(i, end_time - begin_time))\n\n    print(\"Beginning reuse statements test...\")\n    begin_time = time.time()\n    for i in range(2000):\n        cursor.execute(\"select count(*) from t1\")\n        cursor.fetchall()\n    print(\"Took {0} seconds.\".format(time.time() - begin_time))\n\nprint(\"Whole time - %s seconds.\" % (time.time() - whole_begin_time))\n"
  },
  {
    "path": "tests/stress.py",
    "content": "import pg8000\nfrom pg8000.tests.connection_settings import db_connect\nfrom contextlib import closing\n\n\nwith closing(pg8000.connect(**db_connect)) as db:\n    for i in range(100):\n        cursor = db.cursor()\n        cursor.execute(\"\"\"\n        SELECT n.nspname as \"Schema\",\n          pg_catalog.format_type(t.oid, NULL) AS \"Name\",\n            pg_catalog.obj_description(t.oid, 'pg_type') as \"Description\"\n            FROM pg_catalog.pg_type t\n                 LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace\n                 left join pg_catalog.pg_namespace kj on n.oid = t.typnamespace\n                 WHERE (t.typrelid = 0\n                    OR (SELECT c.relkind = 'c'\n                        FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid))\n                    AND NOT EXISTS(\n                        SELECT 1 FROM pg_catalog.pg_type el\n                        WHERE el.oid = t.typelem AND el.typarray = t.oid)\n                     AND pg_catalog.pg_type_is_visible(t.oid)\n                     ORDER BY 1, 2;\"\"\")\n"
  },
  {
    "path": "tests/test_connection.py",
    "content": "import unittest\nimport pg8000\nfrom connection_settings import db_connect\nfrom six import PY2, u\nimport sys\nfrom distutils.version import LooseVersion\nimport socket\nimport struct\n\n\n# Check if running in Jython\nif 'java' in sys.platform:\n    from javax.net.ssl import TrustManager, X509TrustManager\n    from jarray import array\n    from javax.net.ssl import SSLContext\n\n    class TrustAllX509TrustManager(X509TrustManager):\n        '''Define a custom TrustManager which will blindly accept all\n        certificates'''\n\n        def checkClientTrusted(self, chain, auth):\n            pass\n\n        def checkServerTrusted(self, chain, auth):\n            pass\n\n        def getAcceptedIssuers(self):\n            return None\n    # Create a static reference to an SSLContext which will use\n    # our custom TrustManager\n    trust_managers = array([TrustAllX509TrustManager()], TrustManager)\n    TRUST_ALL_CONTEXT = SSLContext.getInstance(\"SSL\")\n    TRUST_ALL_CONTEXT.init(None, trust_managers, None)\n    # Keep a static reference to the JVM's default SSLContext for restoring\n    # at a later time\n    DEFAULT_CONTEXT = SSLContext.getDefault()\n\n\ndef trust_all_certificates(f):\n    '''Decorator function that will make it so the context of the decorated\n    method will run with our TrustManager that accepts all certificates'''\n    def wrapped(*args, **kwargs):\n        # Only do this if running under Jython\n        if 'java' in sys.platform:\n            from javax.net.ssl import SSLContext\n            SSLContext.setDefault(TRUST_ALL_CONTEXT)\n            try:\n                res = f(*args, **kwargs)\n                return res\n            finally:\n                SSLContext.setDefault(DEFAULT_CONTEXT)\n        else:\n            return f(*args, **kwargs)\n    return wrapped\n\n\n# Tests related to connecting to a database.\nclass Tests(unittest.TestCase):\n    def testSocketMissing(self):\n        conn_params = {\n            'unix_sock': \"/file-does-not-exist\",\n            'user': \"doesn't-matter\"}\n        self.assertRaises(pg8000.InterfaceError, pg8000.connect, **conn_params)\n\n    def testDatabaseMissing(self):\n        data = db_connect.copy()\n        data[\"database\"] = \"missing-db\"\n        self.assertRaises(pg8000.ProgrammingError, pg8000.connect, **data)\n\n    def testNotify(self):\n\n        try:\n            db = pg8000.connect(**db_connect)\n            self.assertEqual(list(db.notifications), [])\n            cursor = db.cursor()\n            cursor.execute(\"LISTEN test\")\n            cursor.execute(\"NOTIFY test\")\n            db.commit()\n\n            cursor.execute(\"VALUES (1, 2), (3, 4), (5, 6)\")\n            self.assertEqual(len(db.notifications), 1)\n            self.assertEqual(db.notifications[0][1], \"test\")\n        finally:\n            cursor.close()\n            db.close()\n\n    # This requires a line in pg_hba.conf that requires md5 for the database\n    # pg8000_md5\n\n    def testMd5(self):\n        data = db_connect.copy()\n        data[\"database\"] = \"pg8000_md5\"\n\n        # Should only raise an exception saying db doesn't exist\n        if PY2:\n            self.assertRaises(\n                pg8000.ProgrammingError, pg8000.connect, **data)\n        else:\n            self.assertRaisesRegex(\n                pg8000.ProgrammingError, '3D000', pg8000.connect, **data)\n\n    # This requires a line in pg_hba.conf that requires gss for the database\n    # pg8000_gss\n\n    def testGss(self):\n        data = db_connect.copy()\n        data[\"database\"] = \"pg8000_gss\"\n\n        # Should raise an exception saying gss isn't supported\n        if PY2:\n            self.assertRaises(pg8000.InterfaceError, pg8000.connect, **data)\n        else:\n            self.assertRaisesRegex(\n                pg8000.InterfaceError,\n                \"Authentication method 7 not supported by pg8000.\",\n                pg8000.connect, **data)\n\n    @trust_all_certificates\n    def testSsl(self):\n        data = db_connect.copy()\n        data[\"ssl\"] = True\n        db = pg8000.connect(**data)\n        db.close()\n\n    # This requires a line in pg_hba.conf that requires 'password' for the\n    # database pg8000_password\n\n    def testPassword(self):\n        data = db_connect.copy()\n        data[\"database\"] = \"pg8000_password\"\n\n        # Should only raise an exception saying db doesn't exist\n        if PY2:\n            self.assertRaises(\n                pg8000.ProgrammingError, pg8000.connect, **data)\n        else:\n            self.assertRaisesRegex(\n                pg8000.ProgrammingError, '3D000', pg8000.connect, **data)\n\n    def testUnicodeDatabaseName(self):\n        data = db_connect.copy()\n        data[\"database\"] = \"pg8000_sn\\uFF6Fw\"\n\n        # Should only raise an exception saying db doesn't exist\n        if PY2:\n            self.assertRaises(\n                pg8000.ProgrammingError, pg8000.connect, **data)\n        else:\n            self.assertRaisesRegex(\n                pg8000.ProgrammingError, '3D000', pg8000.connect, **data)\n\n    def testBytesDatabaseName(self):\n        data = db_connect.copy()\n\n        # Should only raise an exception saying db doesn't exist\n        if PY2:\n            data[\"database\"] = \"pg8000_sn\\uFF6Fw\"\n            self.assertRaises(\n                pg8000.ProgrammingError, pg8000.connect, **data)\n        else:\n            data[\"database\"] = bytes(\"pg8000_sn\\uFF6Fw\", 'utf8')\n            self.assertRaisesRegex(\n                pg8000.ProgrammingError, '3D000', pg8000.connect, **data)\n\n    def testBytesPassword(self):\n        db = pg8000.connect(**db_connect)\n        # Create user\n        username = 'boltzmann'\n        password = u('cha\\uFF6Fs')\n        cur = db.cursor()\n\n        # Delete user if left over from previous run\n        try:\n            cur.execute(\"drop role \" + username)\n        except pg8000.ProgrammingError:\n            cur.execute(\"rollback\")\n\n        cur.execute(\n            \"create user \" + username + \" with password '\" + password + \"';\")\n        cur.execute('commit;')\n        db.close()\n\n        data = db_connect.copy()\n        data['user'] = username\n        data['password'] = password.encode('utf8')\n        data['database'] = 'pg8000_md5'\n        if PY2:\n            self.assertRaises(\n                pg8000.ProgrammingError, pg8000.connect, **data)\n        else:\n            self.assertRaisesRegex(\n                pg8000.ProgrammingError, '3D000', pg8000.connect, **data)\n\n        db = pg8000.connect(**db_connect)\n        cur = db.cursor()\n        cur.execute(\"drop role \" + username)\n        cur.execute(\"commit;\")\n        db.close()\n\n    def testBrokenPipe(self):\n        db1 = pg8000.connect(**db_connect)\n        db2 = pg8000.connect(**db_connect)\n\n        try:\n            cur1 = db1.cursor()\n            cur2 = db2.cursor()\n\n            cur1.execute(\"select pg_backend_pid()\")\n            pid1 = cur1.fetchone()[0]\n\n            cur2.execute(\"select pg_terminate_backend(%s)\", (pid1,))\n            try:\n                cur1.execute(\"select 1\")\n            except Exception as e:\n                self.assertTrue(isinstance(e, (socket.error, struct.error)))\n\n            cur2.close()\n        finally:\n            db1.close()\n            db2.close()\n\n    def testApplicatioName(self):\n        params = db_connect.copy()\n        params['application_name'] = 'my test application name'\n        db = pg8000.connect(**params)\n        cur = db.cursor()\n\n        if db._server_version >= LooseVersion('9.2'):\n            cur.execute('select application_name from pg_stat_activity '\n                        ' where pid = pg_backend_pid()')\n        else:\n            # for pg9.1 and earlier, procpod field rather than pid\n            cur.execute('select application_name from pg_stat_activity '\n                        ' where procpid = pg_backend_pid()')\n\n        application_name = cur.fetchone()[0]\n        self.assertEqual(application_name, 'my test application name')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_copy.py",
    "content": "import unittest\nimport pg8000\nfrom connection_settings import db_connect\nfrom six import b, BytesIO, u, iteritems\nfrom sys import exc_info\n\n\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        self.db = pg8000.connect(**db_connect)\n        try:\n            cursor = self.db.cursor()\n            try:\n                cursor = self.db.cursor()\n                cursor.execute(\"DROP TABLE t1\")\n            except pg8000.DatabaseError:\n                e = exc_info()[1]\n                # the only acceptable error is:\n                msg = e.args[0]\n                code = msg['C']\n                self.assertEqual(\n                    code, '42P01',  # table does not exist\n                    \"incorrect error for drop table: \" + str(msg))\n                self.db.rollback()\n            cursor.execute(\n                \"CREATE TEMPORARY TABLE t1 (f1 int primary key, \"\n                \"f2 int not null, f3 varchar(50) null)\")\n        finally:\n            cursor.close()\n\n    def tearDown(self):\n        self.db.close()\n\n    def testCopyToWithTable(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\", (1, 1, 1))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\", (2, 2, 2))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\", (3, 3, 3))\n\n            stream = BytesIO()\n            cursor.execute(\"copy t1 to stdout\", stream=stream)\n            self.assertEqual(\n                stream.getvalue(), b(\"1\\t1\\t1\\n2\\t2\\t2\\n3\\t3\\t3\\n\"))\n            self.assertEqual(cursor.rowcount, 3)\n            self.db.commit()\n        finally:\n            cursor.close()\n\n    def testCopyToWithQuery(self):\n        try:\n            cursor = self.db.cursor()\n            stream = BytesIO()\n            cursor.execute(\n                \"COPY (SELECT 1 as One, 2 as Two) TO STDOUT WITH DELIMITER \"\n                \"'X' CSV HEADER QUOTE AS 'Y' FORCE QUOTE Two\", stream=stream)\n            self.assertEqual(stream.getvalue(), b('oneXtwo\\n1XY2Y\\n'))\n            self.assertEqual(cursor.rowcount, 1)\n            self.db.rollback()\n        finally:\n            cursor.close()\n\n    def testCopyFromWithTable(self):\n        try:\n            cursor = self.db.cursor()\n            stream = BytesIO(b(\"1\\t1\\t1\\n2\\t2\\t2\\n3\\t3\\t3\\n\"))\n            cursor.execute(\"copy t1 from STDIN\", stream=stream)\n            self.assertEqual(cursor.rowcount, 3)\n\n            cursor.execute(\"SELECT * FROM t1 ORDER BY f1\")\n            retval = cursor.fetchall()\n            self.assertEqual(retval, ([1, 1, '1'], [2, 2, '2'], [3, 3, '3']))\n            self.db.rollback()\n        finally:\n            cursor.close()\n\n    def testCopyFromWithQuery(self):\n        try:\n            cursor = self.db.cursor()\n            stream = BytesIO(b(\"f1Xf2\\n1XY1Y\\n\"))\n            cursor.execute(\n                \"COPY t1 (f1, f2) FROM STDIN WITH DELIMITER 'X' CSV HEADER \"\n                \"QUOTE AS 'Y' FORCE NOT NULL f1\", stream=stream)\n            self.assertEqual(cursor.rowcount, 1)\n\n            cursor.execute(\"SELECT * FROM t1 ORDER BY f1\")\n            retval = cursor.fetchall()\n            self.assertEqual(retval, ([1, 1, None],))\n            self.db.commit()\n        finally:\n            cursor.close()\n\n    def testCopyFromWithError(self):\n        try:\n            cursor = self.db.cursor()\n            stream = BytesIO(b(\"f1Xf2\\n\\n1XY1Y\\n\"))\n            cursor.execute(\n                \"COPY t1 (f1, f2) FROM STDIN WITH DELIMITER 'X' CSV HEADER \"\n                \"QUOTE AS 'Y' FORCE NOT NULL f1\", stream=stream)\n            self.assertTrue(False, \"Should have raised an exception\")\n        except:\n            args_dict = {\n                'S': u('ERROR'),\n                'C': u('22P02'),\n                'M': u('invalid input syntax for integer: \"\"'),\n                'W': u('COPY t1, line 2, column f1: \"\"'),\n                'F': u('numutils.c'),\n                'R': u('pg_atoi')\n            }\n            args = exc_info()[1].args[0]\n            for k, v in iteritems(args_dict):\n                self.assertEqual(args[k], v)\n        finally:\n            cursor.close()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_dbapi.py",
    "content": "import unittest\nimport os\nimport time\nimport pg8000\nimport datetime\nfrom connection_settings import db_connect\nfrom sys import exc_info\nfrom six import b\nfrom distutils.version import LooseVersion\n\n\n# DBAPI compatible interface tests\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        self.db = pg8000.connect(**db_connect)\n\n        # Neither Windows nor Jython 2.5.3 have a time.tzset() so skip\n        if hasattr(time, 'tzset'):\n            os.environ['TZ'] = \"UTC\"\n            time.tzset()\n            self.HAS_TZSET = True\n        else:\n            self.HAS_TZSET = False\n\n        try:\n            c = self.db.cursor()\n            try:\n                c = self.db.cursor()\n                c.execute(\"DROP TABLE t1\")\n            except pg8000.DatabaseError:\n                e = exc_info()[1]\n                # the only acceptable error is table does not exist\n                self.assertEqual(e.args[0]['C'], '42P01')\n                self.db.rollback()\n            c.execute(\n                \"CREATE TEMPORARY TABLE t1 \"\n                \"(f1 int primary key, f2 int not null, f3 varchar(50) null)\")\n            c.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (1, 1, None))\n            c.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (2, 10, None))\n            c.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (3, 100, None))\n            c.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (4, 1000, None))\n            c.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (5, 10000, None))\n            self.db.commit()\n        finally:\n            c.close()\n\n    def tearDown(self):\n        self.db.close()\n\n    def testParallelQueries(self):\n        try:\n            c1 = self.db.cursor()\n            c2 = self.db.cursor()\n\n            c1.execute(\"SELECT f1, f2, f3 FROM t1\")\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n                c2.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > %s\", (f1,))\n                while 1:\n                    row = c2.fetchone()\n                    if row is None:\n                        break\n                    f1, f2, f3 = row\n        finally:\n            c1.close()\n            c2.close()\n\n        self.db.rollback()\n\n    def testQmark(self):\n        orig_paramstyle = pg8000.paramstyle\n        try:\n            pg8000.paramstyle = \"qmark\"\n            c1 = self.db.cursor()\n            c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > ?\", (3,))\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n            self.db.rollback()\n        finally:\n            pg8000.paramstyle = orig_paramstyle\n            c1.close()\n\n    def testNumeric(self):\n        orig_paramstyle = pg8000.paramstyle\n        try:\n            pg8000.paramstyle = \"numeric\"\n            c1 = self.db.cursor()\n            c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > :1\", (3,))\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n            self.db.rollback()\n        finally:\n            pg8000.paramstyle = orig_paramstyle\n            c1.close()\n\n    def testNamed(self):\n        orig_paramstyle = pg8000.paramstyle\n        try:\n            pg8000.paramstyle = \"named\"\n            c1 = self.db.cursor()\n            c1.execute(\n                \"SELECT f1, f2, f3 FROM t1 WHERE f1 > :f1\", {\"f1\": 3})\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n            self.db.rollback()\n        finally:\n            pg8000.paramstyle = orig_paramstyle\n            c1.close()\n\n    def testFormat(self):\n        orig_paramstyle = pg8000.paramstyle\n        try:\n            pg8000.paramstyle = \"format\"\n            c1 = self.db.cursor()\n            c1.execute(\"SELECT f1, f2, f3 FROM t1 WHERE f1 > %s\", (3,))\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n            self.db.commit()\n        finally:\n            pg8000.paramstyle = orig_paramstyle\n            c1.close()\n\n    def testPyformat(self):\n        orig_paramstyle = pg8000.paramstyle\n        try:\n            pg8000.paramstyle = \"pyformat\"\n            c1 = self.db.cursor()\n            c1.execute(\n                \"SELECT f1, f2, f3 FROM t1 WHERE f1 > %(f1)s\", {\"f1\": 3})\n            while 1:\n                row = c1.fetchone()\n                if row is None:\n                    break\n                f1, f2, f3 = row\n            self.db.commit()\n        finally:\n            pg8000.paramstyle = orig_paramstyle\n            c1.close()\n\n    def testArraysize(self):\n        try:\n            c1 = self.db.cursor()\n            c1.arraysize = 3\n            c1.execute(\"SELECT * FROM t1\")\n            retval = c1.fetchmany()\n            self.assertEqual(len(retval), c1.arraysize)\n        finally:\n            c1.close()\n        self.db.commit()\n\n    def testDate(self):\n        val = pg8000.Date(2001, 2, 3)\n        self.assertEqual(val, datetime.date(2001, 2, 3))\n\n    def testTime(self):\n        val = pg8000.Time(4, 5, 6)\n        self.assertEqual(val, datetime.time(4, 5, 6))\n\n    def testTimestamp(self):\n        val = pg8000.Timestamp(2001, 2, 3, 4, 5, 6)\n        self.assertEqual(val, datetime.datetime(2001, 2, 3, 4, 5, 6))\n\n    def testDateFromTicks(self):\n        if self.HAS_TZSET:\n            val = pg8000.DateFromTicks(1173804319)\n            self.assertEqual(val, datetime.date(2007, 3, 13))\n\n    def testTimeFromTicks(self):\n        if self.HAS_TZSET:\n            val = pg8000.TimeFromTicks(1173804319)\n            self.assertEqual(val, datetime.time(16, 45, 19))\n\n    def testTimestampFromTicks(self):\n        if self.HAS_TZSET:\n            val = pg8000.TimestampFromTicks(1173804319)\n            self.assertEqual(val, datetime.datetime(2007, 3, 13, 16, 45, 19))\n\n    def testBinary(self):\n        v = pg8000.Binary(b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\"))\n        self.assertEqual(v, b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\"))\n        self.assertTrue(isinstance(v, pg8000.BINARY))\n\n    def testRowCount(self):\n        try:\n            c1 = self.db.cursor()\n            c1.execute(\"SELECT * FROM t1\")\n\n            # Before PostgreSQL 9 we don't know the row count for a select\n            if self.db._server_version > LooseVersion('8.0.0'):\n                self.assertEqual(5, c1.rowcount)\n\n            c1.execute(\"UPDATE t1 SET f3 = %s WHERE f2 > 101\", (\"Hello!\",))\n            self.assertEqual(2, c1.rowcount)\n\n            c1.execute(\"DELETE FROM t1\")\n            self.assertEqual(5, c1.rowcount)\n        finally:\n            c1.close()\n        self.db.commit()\n\n    def testFetchMany(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.arraysize = 2\n            cursor.execute(\"SELECT * FROM t1\")\n            self.assertEqual(2, len(cursor.fetchmany()))\n            self.assertEqual(2, len(cursor.fetchmany()))\n            self.assertEqual(1, len(cursor.fetchmany()))\n            self.assertEqual(0, len(cursor.fetchmany()))\n        finally:\n            cursor.close()\n        self.db.commit()\n\n    def testIterator(self):\n        from warnings import filterwarnings\n        filterwarnings(\"ignore\", \"DB-API extension cursor.next()\")\n        filterwarnings(\"ignore\", \"DB-API extension cursor.__iter__()\")\n\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"SELECT * FROM t1 ORDER BY f1\")\n            f1 = 0\n            for row in cursor:\n                next_f1 = row[0]\n                assert next_f1 > f1\n                f1 = next_f1\n        except:\n            cursor.close()\n\n        self.db.commit()\n\n    # Vacuum can't be run inside a transaction, so we need to turn\n    # autocommit on.\n    def testVacuum(self):\n        self.db.autocommit = True\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"vacuum\")\n        finally:\n            cursor.close()\n\n    def testPreparedStatement(self):\n        cursor = self.db.cursor()\n        cursor.execute(\n            'PREPARE gen_series AS SELECT generate_series(1, 10);')\n        cursor.execute('EXECUTE gen_series')\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_error_recovery.py",
    "content": "import unittest\nimport pg8000\nfrom connection_settings import db_connect\nimport warnings\nimport datetime\nfrom sys import exc_info\n\n\nclass TestException(Exception):\n    pass\n\n\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        self.db = pg8000.connect(**db_connect)\n\n    def tearDown(self):\n        self.db.close()\n\n    def raiseException(self, value):\n        raise TestException(\"oh noes!\")\n\n    def testPyValueFail(self):\n        # Ensure that if types.py_value throws an exception, the original\n        # exception is raised (TestException), and the connection is\n        # still usable after the error.\n        orig = self.db.py_types[datetime.time]\n        self.db.py_types[datetime.time] = (\n            orig[0], orig[1], self.raiseException)\n\n        try:\n            c = self.db.cursor()\n            try:\n                try:\n                    c.execute(\"SELECT %s as f1\", (datetime.time(10, 30),))\n                    c.fetchall()\n                    # shouldn't get here, exception should be thrown\n                    self.fail()\n                except TestException:\n                    # should be TestException type, this is OK!\n                    self.db.rollback()\n            finally:\n                self.db.py_types[datetime.time] = orig\n\n            # ensure that the connection is still usable for a new query\n            c.execute(\"VALUES ('hw3'::text)\")\n            self.assertEqual(c.fetchone()[0], \"hw3\")\n        finally:\n            c.close()\n\n    def testNoDataErrorRecovery(self):\n        for i in range(1, 4):\n            try:\n                try:\n                    cursor = self.db.cursor()\n                    cursor.execute(\"DROP TABLE t1\")\n                finally:\n                    cursor.close()\n            except pg8000.DatabaseError:\n                e = exc_info()[1]\n                # the only acceptable error is 'table does not exist'\n                self.assertEqual(e.args[0]['C'], '42P01')\n                self.db.rollback()\n\n    def testClosedConnection(self):\n        warnings.simplefilter(\"ignore\")\n        my_db = pg8000.connect(**db_connect)\n        cursor = my_db.cursor()\n        my_db.close()\n        try:\n            cursor.execute(\"VALUES ('hw1'::text)\")\n            self.fail(\"Should have raised an exception\")\n        except:\n            e = exc_info()[1]\n            self.assertTrue(isinstance(e, self.db.InterfaceError))\n            self.assertEqual(str(e), 'connection is closed')\n\n        warnings.resetwarnings()\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_paramstyle.py",
    "content": "import unittest\nimport pg8000\n\n\n# Tests of the convert_paramstyle function.\nclass Tests(unittest.TestCase):\n    def testQmark(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"qmark\", \"SELECT ?, ?, \\\"field_?\\\" FROM t \"\n            \"WHERE a='say ''what?''' AND b=? AND c=E'?\\\\'test\\\\'?'\")\n        self.assertEqual(\n            new_query, \"SELECT $1, $2, \\\"field_?\\\" FROM t WHERE \"\n            \"a='say ''what?''' AND b=$3 AND c=E'?\\\\'test\\\\'?'\")\n        self.assertEqual(make_args((1, 2, 3)), (1, 2, 3))\n\n    def testQmark2(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"qmark\", \"SELECT ?, ?, * FROM t WHERE a=? AND b='are you ''sure?'\")\n        self.assertEqual(\n            new_query,\n            \"SELECT $1, $2, * FROM t WHERE a=$3 AND b='are you ''sure?'\")\n        self.assertEqual(make_args((1, 2, 3)), (1, 2, 3))\n\n    def testNumeric(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"numeric\", \"SELECT :2, :1, * FROM t WHERE a=:3\")\n        self.assertEqual(new_query, \"SELECT $2, $1, * FROM t WHERE a=$3\")\n        self.assertEqual(make_args((1, 2, 3)), (1, 2, 3))\n\n    def testNamed(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"named\", \"SELECT :f_2, :f1 FROM t WHERE a=:f_2\")\n        self.assertEqual(new_query, \"SELECT $1, $2 FROM t WHERE a=$1\")\n        self.assertEqual(make_args({\"f_2\": 1, \"f1\": 2}), (1, 2))\n\n    def testFormat(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"format\", \"SELECT %s, %s, \\\"f1_%%\\\", E'txt_%%' \"\n            \"FROM t WHERE a=%s AND b='75%%' AND c = '%' -- Comment with %\")\n        self.assertEqual(\n            new_query,\n            \"SELECT $1, $2, \\\"f1_%%\\\", E'txt_%%' FROM t WHERE a=$3 AND \"\n            \"b='75%%' AND c = '%' -- Comment with %\")\n        self.assertEqual(make_args((1, 2, 3)), (1, 2, 3))\n\n        sql = r\"\"\"COMMENT ON TABLE test_schema.comment_test \"\"\" \\\n            r\"\"\"IS 'the test % '' \" \\ table comment'\"\"\"\n        new_query, make_args = pg8000.core.convert_paramstyle(\"format\", sql)\n        self.assertEqual(new_query, sql)\n\n    def testFormatMultiline(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"format\", \"SELECT -- Comment\\n%s FROM t\")\n        self.assertEqual(\n            new_query,\n            \"SELECT -- Comment\\n$1 FROM t\")\n\n    def testPyformat(self):\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"pyformat\", \"SELECT %(f2)s, %(f1)s, \\\"f1_%%\\\", E'txt_%%' \"\n            \"FROM t WHERE a=%(f2)s AND b='75%%'\")\n        self.assertEqual(\n            new_query,\n            \"SELECT $1, $2, \\\"f1_%%\\\", E'txt_%%' FROM t WHERE a=$1 AND \"\n            \"b='75%%'\")\n        self.assertEqual(make_args({\"f2\": 1, \"f1\": 2, \"f3\": 3}), (1, 2))\n\n        # pyformat should support %s and an array, too:\n        new_query, make_args = pg8000.core.convert_paramstyle(\n            \"pyformat\", \"SELECT %s, %s, \\\"f1_%%\\\", E'txt_%%' \"\n            \"FROM t WHERE a=%s AND b='75%%'\")\n        self.assertEqual(\n            new_query,\n            \"SELECT $1, $2, \\\"f1_%%\\\", E'txt_%%' FROM t WHERE a=$3 AND \"\n            \"b='75%%'\")\n        self.assertEqual(make_args((1, 2, 3)), (1, 2, 3))\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_pg8000_dbapi20.py",
    "content": "#!/usr/bin/env python\nimport dbapi20\nimport unittest\nimport pg8000\nfrom connection_settings import db_connect\n\n\nclass Tests(dbapi20.DatabaseAPI20Test):\n    driver = pg8000\n    connect_args = ()\n    connect_kw_args = db_connect\n\n    lower_func = 'lower'  # For stored procedure test\n\n    def test_nextset(self):\n        pass\n\n    def test_setoutputsize(self):\n        pass\n\n\nif __name__ == '__main__':\n    unittest.main()\n"
  },
  {
    "path": "tests/test_query.py",
    "content": "import unittest\nimport pg8000\nfrom connection_settings import db_connect\nfrom six import u\nfrom sys import exc_info\nimport datetime\nfrom distutils.version import LooseVersion\n\nfrom warnings import filterwarnings\n\n\n# Tests relating to the basic operation of the database driver, driven by the\n# pg8000 custom interface.\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        self.db = pg8000.connect(**db_connect)\n        filterwarnings(\"ignore\", \"DB-API extension cursor.next()\")\n        filterwarnings(\"ignore\", \"DB-API extension cursor.__iter__()\")\n        self.db.paramstyle = 'format'\n        try:\n            cursor = self.db.cursor()\n            try:\n                cursor.execute(\"DROP TABLE t1\")\n            except pg8000.DatabaseError:\n                e = exc_info()[1]\n                # the only acceptable error is 'table does not exist'\n                self.assertEqual(e.args[0]['C'], '42P01')\n                self.db.rollback()\n            cursor.execute(\n                \"CREATE TEMPORARY TABLE t1 (f1 int primary key, \"\n                \"f2 bigint not null, f3 varchar(50) null)\")\n        finally:\n            cursor.close()\n\n        self.db.commit()\n\n    def tearDown(self):\n        self.db.close()\n\n    def testDatabaseError(self):\n        try:\n            cursor = self.db.cursor()\n            self.assertRaises(\n                pg8000.ProgrammingError, cursor.execute,\n                \"INSERT INTO t99 VALUES (1, 2, 3)\")\n        finally:\n            cursor.close()\n\n        self.db.rollback()\n\n    def testParallelQueries(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (1, 1, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (2, 10, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (3, 100, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (4, 1000, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (5, 10000, None))\n            try:\n                c1 = self.db.cursor()\n                c2 = self.db.cursor()\n                c1.execute(\"SELECT f1, f2, f3 FROM t1\")\n                for row in c1:\n                    f1, f2, f3 = row\n                    c2.execute(\n                        \"SELECT f1, f2, f3 FROM t1 WHERE f1 > %s\", (f1,))\n                    for row in c2:\n                        f1, f2, f3 = row\n            finally:\n                c1.close()\n                c2.close()\n        finally:\n            cursor.close()\n        self.db.rollback()\n\n    def testParallelOpenPortals(self):\n        try:\n            c1, c2 = self.db.cursor(), self.db.cursor()\n            c1count, c2count = 0, 0\n            q = \"select * from generate_series(1, %s)\"\n            params = (100,)\n            c1.execute(q, params)\n            c2.execute(q, params)\n            for c2row in c2:\n                c2count += 1\n            for c1row in c1:\n                c1count += 1\n        finally:\n            c1.close()\n            c2.close()\n            self.db.rollback()\n\n        self.assertEqual(c1count, c2count)\n\n    # Run a query on a table, alter the structure of the table, then run the\n    # original query again.\n\n    def testAlter(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"select * from t1\")\n            cursor.execute(\"alter table t1 drop column f3\")\n            cursor.execute(\"select * from t1\")\n        finally:\n            cursor.close()\n            self.db.rollback()\n\n    # Run a query on a table, drop then re-create the table, then run the\n    # original query again.\n\n    def testCreate(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"select * from t1\")\n            cursor.execute(\"drop table t1\")\n            cursor.execute(\"create temporary table t1 (f1 int primary key)\")\n            cursor.execute(\"select * from t1\")\n        finally:\n            cursor.close()\n            self.db.rollback()\n\n    def testInsertReturning(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"CREATE TABLE t2 (id serial, data text)\")\n\n            # Test INSERT ... RETURNING with one row...\n            cursor.execute(\n                \"INSERT INTO t2 (data) VALUES (%s) RETURNING id\",\n                (\"test1\",))\n            row_id = cursor.fetchone()[0]\n            cursor.execute(\"SELECT data FROM t2 WHERE id = %s\", (row_id,))\n            self.assertEqual(\"test1\", cursor.fetchone()[0])\n\n            # Before PostgreSQL 9 we don't know the row count for a select\n            if self.db._server_version > LooseVersion('8.0.0'):\n                self.assertEqual(cursor.rowcount, 1)\n\n            # Test with multiple rows...\n            cursor.execute(\n                \"INSERT INTO t2 (data) VALUES (%s), (%s), (%s) \"\n                \"RETURNING id\", (\"test2\", \"test3\", \"test4\"))\n            self.assertEqual(cursor.rowcount, 3)\n            ids = tuple([x[0] for x in cursor])\n            self.assertEqual(len(ids), 3)\n        finally:\n            cursor.close()\n            self.db.rollback()\n\n    def testRowCount(self):\n        # Before PostgreSQL 9 we don't know the row count for a select\n        if self.db._server_version > LooseVersion('8.0.0'):\n            try:\n                cursor = self.db.cursor()\n                expected_count = 57\n                cursor.executemany(\n                    \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                    tuple((i, i, None) for i in range(expected_count)))\n\n                # Check rowcount after executemany\n                self.assertEqual(expected_count, cursor.rowcount)\n                self.db.commit()\n\n                cursor.execute(\"SELECT * FROM t1\")\n\n                # Check row_count without doing any reading first...\n                self.assertEqual(expected_count, cursor.rowcount)\n\n                # Check rowcount after reading some rows, make sure it still\n                # works...\n                for i in range(expected_count // 2):\n                    cursor.fetchone()\n                self.assertEqual(expected_count, cursor.rowcount)\n            finally:\n                cursor.close()\n                self.db.commit()\n\n            try:\n                cursor = self.db.cursor()\n                # Restart the cursor, read a few rows, and then check rowcount\n                # again...\n                cursor = self.db.cursor()\n                cursor.execute(\"SELECT * FROM t1\")\n                for i in range(expected_count // 3):\n                    cursor.fetchone()\n                self.assertEqual(expected_count, cursor.rowcount)\n                self.db.rollback()\n\n                # Should be -1 for a command with no results\n                cursor.execute(\"DROP TABLE t1\")\n                self.assertEqual(-1, cursor.rowcount)\n            finally:\n                cursor.close()\n                self.db.commit()\n\n    def testRowCountUpdate(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (1, 1, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (2, 10, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (3, 100, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (4, 1000, None))\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (5, 10000, None))\n            cursor.execute(\"UPDATE t1 SET f3 = %s WHERE f2 > 101\", (\"Hello!\",))\n            self.assertEqual(cursor.rowcount, 2)\n        finally:\n            cursor.close()\n            self.db.commit()\n\n    def testIntOid(self):\n        try:\n            cursor = self.db.cursor()\n            # https://bugs.launchpad.net/pg8000/+bug/230796\n            cursor.execute(\n                \"SELECT typname FROM pg_type WHERE oid = %s\", (100,))\n        finally:\n            cursor.close()\n            self.db.rollback()\n\n    def testUnicodeQuery(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\n                u(\n                    \"CREATE TEMPORARY TABLE \\u043c\\u0435\\u0441\\u0442\\u043e \"\n                    \"(\\u0438\\u043c\\u044f VARCHAR(50), \"\n                    \"\\u0430\\u0434\\u0440\\u0435\\u0441 VARCHAR(250))\"))\n        finally:\n            cursor.close()\n            self.db.commit()\n\n    def testExecutemany(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.executemany(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                ((1, 1, 'Avast ye!'), (2, 1, None)))\n\n            cursor.executemany(\n                \"select %s\",\n                (\n                    (datetime.datetime(2014, 5, 7, tzinfo=pg8000.core.utc), ),\n                    (datetime.datetime(2014, 5, 7),)))\n        finally:\n            cursor.close()\n            self.db.commit()\n\n    # Check that autocommit stays off\n    # We keep track of whether we're in a transaction or not by using the\n    # READY_FOR_QUERY message.\n    def testTransactions(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"commit\")\n            cursor.execute(\n                \"INSERT INTO t1 (f1, f2, f3) VALUES (%s, %s, %s)\",\n                (1, 1, \"Zombie\"))\n            cursor.execute(\"rollback\")\n            cursor.execute(\"select * from t1\")\n\n            # Before PostgreSQL 9 we don't know the row count for a select\n            if self.db._server_version > LooseVersion('8.0.0'):\n                self.assertEqual(cursor.rowcount, 0)\n        finally:\n            cursor.close()\n            self.db.commit()\n\n    def testIn(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\n                \"SELECT typname FROM pg_type WHERE oid = any(%s)\", ([16, 23],))\n            ret = cursor.fetchall()\n            self.assertEqual(ret[0][0], 'bool')\n        finally:\n            cursor.close()\n\n    def test_no_previous_tpc(self):\n        try:\n            self.db.tpc_begin('Stacey')\n            cursor = self.db.cursor()\n            cursor.execute(\"SELECT * FROM pg_type\")\n            self.db.tpc_commit()\n        finally:\n            cursor.close()\n\n    # Check that tpc_recover() doesn't start a transaction\n    def test_tpc_recover(self):\n        try:\n            self.db.tpc_recover()\n            cursor = self.db.cursor()\n            self.db.autocommit = True\n\n            # If tpc_recover() has started a transaction, this will fail\n            cursor.execute(\"VACUUM\")\n        finally:\n            cursor.close()\n\n    # An empty query should raise a ProgrammingError\n    def test_empty_query(self):\n        try:\n            cursor = self.db.cursor()\n            self.assertRaises(pg8000.ProgrammingError, cursor.execute, \"\")\n        finally:\n            cursor.close()\n\n    # rolling back when not in a transaction doesn't generate a warning\n    def test_rollback_no_transaction(self):\n        try:\n            # Remove any existing notices\n            self.db.notices.clear()\n\n            cursor = self.db.cursor()\n\n            # First, verify that a raw rollback does produce a notice\n            self.db.execute(cursor, \"rollback\", None)\n\n            self.assertEqual(1, len(self.db.notices))\n            # 25P01 is the code for no_active_sql_tronsaction. It has\n            # a message and severity name, but those might be\n            # localized/depend on the server version.\n            self.assertEqual(self.db.notices.pop().get(b'C'), b'25P01')\n\n            # Now going through the rollback method doesn't produce\n            # any notices because it knows we're not in a transaction.\n            self.db.rollback()\n\n            self.assertEqual(0, len(self.db.notices))\n\n        finally:\n            cursor.close()\n\n    def test_context_manager_class(self):\n        self.assertTrue('__enter__' in pg8000.core.Cursor.__dict__)\n        self.assertTrue('__exit__' in pg8000.core.Cursor.__dict__)\n\n        with self.db.cursor() as cursor:\n            cursor.execute('select 1')\n\n    def test_deallocate_prepared_statements(self):\n        try:\n            cursor = self.db.cursor()\n            cursor.execute(\"select * from t1\")\n            cursor.execute(\"alter table t1 drop column f3\")\n            cursor.execute(\"select count(*) from pg_prepared_statements\")\n            res = cursor.fetchall()\n            self.assertEqual(res[0][0], 1)\n        finally:\n            cursor.close()\n            self.db.rollback()\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_typeconversion.py",
    "content": "import unittest\nimport pg8000\nfrom pg8000 import PGJsonb, PGEnum\nimport datetime\nimport decimal\nimport struct\nfrom connection_settings import db_connect\nfrom six import b, PY2, u\nimport uuid\nimport os\nimport time\nfrom distutils.version import LooseVersion\nimport sys\nimport json\nimport pytz\nfrom collections import OrderedDict\n\n\nIS_JYTHON = sys.platform.lower().count('java') > 0\n\n\n# Type conversion tests\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        self.db = pg8000.connect(**db_connect)\n        self.cursor = self.db.cursor()\n\n    def tearDown(self):\n        self.cursor.close()\n        self.cursor = None\n        self.db.close()\n\n    def testTimeRoundtrip(self):\n        self.cursor.execute(\"SELECT %s as f1\", (datetime.time(4, 5, 6),))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], datetime.time(4, 5, 6))\n\n    def testDateRoundtrip(self):\n        v = datetime.date(2001, 2, 3)\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testBoolRoundtrip(self):\n        self.cursor.execute(\"SELECT %s as f1\", (True,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], True)\n\n    def testNullRoundtrip(self):\n        # We can't just \"SELECT %s\" and set None as the parameter, since it has\n        # no type.  That would result in a PG error, \"could not determine data\n        # type of parameter %s\".  So we create a temporary table, insert null\n        # values, and read them back.\n        self.cursor.execute(\n            \"CREATE TEMPORARY TABLE TestNullWrite \"\n            \"(f1 int4, f2 timestamp, f3 varchar)\")\n        self.cursor.execute(\n            \"INSERT INTO TestNullWrite VALUES (%s, %s, %s)\",\n            (None, None, None,))\n        self.cursor.execute(\"SELECT * FROM TestNullWrite\")\n        retval = self.cursor.fetchone()\n        self.assertEqual(retval, [None, None, None])\n\n    def testNullSelectFailure(self):\n        # See comment in TestNullRoundtrip.  This test is here to ensure that\n        # this behaviour is documented and doesn't mysteriously change.\n        self.assertRaises(\n            pg8000.ProgrammingError, self.cursor.execute,\n            \"SELECT %s as f1\", (None,))\n        self.db.rollback()\n\n    def testDecimalRoundtrip(self):\n        values = (\n            \"1.1\", \"-1.1\", \"10000\", \"20000\", \"-1000000000.123456789\", \"1.0\",\n            \"12.44\")\n        for v in values:\n            self.cursor.execute(\"SELECT %s as f1\", (decimal.Decimal(v),))\n            retval = self.cursor.fetchall()\n            self.assertEqual(str(retval[0][0]), v)\n\n    def testFloatRoundtrip(self):\n        # This test ensures that the binary float value doesn't change in a\n        # roundtrip to the server.  That could happen if the value was\n        # converted to text and got rounded by a decimal place somewhere.\n        val = 1.756e-12\n        bin_orig = struct.pack(\"!d\", val)\n        self.cursor.execute(\"SELECT %s as f1\", (val,))\n        retval = self.cursor.fetchall()\n        bin_new = struct.pack(\"!d\", retval[0][0])\n        self.assertEqual(bin_new, bin_orig)\n\n    def test_float_plus_infinity_roundtrip(self):\n        v = float('inf')\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testStrRoundtrip(self):\n        v = \"hello world\"\n        self.cursor.execute(\n            \"create temporary table test_str (f character varying(255))\")\n        self.cursor.execute(\"INSERT INTO test_str VALUES (%s)\", (v,))\n        self.cursor.execute(\"SELECT * from test_str\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n        if PY2:\n            v = \"hello \\xce\\x94 world\"\n            self.cursor.execute(\"SELECT cast(%s as varchar) as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v.decode('utf8'))\n\n    def test_str_then_int(self):\n        v1 = \"hello world\"\n        self.cursor.execute(\"SELECT cast(%s as varchar) as f1\", (v1,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v1)\n\n        v2 = 1\n        self.cursor.execute(\"SELECT cast(%s as varchar) as f1\", (v2,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], str(v2))\n\n    def testUnicodeRoundtrip(self):\n        v = u(\"hello \\u0173 world\")\n        self.cursor.execute(\"SELECT cast(%s as varchar) as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testLongRoundtrip(self):\n        self.cursor.execute(\n            \"SELECT %s\", (50000000000000,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 50000000000000)\n\n    def testIntExecuteMany(self):\n        self.cursor.executemany(\"SELECT %s\", ((1,), (40000,)))\n        self.cursor.fetchall()\n\n        v = ([None], [4])\n        self.cursor.execute(\n            \"create temporary table test_int (f integer)\")\n        self.cursor.executemany(\"INSERT INTO test_int VALUES (%s)\", v)\n        self.cursor.execute(\"SELECT * from test_int\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval, v)\n\n    def testIntRoundtrip(self):\n        int2 = 21\n        int4 = 23\n        int8 = 20\n\n        test_values = [\n            (0, int2),\n            (-32767, int2),\n            (-32768, int4),\n            (+32767, int2),\n            (+32768, int4),\n            (-2147483647, int4),\n            (-2147483648, int8),\n            (+2147483647, int4),\n            (+2147483648, int8),\n            (-9223372036854775807, int8),\n            (+9223372036854775807, int8)]\n\n        for value, typoid in test_values:\n            self.cursor.execute(\"SELECT %s\", (value,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], value)\n            column_name, column_typeoid = self.cursor.description[0][0:2]\n            self.assertEqual(column_typeoid, typoid)\n\n    def testByteaRoundtrip(self):\n        self.cursor.execute(\n            \"SELECT %s as f1\",\n            (pg8000.Binary(b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\")),))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], b(\"\\x00\\x01\\x02\\x03\\x02\\x01\\x00\"))\n\n    def test_bytearray_round_trip(self):\n        binary = b'\\x00\\x01\\x02\\x03\\x02\\x01\\x00'\n        self.cursor.execute(\"SELECT %s as f1\", (bytearray(binary),))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], binary)\n\n    def test_bytearray_subclass_round_trip(self):\n        class BClass(bytearray):\n            pass\n        binary = b'\\x00\\x01\\x02\\x03\\x02\\x01\\x00'\n        self.cursor.execute(\"SELECT %s as f1\", (BClass(binary),))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], binary)\n\n    def testTimestampRoundtrip(self):\n        v = datetime.datetime(2001, 2, 3, 4, 5, 6, 170000)\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n        # Test that time zone doesn't affect it\n        # Jython 2.5.3 doesn't have a time.tzset() so skip\n        if not IS_JYTHON:\n            orig_tz = os.environ.get('TZ')\n            os.environ['TZ'] = \"America/Edmonton\"\n            time.tzset()\n\n            self.cursor.execute(\"SELECT %s as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v)\n\n            if orig_tz is None:\n                del os.environ['TZ']\n            else:\n                os.environ['TZ'] = orig_tz\n            time.tzset()\n\n    def testIntervalRoundtrip(self):\n        v = pg8000.Interval(microseconds=123456789, days=2, months=24)\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n        v = datetime.timedelta(seconds=30)\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def test_enum_str_round_trip(self):\n        try:\n            self.cursor.execute(\n                \"create type lepton as enum ('electron', 'muon', 'tau')\")\n        except pg8000.ProgrammingError:\n            self.db.rollback()\n\n        v = 'muon'\n        self.cursor.execute(\"SELECT cast(%s as lepton) as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n        self.cursor.execute(\n            \"CREATE TEMPORARY TABLE testenum \"\n            \"(f1 lepton)\")\n        self.cursor.execute(\n            \"INSERT INTO testenum VALUES (cast(%s as lepton))\", ('electron',))\n        self.cursor.execute(\"drop table testenum\")\n        self.cursor.execute(\"drop type lepton\")\n        self.db.commit()\n\n    def test_enum_custom_round_trip(self):\n        class Lepton(object):\n            # Implements PEP 435 in the minimal fashion needed\n            __members__ = OrderedDict()\n\n            def __init__(self, name, value, alias=None):\n                self.name = name\n                self.value = value\n                self.__members__[name] = self\n                setattr(self.__class__, name, self)\n                if alias:\n                    self.__members__[alias] = self\n                    setattr(self.__class__, alias, self)\n\n        try:\n            self.cursor.execute(\n                \"create type lepton as enum ('1', '2', '3')\")\n        except pg8000.ProgrammingError:\n            self.db.rollback()\n\n        v = Lepton('muon', '2')\n        self.cursor.execute(\n            \"SELECT cast(%s as lepton) as f1\", (PGEnum(v),))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v.value)\n        self.cursor.execute(\"drop type lepton\")\n        self.db.commit()\n\n    def test_enum_py_round_trip(self):\n        try:\n            from enum import Enum\n\n            class Lepton(Enum):\n                electron = '1'\n                muon = '2'\n                tau = '3'\n\n            try:\n                self.cursor.execute(\n                    \"create type lepton as enum ('1', '2', '3')\")\n            except pg8000.ProgrammingError:\n                self.db.rollback()\n\n            v = Lepton.muon\n            self.cursor.execute(\"SELECT cast(%s as lepton) as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v.value)\n\n            self.cursor.execute(\n                \"CREATE TEMPORARY TABLE testenum \"\n                \"(f1 lepton)\")\n            self.cursor.execute(\n                \"INSERT INTO testenum VALUES (cast(%s as lepton))\",\n                (Lepton.electron,))\n            self.cursor.execute(\"drop table testenum\")\n            self.cursor.execute(\"drop type lepton\")\n            self.db.commit()\n        except ImportError:\n            pass\n\n    def testXmlRoundtrip(self):\n        v = '<genome>gatccgagtac</genome>'\n        self.cursor.execute(\"select xmlparse(content %s) as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testUuidRoundtrip(self):\n        v = uuid.UUID('911460f2-1f43-fea2-3e2c-e01fd5b5069d')\n        self.cursor.execute(\"select %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testInetRoundtrip(self):\n        try:\n            import ipaddress\n\n            v = ipaddress.ip_network('192.168.0.0/28')\n            self.cursor.execute(\"select %s as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v)\n\n            v = ipaddress.ip_address('192.168.0.1')\n            self.cursor.execute(\"select %s as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v)\n\n        except ImportError:\n            for v in ('192.168.100.128/25', '192.168.0.1'):\n                self.cursor.execute(\n                    \"select cast(cast(%s as varchar) as inet) as f1\", (v,))\n                retval = self.cursor.fetchall()\n                self.assertEqual(retval[0][0], v)\n\n    def testXidRoundtrip(self):\n        v = 86722\n        self.cursor.execute(\n            \"select cast(cast(%s as varchar) as xid) as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n        # Should complete without an exception\n        self.cursor.execute(\n            \"select * from pg_locks where transactionid = %s\", (97712,))\n        retval = self.cursor.fetchall()\n\n    def testInt2VectorIn(self):\n        self.cursor.execute(\"select cast('1 2' as int2vector) as f1\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [1, 2])\n\n        # Should complete without an exception\n        self.cursor.execute(\"select indkey from pg_index\")\n        retval = self.cursor.fetchall()\n\n    def testTimestampTzOut(self):\n        self.cursor.execute(\n            \"SELECT '2001-02-03 04:05:06.17 America/Edmonton'\"\n            \"::timestamp with time zone\")\n        retval = self.cursor.fetchall()\n        dt = retval[0][0]\n        self.assertEqual(dt.tzinfo is not None, True, \"no tzinfo returned\")\n        self.assertEqual(\n            dt.astimezone(pg8000.utc),\n            datetime.datetime(2001, 2, 3, 11, 5, 6, 170000, pg8000.utc),\n            \"retrieved value match failed\")\n\n    def testTimestampTzRoundtrip(self):\n        if not IS_JYTHON:\n            mst = pytz.timezone(\"America/Edmonton\")\n            v1 = mst.localize(datetime.datetime(2001, 2, 3, 4, 5, 6, 170000))\n            self.cursor.execute(\"SELECT %s as f1\", (v1,))\n            retval = self.cursor.fetchall()\n            v2 = retval[0][0]\n            self.assertNotEqual(v2.tzinfo, None)\n            self.assertEqual(v1, v2)\n\n    def testTimestampMismatch(self):\n        if not IS_JYTHON:\n            mst = pytz.timezone(\"America/Edmonton\")\n            self.cursor.execute(\"SET SESSION TIME ZONE 'America/Edmonton'\")\n            try:\n                self.cursor.execute(\n                    \"CREATE TEMPORARY TABLE TestTz \"\n                    \"(f1 timestamp with time zone, \"\n                    \"f2 timestamp without time zone)\")\n                self.cursor.execute(\n                    \"INSERT INTO TestTz (f1, f2) VALUES (%s, %s)\", (\n                        # insert timestamp into timestamptz field (v1)\n                        datetime.datetime(2001, 2, 3, 4, 5, 6, 170000),\n                        # insert timestamptz into timestamp field (v2)\n                        mst.localize(datetime.datetime(\n                            2001, 2, 3, 4, 5, 6, 170000))))\n                self.cursor.execute(\"SELECT f1, f2 FROM TestTz\")\n                retval = self.cursor.fetchall()\n\n                # when inserting a timestamp into a timestamptz field,\n                # postgresql assumes that it is in local time. So the value\n                # that comes out will be the server's local time interpretation\n                # of v1. We've set the server's TZ to MST, the time should\n                # be...\n                f1 = retval[0][0]\n                self.assertEqual(\n                    f1, datetime.datetime(\n                        2001, 2, 3, 11, 5, 6, 170000, pytz.utc))\n\n                # inserting the timestamptz into a timestamp field, pg8000\n                # converts the value into UTC, and then the PG server converts\n                # it into local time for insertion into the field. When we\n                # query for it, we get the same time back, like the tz was\n                # dropped.\n                f2 = retval[0][1]\n                self.assertEqual(\n                    f2, datetime.datetime(2001, 2, 3, 4, 5, 6, 170000))\n            finally:\n                self.cursor.execute(\"SET SESSION TIME ZONE DEFAULT\")\n\n    def testNameOut(self):\n        # select a field that is of \"name\" type:\n        self.cursor.execute(\"SELECT usename FROM pg_user\")\n        self.cursor.fetchall()\n        # It is sufficient that no errors were encountered.\n\n    def testOidOut(self):\n        self.cursor.execute(\"SELECT oid FROM pg_type\")\n        self.cursor.fetchall()\n        # It is sufficient that no errors were encountered.\n\n    def testBooleanOut(self):\n        self.cursor.execute(\"SELECT cast('t' as bool)\")\n        retval = self.cursor.fetchall()\n        self.assertTrue(retval[0][0])\n\n    def testNumericOut(self):\n        for num in ('5000', '50.34'):\n            self.cursor.execute(\"SELECT \" + num + \"::numeric\")\n            retval = self.cursor.fetchall()\n            self.assertEqual(str(retval[0][0]), num)\n\n    def testInt2Out(self):\n        self.cursor.execute(\"SELECT 5000::smallint\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 5000)\n\n    def testInt4Out(self):\n        self.cursor.execute(\"SELECT 5000::integer\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 5000)\n\n    def testInt8Out(self):\n        self.cursor.execute(\"SELECT 50000000000000::bigint\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 50000000000000)\n\n    def testFloat4Out(self):\n        self.cursor.execute(\"SELECT 1.1::real\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 1.1000000238418579)\n\n    def testFloat8Out(self):\n        self.cursor.execute(\"SELECT 1.1::double precision\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], 1.1000000000000001)\n\n    def testVarcharOut(self):\n        self.cursor.execute(\"SELECT 'hello'::varchar(20)\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], \"hello\")\n\n    def testCharOut(self):\n        self.cursor.execute(\"SELECT 'hello'::char(20)\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], \"hello               \")\n\n    def testTextOut(self):\n        self.cursor.execute(\"SELECT 'hello'::text\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], \"hello\")\n\n    def testIntervalOut(self):\n        self.cursor.execute(\n            \"SELECT '1 month 16 days 12 hours 32 minutes 64 seconds'\"\n            \"::interval\")\n        retval = self.cursor.fetchall()\n        expected_value = pg8000.Interval(\n            microseconds=(12 * 60 * 60 * 1000 * 1000) +\n            (32 * 60 * 1000 * 1000) + (64 * 1000 * 1000),\n            days=16, months=1)\n        self.assertEqual(retval[0][0], expected_value)\n\n        self.cursor.execute(\"select interval '30 seconds'\")\n        retval = self.cursor.fetchall()\n        expected_value = datetime.timedelta(seconds=30)\n        self.assertEqual(retval[0][0], expected_value)\n\n        self.cursor.execute(\"select interval '12 days 30 seconds'\")\n        retval = self.cursor.fetchall()\n        expected_value = datetime.timedelta(days=12, seconds=30)\n        self.assertEqual(retval[0][0], expected_value)\n\n    def testTimestampOut(self):\n        self.cursor.execute(\"SELECT '2001-02-03 04:05:06.17'::timestamp\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(\n            retval[0][0], datetime.datetime(2001, 2, 3, 4, 5, 6, 170000))\n\n    # confirms that pg8000's binary output methods have the same output for\n    # a data type as the PG server\n    def testBinaryOutputMethods(self):\n        methods = (\n            (\"float8send\", 22.2),\n            (\"timestamp_send\", datetime.datetime(2001, 2, 3, 4, 5, 6, 789)),\n            (\"byteasend\", pg8000.Binary(b(\"\\x01\\x02\"))),\n            (\"interval_send\", pg8000.Interval(1234567, 123, 123)),)\n        for method_out, value in methods:\n            self.cursor.execute(\"SELECT %s(%%s) as f1\" % method_out, (value,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(\n                retval[0][0], self.db.make_params((value,))[0][2](value))\n\n    def testInt4ArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{1,2,3,4}'::INT[] AS f1, \"\n            \"'{{1,2,3},{4,5,6}}'::INT[][] AS f2, \"\n            \"'{{{1,2},{3,4}},{{NULL,6},{7,8}}}'::INT[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [1, 2, 3, 4])\n        self.assertEqual(f2, [[1, 2, 3], [4, 5, 6]])\n        self.assertEqual(f3, [[[1, 2], [3, 4]], [[None, 6], [7, 8]]])\n\n    def testInt2ArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{1,2,3,4}'::INT2[] AS f1, \"\n            \"'{{1,2,3},{4,5,6}}'::INT2[][] AS f2, \"\n            \"'{{{1,2},{3,4}},{{NULL,6},{7,8}}}'::INT2[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [1, 2, 3, 4])\n        self.assertEqual(f2, [[1, 2, 3], [4, 5, 6]])\n        self.assertEqual(f3, [[[1, 2], [3, 4]], [[None, 6], [7, 8]]])\n\n    def testInt8ArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{1,2,3,4}'::INT8[] AS f1, \"\n            \"'{{1,2,3},{4,5,6}}'::INT8[][] AS f2, \"\n            \"'{{{1,2},{3,4}},{{NULL,6},{7,8}}}'::INT8[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [1, 2, 3, 4])\n        self.assertEqual(f2, [[1, 2, 3], [4, 5, 6]])\n        self.assertEqual(f3, [[[1, 2], [3, 4]], [[None, 6], [7, 8]]])\n\n    def testBoolArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{TRUE,FALSE,FALSE,TRUE}'::BOOL[] AS f1, \"\n            \"'{{TRUE,FALSE,TRUE},{FALSE,TRUE,FALSE}}'::BOOL[][] AS f2, \"\n            \"'{{{TRUE,FALSE},{FALSE,TRUE}},{{NULL,TRUE},{FALSE,FALSE}}}'\"\n            \"::BOOL[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [True, False, False, True])\n        self.assertEqual(f2, [[True, False, True], [False, True, False]])\n        self.assertEqual(\n            f3,\n            [[[True, False], [False, True]], [[None, True], [False, False]]])\n\n    def testFloat4ArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{1,2,3,4}'::FLOAT4[] AS f1, \"\n            \"'{{1,2,3},{4,5,6}}'::FLOAT4[][] AS f2, \"\n            \"'{{{1,2},{3,4}},{{NULL,6},{7,8}}}'::FLOAT4[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [1, 2, 3, 4])\n        self.assertEqual(f2, [[1, 2, 3], [4, 5, 6]])\n        self.assertEqual(f3, [[[1, 2], [3, 4]], [[None, 6], [7, 8]]])\n\n    def testFloat8ArrayOut(self):\n        self.cursor.execute(\n            \"SELECT '{1,2,3,4}'::FLOAT8[] AS f1, \"\n            \"'{{1,2,3},{4,5,6}}'::FLOAT8[][] AS f2, \"\n            \"'{{{1,2},{3,4}},{{NULL,6},{7,8}}}'::FLOAT8[][][] AS f3\")\n        f1, f2, f3 = self.cursor.fetchone()\n        self.assertEqual(f1, [1, 2, 3, 4])\n        self.assertEqual(f2, [[1, 2, 3], [4, 5, 6]])\n        self.assertEqual(f3, [[[1, 2], [3, 4]], [[None, 6], [7, 8]]])\n\n    def testIntArrayRoundtrip(self):\n        # send small int array, should be sent as INT2[]\n        self.cursor.execute(\"SELECT %s as f1\", ([1, 2, 3],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [1, 2, 3])\n        column_name, column_typeoid = self.cursor.description[0][0:2]\n        self.assertEqual(column_typeoid, 1005, \"type should be INT2[]\")\n\n        # test multi-dimensional array, should be sent as INT2[]\n        self.cursor.execute(\"SELECT %s as f1\", ([[1, 2], [3, 4]],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [[1, 2], [3, 4]])\n\n        column_name, column_typeoid = self.cursor.description[0][0:2]\n        self.assertEqual(column_typeoid, 1005, \"type should be INT2[]\")\n\n        # a larger value should kick it up to INT4[]...\n        self.cursor.execute(\"SELECT %s as f1 -- integer[]\", ([70000, 2, 3],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [70000, 2, 3])\n        column_name, column_typeoid = self.cursor.description[0][0:2]\n        self.assertEqual(column_typeoid, 1007, \"type should be INT4[]\")\n\n        # a much larger value should kick it up to INT8[]...\n        self.cursor.execute(\n            \"SELECT %s as f1 -- bigint[]\", ([7000000000, 2, 3],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(\n            retval[0][0], [7000000000, 2, 3],\n            \"retrieved value match failed\")\n        column_name, column_typeoid = self.cursor.description[0][0:2]\n        self.assertEqual(column_typeoid, 1016, \"type should be INT8[]\")\n\n    def testIntArrayWithNullRoundtrip(self):\n        self.cursor.execute(\"SELECT %s as f1\", ([1, None, 3],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [1, None, 3])\n\n    def testFloatArrayRoundtrip(self):\n        self.cursor.execute(\"SELECT %s as f1\", ([1.1, 2.2, 3.3],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [1.1, 2.2, 3.3])\n\n    def testBoolArrayRoundtrip(self):\n        self.cursor.execute(\"SELECT %s as f1\", ([True, False, None],))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], [True, False, None])\n\n    def testStringArrayOut(self):\n        self.cursor.execute(\"SELECT '{a,b,c}'::TEXT[] AS f1\")\n        self.assertEqual(self.cursor.fetchone()[0], [\"a\", \"b\", \"c\"])\n        self.cursor.execute(\"SELECT '{a,b,c}'::CHAR[] AS f1\")\n        self.assertEqual(self.cursor.fetchone()[0], [\"a\", \"b\", \"c\"])\n        self.cursor.execute(\"SELECT '{a,b,c}'::VARCHAR[] AS f1\")\n        self.assertEqual(self.cursor.fetchone()[0], [\"a\", \"b\", \"c\"])\n        self.cursor.execute(\"SELECT '{a,b,c}'::CSTRING[] AS f1\")\n        self.assertEqual(self.cursor.fetchone()[0], [\"a\", \"b\", \"c\"])\n        self.cursor.execute(\"SELECT '{a,b,c}'::NAME[] AS f1\")\n        self.assertEqual(self.cursor.fetchone()[0], [\"a\", \"b\", \"c\"])\n        self.cursor.execute(\"SELECT '{}'::text[];\")\n        self.assertEqual(self.cursor.fetchone()[0], [])\n        self.cursor.execute(\"SELECT '{NULL,\\\"NULL\\\",NULL,\\\"\\\"}'::text[];\")\n        self.assertEqual(self.cursor.fetchone()[0], [None, 'NULL', None, \"\"])\n\n    def testNumericArrayOut(self):\n        self.cursor.execute(\"SELECT '{1.1,2.2,3.3}'::numeric[] AS f1\")\n        self.assertEqual(\n            self.cursor.fetchone()[0], [\n                decimal.Decimal(\"1.1\"), decimal.Decimal(\"2.2\"),\n                decimal.Decimal(\"3.3\")])\n\n    def testNumericArrayRoundtrip(self):\n        v = [decimal.Decimal(\"1.1\"), None, decimal.Decimal(\"3.3\")]\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testStringArrayRoundtrip(self):\n        v = [\n            \"Hello!\", \"World!\", \"abcdefghijklmnopqrstuvwxyz\", \"\",\n            \"A bunch of random characters:\",\n            \" ~!@#$%^&*()_+`1234567890-=[]\\\\{}|{;':\\\",./<>?\\t\", None]\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testUnicodeArrayRoundtrip(self):\n        if PY2:\n            v = map(unicode, (\"Second\", \"To\", None))  # noqa\n            self.cursor.execute(\"SELECT %s as f1\", (v,))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], v)\n\n    def testEmptyArray(self):\n        v = []\n        self.cursor.execute(\"SELECT %s as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n    def testArrayContentNotSupported(self):\n        class Kajigger(object):\n            pass\n        self.assertRaises(\n            pg8000.ArrayContentNotSupportedError,\n            self.db.array_inspect, [[Kajigger()], [None], [None]])\n        self.db.rollback()\n\n    def testArrayDimensions(self):\n        for arr in (\n                [1, [2]], [[1], [2], [3, 4]],\n                [[[1]], [[2]], [[3, 4]]],\n                [[[1]], [[2]], [[3, 4]]],\n                [[[[1]]], [[[2]]], [[[3, 4]]]],\n                [[1, 2, 3], [4, [5], 6]]):\n\n            arr_send = self.db.array_inspect(arr)[2]\n            self.assertRaises(\n                pg8000.ArrayDimensionsNotConsistentError, arr_send, arr)\n            self.db.rollback()\n\n    def testArrayHomogenous(self):\n        arr = [[[1]], [[2]], [[3.1]]]\n        arr_send = self.db.array_inspect(arr)[2]\n        self.assertRaises(\n            pg8000.ArrayContentNotHomogenousError, arr_send, arr)\n        self.db.rollback()\n\n    def testArrayInspect(self):\n        self.db.array_inspect([1, 2, 3])\n        self.db.array_inspect([[1], [2], [3]])\n        self.db.array_inspect([[[1]], [[2]], [[3]]])\n\n    def testMacaddr(self):\n        self.cursor.execute(\"SELECT macaddr '08002b:010203'\")\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], \"08:00:2b:01:02:03\")\n\n    def testTsvectorRoundtrip(self):\n        self.cursor.execute(\n            \"SELECT cast(%s as tsvector)\",\n            ('a fat cat sat on a mat and ate a fat rat',))\n        retval = self.cursor.fetchall()\n        self.assertEqual(\n            retval[0][0], \"'a' 'and' 'ate' 'cat' 'fat' 'mat' 'on' 'rat' 'sat'\")\n\n    def testHstoreRoundtrip(self):\n        val = '\"a\"=>\"1\"'\n        self.cursor.execute(\"SELECT cast(%s as hstore)\", (val,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], val)\n\n    def testJsonRoundtrip(self):\n        if self.db._server_version >= LooseVersion('9.2'):\n            val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}\n            self.cursor.execute(\n                \"SELECT %s\", (pg8000.PGJson(val),))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], val)\n\n    def testJsonbRoundtrip(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}\n            self.cursor.execute(\n                \"SELECT cast(%s as jsonb)\", (json.dumps(val),))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], val)\n\n    def test_json_access_object(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}\n            self.cursor.execute(\n                \"SELECT cast(%s as json) -> %s\", (json.dumps(val), 'name'))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], 'Apollo 11 Cave')\n\n    def test_jsonb_access_object(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            val = {'name': 'Apollo 11 Cave', 'zebra': True, 'age': 26.003}\n            self.cursor.execute(\n                \"SELECT cast(%s as jsonb) -> %s\", (json.dumps(val), 'name'))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], 'Apollo 11 Cave')\n\n    def test_json_access_array(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            val = [-1, -2, -3, -4, -5]\n            self.cursor.execute(\n                \"SELECT cast(%s as json) -> %s\", (json.dumps(val), 2))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], -3)\n\n    def testJsonbAccessArray(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            val = [-1, -2, -3, -4, -5]\n            self.cursor.execute(\n                \"SELECT cast(%s as jsonb) -> %s\", (json.dumps(val), 2))\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], -3)\n\n    def test_jsonb_access_path(self):\n        if self.db._server_version >= LooseVersion('9.4'):\n            j = {\n                \"a\": [1, 2, 3],\n                \"b\": [4, 5, 6]}\n\n            path = ['a', '2']\n\n            self.cursor.execute(\"SELECT %s #>> %s\", [PGJsonb(j), path])\n            retval = self.cursor.fetchall()\n            self.assertEqual(retval[0][0], str(j[path[0]][int(path[1])]))\n\n    def test_timestamp_send_float(self):\n        assert b('A\\xbe\\x19\\xcf\\x80\\x00\\x00\\x00') == \\\n            pg8000.core.timestamp_send_float(\n                datetime.datetime(2016, 1, 2, 0, 0))\n\n    def test_infinity_timestamp_roundtrip(self):\n        v = 'infinity'\n        self.cursor.execute(\"SELECT cast(%s as timestamp) as f1\", (v,))\n        retval = self.cursor.fetchall()\n        self.assertEqual(retval[0][0], v)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tests/test_typeobjects.py",
    "content": "import unittest\nfrom pg8000 import Interval\n\n\n# Type conversion tests\nclass Tests(unittest.TestCase):\n    def setUp(self):\n        pass\n\n    def tearDown(self):\n        pass\n\n    def testIntervalConstructor(self):\n        i = Interval(days=1)\n        self.assertEqual(i.months, 0)\n        self.assertEqual(i.days, 1)\n        self.assertEqual(i.microseconds, 0)\n\n    def intervalRangeTest(self, parameter, in_range, out_of_range):\n        for v in out_of_range:\n            try:\n                Interval(**{parameter: v})\n                self.fail(\"expected OverflowError\")\n            except OverflowError:\n                pass\n        for v in in_range:\n            Interval(**{parameter: v})\n\n    def testIntervalDaysRange(self):\n        out_of_range_days = (-2147483648, +2147483648,)\n        in_range_days = (-2147483647, +2147483647,)\n        self.intervalRangeTest(\"days\", in_range_days, out_of_range_days)\n\n    def testIntervalMonthsRange(self):\n        out_of_range_months = (-2147483648, +2147483648,)\n        in_range_months = (-2147483647, +2147483647,)\n        self.intervalRangeTest(\"months\", in_range_months, out_of_range_months)\n\n    def testIntervalMicrosecondsRange(self):\n        out_of_range_microseconds = (\n            -9223372036854775808, +9223372036854775808,)\n        in_range_microseconds = (\n            -9223372036854775807, +9223372036854775807,)\n        self.intervalRangeTest(\n            \"microseconds\", in_range_microseconds, out_of_range_microseconds)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "tox.ini",
    "content": "# Tox (http://tox.testrun.org/) is a tool for running tests\n# in multiple virtualenvs. This configuration file will run the\n# test suite on all supported python versions. To use it, \"pip install tox\"\n# and then run \"tox\" from this directory.\n\n[tox]\nskip_missing_interpreters=True\n\n\n[testenv]\ncommands =\n    nosetests -x\n    python -m doctest README.adoc\n    flake8 pg8000\n    python setup.py check\ndeps =\n    nose\n    flake8\n    pytz\n"
  },
  {
    "path": "versioneer.py",
    "content": "\n# Version: 0.15\n\n\"\"\"\nThe Versioneer\n==============\n\n* like a rocketeer, but for versions!\n* https://github.com/warner/python-versioneer\n* Brian Warner\n* License: Public Domain\n* Compatible With: python2.6, 2.7, 3.2, 3.3, 3.4, and pypy\n* [![Latest Version]\n(https://pypip.in/version/versioneer/badge.svg?style=flat)\n](https://pypi.python.org/pypi/versioneer/)\n* [![Build Status]\n(https://travis-ci.org/warner/python-versioneer.png?branch=master)\n](https://travis-ci.org/warner/python-versioneer)\n\nThis is a tool for managing a recorded version number in distutils-based\npython projects. The goal is to remove the tedious and error-prone \"update\nthe embedded version string\" step from your release process. Making a new\nrelease should be as easy as recording a new tag in your version-control\nsystem, and maybe making new tarballs.\n\n\n## Quick Install\n\n* `pip install versioneer` to somewhere to your $PATH\n* add a `[versioneer]` section to your setup.cfg (see below)\n* run `versioneer install` in your source tree, commit the results\n\n## Version Identifiers\n\nSource trees come from a variety of places:\n\n* a version-control system checkout (mostly used by developers)\n* a nightly tarball, produced by build automation\n* a snapshot tarball, produced by a web-based VCS browser, like github's\n  \"tarball from tag\" feature\n* a release tarball, produced by \"setup.py sdist\", distributed through PyPI\n\nWithin each source tree, the version identifier (either a string or a number,\nthis tool is format-agnostic) can come from a variety of places:\n\n* ask the VCS tool itself, e.g. \"git describe\" (for checkouts), which knows\n  about recent \"tags\" and an absolute revision-id\n* the name of the directory into which the tarball was unpacked\n* an expanded VCS keyword ($Id$, etc)\n* a `_version.py` created by some earlier build step\n\nFor released software, the version identifier is closely related to a VCS\ntag. Some projects use tag names that include more than just the version\nstring (e.g. \"myproject-1.2\" instead of just \"1.2\"), in which case the tool\nneeds to strip the tag prefix to extract the version identifier. For\nunreleased software (between tags), the version identifier should provide\nenough information to help developers recreate the same tree, while also\ngiving them an idea of roughly how old the tree is (after version 1.2, before\nversion 1.3). Many VCS systems can report a description that captures this,\nfor example `git describe --tags --dirty --always` reports things like\n\"0.7-1-g574ab98-dirty\" to indicate that the checkout is one revision past the\n0.7 tag, has a unique revision id of \"574ab98\", and is \"dirty\" (it has\nuncommitted changes.\n\nThe version identifier is used for multiple purposes:\n\n* to allow the module to self-identify its version: `myproject.__version__`\n* to choose a name and prefix for a 'setup.py sdist' tarball\n\n## Theory of Operation\n\nVersioneer works by adding a special `_version.py` file into your source\ntree, where your `__init__.py` can import it. This `_version.py` knows how to\ndynamically ask the VCS tool for version information at import time.\n\n`_version.py` also contains `$Revision$` markers, and the installation\nprocess marks `_version.py` to have this marker rewritten with a tag name\nduring the `git archive` command. As a result, generated tarballs will\ncontain enough information to get the proper version.\n\nTo allow `setup.py` to compute a version too, a `versioneer.py` is added to\nthe top level of your source tree, next to `setup.py` and the `setup.cfg`\nthat configures it. This overrides several distutils/setuptools commands to\ncompute the version when invoked, and changes `setup.py build` and `setup.py\nsdist` to replace `_version.py` with a small static file that contains just\nthe generated version data.\n\n## Installation\n\nFirst, decide on values for the following configuration variables:\n\n* `VCS`: the version control system you use. Currently accepts \"git\".\n\n* `style`: the style of version string to be produced. See \"Styles\" below for\n  details. Defaults to \"pep440\", which looks like\n  `TAG[+DISTANCE.gSHORTHASH[.dirty]]`.\n\n* `versionfile_source`:\n\n  A project-relative pathname into which the generated version strings should\n  be written. This is usually a `_version.py` next to your project's main\n  `__init__.py` file, so it can be imported at runtime. If your project uses\n  `src/myproject/__init__.py`, this should be `src/myproject/_version.py`.\n  This file should be checked in to your VCS as usual: the copy created below\n  by `setup.py setup_versioneer` will include code that parses expanded VCS\n  keywords in generated tarballs. The 'build' and 'sdist' commands will\n  replace it with a copy that has just the calculated version string.\n\n  This must be set even if your project does not have any modules (and will\n  therefore never import `_version.py`), since \"setup.py sdist\" -based trees\n  still need somewhere to record the pre-calculated version strings. Anywhere\n  in the source tree should do. If there is a `__init__.py` next to your\n  `_version.py`, the `setup.py setup_versioneer` command (described below)\n  will append some `__version__`-setting assignments, if they aren't already\n  present.\n\n* `versionfile_build`:\n\n  Like `versionfile_source`, but relative to the build directory instead of\n  the source directory. These will differ when your setup.py uses\n  'package_dir='. If you have `package_dir={'myproject': 'src/myproject'}`,\n  then you will probably have `versionfile_build='myproject/_version.py'` and\n  `versionfile_source='src/myproject/_version.py'`.\n\n  If this is set to None, then `setup.py build` will not attempt to rewrite\n  any `_version.py` in the built tree. If your project does not have any\n  libraries (e.g. if it only builds a script), then you should use\n  `versionfile_build = None` and override `distutils.command.build_scripts`\n  to explicitly insert a copy of `versioneer.get_version()` into your\n  generated script.\n\n* `tag_prefix`:\n\n  a string, like 'PROJECTNAME-', which appears at the start of all VCS tags.\n  If your tags look like 'myproject-1.2.0', then you should use\n  tag_prefix='myproject-'. If you use unprefixed tags like '1.2.0', this\n  should be an empty string.\n\n* `parentdir_prefix`:\n\n  a optional string, frequently the same as tag_prefix, which appears at the\n  start of all unpacked tarball filenames. If your tarball unpacks into\n  'myproject-1.2.0', this should be 'myproject-'. To disable this feature,\n  just omit the field from your `setup.cfg`.\n\nThis tool provides one script, named `versioneer`. That script has one mode,\n\"install\", which writes a copy of `versioneer.py` into the current directory\nand runs `versioneer.py setup` to finish the installation.\n\nTo versioneer-enable your project:\n\n* 1: Modify your `setup.cfg`, adding a section named `[versioneer]` and\n  populating it with the configuration values you decided earlier (note that\n  the option names are not case-sensitive):\n\n  ````\n  [versioneer]\n  VCS = git\n  style = pep440\n  versionfile_source = src/myproject/_version.py\n  versionfile_build = myproject/_version.py\n  tag_prefix = \"\"\n  parentdir_prefix = myproject-\n  ````\n\n* 2: Run `versioneer install`. This will do the following:\n\n  * copy `versioneer.py` into the top of your source tree\n  * create `_version.py` in the right place (`versionfile_source`)\n  * modify your `__init__.py` (if one exists next to `_version.py`) to define\n    `__version__` (by calling a function from `_version.py`)\n  * modify your `MANIFEST.in` to include both `versioneer.py` and the\n    generated `_version.py` in sdist tarballs\n\n  `versioneer install` will complain about any problems it finds with your\n  `setup.py` or `setup.cfg`. Run it multiple times until you have fixed all\n  the problems.\n\n* 3: add a `import versioneer` to your setup.py, and add the following\n  arguments to the setup() call:\n\n        version=versioneer.get_version(),\n        cmdclass=versioneer.get_cmdclass(),\n\n* 4: commit these changes to your VCS. To make sure you won't forget,\n  `versioneer install` will mark everything it touched for addition using\n  `git add`. Don't forget to add `setup.py` and `setup.cfg` too.\n\n## Post-Installation Usage\n\nOnce established, all uses of your tree from a VCS checkout should get the\ncurrent version string. All generated tarballs should include an embedded\nversion string (so users who unpack them will not need a VCS tool installed).\n\nIf you distribute your project through PyPI, then the release process should\nboil down to two steps:\n\n* 1: git tag 1.0\n* 2: python setup.py register sdist upload\n\nIf you distribute it through github (i.e. users use github to generate\ntarballs with `git archive`), the process is:\n\n* 1: git tag 1.0\n* 2: git push; git push --tags\n\nVersioneer will report \"0+untagged.NUMCOMMITS.gHASH\" until your tree has at\nleast one tag in its history.\n\n## Version-String Flavors\n\nCode which uses Versioneer can learn about its version string at runtime by\nimporting `_version` from your main `__init__.py` file and running the\n`get_versions()` function. From the \"outside\" (e.g. in `setup.py`), you can\nimport the top-level `versioneer.py` and run `get_versions()`.\n\nBoth functions return a dictionary with different flavors of version\ninformation:\n\n* `['version']`: A condensed version string, rendered using the selected\n  style. This is the most commonly used value for the project's version\n  string. The default \"pep440\" style yields strings like `0.11`,\n  `0.11+2.g1076c97`, or `0.11+2.g1076c97.dirty`. See the \"Styles\" section\n  below for alternative styles.\n\n* `['full-revisionid']`: detailed revision identifier. For Git, this is the\n  full SHA1 commit id, e.g. \"1076c978a8d3cfc70f408fe5974aa6c092c949ac\".\n\n* `['dirty']`: a boolean, True if the tree has uncommitted changes. Note that\n  this is only accurate if run in a VCS checkout, otherwise it is likely to\n  be False or None\n\n* `['error']`: if the version string could not be computed, this will be set\n  to a string describing the problem, otherwise it will be None. It may be\n  useful to throw an exception in setup.py if this is set, to avoid e.g.\n  creating tarballs with a version string of \"unknown\".\n\nSome variants are more useful than others. Including `full-revisionid` in a\nbug report should allow developers to reconstruct the exact code being tested\n(or indicate the presence of local changes that should be shared with the\ndevelopers). `version` is suitable for display in an \"about\" box or a CLI\n`--version` output: it can be easily compared against release notes and lists\nof bugs fixed in various releases.\n\nThe installer adds the following text to your `__init__.py` to place a basic\nversion in `YOURPROJECT.__version__`:\n\n    from ._version import get_versions\n    __version__ = get_versions()['version']\n    del get_versions\n\n## Styles\n\nThe setup.cfg `style=` configuration controls how the VCS information is\nrendered into a version string.\n\nThe default style, \"pep440\", produces a PEP440-compliant string, equal to the\nun-prefixed tag name for actual releases, and containing an additional \"local\nversion\" section with more detail for in-between builds. For Git, this is\nTAG[+DISTANCE.gHEX[.dirty]] , using information from `git describe --tags\n--dirty --always`. For example \"0.11+2.g1076c97.dirty\" indicates that the\ntree is like the \"1076c97\" commit but has uncommitted changes (\".dirty\"), and\nthat this commit is two revisions (\"+2\") beyond the \"0.11\" tag. For released\nsoftware (exactly equal to a known tag), the identifier will only contain the\nstripped tag, e.g. \"0.11\".\n\nOther styles are available. See details.md in the Versioneer source tree for\ndescriptions.\n\n## Debugging\n\nVersioneer tries to avoid fatal errors: if something goes wrong, it will tend\nto return a version of \"0+unknown\". To investigate the problem, run `setup.py\nversion`, which will run the version-lookup code in a verbose mode, and will\ndisplay the full contents of `get_versions()` (including the `error` string,\nwhich may help identify what went wrong).\n\n## Updating Versioneer\n\nTo upgrade your project to a new release of Versioneer, do the following:\n\n* install the new Versioneer (`pip install -U versioneer` or equivalent)\n* edit `setup.cfg`, if necessary, to include any new configuration settings\n  indicated by the release notes\n* re-run `versioneer install` in your source tree, to replace\n  `SRC/_version.py`\n* commit any changed files\n\n### Upgrading to 0.15\n\nStarting with this version, Versioneer is configured with a `[versioneer]`\nsection in your `setup.cfg` file. Earlier versions required the `setup.py` to\nset attributes on the `versioneer` module immediately after import. The new\nversion will refuse to run (raising an exception during import) until you\nhave provided the necessary `setup.cfg` section.\n\nIn addition, the Versioneer package provides an executable named\n`versioneer`, and the installation process is driven by running `versioneer\ninstall`. In 0.14 and earlier, the executable was named\n`versioneer-installer` and was run without an argument.\n\n### Upgrading to 0.14\n\n0.14 changes the format of the version string. 0.13 and earlier used\nhyphen-separated strings like \"0.11-2-g1076c97-dirty\". 0.14 and beyond use a\nplus-separated \"local version\" section strings, with dot-separated\ncomponents, like \"0.11+2.g1076c97\". PEP440-strict tools did not like the old\nformat, but should be ok with the new one.\n\n### Upgrading from 0.11 to 0.12\n\nNothing special.\n\n### Upgrading from 0.10 to 0.11\n\nYou must add a `versioneer.VCS = \"git\"` to your `setup.py` before re-running\n`setup.py setup_versioneer`. This will enable the use of additional\nversion-control systems (SVN, etc) in the future.\n\n## Future Directions\n\nThis tool is designed to make it easily extended to other version-control\nsystems: all VCS-specific components are in separate directories like\nsrc/git/ . The top-level `versioneer.py` script is assembled from these\ncomponents by running make-versioneer.py . In the future, make-versioneer.py\nwill take a VCS name as an argument, and will construct a version of\n`versioneer.py` that is specific to the given VCS. It might also take the\nconfiguration arguments that are currently provided manually during\ninstallation by editing setup.py . Alternatively, it might go the other\ndirection and include code from all supported VCS systems, reducing the\nnumber of intermediate scripts.\n\n\n## License\n\nTo make Versioneer easier to embed, all its code is hereby released into the\npublic domain. The `_version.py` that it creates is also in the public\ndomain.\n\n\"\"\"\n\nfrom __future__ import print_function\ntry:\n    import configparser\nexcept ImportError:\n    import ConfigParser as configparser\nimport errno\nimport json\nimport os\nimport re\nimport subprocess\nimport sys\n\n\nclass VersioneerConfig:\n    pass\n\n\ndef get_root():\n    # we require that all commands are run from the project root, i.e. the\n    # directory that contains setup.py, setup.cfg, and versioneer.py .\n    root = os.path.realpath(os.path.abspath(os.getcwd()))\n    setup_py = os.path.join(root, \"setup.py\")\n    versioneer_py = os.path.join(root, \"versioneer.py\")\n    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):\n        # allow 'python path/to/setup.py COMMAND'\n        root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))\n        setup_py = os.path.join(root, \"setup.py\")\n        versioneer_py = os.path.join(root, \"versioneer.py\")\n    if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):\n        err = (\"Versioneer was unable to run the project root directory. \"\n               \"Versioneer requires setup.py to be executed from \"\n               \"its immediate directory (like 'python setup.py COMMAND'), \"\n               \"or in a way that lets it use sys.argv[0] to find the root \"\n               \"(like 'python path/to/setup.py COMMAND').\")\n        raise VersioneerBadRootError(err)\n    try:\n        # Certain runtime workflows (setup.py install/develop in a setuptools\n        # tree) execute all dependencies in a single python process, so\n        # \"versioneer\" may be imported multiple times, and python's shared\n        # module-import table will cache the first one. So we can't use\n        # os.path.dirname(__file__), as that will find whichever\n        # versioneer.py was first imported, even in later projects.\n        me = os.path.realpath(os.path.abspath(__file__))\n        if os.path.splitext(me)[0] != os.path.splitext(versioneer_py)[0]:\n            print(\"Warning: build in %s is using versioneer.py from %s\"\n                  % (os.path.dirname(me), versioneer_py))\n    except NameError:\n        pass\n    return root\n\n\ndef get_config_from_root(root):\n    # This might raise EnvironmentError (if setup.cfg is missing), or\n    # configparser.NoSectionError (if it lacks a [versioneer] section), or\n    # configparser.NoOptionError (if it lacks \"VCS=\"). See the docstring at\n    # the top of versioneer.py for instructions on writing your setup.cfg .\n    setup_cfg = os.path.join(root, \"setup.cfg\")\n    parser = configparser.SafeConfigParser()\n    with open(setup_cfg, \"r\") as f:\n        parser.readfp(f)\n    VCS = parser.get(\"versioneer\", \"VCS\")  # mandatory\n\n    def get(parser, name):\n        if parser.has_option(\"versioneer\", name):\n            return parser.get(\"versioneer\", name)\n        return None\n    cfg = VersioneerConfig()\n    cfg.VCS = VCS\n    cfg.style = get(parser, \"style\") or \"\"\n    cfg.versionfile_source = get(parser, \"versionfile_source\")\n    cfg.versionfile_build = get(parser, \"versionfile_build\")\n    cfg.tag_prefix = get(parser, \"tag_prefix\")\n    cfg.parentdir_prefix = get(parser, \"parentdir_prefix\")\n    cfg.verbose = get(parser, \"verbose\")\n    return cfg\n\n\nclass NotThisMethod(Exception):\n    pass\n\n# these dictionaries contain VCS-specific tools\nLONG_VERSION_PY = {}\nHANDLERS = {}\n\n\ndef register_vcs_handler(vcs, method):  # decorator\n    def decorate(f):\n        if vcs not in HANDLERS:\n            HANDLERS[vcs] = {}\n        HANDLERS[vcs][method] = f\n        return f\n    return decorate\n\n\ndef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):\n    assert isinstance(commands, list)\n    p = None\n    for c in commands:\n        try:\n            dispcmd = str([c] + args)\n            # remember shell=False, so use git.cmd on windows, not just git\n            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,\n                                 stderr=(subprocess.PIPE if hide_stderr\n                                         else None))\n            break\n        except EnvironmentError:\n            e = sys.exc_info()[1]\n            if e.errno == errno.ENOENT:\n                continue\n            if verbose:\n                print(\"unable to run %s\" % dispcmd)\n                print(e)\n            return None\n    else:\n        if verbose:\n            print(\"unable to find command, tried %s\" % (commands,))\n        return None\n    stdout = p.communicate()[0].strip()\n    if sys.version_info[0] >= 3:\n        stdout = stdout.decode()\n    if p.returncode != 0:\n        if verbose:\n            print(\"unable to run %s (error)\" % dispcmd)\n        return None\n    return stdout\nLONG_VERSION_PY['git'] = '''\n# This file helps to compute a version number in source trees obtained from\n# git-archive tarball (such as those provided by githubs download-from-tag\n# feature). Distribution tarballs (built by setup.py sdist) and build\n# directories (produced by setup.py build) will contain a much shorter file\n# that just contains the computed version number.\n\n# This file is released into the public domain. Generated by\n# versioneer-0.15 (https://github.com/warner/python-versioneer)\n\nimport errno\nimport os\nimport re\nimport subprocess\nimport sys\n\n\ndef get_keywords():\n    # these strings will be replaced by git during git-archive.\n    # setup.py/versioneer.py will grep for the variable names, so they must\n    # each be defined on a line of their own. _version.py will just call\n    # get_keywords().\n    git_refnames = \"%(DOLLAR)sFormat:%%d%(DOLLAR)s\"\n    git_full = \"%(DOLLAR)sFormat:%%H%(DOLLAR)s\"\n    keywords = {\"refnames\": git_refnames, \"full\": git_full}\n    return keywords\n\n\nclass VersioneerConfig:\n    pass\n\n\ndef get_config():\n    # these strings are filled in when 'setup.py versioneer' creates\n    # _version.py\n    cfg = VersioneerConfig()\n    cfg.VCS = \"git\"\n    cfg.style = \"%(STYLE)s\"\n    cfg.tag_prefix = \"%(TAG_PREFIX)s\"\n    cfg.parentdir_prefix = \"%(PARENTDIR_PREFIX)s\"\n    cfg.versionfile_source = \"%(VERSIONFILE_SOURCE)s\"\n    cfg.verbose = False\n    return cfg\n\n\nclass NotThisMethod(Exception):\n    pass\n\n\nLONG_VERSION_PY = {}\nHANDLERS = {}\n\n\ndef register_vcs_handler(vcs, method):  # decorator\n    def decorate(f):\n        if vcs not in HANDLERS:\n            HANDLERS[vcs] = {}\n        HANDLERS[vcs][method] = f\n        return f\n    return decorate\n\n\ndef run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):\n    assert isinstance(commands, list)\n    p = None\n    for c in commands:\n        try:\n            dispcmd = str([c] + args)\n            # remember shell=False, so use git.cmd on windows, not just git\n            p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,\n                                 stderr=(subprocess.PIPE if hide_stderr\n                                         else None))\n            break\n        except EnvironmentError:\n            e = sys.exc_info()[1]\n            if e.errno == errno.ENOENT:\n                continue\n            if verbose:\n                print(\"unable to run %%s\" %% dispcmd)\n                print(e)\n            return None\n    else:\n        if verbose:\n            print(\"unable to find command, tried %%s\" %% (commands,))\n        return None\n    stdout = p.communicate()[0].strip()\n    if sys.version_info[0] >= 3:\n        stdout = stdout.decode()\n    if p.returncode != 0:\n        if verbose:\n            print(\"unable to run %%s (error)\" %% dispcmd)\n        return None\n    return stdout\n\n\ndef versions_from_parentdir(parentdir_prefix, root, verbose):\n    # Source tarballs conventionally unpack into a directory that includes\n    # both the project name and a version string.\n    dirname = os.path.basename(root)\n    if not dirname.startswith(parentdir_prefix):\n        if verbose:\n            print(\"guessing rootdir is '%%s', but '%%s' doesn't start with \"\n                  \"prefix '%%s'\" %% (root, dirname, parentdir_prefix))\n        raise NotThisMethod(\"rootdir doesn't start with parentdir_prefix\")\n    return {\"version\": dirname[len(parentdir_prefix):],\n            \"full-revisionid\": None,\n            \"dirty\": False, \"error\": None}\n\n\n@register_vcs_handler(\"git\", \"get_keywords\")\ndef git_get_keywords(versionfile_abs):\n    # the code embedded in _version.py can just fetch the value of these\n    # keywords. When used from setup.py, we don't want to import _version.py,\n    # so we do it with a regexp instead. This function is not used from\n    # _version.py.\n    keywords = {}\n    try:\n        f = open(versionfile_abs, \"r\")\n        for line in f.readlines():\n            if line.strip().startswith(\"git_refnames =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"refnames\"] = mo.group(1)\n            if line.strip().startswith(\"git_full =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"full\"] = mo.group(1)\n        f.close()\n    except EnvironmentError:\n        pass\n    return keywords\n\n\n@register_vcs_handler(\"git\", \"keywords\")\ndef git_versions_from_keywords(keywords, tag_prefix, verbose):\n    if not keywords:\n        raise NotThisMethod(\"no keywords at all, weird\")\n    refnames = keywords[\"refnames\"].strip()\n    if refnames.startswith(\"$Format\"):\n        if verbose:\n            print(\"keywords are unexpanded, not using\")\n        raise NotThisMethod(\"unexpanded keywords, not a git-archive tarball\")\n    refs = set([r.strip() for r in refnames.strip(\"()\").split(\",\")])\n    # starting in git-1.8.3, tags are listed as \"tag: foo-1.0\" instead of\n    # just \"foo-1.0\". If we see a \"tag: \" prefix, prefer those.\n    TAG = \"tag: \"\n    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])\n    if not tags:\n        # Either we're using git < 1.8.3, or there really are no tags. We use\n        # a heuristic: assume all version tags have a digit. The old git %%d\n        # expansion behaves like git log --decorate=short and strips out the\n        # refs/heads/ and refs/tags/ prefixes that would let us distinguish\n        # between branches and tags. By ignoring refnames without digits, we\n        # filter out many common branch names like \"release\" and\n        # \"stabilization\", as well as \"HEAD\" and \"master\".\n        tags = set([r for r in refs if re.search(r'\\d', r)])\n        if verbose:\n            print(\"discarding '%%s', no digits\" %% \",\".join(refs-tags))\n    if verbose:\n        print(\"likely tags: %%s\" %% \",\".join(sorted(tags)))\n    for ref in sorted(tags):\n        # sorting will prefer e.g. \"2.0\" over \"2.0rc1\"\n        if ref.startswith(tag_prefix):\n            r = ref[len(tag_prefix):]\n            if verbose:\n                print(\"picking %%s\" %% r)\n            return {\"version\": r,\n                    \"full-revisionid\": keywords[\"full\"].strip(),\n                    \"dirty\": False, \"error\": None\n                    }\n    # no suitable tags, so version is \"0+unknown\", but full hex is still there\n    if verbose:\n        print(\"no suitable tags, using unknown + full revision id\")\n    return {\"version\": \"0+unknown\",\n            \"full-revisionid\": keywords[\"full\"].strip(),\n            \"dirty\": False, \"error\": \"no suitable tags\"}\n\n\n@register_vcs_handler(\"git\", \"pieces_from_vcs\")\ndef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n    # this runs 'git' from the root of the source tree. This only gets called\n    # if the git-archive 'subst' keywords were *not* expanded, and\n    # _version.py hasn't already been rewritten with a short version string,\n    # meaning we're inside a checked out source tree.\n\n    if not os.path.exists(os.path.join(root, \".git\")):\n        if verbose:\n            print(\"no .git in %%s\" %% root)\n        raise NotThisMethod(\"no .git directory\")\n\n    GITS = [\"git\"]\n    if sys.platform == \"win32\":\n        GITS = [\"git.cmd\", \"git.exe\"]\n    # if there is a tag, this yields TAG-NUM-gHEX[-dirty]\n    # if there are no tags, this yields HEX[-dirty] (no NUM)\n    describe_out = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n                                      \"--always\", \"--long\"],\n                               cwd=root)\n    # --long was added in git-1.5.5\n    if describe_out is None:\n        raise NotThisMethod(\"'git describe' failed\")\n    describe_out = describe_out.strip()\n    full_out = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n    if full_out is None:\n        raise NotThisMethod(\"'git rev-parse' failed\")\n    full_out = full_out.strip()\n\n    pieces = {}\n    pieces[\"long\"] = full_out\n    pieces[\"short\"] = full_out[:7]  # maybe improved later\n    pieces[\"error\"] = None\n\n    # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]\n    # TAG might have hyphens.\n    git_describe = describe_out\n\n    # look for -dirty suffix\n    dirty = git_describe.endswith(\"-dirty\")\n    pieces[\"dirty\"] = dirty\n    if dirty:\n        git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n    # now we have TAG-NUM-gHEX or HEX\n\n    if \"-\" in git_describe:\n        # TAG-NUM-gHEX\n        mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n        if not mo:\n            # unparseable. Maybe git-describe is misbehaving?\n            pieces[\"error\"] = (\"unable to parse git-describe output: '%%s'\"\n                               %% describe_out)\n            return pieces\n\n        # tag\n        full_tag = mo.group(1)\n        if not full_tag.startswith(tag_prefix):\n            if verbose:\n                fmt = \"tag '%%s' doesn't start with prefix '%%s'\"\n                print(fmt %% (full_tag, tag_prefix))\n            pieces[\"error\"] = (\"tag '%%s' doesn't start with prefix '%%s'\"\n                               %% (full_tag, tag_prefix))\n            return pieces\n        pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n        # distance: number of commits since tag\n        pieces[\"distance\"] = int(mo.group(2))\n\n        # commit: short hex revision ID\n        pieces[\"short\"] = mo.group(3)\n\n    else:\n        # HEX: no tags\n        pieces[\"closest-tag\"] = None\n        count_out = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n                                cwd=root)\n        pieces[\"distance\"] = int(count_out)  # total number of commits\n\n    return pieces\n\n\ndef plus_or_dot(pieces):\n    if \"+\" in pieces.get(\"closest-tag\", \"\"):\n        return \".\"\n    return \"+\"\n\n\ndef render_pep440(pieces):\n    # now build up version string, with post-release \"local version\n    # identifier\". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you\n    # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty\n\n    # exceptions:\n    # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += plus_or_dot(pieces)\n            rendered += \"%%d.g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n            if pieces[\"dirty\"]:\n                rendered += \".dirty\"\n    else:\n        # exception #1\n        rendered = \"0+untagged.%%d.g%%s\" %% (pieces[\"distance\"],\n                                          pieces[\"short\"])\n        if pieces[\"dirty\"]:\n            rendered += \".dirty\"\n    return rendered\n\n\ndef render_pep440_pre(pieces):\n    # TAG[.post.devDISTANCE] . No -dirty\n\n    # exceptions:\n    # 1: no tags. 0.post.devDISTANCE\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \".post.dev%%d\" %% pieces[\"distance\"]\n    else:\n        # exception #1\n        rendered = \"0.post.dev%%d\" %% pieces[\"distance\"]\n    return rendered\n\n\ndef render_pep440_post(pieces):\n    # TAG[.postDISTANCE[.dev0]+gHEX] . The \".dev0\" means dirty. Note that\n    # .dev0 sorts backwards (a dirty tree will appear \"older\" than the\n    # corresponding clean one), but you shouldn't be releasing software with\n    # -dirty anyways.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%%d\" %% pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n            rendered += plus_or_dot(pieces)\n            rendered += \"g%%s\" %% pieces[\"short\"]\n    else:\n        # exception #1\n        rendered = \"0.post%%d\" %% pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n        rendered += \"+g%%s\" %% pieces[\"short\"]\n    return rendered\n\n\ndef render_pep440_old(pieces):\n    # TAG[.postDISTANCE[.dev0]] . The \".dev0\" means dirty.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%%d\" %% pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n    else:\n        # exception #1\n        rendered = \"0.post%%d\" %% pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n    return rendered\n\n\ndef render_git_describe(pieces):\n    # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty\n    # --always'\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \"-%%d-g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render_git_describe_long(pieces):\n    # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty\n    # --always -long'. The distance/hash is unconditional.\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        rendered += \"-%%d-g%%s\" %% (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render(pieces, style):\n    if pieces[\"error\"]:\n        return {\"version\": \"unknown\",\n                \"full-revisionid\": pieces.get(\"long\"),\n                \"dirty\": None,\n                \"error\": pieces[\"error\"]}\n\n    if not style or style == \"default\":\n        style = \"pep440\"  # the default\n\n    if style == \"pep440\":\n        rendered = render_pep440(pieces)\n    elif style == \"pep440-pre\":\n        rendered = render_pep440_pre(pieces)\n    elif style == \"pep440-post\":\n        rendered = render_pep440_post(pieces)\n    elif style == \"pep440-old\":\n        rendered = render_pep440_old(pieces)\n    elif style == \"git-describe\":\n        rendered = render_git_describe(pieces)\n    elif style == \"git-describe-long\":\n        rendered = render_git_describe_long(pieces)\n    else:\n        raise ValueError(\"unknown style '%%s'\" %% style)\n\n    return {\"version\": rendered, \"full-revisionid\": pieces[\"long\"],\n            \"dirty\": pieces[\"dirty\"], \"error\": None}\n\n\ndef get_versions():\n    # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have\n    # __file__, we can work backwards from there to the root. Some\n    # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which\n    # case we can only use expanded keywords.\n\n    cfg = get_config()\n    verbose = cfg.verbose\n\n    try:\n        return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,\n                                          verbose)\n    except NotThisMethod:\n        pass\n\n    try:\n        root = os.path.realpath(__file__)\n        # versionfile_source is the relative path from the top of the source\n        # tree (where the .git directory might live) to this file. Invert\n        # this to find the root from __file__.\n        for i in cfg.versionfile_source.split('/'):\n            root = os.path.dirname(root)\n    except NameError:\n        return {\"version\": \"0+unknown\", \"full-revisionid\": None,\n                \"dirty\": None,\n                \"error\": \"unable to find root of source tree\"}\n\n    try:\n        pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose)\n        return render(pieces, cfg.style)\n    except NotThisMethod:\n        pass\n\n    try:\n        if cfg.parentdir_prefix:\n            return versions_from_parentdir(cfg.parentdir_prefix, root, verbose)\n    except NotThisMethod:\n        pass\n\n    return {\"version\": \"0+unknown\", \"full-revisionid\": None,\n            \"dirty\": None,\n            \"error\": \"unable to compute version\"}\n'''\n\n\n@register_vcs_handler(\"git\", \"get_keywords\")\ndef git_get_keywords(versionfile_abs):\n    # the code embedded in _version.py can just fetch the value of these\n    # keywords. When used from setup.py, we don't want to import _version.py,\n    # so we do it with a regexp instead. This function is not used from\n    # _version.py.\n    keywords = {}\n    try:\n        f = open(versionfile_abs, \"r\")\n        for line in f.readlines():\n            if line.strip().startswith(\"git_refnames =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"refnames\"] = mo.group(1)\n            if line.strip().startswith(\"git_full =\"):\n                mo = re.search(r'=\\s*\"(.*)\"', line)\n                if mo:\n                    keywords[\"full\"] = mo.group(1)\n        f.close()\n    except EnvironmentError:\n        pass\n    return keywords\n\n\n@register_vcs_handler(\"git\", \"keywords\")\ndef git_versions_from_keywords(keywords, tag_prefix, verbose):\n    if not keywords:\n        raise NotThisMethod(\"no keywords at all, weird\")\n    refnames = keywords[\"refnames\"].strip()\n    if refnames.startswith(\"$Format\"):\n        if verbose:\n            print(\"keywords are unexpanded, not using\")\n        raise NotThisMethod(\"unexpanded keywords, not a git-archive tarball\")\n    refs = set([r.strip() for r in refnames.strip(\"()\").split(\",\")])\n    # starting in git-1.8.3, tags are listed as \"tag: foo-1.0\" instead of\n    # just \"foo-1.0\". If we see a \"tag: \" prefix, prefer those.\n    TAG = \"tag: \"\n    tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)])\n    if not tags:\n        # Either we're using git < 1.8.3, or there really are no tags. We use\n        # a heuristic: assume all version tags have a digit. The old git %d\n        # expansion behaves like git log --decorate=short and strips out the\n        # refs/heads/ and refs/tags/ prefixes that would let us distinguish\n        # between branches and tags. By ignoring refnames without digits, we\n        # filter out many common branch names like \"release\" and\n        # \"stabilization\", as well as \"HEAD\" and \"master\".\n        tags = set([r for r in refs if re.search(r'\\d', r)])\n        if verbose:\n            print(\"discarding '%s', no digits\" % \",\".join(refs-tags))\n    if verbose:\n        print(\"likely tags: %s\" % \",\".join(sorted(tags)))\n    for ref in sorted(tags):\n        # sorting will prefer e.g. \"2.0\" over \"2.0rc1\"\n        if ref.startswith(tag_prefix):\n            r = ref[len(tag_prefix):]\n            if verbose:\n                print(\"picking %s\" % r)\n            return {\"version\": r,\n                    \"full-revisionid\": keywords[\"full\"].strip(),\n                    \"dirty\": False, \"error\": None\n                    }\n    # no suitable tags, so version is \"0+unknown\", but full hex is still there\n    if verbose:\n        print(\"no suitable tags, using unknown + full revision id\")\n    return {\"version\": \"0+unknown\",\n            \"full-revisionid\": keywords[\"full\"].strip(),\n            \"dirty\": False, \"error\": \"no suitable tags\"}\n\n\n@register_vcs_handler(\"git\", \"pieces_from_vcs\")\ndef git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):\n    # this runs 'git' from the root of the source tree. This only gets called\n    # if the git-archive 'subst' keywords were *not* expanded, and\n    # _version.py hasn't already been rewritten with a short version string,\n    # meaning we're inside a checked out source tree.\n\n    if not os.path.exists(os.path.join(root, \".git\")):\n        if verbose:\n            print(\"no .git in %s\" % root)\n        raise NotThisMethod(\"no .git directory\")\n\n    GITS = [\"git\"]\n    if sys.platform == \"win32\":\n        GITS = [\"git.cmd\", \"git.exe\"]\n    # if there is a tag, this yields TAG-NUM-gHEX[-dirty]\n    # if there are no tags, this yields HEX[-dirty] (no NUM)\n    describe_out = run_command(GITS, [\"describe\", \"--tags\", \"--dirty\",\n                                      \"--always\", \"--long\"],\n                               cwd=root)\n    # --long was added in git-1.5.5\n    if describe_out is None:\n        raise NotThisMethod(\"'git describe' failed\")\n    describe_out = describe_out.strip()\n    full_out = run_command(GITS, [\"rev-parse\", \"HEAD\"], cwd=root)\n    if full_out is None:\n        raise NotThisMethod(\"'git rev-parse' failed\")\n    full_out = full_out.strip()\n\n    pieces = {}\n    pieces[\"long\"] = full_out\n    pieces[\"short\"] = full_out[:7]  # maybe improved later\n    pieces[\"error\"] = None\n\n    # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty]\n    # TAG might have hyphens.\n    git_describe = describe_out\n\n    # look for -dirty suffix\n    dirty = git_describe.endswith(\"-dirty\")\n    pieces[\"dirty\"] = dirty\n    if dirty:\n        git_describe = git_describe[:git_describe.rindex(\"-dirty\")]\n\n    # now we have TAG-NUM-gHEX or HEX\n\n    if \"-\" in git_describe:\n        # TAG-NUM-gHEX\n        mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)\n        if not mo:\n            # unparseable. Maybe git-describe is misbehaving?\n            pieces[\"error\"] = (\"unable to parse git-describe output: '%s'\"\n                               % describe_out)\n            return pieces\n\n        # tag\n        full_tag = mo.group(1)\n        if not full_tag.startswith(tag_prefix):\n            if verbose:\n                fmt = \"tag '%s' doesn't start with prefix '%s'\"\n                print(fmt % (full_tag, tag_prefix))\n            pieces[\"error\"] = (\"tag '%s' doesn't start with prefix '%s'\"\n                               % (full_tag, tag_prefix))\n            return pieces\n        pieces[\"closest-tag\"] = full_tag[len(tag_prefix):]\n\n        # distance: number of commits since tag\n        pieces[\"distance\"] = int(mo.group(2))\n\n        # commit: short hex revision ID\n        pieces[\"short\"] = mo.group(3)\n\n    else:\n        # HEX: no tags\n        pieces[\"closest-tag\"] = None\n        count_out = run_command(GITS, [\"rev-list\", \"HEAD\", \"--count\"],\n                                cwd=root)\n        pieces[\"distance\"] = int(count_out)  # total number of commits\n\n    return pieces\n\n\ndef do_vcs_install(manifest_in, versionfile_source, ipy):\n    GITS = [\"git\"]\n    if sys.platform == \"win32\":\n        GITS = [\"git.cmd\", \"git.exe\"]\n    files = [manifest_in, versionfile_source]\n    if ipy:\n        files.append(ipy)\n    try:\n        me = __file__\n        if me.endswith(\".pyc\") or me.endswith(\".pyo\"):\n            me = os.path.splitext(me)[0] + \".py\"\n        versioneer_file = os.path.relpath(me)\n    except NameError:\n        versioneer_file = \"versioneer.py\"\n    files.append(versioneer_file)\n    present = False\n    try:\n        f = open(\".gitattributes\", \"r\")\n        for line in f.readlines():\n            if line.strip().startswith(versionfile_source):\n                if \"export-subst\" in line.strip().split()[1:]:\n                    present = True\n        f.close()\n    except EnvironmentError:\n        pass\n    if not present:\n        f = open(\".gitattributes\", \"a+\")\n        f.write(\"%s export-subst\\n\" % versionfile_source)\n        f.close()\n        files.append(\".gitattributes\")\n    run_command(GITS, [\"add\", \"--\"] + files)\n\n\ndef versions_from_parentdir(parentdir_prefix, root, verbose):\n    # Source tarballs conventionally unpack into a directory that includes\n    # both the project name and a version string.\n    dirname = os.path.basename(root)\n    if not dirname.startswith(parentdir_prefix):\n        if verbose:\n            print(\"guessing rootdir is '%s', but '%s' doesn't start with \"\n                  \"prefix '%s'\" % (root, dirname, parentdir_prefix))\n        raise NotThisMethod(\"rootdir doesn't start with parentdir_prefix\")\n    return {\"version\": dirname[len(parentdir_prefix):],\n            \"full-revisionid\": None,\n            \"dirty\": False, \"error\": None}\n\nSHORT_VERSION_PY = \"\"\"\n# This file was generated by 'versioneer.py' (0.15) from\n# revision-control system data, or from the parent directory name of an\n# unpacked source archive. Distribution tarballs contain a pre-generated copy\n# of this file.\n\nimport json\nimport sys\n\nversion_json = '''\n%s\n'''  # END VERSION_JSON\n\n\ndef get_versions():\n    return json.loads(version_json)\n\"\"\"\n\n\ndef versions_from_file(filename):\n    try:\n        with open(filename) as f:\n            contents = f.read()\n    except EnvironmentError:\n        raise NotThisMethod(\"unable to read _version.py\")\n    mo = re.search(r\"version_json = '''\\n(.*)'''  # END VERSION_JSON\",\n                   contents, re.M | re.S)\n    if not mo:\n        raise NotThisMethod(\"no version_json in _version.py\")\n    return json.loads(mo.group(1))\n\n\ndef write_to_version_file(filename, versions):\n    os.unlink(filename)\n    contents = json.dumps(versions, sort_keys=True,\n                          indent=1, separators=(\",\", \": \"))\n    with open(filename, \"w\") as f:\n        f.write(SHORT_VERSION_PY % contents)\n\n    print(\"set %s to '%s'\" % (filename, versions[\"version\"]))\n\n\ndef plus_or_dot(pieces):\n    if \"+\" in pieces.get(\"closest-tag\", \"\"):\n        return \".\"\n    return \"+\"\n\n\ndef render_pep440(pieces):\n    # now build up version string, with post-release \"local version\n    # identifier\". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you\n    # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty\n\n    # exceptions:\n    # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += plus_or_dot(pieces)\n            rendered += \"%d.g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n            if pieces[\"dirty\"]:\n                rendered += \".dirty\"\n    else:\n        # exception #1\n        rendered = \"0+untagged.%d.g%s\" % (pieces[\"distance\"],\n                                          pieces[\"short\"])\n        if pieces[\"dirty\"]:\n            rendered += \".dirty\"\n    return rendered\n\n\ndef render_pep440_pre(pieces):\n    # TAG[.post.devDISTANCE] . No -dirty\n\n    # exceptions:\n    # 1: no tags. 0.post.devDISTANCE\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \".post.dev%d\" % pieces[\"distance\"]\n    else:\n        # exception #1\n        rendered = \"0.post.dev%d\" % pieces[\"distance\"]\n    return rendered\n\n\ndef render_pep440_post(pieces):\n    # TAG[.postDISTANCE[.dev0]+gHEX] . The \".dev0\" means dirty. Note that\n    # .dev0 sorts backwards (a dirty tree will appear \"older\" than the\n    # corresponding clean one), but you shouldn't be releasing software with\n    # -dirty anyways.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%d\" % pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n            rendered += plus_or_dot(pieces)\n            rendered += \"g%s\" % pieces[\"short\"]\n    else:\n        # exception #1\n        rendered = \"0.post%d\" % pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n        rendered += \"+g%s\" % pieces[\"short\"]\n    return rendered\n\n\ndef render_pep440_old(pieces):\n    # TAG[.postDISTANCE[.dev0]] . The \".dev0\" means dirty.\n\n    # exceptions:\n    # 1: no tags. 0.postDISTANCE[.dev0]\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"] or pieces[\"dirty\"]:\n            rendered += \".post%d\" % pieces[\"distance\"]\n            if pieces[\"dirty\"]:\n                rendered += \".dev0\"\n    else:\n        # exception #1\n        rendered = \"0.post%d\" % pieces[\"distance\"]\n        if pieces[\"dirty\"]:\n            rendered += \".dev0\"\n    return rendered\n\n\ndef render_git_describe(pieces):\n    # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty\n    # --always'\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        if pieces[\"distance\"]:\n            rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render_git_describe_long(pieces):\n    # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty\n    # --always -long'. The distance/hash is unconditional.\n\n    # exceptions:\n    # 1: no tags. HEX[-dirty]  (note: no 'g' prefix)\n\n    if pieces[\"closest-tag\"]:\n        rendered = pieces[\"closest-tag\"]\n        rendered += \"-%d-g%s\" % (pieces[\"distance\"], pieces[\"short\"])\n    else:\n        # exception #1\n        rendered = pieces[\"short\"]\n    if pieces[\"dirty\"]:\n        rendered += \"-dirty\"\n    return rendered\n\n\ndef render(pieces, style):\n    if pieces[\"error\"]:\n        return {\"version\": \"unknown\",\n                \"full-revisionid\": pieces.get(\"long\"),\n                \"dirty\": None,\n                \"error\": pieces[\"error\"]}\n\n    if not style or style == \"default\":\n        style = \"pep440\"  # the default\n\n    if style == \"pep440\":\n        rendered = render_pep440(pieces)\n    elif style == \"pep440-pre\":\n        rendered = render_pep440_pre(pieces)\n    elif style == \"pep440-post\":\n        rendered = render_pep440_post(pieces)\n    elif style == \"pep440-old\":\n        rendered = render_pep440_old(pieces)\n    elif style == \"git-describe\":\n        rendered = render_git_describe(pieces)\n    elif style == \"git-describe-long\":\n        rendered = render_git_describe_long(pieces)\n    else:\n        raise ValueError(\"unknown style '%s'\" % style)\n\n    return {\"version\": rendered, \"full-revisionid\": pieces[\"long\"],\n            \"dirty\": pieces[\"dirty\"], \"error\": None}\n\n\nclass VersioneerBadRootError(Exception):\n    pass\n\n\ndef get_versions(verbose=False):\n    # returns dict with two keys: 'version' and 'full'\n\n    if \"versioneer\" in sys.modules:\n        # see the discussion in cmdclass.py:get_cmdclass()\n        del sys.modules[\"versioneer\"]\n\n    root = get_root()\n    cfg = get_config_from_root(root)\n\n    assert cfg.VCS is not None, \"please set [versioneer]VCS= in setup.cfg\"\n    handlers = HANDLERS.get(cfg.VCS)\n    assert handlers, \"unrecognized VCS '%s'\" % cfg.VCS\n    verbose = verbose or cfg.verbose\n    assert cfg.versionfile_source is not None, \\\n        \"please set versioneer.versionfile_source\"\n    assert cfg.tag_prefix is not None, \"please set versioneer.tag_prefix\"\n\n    versionfile_abs = os.path.join(root, cfg.versionfile_source)\n\n    # extract version from first of: _version.py, VCS command (e.g. 'git\n    # describe'), parentdir. This is meant to work for developers using a\n    # source checkout, for users of a tarball created by 'setup.py sdist',\n    # and for users of a tarball/zipball created by 'git archive' or github's\n    # download-from-tag feature or the equivalent in other VCSes.\n\n    get_keywords_f = handlers.get(\"get_keywords\")\n    from_keywords_f = handlers.get(\"keywords\")\n    if get_keywords_f and from_keywords_f:\n        try:\n            keywords = get_keywords_f(versionfile_abs)\n            ver = from_keywords_f(keywords, cfg.tag_prefix, verbose)\n            if verbose:\n                print(\"got version from expanded keyword %s\" % ver)\n            return ver\n        except NotThisMethod:\n            pass\n\n    try:\n        ver = versions_from_file(versionfile_abs)\n        if verbose:\n            print(\"got version from file %s %s\" % (versionfile_abs, ver))\n        return ver\n    except NotThisMethod:\n        pass\n\n    from_vcs_f = handlers.get(\"pieces_from_vcs\")\n    if from_vcs_f:\n        try:\n            pieces = from_vcs_f(cfg.tag_prefix, root, verbose)\n            ver = render(pieces, cfg.style)\n            if verbose:\n                print(\"got version from VCS %s\" % ver)\n            return ver\n        except NotThisMethod:\n            pass\n\n    try:\n        if cfg.parentdir_prefix:\n            ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose)\n            if verbose:\n                print(\"got version from parentdir %s\" % ver)\n            return ver\n    except NotThisMethod:\n        pass\n\n    if verbose:\n        print(\"unable to compute version\")\n\n    return {\"version\": \"0+unknown\", \"full-revisionid\": None,\n            \"dirty\": None, \"error\": \"unable to compute version\"}\n\n\ndef get_version():\n    return get_versions()[\"version\"]\n\n\ndef get_cmdclass():\n    if \"versioneer\" in sys.modules:\n        del sys.modules[\"versioneer\"]\n        # this fixes the \"python setup.py develop\" case (also 'install' and\n        # 'easy_install .'), in which subdependencies of the main project are\n        # built (using setup.py bdist_egg) in the same python process. Assume\n        # a main project A and a dependency B, which use different versions\n        # of Versioneer. A's setup.py imports A's Versioneer, leaving it in\n        # sys.modules by the time B's setup.py is executed, causing B to run\n        # with the wrong versioneer. Setuptools wraps the sub-dep builds in a\n        # sandbox that restores sys.modules to it's pre-build state, so the\n        # parent is protected against the child's \"import versioneer\". By\n        # removing ourselves from sys.modules here, before the child build\n        # happens, we protect the child from the parent's versioneer too.\n        # Also see https://github.com/warner/python-versioneer/issues/52\n\n    cmds = {}\n\n    # we add \"version\" to both distutils and setuptools\n    from distutils.core import Command\n\n    class cmd_version(Command):\n        description = \"report generated version string\"\n        user_options = []\n        boolean_options = []\n\n        def initialize_options(self):\n            pass\n\n        def finalize_options(self):\n            pass\n\n        def run(self):\n            vers = get_versions(verbose=True)\n            print(\"Version: %s\" % vers[\"version\"])\n            print(\" full-revisionid: %s\" % vers.get(\"full-revisionid\"))\n            print(\" dirty: %s\" % vers.get(\"dirty\"))\n            if vers[\"error\"]:\n                print(\" error: %s\" % vers[\"error\"])\n    cmds[\"version\"] = cmd_version\n\n    # we override \"build_py\" in both distutils and setuptools\n    #\n    # most invocation pathways end up running build_py:\n    #  distutils/build -> build_py\n    #  distutils/install -> distutils/build ->..\n    #  setuptools/bdist_wheel -> distutils/install ->..\n    #  setuptools/bdist_egg -> distutils/install_lib -> build_py\n    #  setuptools/install -> bdist_egg ->..\n    #  setuptools/develop -> ?\n\n    from distutils.command.build_py import build_py as _build_py\n\n    class cmd_build_py(_build_py):\n        def run(self):\n            root = get_root()\n            cfg = get_config_from_root(root)\n            versions = get_versions()\n            _build_py.run(self)\n            # now locate _version.py in the new build/ directory and replace\n            # it with an updated value\n            if cfg.versionfile_build:\n                target_versionfile = os.path.join(self.build_lib,\n                                                  cfg.versionfile_build)\n                print(\"UPDATING %s\" % target_versionfile)\n                write_to_version_file(target_versionfile, versions)\n    cmds[\"build_py\"] = cmd_build_py\n\n    if \"cx_Freeze\" in sys.modules:  # cx_freeze enabled?\n        from cx_Freeze.dist import build_exe as _build_exe\n\n        class cmd_build_exe(_build_exe):\n            def run(self):\n                root = get_root()\n                cfg = get_config_from_root(root)\n                versions = get_versions()\n                target_versionfile = cfg.versionfile_source\n                print(\"UPDATING %s\" % target_versionfile)\n                write_to_version_file(target_versionfile, versions)\n\n                _build_exe.run(self)\n                os.unlink(target_versionfile)\n                with open(cfg.versionfile_source, \"w\") as f:\n                    LONG = LONG_VERSION_PY[cfg.VCS]\n                    f.write(LONG %\n                            {\"DOLLAR\": \"$\",\n                             \"STYLE\": cfg.style,\n                             \"TAG_PREFIX\": cfg.tag_prefix,\n                             \"PARENTDIR_PREFIX\": cfg.parentdir_prefix,\n                             \"VERSIONFILE_SOURCE\": cfg.versionfile_source,\n                             })\n        cmds[\"build_exe\"] = cmd_build_exe\n        del cmds[\"build_py\"]\n\n    # we override different \"sdist\" commands for both environments\n    if \"setuptools\" in sys.modules:\n        from setuptools.command.sdist import sdist as _sdist\n    else:\n        from distutils.command.sdist import sdist as _sdist\n\n    class cmd_sdist(_sdist):\n        def run(self):\n            versions = get_versions()\n            self._versioneer_generated_versions = versions\n            # unless we update this, the command will keep using the old\n            # version\n            self.distribution.metadata.version = versions[\"version\"]\n            return _sdist.run(self)\n\n        def make_release_tree(self, base_dir, files):\n            root = get_root()\n            cfg = get_config_from_root(root)\n            _sdist.make_release_tree(self, base_dir, files)\n            # now locate _version.py in the new base_dir directory\n            # (remembering that it may be a hardlink) and replace it with an\n            # updated value\n            target_versionfile = os.path.join(base_dir, cfg.versionfile_source)\n            print(\"UPDATING %s\" % target_versionfile)\n            write_to_version_file(target_versionfile,\n                                  self._versioneer_generated_versions)\n    cmds[\"sdist\"] = cmd_sdist\n\n    return cmds\n\n\nCONFIG_ERROR = \"\"\"\nsetup.cfg is missing the necessary Versioneer configuration. You need\na section like:\n\n [versioneer]\n VCS = git\n style = pep440\n versionfile_source = src/myproject/_version.py\n versionfile_build = myproject/_version.py\n tag_prefix = \"\"\n parentdir_prefix = myproject-\n\nYou will also need to edit your setup.py to use the results:\n\n import versioneer\n setup(version=versioneer.get_version(),\n       cmdclass=versioneer.get_cmdclass(), ...)\n\nPlease read the docstring in ./versioneer.py for configuration instructions,\nedit setup.cfg, and re-run the installer or 'python versioneer.py setup'.\n\"\"\"\n\nSAMPLE_CONFIG = \"\"\"\n# See the docstring in versioneer.py for instructions. Note that you must\n# re-run 'versioneer.py setup' after changing this section, and commit the\n# resulting files.\n\n[versioneer]\n#VCS = git\n#style = pep440\n#versionfile_source =\n#versionfile_build =\n#tag_prefix =\n#parentdir_prefix =\n\n\"\"\"\n\nINIT_PY_SNIPPET = \"\"\"\nfrom ._version import get_versions\n__version__ = get_versions()['version']\ndel get_versions\n\"\"\"\n\n\ndef do_setup():\n    root = get_root()\n    try:\n        cfg = get_config_from_root(root)\n    except (EnvironmentError, configparser.NoSectionError,\n            configparser.NoOptionError) as e:\n        if isinstance(e, (EnvironmentError, configparser.NoSectionError)):\n            print(\"Adding sample versioneer config to setup.cfg\",\n                  file=sys.stderr)\n            with open(os.path.join(root, \"setup.cfg\"), \"a\") as f:\n                f.write(SAMPLE_CONFIG)\n        print(CONFIG_ERROR, file=sys.stderr)\n        return 1\n\n    print(\" creating %s\" % cfg.versionfile_source)\n    with open(cfg.versionfile_source, \"w\") as f:\n        LONG = LONG_VERSION_PY[cfg.VCS]\n        f.write(LONG % {\"DOLLAR\": \"$\",\n                        \"STYLE\": cfg.style,\n                        \"TAG_PREFIX\": cfg.tag_prefix,\n                        \"PARENTDIR_PREFIX\": cfg.parentdir_prefix,\n                        \"VERSIONFILE_SOURCE\": cfg.versionfile_source,\n                        })\n\n    ipy = os.path.join(os.path.dirname(cfg.versionfile_source),\n                       \"__init__.py\")\n    if os.path.exists(ipy):\n        try:\n            with open(ipy, \"r\") as f:\n                old = f.read()\n        except EnvironmentError:\n            old = \"\"\n        if INIT_PY_SNIPPET not in old:\n            print(\" appending to %s\" % ipy)\n            with open(ipy, \"a\") as f:\n                f.write(INIT_PY_SNIPPET)\n        else:\n            print(\" %s unmodified\" % ipy)\n    else:\n        print(\" %s doesn't exist, ok\" % ipy)\n        ipy = None\n\n    # Make sure both the top-level \"versioneer.py\" and versionfile_source\n    # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so\n    # they'll be copied into source distributions. Pip won't be able to\n    # install the package without this.\n    manifest_in = os.path.join(root, \"MANIFEST.in\")\n    simple_includes = set()\n    try:\n        with open(manifest_in, \"r\") as f:\n            for line in f:\n                if line.startswith(\"include \"):\n                    for include in line.split()[1:]:\n                        simple_includes.add(include)\n    except EnvironmentError:\n        pass\n    # That doesn't cover everything MANIFEST.in can do\n    # (http://docs.python.org/2/distutils/sourcedist.html#commands), so\n    # it might give some false negatives. Appending redundant 'include'\n    # lines is safe, though.\n    if \"versioneer.py\" not in simple_includes:\n        print(\" appending 'versioneer.py' to MANIFEST.in\")\n        with open(manifest_in, \"a\") as f:\n            f.write(\"include versioneer.py\\n\")\n    else:\n        print(\" 'versioneer.py' already in MANIFEST.in\")\n    if cfg.versionfile_source not in simple_includes:\n        print(\" appending versionfile_source ('%s') to MANIFEST.in\" %\n              cfg.versionfile_source)\n        with open(manifest_in, \"a\") as f:\n            f.write(\"include %s\\n\" % cfg.versionfile_source)\n    else:\n        print(\" versionfile_source already in MANIFEST.in\")\n\n    # Make VCS-specific changes. For git, this means creating/changing\n    # .gitattributes to mark _version.py for export-time keyword\n    # substitution.\n    do_vcs_install(manifest_in, cfg.versionfile_source, ipy)\n    return 0\n\n\ndef scan_setup_py():\n    found = set()\n    setters = False\n    errors = 0\n    with open(\"setup.py\", \"r\") as f:\n        for line in f.readlines():\n            if \"import versioneer\" in line:\n                found.add(\"import\")\n            if \"versioneer.get_cmdclass()\" in line:\n                found.add(\"cmdclass\")\n            if \"versioneer.get_version()\" in line:\n                found.add(\"get_version\")\n            if \"versioneer.VCS\" in line:\n                setters = True\n            if \"versioneer.versionfile_source\" in line:\n                setters = True\n    if len(found) != 3:\n        print(\"\")\n        print(\"Your setup.py appears to be missing some important items\")\n        print(\"(but I might be wrong). Please make sure it has something\")\n        print(\"roughly like the following:\")\n        print(\"\")\n        print(\" import versioneer\")\n        print(\" setup( version=versioneer.get_version(),\")\n        print(\"        cmdclass=versioneer.get_cmdclass(),  ...)\")\n        print(\"\")\n        errors += 1\n    if setters:\n        print(\"You should remove lines like 'versioneer.VCS = ' and\")\n        print(\"'versioneer.versionfile_source = ' . This configuration\")\n        print(\"now lives in setup.cfg, and should be removed from setup.py\")\n        print(\"\")\n        errors += 1\n    return errors\n\nif __name__ == \"__main__\":\n    cmd = sys.argv[1]\n    if cmd == \"setup\":\n        errors = do_setup()\n        errors += scan_setup_py()\n        if errors:\n            sys.exit(1)\n"
  }
]