sqlalchemy-haystack 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
137
+ .idea
138
+
139
+ # macOS
140
+ .DS_Store
141
+
142
+ # http cache (requests-cache)
143
+ **/http_cache.sqlite
144
+
145
+ # ruff
146
+ .ruff_cache
@@ -0,0 +1,7 @@
1
+ # Changelog
2
+
3
+ ## [integrations/sqlalchemy-v0.1.0] - 2026-04-02
4
+
5
+ ### 🚀 Features
6
+
7
+ - Initial release of `sqlalchemy-haystack` integration (#3077)
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqlalchemy-haystack
3
+ Version: 0.1.0
4
+ Summary: A SQLAlchemy integration for the Haystack framework.
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/sqlalchemy#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/sqlalchemy
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Programming Language :: Python
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Programming Language :: Python :: 3.14
19
+ Classifier: Programming Language :: Python :: Implementation :: CPython
20
+ Classifier: Programming Language :: Python :: Implementation :: PyPy
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: haystack-ai>=2.22.0
23
+ Requires-Dist: pandas>=2.2.3; python_version < '3.11'
24
+ Requires-Dist: pandas>=3.0.0; python_version >= '3.11'
25
+ Requires-Dist: sqlalchemy>=2.0.36
26
+ Description-Content-Type: text/markdown
27
+
28
+ # sqlalchemy-haystack
29
+
30
+ [![PyPI - Version](https://img.shields.io/pypi/v/sqlalchemy-haystack.svg)](https://pypi.org/project/sqlalchemy-haystack)
31
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/sqlalchemy-haystack.svg)](https://pypi.org/project/sqlalchemy-haystack)
32
+
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/sqlalchemy/CHANGELOG.md)
34
+
35
+ ---
36
+
37
+ A Haystack integration for querying SQL databases via [SQLAlchemy](https://www.sqlalchemy.org/).
38
+ Provides a `SQLAlchemyTableRetriever` component that connects to any SQLAlchemy-supported database,
39
+ executes a SQL query, and returns results as a Pandas DataFrame and an optional Markdown table.
40
+
41
+ ## Installation
42
+
43
+ ```bash
44
+ pip install sqlalchemy-haystack
45
+ ```
46
+
47
+ You also need to install the appropriate database driver for your backend:
48
+
49
+ | Backend | Driver package |
50
+ |---------|---------------|
51
+ | PostgreSQL | `psycopg2-binary` or `psycopg[binary]` |
52
+ | MySQL / MariaDB | `pymysql` or `mysqlclient` |
53
+ | SQLite | built-in (no extra package needed) |
54
+ | MSSQL | `pyodbc` |
55
+ | Oracle | `cx_oracle` or `oracledb` |
56
+
57
+ ## Usage
58
+
59
+ ```python
60
+ from haystack_integrations.components.retrievers.sqlalchemy import SQLAlchemyTableRetriever
61
+
62
+ # SQLite in-memory example (no driver needed)
63
+ retriever = SQLAlchemyTableRetriever(
64
+ drivername="sqlite",
65
+ database=":memory:",
66
+ init_script=[
67
+ "CREATE TABLE products (id INTEGER, name TEXT, price REAL)",
68
+ "INSERT INTO products VALUES (1, 'Widget', 9.99)",
69
+ "INSERT INTO products VALUES (2, 'Gadget', 19.99)",
70
+ ],
71
+ )
72
+ retriever.warm_up()
73
+
74
+ result = retriever.run(query="SELECT * FROM products WHERE price < 15")
75
+ print(result["dataframe"])
76
+ print(result["table"])
77
+ ```
78
+
79
+ For PostgreSQL:
80
+
81
+ ```python
82
+ from haystack.utils import Secret
83
+
84
+ retriever = SQLAlchemyTableRetriever(
85
+ drivername="postgresql+psycopg2",
86
+ host="localhost",
87
+ port=5432,
88
+ database="mydb",
89
+ username="myuser",
90
+ password=Secret.from_env_var("DB_PASSWORD"),
91
+ )
92
+ ```
93
+
94
+ ## Security
95
+
96
+ This component executes raw SQL queries passed at runtime. Keep the following in mind:
97
+
98
+ - **Never pass unsanitised user input** directly as a query — this exposes you to SQL injection.
99
+ - **Use a read-only database user.** This is the most effective mitigation. Even if a malicious
100
+ query is executed, a read-only user cannot modify or delete data.
101
+ - **Restrict database permissions** to the minimum required — specific tables and schemas only,
102
+ no DDL privileges (no `CREATE`, `DROP`, `ALTER`).
103
+
104
+ ## Contributing
105
+
106
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,79 @@
1
+ # sqlalchemy-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/sqlalchemy-haystack.svg)](https://pypi.org/project/sqlalchemy-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/sqlalchemy-haystack.svg)](https://pypi.org/project/sqlalchemy-haystack)
5
+
6
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/sqlalchemy/CHANGELOG.md)
7
+
8
+ ---
9
+
10
+ A Haystack integration for querying SQL databases via [SQLAlchemy](https://www.sqlalchemy.org/).
11
+ Provides a `SQLAlchemyTableRetriever` component that connects to any SQLAlchemy-supported database,
12
+ executes a SQL query, and returns results as a Pandas DataFrame and an optional Markdown table.
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ pip install sqlalchemy-haystack
18
+ ```
19
+
20
+ You also need to install the appropriate database driver for your backend:
21
+
22
+ | Backend | Driver package |
23
+ |---------|---------------|
24
+ | PostgreSQL | `psycopg2-binary` or `psycopg[binary]` |
25
+ | MySQL / MariaDB | `pymysql` or `mysqlclient` |
26
+ | SQLite | built-in (no extra package needed) |
27
+ | MSSQL | `pyodbc` |
28
+ | Oracle | `cx_oracle` or `oracledb` |
29
+
30
+ ## Usage
31
+
32
+ ```python
33
+ from haystack_integrations.components.retrievers.sqlalchemy import SQLAlchemyTableRetriever
34
+
35
+ # SQLite in-memory example (no driver needed)
36
+ retriever = SQLAlchemyTableRetriever(
37
+ drivername="sqlite",
38
+ database=":memory:",
39
+ init_script=[
40
+ "CREATE TABLE products (id INTEGER, name TEXT, price REAL)",
41
+ "INSERT INTO products VALUES (1, 'Widget', 9.99)",
42
+ "INSERT INTO products VALUES (2, 'Gadget', 19.99)",
43
+ ],
44
+ )
45
+ retriever.warm_up()
46
+
47
+ result = retriever.run(query="SELECT * FROM products WHERE price < 15")
48
+ print(result["dataframe"])
49
+ print(result["table"])
50
+ ```
51
+
52
+ For PostgreSQL:
53
+
54
+ ```python
55
+ from haystack.utils import Secret
56
+
57
+ retriever = SQLAlchemyTableRetriever(
58
+ drivername="postgresql+psycopg2",
59
+ host="localhost",
60
+ port=5432,
61
+ database="mydb",
62
+ username="myuser",
63
+ password=Secret.from_env_var("DB_PASSWORD"),
64
+ )
65
+ ```
66
+
67
+ ## Security
68
+
69
+ This component executes raw SQL queries passed at runtime. Keep the following in mind:
70
+
71
+ - **Never pass unsanitised user input** directly as a query — this exposes you to SQL injection.
72
+ - **Use a read-only database user.** This is the most effective mitigation. Even if a malicious
73
+ query is executed, a read-only user cannot modify or delete data.
74
+ - **Restrict database permissions** to the minimum required — specific tables and schemas only,
75
+ no DDL privileges (no `CREATE`, `DROP`, `ALTER`).
76
+
77
+ ## Contributing
78
+
79
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.retrievers.sqlalchemy.sqlalchemy_table_retriever
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: SQLAlchemy integration for Haystack
11
+ id: integrations-sqlalchemy
12
+ filename: sqlalchemy.md
13
+ title: SQLAlchemy
@@ -0,0 +1,164 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "sqlalchemy-haystack"
7
+ dynamic = ["version"]
8
+ description = 'A SQLAlchemy integration for the Haystack framework.'
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = []
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: Implementation :: CPython",
24
+ "Programming Language :: Python :: Implementation :: PyPy",
25
+ ]
26
+ dependencies = [
27
+ "haystack-ai>=2.22.0",
28
+ "sqlalchemy>=2.0.36",
29
+ "pandas>=2.2.3; python_version < '3.11'",
30
+ "pandas>=3.0.0; python_version >= '3.11'",
31
+ ]
32
+
33
+ [project.urls]
34
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/sqlalchemy#readme"
35
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
36
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/sqlalchemy"
37
+
38
+ [tool.hatch.build.targets.wheel]
39
+ packages = ["src/haystack_integrations"]
40
+
41
+ [tool.hatch.version]
42
+ source = "vcs"
43
+ tag-pattern = 'integrations\/sqlalchemy-v(?P<version>.*)'
44
+
45
+ [tool.hatch.version.raw-options]
46
+ root = "../.."
47
+ git_describe_command = 'git describe --tags --match="integrations/sqlalchemy-v[0-9]*"'
48
+
49
+ [tool.hatch.envs.default]
50
+ installer = "uv"
51
+ dependencies = ["haystack-pydoc-tools", "ruff"]
52
+
53
+ [tool.hatch.envs.default.scripts]
54
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
55
+ fmt = "ruff check --fix {args}; ruff format {args}"
56
+ fmt-check = "ruff check {args} && ruff format --check {args}"
57
+
58
+ [tool.hatch.envs.test]
59
+ dependencies = [
60
+ "pytest",
61
+ "pytest-asyncio",
62
+ "pytest-cov",
63
+ "pytest-rerunfailures",
64
+ "mypy",
65
+ "pip",
66
+ "pandas-stubs",
67
+ ]
68
+
69
+ [tool.hatch.envs.test.scripts]
70
+ unit = 'pytest -m "not integration" {args:tests}'
71
+ integration = 'pytest -m "integration" {args:tests}'
72
+ all = 'pytest {args:tests}'
73
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
74
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
75
+
76
+ types = "mypy -p haystack_integrations.components.retrievers.sqlalchemy {args}"
77
+
78
+ [tool.mypy]
79
+ install_types = true
80
+ non_interactive = true
81
+ check_untyped_defs = true
82
+ disallow_incomplete_defs = true
83
+
84
+ [tool.ruff]
85
+ line-length = 120
86
+
87
+ [tool.ruff.lint]
88
+ select = [
89
+ "A",
90
+ "ANN",
91
+ "ARG",
92
+ "B",
93
+ "C",
94
+ "D102",
95
+ "D103",
96
+ "D205",
97
+ "D209",
98
+ "D213",
99
+ "D417",
100
+ "D419",
101
+ "DTZ",
102
+ "E",
103
+ "EM",
104
+ "F",
105
+ "FBT",
106
+ "I",
107
+ "ICN",
108
+ "ISC",
109
+ "N",
110
+ "PLC",
111
+ "PLE",
112
+ "PLR",
113
+ "PLW",
114
+ "Q",
115
+ "RUF",
116
+ "S",
117
+ "T",
118
+ "TID",
119
+ "UP",
120
+ "W",
121
+ "YTT",
122
+ ]
123
+ ignore = [
124
+ # Allow non-abstract empty methods in abstract base classes
125
+ "B027",
126
+ # Allow Any in type annotations at dynamic boundaries
127
+ "ANN401",
128
+ # Allow boolean positional values in function calls, like `dict.get(... True)`
129
+ "FBT003",
130
+ # Ignore checks for possible passwords
131
+ "S105",
132
+ "S106",
133
+ "S107",
134
+ # Ignore complexity
135
+ "C901",
136
+ "PLR0911",
137
+ "PLR0912",
138
+ "PLR0913",
139
+ "PLR0915",
140
+ # Ignore SQL injection warning (user-provided queries are expected)
141
+ "S608",
142
+ # Unused method argument
143
+ "ARG002",
144
+ ]
145
+
146
+ [tool.ruff.lint.isort]
147
+ known-first-party = ["haystack_integrations"]
148
+
149
+ [tool.ruff.lint.flake8-tidy-imports]
150
+ ban-relative-imports = "parents"
151
+
152
+ [tool.ruff.lint.per-file-ignores]
153
+ "tests/**/*" = ["D", "PLR2004", "S101", "TID252", "ANN"]
154
+
155
+ [tool.coverage.run]
156
+ source = ["haystack_integrations"]
157
+ branch = true
158
+ relative_files = true
159
+ parallel = false
160
+
161
+ [tool.coverage.report]
162
+ omit = ["*/tests/*", "*/__init__.py"]
163
+ show_missing = true
164
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from .sqlalchemy_table_retriever import SQLAlchemyTableRetriever
6
+
7
+ __all__ = ["SQLAlchemyTableRetriever"]
@@ -0,0 +1,184 @@
1
+ # SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from typing import Any
6
+
7
+ from haystack import component, default_from_dict, default_to_dict, logging
8
+ from haystack.utils import Secret, deserialize_secrets_inplace
9
+ from pandas import DataFrame
10
+
11
+ from sqlalchemy import create_engine, text
12
+ from sqlalchemy.engine import URL, Engine
13
+ from sqlalchemy.exc import SQLAlchemyError
14
+ from sqlalchemy.pool import StaticPool
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+ MAX_SYS_ROWS = 10_000
19
+
20
+
21
+ @component
22
+ class SQLAlchemyTableRetriever:
23
+ """
24
+ Connects to any SQLAlchemy-supported database and executes a SQL query.
25
+
26
+ Returns results as a Pandas DataFrame and an optional Markdown-formatted table string.
27
+ Supports any database backend that SQLAlchemy supports, including PostgreSQL, MySQL,
28
+ SQLite, and MSSQL.
29
+
30
+ ### Usage example:
31
+
32
+ ```python
33
+ from haystack_integrations.components.retrievers.sqlalchemy import SQLAlchemyTableRetriever
34
+
35
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
36
+ retriever.warm_up()
37
+ result = retriever.run(query="SELECT 1 AS value")
38
+ print(result["dataframe"])
39
+ print(result["table"])
40
+ ```
41
+ """
42
+
43
+ def __init__(
44
+ self,
45
+ drivername: str,
46
+ username: str | None = None,
47
+ password: Secret | None = None,
48
+ host: str | None = None,
49
+ port: int | None = None,
50
+ database: str | None = None,
51
+ init_script: list[str] | None = None,
52
+ ) -> None:
53
+ """
54
+ Initialize SQLAlchemyTableRetriever.
55
+
56
+ :param drivername: The SQLAlchemy driver name (e.g., ``"sqlite"``,
57
+ ``"postgresql+psycopg2"``).
58
+ :param username: Database username.
59
+ :param password: Database password as a Haystack ``Secret``.
60
+ :param host: Database host.
61
+ :param port: Database port.
62
+ :param database: Database name or path (e.g., ``":memory:"`` for SQLite in-memory).
63
+ :param init_script: Optional list of SQL statements executed once on ``warm_up()``
64
+ (e.g., to create tables or insert seed data). Each statement should be a
65
+ separate string in the list.
66
+ """
67
+ self.drivername = drivername
68
+ self.username = username
69
+ self.password = password
70
+ self.host = host
71
+ self.port = port
72
+ self.database = database
73
+ self.init_script = init_script
74
+ self._engine: Engine | None = None
75
+ self._warmed_up = False
76
+
77
+ def warm_up(self) -> None:
78
+ """
79
+ Initialize the database engine and execute ``init_script`` if provided.
80
+
81
+ Called automatically by ``run()`` on first invocation if not already warmed up.
82
+ """
83
+ if self._warmed_up:
84
+ return
85
+
86
+ url = URL.create(
87
+ drivername=self.drivername,
88
+ username=self.username,
89
+ password=self.password.resolve_value() if self.password else None,
90
+ host=self.host,
91
+ port=self.port,
92
+ database=self.database,
93
+ )
94
+
95
+ engine_kwargs: dict[str, Any] = {}
96
+ if url.drivername.startswith("sqlite") and url.database in (":memory:", "", None):
97
+ engine_kwargs["connect_args"] = {"check_same_thread": False}
98
+ engine_kwargs["poolclass"] = StaticPool
99
+
100
+ self._engine = create_engine(url, **engine_kwargs)
101
+
102
+ if self.init_script:
103
+ with self._engine.connect() as conn:
104
+ for stmt in self.init_script:
105
+ stripped = stmt.strip()
106
+ if stripped:
107
+ conn.execute(text(stripped))
108
+ conn.commit()
109
+
110
+ self._warmed_up = True
111
+
112
+ def to_dict(self) -> dict[str, Any]:
113
+ """
114
+ Serialize the component to a dictionary.
115
+
116
+ :returns: Dictionary with serialized data.
117
+ """
118
+ return default_to_dict(
119
+ self,
120
+ drivername=self.drivername,
121
+ username=self.username,
122
+ password=self.password.to_dict() if self.password else None,
123
+ host=self.host,
124
+ port=self.port,
125
+ database=self.database,
126
+ init_script=self.init_script,
127
+ )
128
+
129
+ @classmethod
130
+ def from_dict(cls, data: dict[str, Any]) -> "SQLAlchemyTableRetriever":
131
+ """
132
+ Deserialize the component from a dictionary.
133
+
134
+ :param data: Dictionary to deserialize from.
135
+ :returns: Deserialized component.
136
+ """
137
+ deserialize_secrets_inplace(data.get("init_parameters", {}), ["password"])
138
+ return default_from_dict(cls, data)
139
+
140
+ @staticmethod
141
+ def _df_to_markdown(df: DataFrame) -> str:
142
+ if df.empty:
143
+ return ""
144
+ header = "| " + " | ".join(str(c) for c in df.columns) + " |"
145
+ separator = "| " + " | ".join("---" for _ in df.columns) + " |"
146
+ rows = ["| " + " | ".join(str(v) for v in row) + " |" for row in df.itertuples(index=False)]
147
+ return "\n".join([header, separator, *rows])
148
+
149
+ @component.output_types(dataframe=DataFrame, table=str, error=str)
150
+ def run(self, query: str) -> dict[str, Any]:
151
+ """
152
+ Execute a SQL query and return the results.
153
+
154
+ :param query: The SQL query to execute.
155
+ :returns: A dictionary with:
156
+
157
+ - ``dataframe``: A Pandas DataFrame with the query results.
158
+ - ``table``: A Markdown-formatted string of the results.
159
+ - ``error``: An error message if the query failed, otherwise an empty string.
160
+ """
161
+ if not isinstance(query, str):
162
+ logger.warning("Query is not a string, returning empty DataFrame")
163
+ return {"dataframe": DataFrame(), "table": "", "error": "query is not a string"}
164
+
165
+ if not query.strip():
166
+ return {"dataframe": DataFrame(), "table": "", "error": "empty query"}
167
+
168
+ if not self._warmed_up:
169
+ self.warm_up()
170
+
171
+ if self._engine is None: # pragma: no cover
172
+ msg = "Engine is not initialized."
173
+ raise RuntimeError(msg)
174
+
175
+ try:
176
+ with self._engine.connect() as conn:
177
+ result = conn.execute(text(query))
178
+ rows = result.fetchmany(MAX_SYS_ROWS)
179
+ columns = list(result.keys())
180
+ df = DataFrame(rows, columns=columns)
181
+ return {"dataframe": df, "table": self._df_to_markdown(df), "error": ""}
182
+ except SQLAlchemyError as e:
183
+ logger.warning("Error executing query: {error}", error=str(e))
184
+ return {"dataframe": DataFrame(), "table": "", "error": str(e)}
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,173 @@
1
+ # SPDX-FileCopyrightText: 2025-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import pytest
6
+ from haystack.utils import Secret
7
+
8
+ import haystack_integrations.components.retrievers.sqlalchemy.sqlalchemy_table_retriever as module
9
+ from haystack_integrations.components.retrievers.sqlalchemy import SQLAlchemyTableRetriever
10
+
11
+
12
+ class TestSQLAlchemyTableRetrieverInit:
13
+ def test_init_defaults(self):
14
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite")
15
+ assert retriever.drivername == "sqlite"
16
+ assert retriever.username is None
17
+ assert retriever.password is None
18
+ assert retriever.host is None
19
+ assert retriever.port is None
20
+ assert retriever.database is None
21
+ assert retriever.init_script is None
22
+
23
+ def test_init_all_params(self):
24
+ password = Secret.from_token("secret")
25
+ retriever = SQLAlchemyTableRetriever(
26
+ drivername="postgresql+psycopg2",
27
+ username="user",
28
+ password=password,
29
+ host="localhost",
30
+ port=5432,
31
+ database="mydb",
32
+ init_script=["CREATE TABLE t (x INTEGER)"],
33
+ )
34
+ assert retriever.drivername == "postgresql+psycopg2"
35
+ assert retriever.username == "user"
36
+ assert retriever.password is password
37
+ assert retriever.host == "localhost"
38
+ assert retriever.port == 5432
39
+ assert retriever.database == "mydb"
40
+ assert retriever.init_script == ["CREATE TABLE t (x INTEGER)"]
41
+
42
+
43
+ class TestSQLAlchemyTableRetrieverSerialization:
44
+ def test_to_dict(self):
45
+ password = Secret.from_env_var("DB_PASSWORD")
46
+ init_script = ["CREATE TABLE t (x INTEGER)", "INSERT INTO t VALUES (1)"]
47
+ retriever = SQLAlchemyTableRetriever(
48
+ drivername="sqlite",
49
+ database=":memory:",
50
+ password=password,
51
+ init_script=init_script,
52
+ )
53
+ d = retriever.to_dict()
54
+ expected_type = (
55
+ "haystack_integrations.components.retrievers.sqlalchemy.sqlalchemy_table_retriever.SQLAlchemyTableRetriever"
56
+ )
57
+ assert d["type"] == expected_type
58
+ params = d["init_parameters"]
59
+ assert params["drivername"] == "sqlite"
60
+ assert params["database"] == ":memory:"
61
+ assert params["password"]["type"] == "env_var"
62
+ assert params["init_script"] == init_script
63
+
64
+ def test_from_dict(self, monkeypatch):
65
+ monkeypatch.setenv("DB_PASSWORD", "secret")
66
+ password = Secret.from_env_var("DB_PASSWORD")
67
+ init_script = ["CREATE TABLE t (x INTEGER)", "INSERT INTO t VALUES (1)"]
68
+ retriever = SQLAlchemyTableRetriever(
69
+ drivername="sqlite",
70
+ database=":memory:",
71
+ password=password,
72
+ init_script=init_script,
73
+ )
74
+ d = retriever.to_dict()
75
+ restored = SQLAlchemyTableRetriever.from_dict(d)
76
+ assert restored.drivername == "sqlite"
77
+ assert restored.database == ":memory:"
78
+ assert restored.password is not None
79
+ assert restored.password.resolve_value() == "secret"
80
+ assert restored.init_script == init_script
81
+
82
+
83
+ class TestSQLAlchemyTableRetrieverRun:
84
+ @pytest.fixture()
85
+ def retriever_with_data(self):
86
+ init_sql = [
87
+ "CREATE TABLE employees (id INTEGER PRIMARY KEY, name TEXT NOT NULL,"
88
+ " department TEXT NOT NULL, salary INTEGER NOT NULL)",
89
+ "INSERT INTO employees VALUES (1, 'Alice', 'Engineering', 95000)",
90
+ "INSERT INTO employees VALUES (2, 'Bob', 'Marketing', 72000)",
91
+ "INSERT INTO employees VALUES (3, 'Carol', 'Engineering', 88000)",
92
+ ]
93
+ retriever = SQLAlchemyTableRetriever(
94
+ drivername="sqlite",
95
+ database=":memory:",
96
+ init_script=init_sql,
97
+ )
98
+ retriever.warm_up()
99
+ return retriever
100
+
101
+ def test_run_non_string_query(self):
102
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
103
+ result = retriever.run(query=123) # type: ignore[arg-type]
104
+ assert result["error"] == "query is not a string"
105
+ assert result["dataframe"].empty
106
+ assert result["table"] == ""
107
+
108
+ @pytest.mark.parametrize("query", ["", " ", "\t", "\n"])
109
+ def test_run_empty_query(self, query):
110
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
111
+ result = retriever.run(query=query)
112
+ assert result["error"] == "empty query"
113
+ assert result["dataframe"].empty
114
+ assert result["table"] == ""
115
+
116
+ def test_run_returns_dataframe(self, retriever_with_data):
117
+ result = retriever_with_data.run(query="SELECT * FROM employees ORDER BY id")
118
+ df = result["dataframe"]
119
+ assert result["error"] == ""
120
+ assert list(df.columns) == ["id", "name", "department", "salary"]
121
+ assert len(df) == 3
122
+ assert df.iloc[0]["name"] == "Alice"
123
+ assert df.iloc[1]["department"] == "Marketing"
124
+ assert df.iloc[2]["salary"] == 88000
125
+
126
+ def test_run_returns_markdown(self, retriever_with_data):
127
+ result = retriever_with_data.run(query="SELECT * FROM employees ORDER BY id")
128
+ expected = (
129
+ "| id | name | department | salary |\n"
130
+ "| --- | --- | --- | --- |\n"
131
+ "| 1 | Alice | Engineering | 95000 |\n"
132
+ "| 2 | Bob | Marketing | 72000 |\n"
133
+ "| 3 | Carol | Engineering | 88000 |"
134
+ )
135
+ assert result["table"] == expected
136
+
137
+ def test_run_sql_error(self):
138
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
139
+ retriever.warm_up()
140
+ result = retriever.run(query="SELECT * FROM nonexistent_table_xyz")
141
+ assert result["error"] != ""
142
+ assert result["dataframe"].empty
143
+
144
+ def test_max_row_limit(self, monkeypatch):
145
+ init_sql = [
146
+ "CREATE TABLE t (x INTEGER)",
147
+ "INSERT INTO t VALUES (1)",
148
+ "INSERT INTO t VALUES (2)",
149
+ "INSERT INTO t VALUES (3)",
150
+ ]
151
+ retriever = SQLAlchemyTableRetriever(
152
+ drivername="sqlite",
153
+ database=":memory:",
154
+ init_script=init_sql,
155
+ )
156
+ monkeypatch.setattr(module, "MAX_SYS_ROWS", 2)
157
+ retriever.warm_up()
158
+ result = retriever.run(query="SELECT * FROM t")
159
+ assert len(result["dataframe"]) == 2
160
+
161
+ def test_warm_up_idempotent(self):
162
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
163
+ retriever.warm_up()
164
+ engine = retriever._engine
165
+ retriever.warm_up()
166
+ assert retriever._engine is engine
167
+
168
+ def test_run_calls_warm_up_automatically(self):
169
+ retriever = SQLAlchemyTableRetriever(drivername="sqlite", database=":memory:")
170
+ assert not retriever._warmed_up
171
+ result = retriever.run(query="SELECT 1 AS x")
172
+ assert retriever._warmed_up
173
+ assert not result["dataframe"].empty