pysqlcipher.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. # dialects/sqlite/pysqlcipher.py
  2. # Copyright (C) 2005-2025 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: https://www.opensource.org/licenses/mit-license.php
  7. # mypy: ignore-errors
  8. """
  9. .. dialect:: sqlite+pysqlcipher
  10. :name: pysqlcipher
  11. :dbapi: sqlcipher 3 or pysqlcipher
  12. :connectstring: sqlite+pysqlcipher://:passphrase@/file_path[?kdf_iter=<iter>]
  13. Dialect for support of DBAPIs that make use of the
  14. `SQLCipher <https://www.zetetic.net/sqlcipher>`_ backend.
  15. Driver
  16. ------
  17. Current dialect selection logic is:
  18. * If the :paramref:`_sa.create_engine.module` parameter supplies a DBAPI module,
  19. that module is used.
  20. * Otherwise for Python 3, choose https://pypi.org/project/sqlcipher3/
  21. * If not available, fall back to https://pypi.org/project/pysqlcipher3/
  22. * For Python 2, https://pypi.org/project/pysqlcipher/ is used.
  23. .. warning:: The ``pysqlcipher3`` and ``pysqlcipher`` DBAPI drivers are no
  24. longer maintained; the ``sqlcipher3`` driver as of this writing appears
  25. to be current. For future compatibility, any pysqlcipher-compatible DBAPI
  26. may be used as follows::
  27. import sqlcipher_compatible_driver
  28. from sqlalchemy import create_engine
  29. e = create_engine(
  30. "sqlite+pysqlcipher://:password@/dbname.db",
  31. module=sqlcipher_compatible_driver,
  32. )
  33. These drivers make use of the SQLCipher engine. This system essentially
  34. introduces new PRAGMA commands to SQLite which allows the setting of a
  35. passphrase and other encryption parameters, allowing the database file to be
  36. encrypted.
  37. Connect Strings
  38. ---------------
  39. The format of the connect string is in every way the same as that
  40. of the :mod:`~sqlalchemy.dialects.sqlite.pysqlite` driver, except that the
  41. "password" field is now accepted, which should contain a passphrase::
  42. e = create_engine("sqlite+pysqlcipher://:testing@/foo.db")
  43. For an absolute file path, two leading slashes should be used for the
  44. database name::
  45. e = create_engine("sqlite+pysqlcipher://:testing@//path/to/foo.db")
  46. A selection of additional encryption-related pragmas supported by SQLCipher
  47. as documented at https://www.zetetic.net/sqlcipher/sqlcipher-api/ can be passed
  48. in the query string, and will result in that PRAGMA being called for each
  49. new connection. Currently, ``cipher``, ``kdf_iter``
  50. ``cipher_page_size`` and ``cipher_use_hmac`` are supported::
  51. e = create_engine(
  52. "sqlite+pysqlcipher://:testing@/foo.db?cipher=aes-256-cfb&kdf_iter=64000"
  53. )
  54. .. warning:: Previous versions of sqlalchemy did not take into consideration
  55. the encryption-related pragmas passed in the url string, that were silently
  56. ignored. This may cause errors when opening files saved by a
  57. previous sqlalchemy version if the encryption options do not match.
  58. Pooling Behavior
  59. ----------------
  60. The driver makes a change to the default pool behavior of pysqlite
  61. as described in :ref:`pysqlite_threading_pooling`. The pysqlcipher driver
  62. has been observed to be significantly slower on connection than the
  63. pysqlite driver, most likely due to the encryption overhead, so the
  64. dialect here defaults to using the :class:`.SingletonThreadPool`
  65. implementation,
  66. instead of the :class:`.NullPool` pool used by pysqlite. As always, the pool
  67. implementation is entirely configurable using the
  68. :paramref:`_sa.create_engine.poolclass` parameter; the :class:`.
  69. StaticPool` may
  70. be more feasible for single-threaded use, or :class:`.NullPool` may be used
  71. to prevent unencrypted connections from being held open for long periods of
  72. time, at the expense of slower startup time for new connections.
  73. """ # noqa
  74. from .pysqlite import SQLiteDialect_pysqlite
  75. from ... import pool
  76. class SQLiteDialect_pysqlcipher(SQLiteDialect_pysqlite):
  77. driver = "pysqlcipher"
  78. supports_statement_cache = True
  79. pragmas = ("kdf_iter", "cipher", "cipher_page_size", "cipher_use_hmac")
  80. @classmethod
  81. def import_dbapi(cls):
  82. try:
  83. import sqlcipher3 as sqlcipher
  84. except ImportError:
  85. pass
  86. else:
  87. return sqlcipher
  88. from pysqlcipher3 import dbapi2 as sqlcipher
  89. return sqlcipher
  90. @classmethod
  91. def get_pool_class(cls, url):
  92. return pool.SingletonThreadPool
  93. def on_connect_url(self, url):
  94. super_on_connect = super().on_connect_url(url)
  95. # pull the info we need from the URL early. Even though URL
  96. # is immutable, we don't want any in-place changes to the URL
  97. # to affect things
  98. passphrase = url.password or ""
  99. url_query = dict(url.query)
  100. def on_connect(conn):
  101. cursor = conn.cursor()
  102. cursor.execute('pragma key="%s"' % passphrase)
  103. for prag in self.pragmas:
  104. value = url_query.get(prag, None)
  105. if value is not None:
  106. cursor.execute('pragma %s="%s"' % (prag, value))
  107. cursor.close()
  108. if super_on_connect:
  109. super_on_connect(conn)
  110. return on_connect
  111. def create_connect_args(self, url):
  112. plain_url = url._replace(password=None)
  113. plain_url = plain_url.difference_update_query(self.pragmas)
  114. return super().create_connect_args(plain_url)
  115. dialect = SQLiteDialect_pysqlcipher