kinterbasdb.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # firebird/kinterbasdb.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:: firebird+kinterbasdb
  9. :name: kinterbasdb
  10. :dbapi: kinterbasdb
  11. :connectstring: firebird+kinterbasdb://user:password@host:port/path/to/db\
  12. [?key=value&key=value...]
  13. :url: http://firebirdsql.org/index.php?op=devel&sub=python
  14. Arguments
  15. ----------
  16. The Kinterbasdb backend accepts the ``enable_rowcount`` and ``retaining``
  17. arguments accepted by the :mod:`sqlalchemy.dialects.firebird.fdb` dialect.
  18. In addition, it also accepts the following:
  19. * ``type_conv`` - select the kind of mapping done on the types: by default
  20. SQLAlchemy uses 200 with Unicode, datetime and decimal support. See
  21. the linked documents below for further information.
  22. * ``concurrency_level`` - set the backend policy with regards to threading
  23. issues: by default SQLAlchemy uses policy 1. See the linked documents
  24. below for further information.
  25. .. seealso::
  26. http://sourceforge.net/projects/kinterbasdb
  27. http://kinterbasdb.sourceforge.net/dist_docs/usage.html#adv_param_conv_dynamic_type_translation
  28. http://kinterbasdb.sourceforge.net/dist_docs/usage.html#special_issue_concurrency
  29. """
  30. from .base import FBDialect, FBExecutionContext
  31. from ... import util, types as sqltypes
  32. from re import match
  33. import decimal
  34. class _kinterbasdb_numeric(object):
  35. def bind_processor(self, dialect):
  36. def process(value):
  37. if isinstance(value, decimal.Decimal):
  38. return str(value)
  39. else:
  40. return value
  41. return process
  42. class _FBNumeric_kinterbasdb(_kinterbasdb_numeric, sqltypes.Numeric):
  43. pass
  44. class _FBFloat_kinterbasdb(_kinterbasdb_numeric, sqltypes.Float):
  45. pass
  46. class FBExecutionContext_kinterbasdb(FBExecutionContext):
  47. @property
  48. def rowcount(self):
  49. if self.execution_options.get('enable_rowcount',
  50. self.dialect.enable_rowcount):
  51. return self.cursor.rowcount
  52. else:
  53. return -1
  54. class FBDialect_kinterbasdb(FBDialect):
  55. driver = 'kinterbasdb'
  56. supports_sane_rowcount = False
  57. supports_sane_multi_rowcount = False
  58. execution_ctx_cls = FBExecutionContext_kinterbasdb
  59. supports_native_decimal = True
  60. colspecs = util.update_copy(
  61. FBDialect.colspecs,
  62. {
  63. sqltypes.Numeric: _FBNumeric_kinterbasdb,
  64. sqltypes.Float: _FBFloat_kinterbasdb,
  65. }
  66. )
  67. def __init__(self, type_conv=200, concurrency_level=1,
  68. enable_rowcount=True,
  69. retaining=False, **kwargs):
  70. super(FBDialect_kinterbasdb, self).__init__(**kwargs)
  71. self.enable_rowcount = enable_rowcount
  72. self.type_conv = type_conv
  73. self.concurrency_level = concurrency_level
  74. self.retaining = retaining
  75. if enable_rowcount:
  76. self.supports_sane_rowcount = True
  77. @classmethod
  78. def dbapi(cls):
  79. return __import__('kinterbasdb')
  80. def do_execute(self, cursor, statement, parameters, context=None):
  81. # kinterbase does not accept a None, but wants an empty list
  82. # when there are no arguments.
  83. cursor.execute(statement, parameters or [])
  84. def do_rollback(self, dbapi_connection):
  85. dbapi_connection.rollback(self.retaining)
  86. def do_commit(self, dbapi_connection):
  87. dbapi_connection.commit(self.retaining)
  88. def create_connect_args(self, url):
  89. opts = url.translate_connect_args(username='user')
  90. if opts.get('port'):
  91. opts['host'] = "%s/%s" % (opts['host'], opts['port'])
  92. del opts['port']
  93. opts.update(url.query)
  94. util.coerce_kw_type(opts, 'type_conv', int)
  95. type_conv = opts.pop('type_conv', self.type_conv)
  96. concurrency_level = opts.pop('concurrency_level',
  97. self.concurrency_level)
  98. if self.dbapi is not None:
  99. initialized = getattr(self.dbapi, 'initialized', None)
  100. if initialized is None:
  101. # CVS rev 1.96 changed the name of the attribute:
  102. # http://kinterbasdb.cvs.sourceforge.net/viewvc/kinterbasdb/
  103. # Kinterbasdb-3.0/__init__.py?r1=1.95&r2=1.96
  104. initialized = getattr(self.dbapi, '_initialized', False)
  105. if not initialized:
  106. self.dbapi.init(type_conv=type_conv,
  107. concurrency_level=concurrency_level)
  108. return ([], opts)
  109. def _get_server_version_info(self, connection):
  110. """Get the version of the Firebird server used by a connection.
  111. Returns a tuple of (`major`, `minor`, `build`), three integers
  112. representing the version of the attached server.
  113. """
  114. # This is the simpler approach (the other uses the services api),
  115. # that for backward compatibility reasons returns a string like
  116. # LI-V6.3.3.12981 Firebird 2.0
  117. # where the first version is a fake one resembling the old
  118. # Interbase signature.
  119. fbconn = connection.connection
  120. version = fbconn.server_version
  121. return self._parse_version_info(version)
  122. def _parse_version_info(self, version):
  123. m = match(
  124. r'\w+-V(\d+)\.(\d+)\.(\d+)\.(\d+)( \w+ (\d+)\.(\d+))?', version)
  125. if not m:
  126. raise AssertionError(
  127. "Could not determine version from string '%s'" % version)
  128. if m.group(5) != None:
  129. return tuple([int(x) for x in m.group(6, 7, 4)] + ['firebird'])
  130. else:
  131. return tuple([int(x) for x in m.group(1, 2, 3)] + ['interbase'])
  132. def is_disconnect(self, e, connection, cursor):
  133. if isinstance(e, (self.dbapi.OperationalError,
  134. self.dbapi.ProgrammingError)):
  135. msg = str(e)
  136. return ('Unable to complete network request to host' in msg or
  137. 'Invalid connection state' in msg or
  138. 'Invalid cursor state' in msg or
  139. 'connection shutdown' in msg)
  140. else:
  141. return False
  142. dialect = FBDialect_kinterbasdb