PageRenderTime 43ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/hd-venv/lib/python2.7/site-packages/psycopg2/__init__.py

https://github.com/Riegerb/GSWD_Tutorial
Python | 182 lines | 105 code | 20 blank | 57 comment | 9 complexity | 25d59b32e9861380fe5b4801a4ad5b1d MD5 | raw file
  1. """A Python driver for PostgreSQL
  2. psycopg is a PostgreSQL_ database adapter for the Python_ programming
  3. language. This is version 2, a complete rewrite of the original code to
  4. provide new-style classes for connection and cursor objects and other sweet
  5. candies. Like the original, psycopg 2 was written with the aim of being very
  6. small and fast, and stable as a rock.
  7. Homepage: http://initd.org/projects/psycopg2
  8. .. _PostgreSQL: http://www.postgresql.org/
  9. .. _Python: http://www.python.org/
  10. :Groups:
  11. * `Connections creation`: connect
  12. * `Value objects constructors`: Binary, Date, DateFromTicks, Time,
  13. TimeFromTicks, Timestamp, TimestampFromTicks
  14. """
  15. # psycopg/__init__.py - initialization of the psycopg module
  16. #
  17. # Copyright (C) 2003-2010 Federico Di Gregorio <fog@debian.org>
  18. #
  19. # psycopg2 is free software: you can redistribute it and/or modify it
  20. # under the terms of the GNU Lesser General Public License as published
  21. # by the Free Software Foundation, either version 3 of the License, or
  22. # (at your option) any later version.
  23. #
  24. # In addition, as a special exception, the copyright holders give
  25. # permission to link this program with the OpenSSL library (or with
  26. # modified versions of OpenSSL that use the same license as OpenSSL),
  27. # and distribute linked combinations including the two.
  28. #
  29. # You must obey the GNU Lesser General Public License in all respects for
  30. # all of the code used other than OpenSSL.
  31. #
  32. # psycopg2 is distributed in the hope that it will be useful, but WITHOUT
  33. # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  34. # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
  35. # License for more details.
  36. # Import modules needed by _psycopg to allow tools like py2exe to do
  37. # their work without bothering about the module dependencies.
  38. import sys, warnings
  39. if sys.version_info >= (2, 3):
  40. try:
  41. import datetime as _psycopg_needs_datetime
  42. except:
  43. warnings.warn(
  44. "can't import datetime module probably needed by _psycopg",
  45. RuntimeWarning)
  46. if sys.version_info >= (2, 4):
  47. try:
  48. import decimal as _psycopg_needs_decimal
  49. except:
  50. warnings.warn(
  51. "can't import decimal module probably needed by _psycopg",
  52. RuntimeWarning)
  53. del sys, warnings
  54. # Note: the first internal import should be _psycopg, otherwise the real cause
  55. # of a failed loading of the C module may get hidden, see
  56. # http://archives.postgresql.org/psycopg/2011-02/msg00044.php
  57. # Import the DBAPI-2.0 stuff into top-level module.
  58. from psycopg2._psycopg import BINARY, NUMBER, STRING, DATETIME, ROWID
  59. from psycopg2._psycopg import Binary, Date, Time, Timestamp
  60. from psycopg2._psycopg import DateFromTicks, TimeFromTicks, TimestampFromTicks
  61. from psycopg2._psycopg import Error, Warning, DataError, DatabaseError, ProgrammingError
  62. from psycopg2._psycopg import IntegrityError, InterfaceError, InternalError
  63. from psycopg2._psycopg import NotSupportedError, OperationalError
  64. from psycopg2._psycopg import _connect, apilevel, threadsafety, paramstyle
  65. from psycopg2._psycopg import __version__
  66. from psycopg2 import tz
  67. # Register default adapters.
  68. import psycopg2.extensions as _ext
  69. _ext.register_adapter(tuple, _ext.SQL_IN)
  70. _ext.register_adapter(type(None), _ext.NoneAdapter)
  71. # Register the Decimal adapter here instead of in the C layer.
  72. # This way a new class is registered for each sub-interpreter.
  73. # See ticket #52
  74. try:
  75. from decimal import Decimal
  76. except ImportError:
  77. pass
  78. else:
  79. from psycopg2._psycopg import Decimal as Adapter
  80. _ext.register_adapter(Decimal, Adapter)
  81. del Decimal, Adapter
  82. import re
  83. def _param_escape(s,
  84. re_escape=re.compile(r"([\\'])"),
  85. re_space=re.compile(r'\s')):
  86. """
  87. Apply the escaping rule required by PQconnectdb
  88. """
  89. if not s: return "''"
  90. s = re_escape.sub(r'\\\1', s)
  91. if re_space.search(s):
  92. s = "'" + s + "'"
  93. return s
  94. del re
  95. def connect(dsn=None,
  96. database=None, user=None, password=None, host=None, port=None,
  97. connection_factory=None, async=False, **kwargs):
  98. """
  99. Create a new database connection.
  100. The connection parameters can be specified either as a string:
  101. conn = psycopg2.connect("dbname=test user=postgres password=secret")
  102. or using a set of keyword arguments:
  103. conn = psycopg2.connect(database="test", user="postgres", password="secret")
  104. The basic connection parameters are:
  105. - *dbname*: the database name (only in dsn string)
  106. - *database*: the database name (only as keyword argument)
  107. - *user*: user name used to authenticate
  108. - *password*: password used to authenticate
  109. - *host*: database host address (defaults to UNIX socket if not provided)
  110. - *port*: connection port number (defaults to 5432 if not provided)
  111. Using the *connection_factory* parameter a different class or connections
  112. factory can be specified. It should be a callable object taking a dsn
  113. argument.
  114. Using *async*=True an asynchronous connection will be created.
  115. Any other keyword parameter will be passed to the underlying client
  116. library: the list of supported parameters depends on the library version.
  117. """
  118. items = []
  119. if database is not None:
  120. items.append(('dbname', database))
  121. if user is not None:
  122. items.append(('user', user))
  123. if password is not None:
  124. items.append(('password', password))
  125. if host is not None:
  126. items.append(('host', host))
  127. if port is not None:
  128. items.append(('port', port))
  129. items.extend([(k, v) for (k, v) in kwargs.iteritems() if v is not None])
  130. if dsn is not None and items:
  131. raise TypeError(
  132. "'%s' is an invalid keyword argument when the dsn is specified"
  133. % items[0][0])
  134. if dsn is None:
  135. if not items:
  136. raise TypeError('missing dsn and no parameters')
  137. else:
  138. dsn = " ".join(["%s=%s" % (k, _param_escape(str(v)))
  139. for (k, v) in items])
  140. return _connect(dsn, connection_factory=connection_factory, async=async)
  141. __all__ = filter(lambda k: not k.startswith('_'), locals().keys())