pypostgresql.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. # postgresql/pypostgresql.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. """
  8. .. dialect:: postgresql+pypostgresql
  9. :name: py-postgresql
  10. :dbapi: pypostgresql
  11. :connectstring: postgresql+pypostgresql://user:password@host:port/dbname\
  12. [?key=value&key=value...]
  13. :url: http://python.projects.pgfoundry.org/
  14. """
  15. from ... import util
  16. from ... import types as sqltypes
  17. from .base import PGDialect, PGExecutionContext
  18. from ... import processors
  19. class PGNumeric(sqltypes.Numeric):
  20. def bind_processor(self, dialect):
  21. return processors.to_str
  22. def result_processor(self, dialect, coltype):
  23. if self.asdecimal:
  24. return None
  25. else:
  26. return processors.to_float
  27. class PGExecutionContext_pypostgresql(PGExecutionContext):
  28. pass
  29. class PGDialect_pypostgresql(PGDialect):
  30. driver = 'pypostgresql'
  31. supports_unicode_statements = True
  32. supports_unicode_binds = True
  33. description_encoding = None
  34. default_paramstyle = 'pyformat'
  35. # requires trunk version to support sane rowcounts
  36. # TODO: use dbapi version information to set this flag appropriately
  37. supports_sane_rowcount = True
  38. supports_sane_multi_rowcount = False
  39. execution_ctx_cls = PGExecutionContext_pypostgresql
  40. colspecs = util.update_copy(
  41. PGDialect.colspecs,
  42. {
  43. sqltypes.Numeric: PGNumeric,
  44. # prevents PGNumeric from being used
  45. sqltypes.Float: sqltypes.Float,
  46. }
  47. )
  48. @classmethod
  49. def dbapi(cls):
  50. from postgresql.driver import dbapi20
  51. return dbapi20
  52. _DBAPI_ERROR_NAMES = [
  53. "Error",
  54. "InterfaceError", "DatabaseError", "DataError",
  55. "OperationalError", "IntegrityError", "InternalError",
  56. "ProgrammingError", "NotSupportedError"
  57. ]
  58. @util.memoized_property
  59. def dbapi_exception_translation_map(self):
  60. if self.dbapi is None:
  61. return {}
  62. return dict(
  63. (getattr(self.dbapi, name).__name__, name)
  64. for name in self._DBAPI_ERROR_NAMES
  65. )
  66. def create_connect_args(self, url):
  67. opts = url.translate_connect_args(username='user')
  68. if 'port' in opts:
  69. opts['port'] = int(opts['port'])
  70. else:
  71. opts['port'] = 5432
  72. opts.update(url.query)
  73. return ([], opts)
  74. def is_disconnect(self, e, connection, cursor):
  75. return "connection is closed" in str(e)
  76. dialect = PGDialect_pypostgresql