You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

version.py 1.5 KiB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """
  2. Extracts the version of the PostgreSQL server.
  3. """
  4. import re
  5. # This reg-exp is intentionally fairly flexible here.
  6. # Needs to be able to handle stuff like:
  7. # PostgreSQL #.#.#
  8. # EnterpriseDB #.#
  9. # PostgreSQL #.# beta#
  10. # PostgreSQL #.#beta#
  11. VERSION_RE = re.compile(r'\S+ (\d+)\.(\d+)\.?(\d+)?')
  12. def _parse_version(text):
  13. "Internal parsing method. Factored out for testing purposes."
  14. major, major2, minor = VERSION_RE.search(text).groups()
  15. try:
  16. return int(major) * 10000 + int(major2) * 100 + int(minor)
  17. except (ValueError, TypeError):
  18. return int(major) * 10000 + int(major2) * 100
  19. def get_version(connection):
  20. """
  21. Returns an integer representing the major, minor and revision number of the
  22. server. Format is the one used for the return value of libpq
  23. PQServerVersion()/``server_version`` connection attribute (available in
  24. newer psycopg2 versions.)
  25. For example, 90304 for 9.3.4. The last two digits will be 00 in the case of
  26. releases (e.g., 90400 for 'PostgreSQL 9.4') or in the case of beta and
  27. prereleases (e.g. 90100 for 'PostgreSQL 9.1beta2').
  28. PQServerVersion()/``server_version`` doesn't execute a query so try that
  29. first, then fallback to a ``SELECT version()`` query.
  30. """
  31. if hasattr(connection, 'server_version'):
  32. return connection.server_version
  33. else:
  34. with connection.cursor() as cursor:
  35. cursor.execute("SELECT version()")
  36. return _parse_version(cursor.fetchone()[0])