├── .github ├── dependabot.yml └── workflows │ ├── release-test.yml │ ├── release.yml │ └── tests.yml ├── .gitignore ├── .run └── Python tests in tests.run.xml ├── LICENSE ├── README.md ├── pydbzengine ├── __init__.py ├── airflow.py ├── config │ └── log4j2.properties ├── debezium │ └── libs │ │ ├── activation-1.1.1.jar │ │ ├── antlr4-runtime-4.10.1.jar │ │ ├── aopalliance-repackaged-2.6.1.jar │ │ ├── bson-5.2.0.jar │ │ ├── bson-record-codec-5.2.0.jar │ │ ├── checker-qual-3.31.0.jar │ │ ├── commons-lang3-3.12.0.jar │ │ ├── connect-api-3.9.0.jar │ │ ├── connect-file-3.9.0.jar │ │ ├── connect-json-3.9.0.jar │ │ ├── connect-runtime-3.9.0.jar │ │ ├── connect-transforms-3.9.0.jar │ │ ├── debezium-api-3.1.1.Final.jar │ │ ├── debezium-connector-binlog-3.1.1.Final.jar │ │ ├── debezium-connector-mongodb-3.1.1.Final.jar │ │ ├── debezium-connector-mysql-3.1.1.Final.jar │ │ ├── debezium-connector-postgres-3.1.1.Final.jar │ │ ├── debezium-core-3.1.1.Final.jar │ │ ├── debezium-ddl-parser-3.1.1.Final.jar │ │ ├── debezium-embedded-3.1.1.Final.jar │ │ ├── debezium-sink-3.1.1.Final.jar │ │ ├── debezium-storage-file-3.1.1.Final.jar │ │ ├── debezium-storage-kafka-3.1.1.Final.jar │ │ ├── hk2-api-2.6.1.jar │ │ ├── hk2-locator-2.6.1.jar │ │ ├── hk2-utils-2.6.1.jar │ │ ├── jackson-annotations-2.16.2.jar │ │ ├── jackson-core-2.16.2.jar │ │ ├── jackson-databind-2.16.2.jar │ │ ├── jackson-datatype-jdk8-2.16.2.jar │ │ ├── jackson-datatype-jsr310-2.16.2.jar │ │ ├── jackson-jaxrs-base-2.16.2.jar │ │ ├── jackson-jaxrs-json-provider-2.16.2.jar │ │ ├── jackson-module-afterburner-2.16.2.jar │ │ ├── jackson-module-jaxb-annotations-2.16.2.jar │ │ ├── jakarta.activation-api-1.2.2.jar │ │ ├── jakarta.annotation-api-1.3.5.jar │ │ ├── jakarta.inject-2.6.1.jar │ │ ├── jakarta.validation-api-2.0.2.jar │ │ ├── jakarta.ws.rs-api-2.1.6.jar │ │ ├── jakarta.xml.bind-api-2.3.3.jar │ │ ├── javassist-3.29.0-GA.jar │ │ ├── javax.activation-api-1.2.0.jar │ │ ├── javax.servlet-api-3.1.0.jar │ │ ├── javax.ws.rs-api-2.1.1.jar │ │ ├── jaxb-api-2.3.1.jar │ │ ├── jersey-client-2.39.1.jar │ │ ├── jersey-common-2.39.1.jar │ │ ├── jersey-container-servlet-2.39.1.jar │ │ ├── jersey-container-servlet-core-2.39.1.jar │ │ ├── jersey-hk2-2.39.1.jar │ │ ├── jersey-server-2.39.1.jar │ │ ├── jetty-client-9.4.56.v20240826.jar │ │ ├── jetty-continuation-9.4.56.v20240826.jar │ │ ├── jetty-http-9.4.56.v20240826.jar │ │ ├── jetty-io-9.4.56.v20240826.jar │ │ ├── jetty-security-9.4.12.v20180830.jar │ │ ├── jetty-server-9.4.56.v20240826.jar │ │ ├── jetty-servlet-9.4.12.v20180830.jar │ │ ├── jetty-servlets-9.4.56.v20240826.jar │ │ ├── jetty-util-9.4.56.v20240826.jar │ │ ├── jose4j-0.9.4.jar │ │ ├── kafka-clients-3.9.0.jar │ │ ├── log4j-api-2.24.3.jar │ │ ├── log4j-core-2.24.3.jar │ │ ├── log4j-slf4j2-impl-2.24.3.jar │ │ ├── lz4-java-1.8.0.jar │ │ ├── maven-artifact-3.9.6.jar │ │ ├── mongodb-driver-core-5.2.0.jar │ │ ├── mongodb-driver-sync-5.2.0.jar │ │ ├── mysql-binlog-connector-java-0.40.2.jar │ │ ├── mysql-connector-j-9.1.0.jar │ │ ├── osgi-resource-locator-1.0.3.jar │ │ ├── plexus-utils-3.5.1.jar │ │ ├── postgresql-42.6.1.jar │ │ ├── protobuf-java-3.25.5.jar │ │ ├── reflections-0.9.12.jar │ │ ├── reload4j-1.2.25.jar │ │ ├── slf4j-api-2.0.16.jar │ │ ├── snappy-java-1.1.10.5.jar │ │ ├── swagger-annotations-2.2.8.jar │ │ └── zstd-jni-1.5.6-4.jar ├── examples │ └── dlt_consuming.py ├── handlers │ ├── __init__.py │ ├── dlt.py │ └── iceberg.py ├── helper.py ├── install_libs.sh └── pom.xml ├── pyproject.toml └── tests ├── base_postgresql_test.py ├── catalog_rest.py ├── config └── log4j2-test.properties ├── db_postgresql.py ├── s3_minio.py ├── test_change_handler.py ├── test_dlt_handler.py ├── test_engine.py └── test_iceberg_handler.py /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: "github-actions" 4 | directory: "/" 5 | schedule: 6 | interval: "weekly" 7 | - package-ecosystem: "pip" 8 | directory: "/" 9 | schedule: 10 | interval: "weekly" 11 | - package-ecosystem: "maven" 12 | directory: "/" 13 | schedule: 14 | interval: "weekly" -------------------------------------------------------------------------------- /.github/workflows/release-test.yml: -------------------------------------------------------------------------------- 1 | name: Create Test Pypi Release 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ main ] 7 | 8 | jobs: 9 | build: 10 | if: github.repository_owner == 'memiiso' 11 | runs-on: ubuntu-latest 12 | strategy: 13 | matrix: 14 | python-version: [ 3.9 ] 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | - name: Set up Python ${{ matrix.python-version }} 19 | uses: actions/setup-python@v5 20 | with: 21 | python-version: ${{ matrix.python-version }} 22 | - name: Install pypa/build 23 | run: | 24 | python -m pip install build --user 25 | - name: Build a binary wheel and a source tarball 26 | run: | 27 | python -m build --sdist --wheel --outdir dist/ . 28 | 29 | - name: Publish main to Test Pypi 30 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/heads/main') 31 | uses: pypa/gh-action-pypi-publish@release/v1 32 | with: 33 | user: __token__ 34 | password: ${{ secrets.TEST_PYPI_API_TOKEN }} 35 | repository-url: https://test.pypi.org/legacy/ 36 | skip-existing: true -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create Pypi Release 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | tags: 7 | - '*.*.*.*' 8 | 9 | jobs: 10 | build: 11 | if: github.repository_owner == 'memiiso' 12 | runs-on: ubuntu-latest 13 | strategy: 14 | matrix: 15 | python-version: [ 3.9 ] 16 | permissions: 17 | id-token: write # IMPORTANT: this permission is mandatory for trusted publishing 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | - name: Install pypa/build 26 | run: | 27 | python -m pip install build --user 28 | - name: Build a binary wheel and a source tarball 29 | run: | 30 | python -m build --sdist --wheel --outdir dist/ . 31 | 32 | - name: Publish to Pypi 33 | if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags') 34 | uses: pypa/gh-action-pypi-publish@release/v1 35 | with: 36 | user: __token__ 37 | password: ${{ secrets.PYPI_API_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | branches: [ main ] 7 | paths-ignore: 8 | - '.github/**' 9 | - '.idea/**' 10 | - '.run/**' 11 | pull_request: 12 | branches: [ main ] 13 | paths-ignore: 14 | - '.idea/**' 15 | - '.run/**' 16 | 17 | jobs: 18 | build: 19 | runs-on: ubuntu-latest 20 | strategy: 21 | matrix: 22 | python-version: [ "3.9", "3.10", "3.11", "3.12" ] 23 | steps: 24 | - uses: actions/checkout@v4 25 | - name: Set up Python ${{ matrix.python-version }} 26 | uses: actions/setup-python@v5 27 | with: 28 | python-version: ${{ matrix.python-version }} 29 | cache: 'pip' # caching pip dependencies 30 | - name: Build & Install & Test 31 | run: | 32 | python3 --version 33 | pip install coverage pylint pytest setuptools 34 | python3 -m compileall -f pydbzengine 35 | pip install .[dev,dlt,iceberg] 36 | python3 -m coverage report -m ./pydbzengine/*.py 37 | python3 -m coverage run --source=./tests/ -m unittest discover -s tests/ 38 | # python3 -m pylint pydbzengine 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | pydbzengine.iml 2 | .idea 3 | dbzjava 4 | build 5 | tests/logs 6 | pydbzengine/examples/logs 7 | **.duckdb 8 | **offsets.dat 9 | 10 | # Byte-compiled / optimized / DLL files 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | build/ 21 | develop-eggs/ 22 | dist/ 23 | downloads/ 24 | eggs/ 25 | .eggs/ 26 | lib/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | share/python-wheels/ 33 | *.egg-info/ 34 | .installed.cfg 35 | *.egg 36 | MANIFEST 37 | 38 | # PyInstaller 39 | # Usually these files are written by a python script from a template 40 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 41 | *.manifest 42 | *.spec 43 | 44 | # Installer logs 45 | pip-log.txt 46 | pip-delete-this-directory.txt 47 | 48 | # Unit test / coverage reports 49 | htmlcov/ 50 | .tox/ 51 | .nox/ 52 | .coverage 53 | .coverage.* 54 | .cache 55 | nosetests.xml 56 | coverage.xml 57 | *.cover 58 | *.py,cover 59 | .hypothesis/ 60 | .pytest_cache/ 61 | cover/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | .pybuilder/ 85 | target/ 86 | 87 | # Jupyter Notebook 88 | .ipynb_checkpoints 89 | 90 | # IPython 91 | profile_default/ 92 | ipython_config.py 93 | 94 | # pyenv 95 | # For a library or package, you might want to ignore these files since the code is 96 | # intended to run in multiple environments; otherwise, check them in: 97 | # .python-version 98 | 99 | # pipenv 100 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 101 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 102 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 103 | # install all needed dependencies. 104 | #Pipfile.lock 105 | 106 | # UV 107 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 108 | # This is especially recommended for binary packages to ensure reproducibility, and is more 109 | # commonly ignored for libraries. 110 | #uv.lock 111 | 112 | # poetry 113 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 114 | # This is especially recommended for binary packages to ensure reproducibility, and is more 115 | # commonly ignored for libraries. 116 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 117 | #poetry.lock 118 | 119 | # pdm 120 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 121 | #pdm.lock 122 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 123 | # in version control. 124 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 125 | .pdm.toml 126 | .pdm-python 127 | .pdm-build/ 128 | 129 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 130 | __pypackages__/ 131 | 132 | # Celery stuff 133 | celerybeat-schedule 134 | celerybeat.pid 135 | 136 | # SageMath parsed files 137 | *.sage.py 138 | 139 | # Environments 140 | .env 141 | .venv 142 | env/ 143 | venv/ 144 | ENV/ 145 | env.bak/ 146 | venv.bak/ 147 | 148 | # Spyder project settings 149 | .spyderproject 150 | .spyproject 151 | 152 | # Rope project settings 153 | .ropeproject 154 | 155 | # mkdocs documentation 156 | /site 157 | 158 | # mypy 159 | .mypy_cache/ 160 | .dmypy.json 161 | dmypy.json 162 | 163 | # Pyre type checker 164 | .pyre/ 165 | 166 | # pytype static type analyzer 167 | .pytype/ 168 | 169 | # Cython debug symbols 170 | cython_debug/ 171 | 172 | # PyCharm 173 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 174 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 175 | # and can be added to the global gitignore or merged into this file. For a more nuclear 176 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 177 | #.idea/ 178 | 179 | # PyPI configuration file 180 | .pypirc 181 | -------------------------------------------------------------------------------- /.run/Python tests in tests.run.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![License](http://img.shields.io/:license-apache%202.0-brightgreen.svg)](http://www.apache.org/licenses/LICENSE-2.0.html) 2 | [![PyPI version](https://badge.fury.io/py/pydbzengine.svg)](https://badge.fury.io/py/pydbzengine) 3 | [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/memiiso/pydbzengine/graphs/contributors) 4 | [![Create Pypi Release](https://github.com/memiiso/pydbzengine/actions/workflows/release.yml/badge.svg)](https://github.com/memiiso/pydbzengine/actions/workflows/release.yml) 5 | 6 | # pydbzengine 7 | 8 | A Pythonic interface for the [Debezium Engine](https://debezium.io/documentation/reference/stable/development/engine.html), allowing you to consume database Change Data Capture (CDC) events directly in your Python applications. 9 | 10 | ## Features 11 | 12 | * **Pure Python Interface**: Interact with the powerful Debezium Engine using simple Python classes and methods. 13 | * **Pluggable Event Handlers**: Easily create custom handlers to process CDC events according to your specific needs. 14 | * **Built-in Iceberg Handler**: Stream change events directly into Apache Iceberg tables with zero boilerplate. 15 | * **Seamless Integration**: Designed to work with popular Python data tools like [dlt (data load tool)](https://dlthub.com/). 16 | * **All Debezium Connectors**: Supports all standard Debezium connectors (PostgreSQL, MySQL, SQL Server, Oracle, etc.). 17 | 18 | ## How it Works 19 | 20 | This library acts as a bridge between the Python world and the Java-based Debezium Engine. It uses [Pyjnius](https://pyjnius.readthedocs.io/en/latest/) to manage the JVM and interact with Debezium's Java classes, exposing a clean, Pythonic API so you can focus on your data logic without writing Java code. 21 | 22 | ## Installation 23 | 24 | ### Prerequisites 25 | You must have a **Java Development Kit (JDK) version 11 or newer** installed and available in your system's `PATH`. 26 | 27 | ### From PyPI 28 | 29 | ```shell 30 | # For core functionality 31 | pip install pydbzengine 32 | 33 | # To include dependencies for the Apache Iceberg handler 34 | pip install 'pydbzengine[iceberg]' 35 | 36 | # To include dependencies for the dlt handler example 37 | pip install 'pydbzengine[dlt]' 38 | ``` 39 | 40 | ## How to Use 41 | 42 | ### Consume events With custom Python consumer 43 | 44 | 1. First install the packages, `pip install pydbzengine[dev]` 45 | 3. Second extend the BasePythonChangeHandler and implement your python consuming logic. see the example below 46 | 47 | ```python 48 | from typing import List 49 | from pydbzengine import ChangeEvent, BasePythonChangeHandler 50 | from pydbzengine import Properties, DebeziumJsonEngine 51 | 52 | 53 | class PrintChangeHandler(BasePythonChangeHandler): 54 | """ 55 | A custom change event handler class. 56 | 57 | This class processes batches of Debezium change events received from the engine. 58 | The `handleJsonBatch` method is where you implement your logic for consuming 59 | and processing these events. Currently, it prints basic information about 60 | each event to the console. 61 | """ 62 | 63 | def handleJsonBatch(self, records: List[ChangeEvent]): 64 | """ 65 | Handles a batch of Debezium change events. 66 | 67 | This method is called by the Debezium engine with a list of ChangeEvent objects. 68 | Change this method to implement your desired processing logic. For example, 69 | you might parse the event data, transform it, and load it into a database or 70 | other destination. 71 | 72 | Args: 73 | records: A list of ChangeEvent objects representing the changes captured by Debezium. 74 | """ 75 | print(f"Received {len(records)} records") 76 | for record in records: 77 | print(f"destination: {record.destination()}") 78 | print(f"key: {record.key()}") 79 | print(f"value: {record.value()}") 80 | print("--------------------------------------") 81 | 82 | 83 | if __name__ == '__main__': 84 | props = Properties() 85 | props.setProperty("name", "engine") 86 | props.setProperty("snapshot.mode", "initial_only") 87 | # Add further Debezium connector configuration properties here. For example: 88 | # props.setProperty("connector.class", "io.debezium.connector.mysql.MySqlConnector") 89 | # props.setProperty("database.hostname", "your_database_host") 90 | # props.setProperty("database.port", "3306") 91 | 92 | # Create a DebeziumJsonEngine instance, passing the configuration properties and the custom change event handler. 93 | engine = DebeziumJsonEngine(properties=props, handler=PrintChangeHandler()) 94 | 95 | # Start the Debezium engine to begin consuming and processing change events. 96 | engine.run() 97 | 98 | ``` 99 | ### Consume events to Apache Iceberg 100 | 101 | ```python 102 | from pyiceberg.catalog import load_catalog 103 | from pydbzengine import DebeziumJsonEngine 104 | from pydbzengine.handlers.iceberg import IcebergChangeHandler 105 | from pydbzengine import Properties 106 | 107 | conf = { 108 | "uri": "http://localhost:8181", 109 | # "s3.path-style.access": "true", 110 | "warehouse": "warehouse", 111 | "s3.endpoint": "http://localhost:9000", 112 | "s3.access-key-id": "minioadmin", 113 | "s3.secret-access-key": "minioadmin", 114 | } 115 | catalog = load_catalog(name="rest", **conf) 116 | handler = IcebergChangeHandler(catalog=catalog, destination_namespace=("iceberg", "debezium_cdc_data",)) 117 | 118 | dbz_props = Properties() 119 | dbz_props.setProperty("name", "engine") 120 | dbz_props.setProperty("snapshot.mode", "always") 121 | # .... 122 | # Add further Debezium connector configuration properties here. For example: 123 | # dbz_props.setProperty("connector.class", "io.debezium.connector.mysql.MySqlConnector") 124 | engine = DebeziumJsonEngine(properties=dbz_props, handler=handler) 125 | engine.run() 126 | ``` 127 | 128 | 129 | ### Consume events with dlt 130 | For the full code please see [dlt_consuming.py](pydbzengine/examples/dlt_consuming.py) 131 | 132 | ```python 133 | from pydbzengine import DebeziumJsonEngine 134 | from pydbzengine.helper import Utils 135 | from pydbzengine.handlers.dlt import DltChangeHandler 136 | from pydbzengine import Properties 137 | import dlt 138 | 139 | # Create a dlt pipeline and set destination. in this case DuckDb. 140 | dlt_pipeline = dlt.pipeline( 141 | pipeline_name="dbz_cdc_events_example", 142 | destination="duckdb", 143 | dataset_name="dbz_data" 144 | ) 145 | 146 | handler = DltChangeHandler(dlt_pipeline=dlt_pipeline) 147 | dbz_props = Properties() 148 | dbz_props.setProperty("name", "engine") 149 | dbz_props.setProperty("snapshot.mode", "always") 150 | # .... 151 | engine = DebeziumJsonEngine(properties=dbz_props, handler=handler) 152 | 153 | # Run the Debezium engine asynchronously with a timeout. 154 | # This runs for a limited time and then terminates automatically. 155 | Utils.run_engine_async(engine=engine, timeout_sec=60) 156 | ``` 157 | 158 | ### Contributors 159 | 160 | 161 | 162 | 163 | -------------------------------------------------------------------------------- /pydbzengine/__init__.py: -------------------------------------------------------------------------------- 1 | import traceback 2 | from abc import ABC 3 | from pathlib import Path 4 | from typing import List 5 | 6 | ################# INIT PYJNIUS #################### 7 | # Define paths to Debezium Java libraries and configuration directory. 8 | DEBEZIUM_JAVA_LIBS_DIR = Path(__file__).parent.joinpath("debezium/libs/*").as_posix() 9 | DEBEZIUM_CONF_DIR = Path(__file__).parent.joinpath("config").as_posix() 10 | CLASS_PATHS = [DEBEZIUM_JAVA_LIBS_DIR, DEBEZIUM_CONF_DIR] 11 | 12 | # Add current working directory's config folder to classpath if exists 13 | CONFIG_DIR = Path().cwd().joinpath('config') 14 | if CONFIG_DIR.is_dir() and CONFIG_DIR.exists(): 15 | print(f"Adding classpath: {CONFIG_DIR.as_posix()}") 16 | CLASS_PATHS.append(CONFIG_DIR.as_posix()) 17 | 18 | import jnius_config 19 | 20 | # Add the necessary classpaths for JNI interaction with Java. 21 | jnius_config.add_classpath(*CLASS_PATHS) 22 | 23 | from jnius import autoclass 24 | from jnius import PythonJavaClass, java_method, JavaMethod 25 | 26 | ################# JAVA REFLECTION CLASSES ################# 27 | # Import Java classes using jnius's autoclass for reflection. 28 | Properties = autoclass('java.util.Properties') 29 | DebeziumEngine = autoclass('io.debezium.engine.DebeziumEngine') 30 | DebeziumEngineBuilder = autoclass('io.debezium.engine.DebeziumEngine$Builder') 31 | 32 | # Override the notifying method of DebeziumEngineBuilder to use the correct JavaMethod signature. 33 | # This is a workaround for a potential jnius issue where the wrong Java method is called. 34 | DebeziumEngineBuilder.notifying = JavaMethod( 35 | '(Lio/debezium/engine/DebeziumEngine$ChangeConsumer;)Lio/debezium/engine/DebeziumEngine$Builder;') 36 | 37 | StopEngineException = autoclass('io.debezium.engine.StopEngineException') 38 | JavaLangSystem = autoclass('java.lang.System') 39 | JavaLangThread = autoclass('java.lang.Thread') 40 | 41 | 42 | class RecordCommitter(ABC): 43 | """ 44 | Abstract base class for type hinting the RecordCommitter. 45 | Mimics the io.debezium.engine.DebeziumEngine$RecordCommitter interface for Python. 46 | """ 47 | 48 | def markProcessed(self, record): 49 | """Marks a single record as processed.""" 50 | pass 51 | 52 | def markBatchFinished(self): 53 | """Marks the entire batch as finished.""" 54 | pass 55 | 56 | 57 | class ChangeEvent(ABC): 58 | """ 59 | Abstract base class for type hinting the ChangeEvent. 60 | Mimics the org.apache.kafka.connect.connector.ConnectRecord interface for Python. 61 | """ 62 | 63 | def key(self) -> str: 64 | """Returns the record key.""" 65 | pass 66 | 67 | def value(self) -> str: 68 | """Returns the record value (payload).""" 69 | pass 70 | 71 | def destination(self) -> str: 72 | """Returns the destination topic/table.""" 73 | pass 74 | 75 | def partition(self) -> int: 76 | """Returns the partition the record belongs to.""" 77 | pass 78 | 79 | 80 | class EngineFormat: 81 | """ 82 | Class holding constants for Debezium engine formats. 83 | """ 84 | JSON = autoclass('io.debezium.engine.format.Json') 85 | 86 | 87 | class BasePythonChangeHandler(ABC): 88 | """ 89 | Abstract base class for user-defined change event handlers. 90 | Users must implement the `handleJsonBatch` method to process Debezium events. 91 | """ 92 | 93 | def handleJsonBatch(self, records: List[ChangeEvent]): 94 | """ 95 | Handles a batch of change events. 96 | 97 | This method receives a list of ChangeEvent objects (which are representations of 98 | Java ConnectRecords) and should process them. 99 | 100 | Args: 101 | records: A list of ChangeEvent objects representing the changes. 102 | 103 | Raises: 104 | NotImplementedError: If the method is not implemented. 105 | """ 106 | raise NotImplementedError( 107 | "Not implemented, Please implement BasePythonChangeHandler and use it to consume events!") 108 | 109 | 110 | class PythonChangeConsumer(PythonJavaClass): 111 | """ 112 | Python implementation of the Debezium ChangeConsumer interface. 113 | This class acts as a bridge between Java Debezium Engine and the Python handler. 114 | """ 115 | __javainterfaces__ = ['io/debezium/engine/DebeziumEngine$ChangeConsumer'] 116 | 117 | def __init__(self): 118 | self.handler: BasePythonChangeHandler = None # The Python handler instance. 119 | 120 | @java_method('(Ljava/util/List;Lio/debezium/engine/DebeziumEngine$RecordCommitter;)V') 121 | def handleBatch(self, records: List[ChangeEvent], committer: RecordCommitter): 122 | """ 123 | Handles a batch of change events received from the Debezium engine. 124 | 125 | This method is called by the Java Debezium engine. It calls the user-defined 126 | Python handler to process the events and then acknowledges the batch. 127 | 128 | Args: 129 | records: A list of ChangeEvent objects representing the changes. 130 | committer: The RecordCommitter used to acknowledge processed records. 131 | """ 132 | try: 133 | self.handler.handleJsonBatch(records=records) 134 | for e in records: 135 | committer.markProcessed(e) # Mark each record as processed. 136 | committer.markBatchFinished() # Mark the batch as finished. 137 | except Exception as e: 138 | print("ERROR: failed to consume events in python") 139 | print(str(e)) 140 | print(traceback.format_exc()) 141 | JavaLangThread.currentThread().interrupt() # Interrupt the Debezium engine on error. 142 | 143 | @java_method('()Z') 144 | def supportsTombstoneEvents(self): 145 | """ 146 | Indicates whether the consumer supports tombstone events. 147 | """ 148 | return True 149 | 150 | def set_change_handler(self, handler: BasePythonChangeHandler): 151 | """ 152 | Sets the Python change event handler. 153 | 154 | Args: 155 | handler: The Python change event handler instance. 156 | """ 157 | self.handler = handler 158 | 159 | def interrupt(self): 160 | """ 161 | Interrupts the Debezium engine. 162 | """ 163 | print("Interrupt called in python consumer") 164 | JavaLangThread.currentThread().interrupt() # Interrupt the current thread (Debezium engine thread). 165 | 166 | def __exit__(self, exc_type, exc_value, traceback): 167 | print("Python Exit method called! calling interrupt to stop the engine") 168 | self.interrupt() 169 | 170 | class DebeziumJsonEngine: 171 | """ 172 | Main class to manage the Debezium embedded engine. 173 | """ 174 | 175 | def __init__(self, properties: Properties, handler: BasePythonChangeHandler): 176 | """ 177 | Initializes the DebeziumJsonEngine. 178 | 179 | Args: 180 | properties: Java Properties object containing the Debezium configuration. 181 | handler: The Python change event handler instance. 182 | """ 183 | self.properties: Properties = properties 184 | 185 | if self.properties is None: 186 | raise ValueError("Please provide debezium config properties!") 187 | if handler is None: 188 | raise ValueError("Please provide handler class, see example class `pydbzengine.BasePythonChangeHandler`!") 189 | 190 | self.consumer = PythonChangeConsumer() # Create the Python change consumer. 191 | self._handler = handler # Store the handler. 192 | self.consumer.set_change_handler(self._handler) # Set the handler for the consumer. 193 | 194 | # Create and configure the Debezium engine. 195 | self.engine: DebeziumEngine = (DebeziumEngine.create(EngineFormat.JSON) # Use JSON format. 196 | .using(self.properties) # Set the configuration properties. 197 | .notifying(self.consumer) # Set the change consumer. 198 | .build()) # Build the engine. 199 | 200 | def run(self): 201 | """ 202 | Starts the Debezium embedded engine. 203 | """ 204 | self.engine.run() 205 | 206 | def interrupt(self): 207 | """ 208 | Interrupts the Debezium embedded engine. 209 | """ 210 | self.consumer.interrupt() -------------------------------------------------------------------------------- /pydbzengine/airflow.py: -------------------------------------------------------------------------------- 1 | import sys 2 | try: 3 | from airflow.models import BaseOperator 4 | except ImportError: 5 | print("Error: airflow is required for this functionality.", file=sys.stderr) # Print to stderr 6 | print("Please install it using 'pip install apache-airflow' (or the appropriate command for your Airflow installation).", file=sys.stderr) 7 | raise 8 | 9 | from pydbzengine import DebeziumJsonEngine 10 | 11 | 12 | class DebeziumEngineOperator(BaseOperator): 13 | 14 | def __init__(self, engine: DebeziumJsonEngine, **kwargs) -> None: 15 | super().__init__(**kwargs) 16 | self.engine = engine 17 | self.kill_called = False 18 | 19 | def execute(self, context): 20 | self.log.info(f"Starting Debezium engine") 21 | self.engine.run() 22 | 23 | def on_kill(self) -> None: 24 | self.kill_called = True 25 | self.engine.interrupt() -------------------------------------------------------------------------------- /pydbzengine/config/log4j2.properties: -------------------------------------------------------------------------------- 1 | #status = DEBUG 2 | # Root logger level 3 | rootLogger.level=INFO 4 | # Console appender configuration 5 | appender.console.type=Console 6 | appender.console.name=consoleLogger 7 | appender.console.direct=true 8 | appender.console.layout.type=PatternLayout 9 | appender.console.layout.pattern=%date [%level] [%threadName] %c{6} (%F:%L) - %m%n 10 | # Rotate log file 11 | appender.rolling.type=RollingFile 12 | appender.rolling.name=fileLogger 13 | appender.rolling.fileName=logs/pydbzengine.log 14 | appender.rolling.filePattern=logs/pydbzengine-%d{yyyy-MM-dd}.log.gz 15 | appender.rolling.layout.type=PatternLayout 16 | appender.rolling.layout.pattern=%date [%level] [%threadName] %c{6} (%F:%L) - %m%n 17 | appender.rolling.policies.type=Policies 18 | appender.rolling.policies.time.type=TimeBasedTriggeringPolicy 19 | appender.rolling.policies.size.type=SizeBasedTriggeringPolicy 20 | appender.rolling.policies.size.size=10MB 21 | appender.rolling.strategy.type=DefaultRolloverStrategy 22 | appender.rolling.strategy.max=10 23 | # package level log 24 | #logger.dbzstorage.name=org.apache.kafka.connect.storage 25 | #logger.dbzstorage.level=DEBUG 26 | # Root logger referring to console appender 27 | #rootLogger.additivity = false 28 | rootLogger.appenderRef.rolling.ref=fileLogger 29 | rootLogger.appenderRef.stdout.ref=consoleLogger -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/activation-1.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/activation-1.1.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/antlr4-runtime-4.10.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/antlr4-runtime-4.10.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/aopalliance-repackaged-2.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/aopalliance-repackaged-2.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/bson-5.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/bson-5.2.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/bson-record-codec-5.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/bson-record-codec-5.2.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/checker-qual-3.31.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/checker-qual-3.31.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/commons-lang3-3.12.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/commons-lang3-3.12.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/connect-api-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/connect-api-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/connect-file-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/connect-file-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/connect-json-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/connect-json-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/connect-runtime-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/connect-runtime-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/connect-transforms-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/connect-transforms-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-api-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-api-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-connector-binlog-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-connector-binlog-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-connector-mongodb-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-connector-mongodb-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-connector-mysql-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-connector-mysql-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-connector-postgres-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-connector-postgres-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-core-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-core-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-ddl-parser-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-ddl-parser-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-embedded-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-embedded-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-sink-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-sink-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-storage-file-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-storage-file-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/debezium-storage-kafka-3.1.1.Final.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/debezium-storage-kafka-3.1.1.Final.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/hk2-api-2.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/hk2-api-2.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/hk2-locator-2.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/hk2-locator-2.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/hk2-utils-2.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/hk2-utils-2.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-annotations-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-annotations-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-core-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-core-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-databind-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-databind-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-datatype-jdk8-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-datatype-jdk8-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-datatype-jsr310-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-datatype-jsr310-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-jaxrs-base-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-jaxrs-base-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-jaxrs-json-provider-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-jaxrs-json-provider-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-module-afterburner-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-module-afterburner-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jackson-module-jaxb-annotations-2.16.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jackson-module-jaxb-annotations-2.16.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.activation-api-1.2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.activation-api-1.2.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.annotation-api-1.3.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.annotation-api-1.3.5.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.inject-2.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.inject-2.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.validation-api-2.0.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.validation-api-2.0.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.ws.rs-api-2.1.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.ws.rs-api-2.1.6.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jakarta.xml.bind-api-2.3.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jakarta.xml.bind-api-2.3.3.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/javassist-3.29.0-GA.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/javassist-3.29.0-GA.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/javax.activation-api-1.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/javax.activation-api-1.2.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/javax.servlet-api-3.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/javax.servlet-api-3.1.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/javax.ws.rs-api-2.1.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/javax.ws.rs-api-2.1.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jaxb-api-2.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jaxb-api-2.3.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-client-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-client-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-common-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-common-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-container-servlet-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-container-servlet-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-container-servlet-core-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-container-servlet-core-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-hk2-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-hk2-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jersey-server-2.39.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jersey-server-2.39.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-client-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-client-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-continuation-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-continuation-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-http-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-http-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-io-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-io-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-security-9.4.12.v20180830.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-security-9.4.12.v20180830.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-server-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-server-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-servlet-9.4.12.v20180830.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-servlet-9.4.12.v20180830.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-servlets-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-servlets-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jetty-util-9.4.56.v20240826.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jetty-util-9.4.56.v20240826.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/jose4j-0.9.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/jose4j-0.9.4.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/kafka-clients-3.9.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/kafka-clients-3.9.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/log4j-api-2.24.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/log4j-api-2.24.3.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/log4j-core-2.24.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/log4j-core-2.24.3.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/log4j-slf4j2-impl-2.24.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/log4j-slf4j2-impl-2.24.3.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/lz4-java-1.8.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/lz4-java-1.8.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/maven-artifact-3.9.6.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/maven-artifact-3.9.6.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/mongodb-driver-core-5.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/mongodb-driver-core-5.2.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/mongodb-driver-sync-5.2.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/mongodb-driver-sync-5.2.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/mysql-binlog-connector-java-0.40.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/mysql-binlog-connector-java-0.40.2.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/mysql-connector-j-9.1.0.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/mysql-connector-j-9.1.0.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/osgi-resource-locator-1.0.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/osgi-resource-locator-1.0.3.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/plexus-utils-3.5.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/plexus-utils-3.5.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/postgresql-42.6.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/postgresql-42.6.1.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/protobuf-java-3.25.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/protobuf-java-3.25.5.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/reflections-0.9.12.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/reflections-0.9.12.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/reload4j-1.2.25.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/reload4j-1.2.25.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/slf4j-api-2.0.16.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/slf4j-api-2.0.16.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/snappy-java-1.1.10.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/snappy-java-1.1.10.5.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/swagger-annotations-2.2.8.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/swagger-annotations-2.2.8.jar -------------------------------------------------------------------------------- /pydbzengine/debezium/libs/zstd-jni-1.5.6-4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/debezium/libs/zstd-jni-1.5.6-4.jar -------------------------------------------------------------------------------- /pydbzengine/examples/dlt_consuming.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | 4 | import dlt 5 | import duckdb 6 | from testcontainers.core.config import testcontainers_config 7 | from testcontainers.core.waiting_utils import wait_for_logs 8 | from testcontainers.postgres import PostgresContainer 9 | 10 | from pydbzengine import DebeziumJsonEngine, Properties 11 | from pydbzengine.handlers.dlt import DltChangeHandler 12 | from pydbzengine.helper import Utils 13 | 14 | # set global variables 15 | CURRENT_DIR = Path(__file__).parent 16 | DUCKDB_FILE = CURRENT_DIR.joinpath("dbz_cdc_events_example.duckdb") 17 | OFFSET_FILE = CURRENT_DIR.joinpath('postgresql-offsets.dat') 18 | 19 | 20 | def wait_for_postgresql_to_start(self) -> None: 21 | wait_for_logs(self, ".*database system is ready to accept connections.*") 22 | wait_for_logs(self, ".*PostgreSQL init process complete.*") 23 | 24 | 25 | class DbPostgresql: 26 | POSTGRES_USER = "postgres" 27 | POSTGRES_PASSWORD = "postgres" 28 | POSTGRES_DBNAME = "postgres" 29 | POSTGRES_IMAGE = "debezium/example-postgres:3.0.0.Final" 30 | POSTGRES_HOST = "localhost" 31 | POSTGRES_PORT_DEFAULT = 5432 32 | CONTAINER: PostgresContainer = (PostgresContainer(image=POSTGRES_IMAGE, 33 | port=POSTGRES_PORT_DEFAULT, 34 | username=POSTGRES_USER, 35 | password=POSTGRES_PASSWORD, 36 | dbname=POSTGRES_DBNAME, 37 | ) 38 | .with_exposed_ports(POSTGRES_PORT_DEFAULT) 39 | ) 40 | PostgresContainer._connect = wait_for_postgresql_to_start 41 | 42 | def clean_files(self): 43 | if OFFSET_FILE.exists(): 44 | os.remove(OFFSET_FILE) 45 | if DUCKDB_FILE.exists(): 46 | os.remove(DUCKDB_FILE) 47 | 48 | def start(self): 49 | testcontainers_config.ryuk_disabled = True 50 | self.clean_files() 51 | print("Starting Postgresql Db...") 52 | self.CONTAINER.start() 53 | 54 | def stop(self): 55 | print("Stopping Postgresql Db...") 56 | self.CONTAINER.stop() 57 | self.clean_files() 58 | 59 | def __exit__(self, exc_type, exc_value, traceback): 60 | self.stop() 61 | 62 | 63 | def debezium_engine_props(sourcedb: DbPostgresql): 64 | props = Properties() 65 | props.setProperty("name", "engine") 66 | props.setProperty("snapshot.mode", "initial_only") 67 | props.setProperty("database.hostname", sourcedb.CONTAINER.get_container_host_ip()) 68 | props.setProperty("database.port", 69 | sourcedb.CONTAINER.get_exposed_port(sourcedb.POSTGRES_PORT_DEFAULT)) 70 | props.setProperty("database.user", sourcedb.POSTGRES_USER) 71 | props.setProperty("database.password", sourcedb.POSTGRES_PASSWORD) 72 | props.setProperty("database.dbname", sourcedb.POSTGRES_DBNAME) 73 | props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector") 74 | props.setProperty("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") 75 | props.setProperty("offset.storage.file.filename", OFFSET_FILE.as_posix()) 76 | props.setProperty("max.batch.size", "5") 77 | props.setProperty("poll.interval.ms", "10000") 78 | props.setProperty("converter.schemas.enable", "false") 79 | props.setProperty("offset.flush.interval.ms", "1000") 80 | props.setProperty("database.server.name", "testc") 81 | props.setProperty("database.server.id", "1234") 82 | props.setProperty("topic.prefix", "testc") 83 | props.setProperty("schema.whitelist", "inventory") 84 | props.setProperty("database.whitelist", "inventory") 85 | props.setProperty("table.whitelist", "inventory.*") 86 | props.setProperty("replica.identity.autoset.values", "inventory.*:FULL") 87 | # // debezium unwrap message 88 | props.setProperty("transforms", "unwrap") 89 | props.setProperty("transforms.unwrap.type", "io.debezium.transforms.ExtractNewRecordState") 90 | props.setProperty("transforms.unwrap.add.fields", "op,table,source.ts_ms,sourcedb,ts_ms") 91 | props.setProperty("transforms.unwrap.delete.handling.mode", "rewrite") 92 | # props.setProperty("debezium.transforms.unwrap.drop.tombstones", "true") 93 | return props 94 | 95 | 96 | def main(): 97 | """ 98 | Demonstrates capturing change data from PostgreSQL using Debezium and loading 99 | it into DuckDB using dlt. 100 | 101 | This example starts a PostgreSQL container, configures Debezium to capture changes, 102 | processes the change events with a custom handler using dlt, and finally queries 103 | the DuckDB database to display the loaded data. 104 | """ 105 | 106 | # Start the PostgreSQL container that will serve as the replication source. 107 | sourcedb = DbPostgresql() 108 | sourcedb.start() 109 | 110 | # Get Debezium engine configuration properties, including connection details 111 | # for the PostgreSQL database. This function debezium_engine_props returns all the properties 112 | props = debezium_engine_props(sourcedb=sourcedb) 113 | 114 | # Create a dlt pipeline to load the change events into DuckDB. 115 | dlt_pipeline = dlt.pipeline( 116 | pipeline_name="dbz_cdc_events_example", 117 | destination="duckdb", 118 | dataset_name="dbz_data" 119 | ) 120 | 121 | # Instantiate change event handler (DltChangeHandler) that uses the dlt pipeline 122 | # to process and load the Debezium events. This handler has 123 | # the logic for transforming and loading the events. 124 | handler = DltChangeHandler(dlt_pipeline=dlt_pipeline) 125 | 126 | # Create a DebeziumJsonEngine instance, providing the configuration properties 127 | # and the custom event handler. 128 | engine = DebeziumJsonEngine(properties=props, handler=handler) 129 | 130 | # Run the Debezium engine asynchronously with a timeout. This allows the example 131 | # to run for a limited time and then terminate automatically. 132 | Utils.run_engine_async(engine=engine, timeout_sec=60) 133 | # engine.run() # This would be used for synchronous execution (without timeout) 134 | 135 | # ================ PRINT THE CONSUMED DATA FROM DUCKDB =========================== 136 | # Connect to the DuckDB database. 137 | con = duckdb.connect(DUCKDB_FILE.as_posix()) 138 | 139 | # Retrieve a list of all tables in the DuckDB database. 140 | result = con.sql("SHOW ALL TABLES").fetchall() 141 | 142 | # Iterate through the tables and display the data from tables within the 'dbz_data' schema. 143 | for r in result: 144 | database, schema, table = r[:3] # Extract database, schema, and table names. 145 | if schema == "dbz_data": # Only show data from the schema where Debezium loaded the data. 146 | print(f"Data in table {table}:") 147 | con.sql(f"select * from {database}.{schema}.{table} limit 5").show() # Display table data 148 | 149 | 150 | if __name__ == "__main__": 151 | """ 152 | Main entry point for the script. 153 | 154 | Before running, ensure you have installed the necessary dependencies: 155 | `pip install pydbzengine[dev]` 156 | """ 157 | main() 158 | -------------------------------------------------------------------------------- /pydbzengine/handlers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/memiiso/pydbzengine/98268744a35086aaea06ff96455a2644db13628b/pydbzengine/handlers/__init__.py -------------------------------------------------------------------------------- /pydbzengine/handlers/dlt.py: -------------------------------------------------------------------------------- 1 | import json 2 | import logging 3 | from typing import List, Dict 4 | 5 | import dlt 6 | 7 | from pydbzengine import ChangeEvent, BasePythonChangeHandler 8 | 9 | 10 | @dlt.source 11 | def debezium_source_events(records: List[ChangeEvent]): 12 | """ 13 | A DLT source that processes Debezium change events. 14 | 15 | This function takes a list of Debezium ChangeEvent objects, groups them by table, 16 | and yields them as DLT resources. This allows DLT to load the data into separate tables. 17 | 18 | Args: 19 | records: A list of Debezium ChangeEvent objects. These represent changes captured 20 | from a database (e.g., inserts, updates, deletes). 21 | 22 | Yields: 23 | dlt.Resource: A DLT resource for each table, containing the corresponding change events. 24 | """ 25 | # group the events per table 26 | table_events: Dict[str, List[str]] = {} 27 | for e in records: 28 | table = e.destination().replace(".", "_") 29 | val = json.loads(e.value()) 30 | if table in table_events: 31 | table_events[table].append(val) 32 | else: 33 | table_events[table] = [val] 34 | 35 | for table_name, events in table_events.items(): 36 | yield dlt.resource(events, name=table_name) 37 | 38 | 39 | class DltChangeHandler(BasePythonChangeHandler): 40 | """ 41 | A change handler that uses the dlt library to process Debezium change events. 42 | 43 | This class receives batches of Debezium ChangeEvent objects and uses a dlt pipeline 44 | to load the data into a destination (e.g., a data warehouse). 45 | """ 46 | LOGGER_NAME = "debeziumdlt.DltChangeHandler" 47 | 48 | def __init__(self, dlt_pipeline): 49 | """ 50 | Initializes the DltChangeHandler. 51 | 52 | Args: 53 | dlt_pipeline: The dlt pipeline instance to use for loading data. 54 | """ 55 | self.dlt_pipeline = dlt_pipeline 56 | self.log = logging.getLogger(self.LOGGER_NAME) 57 | 58 | def handleJsonBatch(self, records: List[ChangeEvent]): 59 | """ 60 | Handles a batch of Debezium ChangeEvent records. 61 | 62 | This method is called by the Debezium connector when a batch of change events 63 | is received. It runs the dlt pipeline 64 | to process the records. 65 | 66 | Args: 67 | records: A list of Debezium ChangeEvent objects representing database changes. 68 | """ 69 | self.log.info(f"Received {len(records)} records") 70 | self.dlt_pipeline.run(debezium_source_events(records)) 71 | self.log.info(f"Consumed {len(records)} records") 72 | -------------------------------------------------------------------------------- /pydbzengine/handlers/iceberg.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import json 3 | import logging 4 | import uuid 5 | from typing import List, Dict 6 | 7 | import pyarrow as pa 8 | from pyiceberg.catalog import Catalog 9 | from pyiceberg.exceptions import NoSuchTableError 10 | from pyiceberg.partitioning import PartitionSpec, PartitionField 11 | from pyiceberg.schema import Schema 12 | from pyiceberg.table import Table 13 | from pyiceberg.transforms import DayTransform 14 | from pyiceberg.types import ( 15 | StringType, 16 | NestedField, 17 | LongType, 18 | UUIDType, 19 | TimestampType, 20 | ) 21 | 22 | from pydbzengine import ChangeEvent, BasePythonChangeHandler 23 | 24 | 25 | class IcebergChangeHandler(BasePythonChangeHandler): 26 | """ 27 | A change handler that uses Apache Iceberg to process Debezium change events. 28 | This class receives batches of Debezium ChangeEvent objects and applies the changes 29 | to the corresponding Iceberg tables. 30 | """ 31 | 32 | DEBEZIUM_EVENT_PARTITION_SPEC = PartitionSpec( 33 | PartitionField(source_id=10, field_id=1000, name="_consumed_at_day", transform=DayTransform()) 34 | ) 35 | LOGGER_NAME = "pydbzengine.iceberg.IcebergChangeHandler" 36 | 37 | def __init__(self, catalog: "Catalog", destination_namespace: tuple, supports_variant:bool=False): 38 | """ 39 | Initializes the IcebergChangeHandler. 40 | """ 41 | self.log = logging.getLogger(self.LOGGER_NAME) 42 | self.destination_namespace: tuple = destination_namespace 43 | self.catalog = catalog 44 | self.supports_variant = supports_variant 45 | 46 | def handleJsonBatch(self, records: List[ChangeEvent]): 47 | """ 48 | Handles a batch of Debezium ChangeEvent records. 49 | This method is called by the Debezium connector when a batch of change events 50 | is received. It groups the records by destination table, and then for each 51 | table, it applies the changes (inserts, updates, deletes) to the corresponding 52 | Iceberg table. 53 | Args: 54 | records: A list of Debezium ChangeEvent objects representing database changes. 55 | """ 56 | self.log.info(f"Received {len(records)} records") 57 | table_events: Dict[str, list] = {} 58 | for record in records: 59 | destination = record.destination() 60 | if destination not in table_events: 61 | table_events[destination] = [] 62 | table_events[destination].append(record) 63 | 64 | for destination, event_records in table_events.items(): 65 | self._handle_table_changes(destination, event_records) 66 | 67 | self.log.info(f"Consumed {len(records)} records") 68 | 69 | def _handle_table_changes(self, destination: str, records: List[ChangeEvent]): 70 | """ 71 | Handles changes for a specific table. 72 | Args: 73 | destination: The name of the table to apply the changes to. 74 | records: A list of ChangeEvent objects for the specified table. 75 | """ 76 | table = self.get_table(destination) 77 | consumed_at = datetime.datetime.now(datetime.timezone.utc) 78 | arrow_data = [] 79 | for record in records: 80 | # Create a dictionary matching the schema 81 | avro_record = self._transform_event_to_row_dict(record=record, consumed_at=consumed_at) 82 | arrow_data.append(avro_record) 83 | 84 | if arrow_data: 85 | pa_table = pa.Table.from_pylist(mapping=arrow_data, schema=self._target_schema.as_arrow()) 86 | table.append(pa_table) 87 | self.log.info(f"Appended {len(arrow_data)} records to table {'.'.join(table.name())}") 88 | 89 | def _transform_event_to_row_dict(self, record: ChangeEvent, consumed_at: datetime) -> dict: 90 | # Parse the JSON payload 91 | payload = json.loads(record.value()) 92 | 93 | # Extract relevant fields based on schema 94 | op = payload.get("op") 95 | ts_ms = payload.get("ts_ms") 96 | ts_us = payload.get("ts_us") 97 | ts_ns = payload.get("ts_ns") 98 | source = payload.get("source") 99 | before = payload.get("before") 100 | after = payload.get("after") 101 | dbz_event_key = record.key() # its string by default 102 | dbz_event_key_hash = uuid.uuid5(uuid.NAMESPACE_DNS, dbz_event_key) if dbz_event_key else None 103 | 104 | return { 105 | "op": op, 106 | "ts_ms": ts_ms, 107 | "ts_us": ts_us, 108 | "ts_ns": ts_ns, 109 | "source": json.dumps(source) if source is not None else None, 110 | "before": json.dumps(before) if before is not None else None, 111 | "after": json.dumps(after) if after is not None else None, 112 | "_dbz_event_key": dbz_event_key, 113 | "_dbz_event_key_hash": dbz_event_key_hash.bytes, 114 | "_consumed_at": consumed_at, 115 | } 116 | 117 | def get_table(self, destination: str) -> "Table": 118 | # TODO keep table object in map to avoid calling catalog 119 | iceberg_table: tuple = self._resolve_table_identifier(destination) 120 | return self.load_table(iceberg_table=iceberg_table) 121 | 122 | def load_table(self, iceberg_table): 123 | try: 124 | return self.catalog.load_table(identifier=iceberg_table) 125 | except NoSuchTableError: 126 | self.log.warning(f"Iceberg table {'.'.join(iceberg_table)} not found, creating it.") 127 | table = self.catalog.create_table(identifier=iceberg_table, 128 | schema=self._target_schema, 129 | partition_spec=self.DEBEZIUM_EVENT_PARTITION_SPEC) 130 | self.log.info(f"Created iceberg table {'.'.join(iceberg_table)} with daily partitioning on _consumed_at.") 131 | return table 132 | 133 | def _resolve_table_identifier(self, destination: str) -> tuple: 134 | table_name = destination.replace('.', '_').replace(' ', '_').replace('-', '_') 135 | return self.destination_namespace + (table_name,) 136 | 137 | @property 138 | def _target_schema(self) -> Schema: 139 | # @TODO according to self.supports_variant we can return different schemas! 140 | return Schema( 141 | NestedField(field_id=1, name="op", field_type=StringType(), required=True, 142 | doc="The operation type: c, u, d, r"), 143 | NestedField(field_id=2, name="ts_ms", field_type=LongType(), required=False, 144 | doc="Timestamp of the event in milliseconds"), 145 | NestedField(field_id=3, name="ts_us", field_type=LongType(), required=False, 146 | doc="Timestamp of the event in microseconds"), 147 | NestedField(field_id=4, name="ts_ns", field_type=LongType(), required=False, 148 | doc="Timestamp of the event in nanoseconds"), 149 | NestedField( 150 | field_id=5, 151 | name="source", 152 | field_type=StringType(), 153 | required=True, 154 | doc="Debezium source metadata", 155 | ), 156 | NestedField( 157 | field_id=6, 158 | name="before", 159 | field_type=StringType(), 160 | required=False, 161 | doc="JSON string of the row state before the change", 162 | ), 163 | NestedField( 164 | field_id=7, 165 | name="after", 166 | field_type=StringType(), 167 | required=False, 168 | doc="JSON string of the row state after the change", 169 | ), 170 | NestedField( 171 | field_id=8, 172 | name="_dbz_event_key", 173 | field_type=StringType(), 174 | required=False, 175 | doc="JSON string of the Debezium event key", 176 | ), 177 | NestedField( 178 | field_id=9, 179 | name="_dbz_event_key_hash", 180 | field_type=UUIDType(), 181 | required=False, 182 | doc="UUID hash of the Debezium event key", 183 | ), 184 | NestedField( 185 | field_id=10, 186 | name="_consumed_at", 187 | field_type=TimestampType(), 188 | required=False, 189 | doc="Timestamp of when the event was consumed", 190 | ), 191 | ) 192 | -------------------------------------------------------------------------------- /pydbzengine/helper.py: -------------------------------------------------------------------------------- 1 | import signal 2 | import threading 3 | 4 | def timeout_handler(signum, frame): 5 | """ 6 | Signal handler for timeouts. 7 | 8 | Raises a TimeoutError when the specified timeout is reached. 9 | 10 | Args: 11 | signum: The signal number (unused). 12 | frame: The current stack frame (unused). 13 | 14 | Raises: 15 | TimeoutError: If the timeout is reached. 16 | """ 17 | raise TimeoutError("Engine run timed out!") 18 | 19 | 20 | class Utils: 21 | 22 | @staticmethod 23 | def run_engine_async(engine, timeout_sec=22): 24 | """ 25 | Runs an engine asynchronously with a timeout. 26 | 27 | This method runs the given engine's `run` method in a separate thread 28 | and applies a timeout. If the engine's `run` method doesn't complete 29 | within the specified timeout, a TimeoutError is raised, and the thread 30 | is interrupted. 31 | 32 | Args: 33 | engine: The engine object to run. It is expected to have a `run` method. 34 | timeout_sec: The timeout duration in seconds. Defaults to 22 seconds. 35 | """ 36 | signal.signal(signal.SIGALRM, timeout_handler) 37 | signal.alarm(timeout_sec) 38 | 39 | try: 40 | thread = threading.Thread(target=engine.run) 41 | thread.start() 42 | 43 | # Wait for the thread to complete (or the timeout to occur). 44 | thread.join() # This will block until the thread finishes or the signal is received. 45 | 46 | except TimeoutError: 47 | # Handle the timeout exception. 48 | print("Engine run timed out!") # use logger here for better logging 49 | return # Or potentially handle the timeout differently (e.g., attempt to stop the engine). 50 | 51 | finally: 52 | # **Crucially important:** Cancel the alarm. This prevents the timeout 53 | # from triggering again later if the main thread continues to run. 54 | signal.alarm(0) # 0 means cancel the alarm. 55 | 56 | # If the engine.run() finishes within the timeout, this point will be reached. 57 | # No explicit return is needed as the function doesn't return anything. 58 | print("Engine run completed successfully.") # Add a log message to signal success -------------------------------------------------------------------------------- /pydbzengine/install_libs.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | CURRENT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd ) 4 | 5 | cd ${CURRENT_DIR} 6 | find "${CURRENT_DIR}/debezium/libs" -type f -delete 7 | mvn dependency:copy-dependencies -DoutputDirectory="${CURRENT_DIR}/debezium/libs" -------------------------------------------------------------------------------- /pydbzengine/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | org.memiiso 7 | pydebezium 8 | 1.0-SNAPSHOT 9 | 10 | 17 11 | 17 12 | UTF-8 13 | 3.1.1.Final 14 | 15 | 16 | 17 | 18 | 19 | 20 | io.debezium 21 | debezium-bom 22 | ${version.debezium} 23 | pom 24 | import 25 | 26 | 27 | 28 | 29 | 30 | 31 | io.debezium 32 | debezium-api 33 | 34 | 35 | io.debezium 36 | debezium-embedded 37 | 38 | 39 | io.debezium 40 | debezium-connector-mysql 41 | 42 | 43 | io.debezium 44 | debezium-connector-postgres 45 | 46 | 47 | io.debezium 48 | debezium-connector-mongodb 49 | 50 | 51 | org.slf4j 52 | slf4j-api 53 | 2.0.16 54 | 55 | 56 | org.apache.logging.log4j 57 | log4j-slf4j2-impl 58 | 2.24.3 59 | 60 | 61 | org.apache.logging.log4j 62 | log4j-core 63 | 2.24.3 64 | 65 | 66 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools", "setuptools-scm"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [tool.setuptools] 6 | include-package-data = true # Important: Enables inclusion of non-code files 7 | packages = ["pydbzengine"] 8 | 9 | [project] 10 | name = "pydbzengine" 11 | version = "3.1.1.0" 12 | authors = [ 13 | { name = "Memiiso Organization" }, 14 | ] 15 | description = "Python Debezium Embedded Engine" 16 | readme = "README.md" 17 | requires-python = ">=3.8" 18 | keywords = ["Debezium", "Replication", "CDC"] 19 | license = { text = "Apache License 2.0" } 20 | classifiers = [ 21 | "Development Status :: 5 - Production/Stable", 22 | "Programming Language :: Python :: 3", 23 | ] 24 | dependencies = [ 25 | "pyjnius==1.6.1", 26 | ] 27 | [project.optional-dependencies] 28 | iceberg = [ 29 | "pyiceberg>=0.9.1", 30 | "pyarrow", 31 | ] 32 | dlt = [ 33 | "dlt>=1.5.0", 34 | ] 35 | dev = [ 36 | "testcontainers[minio]>=4.9.1", 37 | "dlt[duckdb]>=1.5.0", 38 | "apache-airflow>=2.10.4", 39 | ] 40 | #[project.scripts] 41 | #debezium = "pydbzengine.__main__:main" 42 | 43 | [project.urls] 44 | Homepage = "https://github.com/memiiso/pydbzengine" 45 | Documentation = "https://github.com/memiiso/pydbzengine" 46 | Repository = "https://github.com/memiiso/pydbzengine" 47 | -------------------------------------------------------------------------------- /tests/base_postgresql_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | from pathlib import Path 4 | 5 | from db_postgresql import DbPostgresql 6 | from pydbzengine import Properties 7 | 8 | 9 | class BasePostgresqlTest(unittest.TestCase): 10 | CURRENT_DIR = Path(__file__).parent 11 | OFFSET_FILE = CURRENT_DIR.joinpath('postgresql-offsets.dat') 12 | SOURCEPGDB = DbPostgresql() 13 | 14 | def debezium_engine_props(self, unwrap_messages=True): 15 | current_dir = Path(__file__).parent 16 | offset_file_path = current_dir.joinpath('postgresql-offsets.dat') 17 | 18 | props = Properties() 19 | props.setProperty("name", "engine") 20 | props.setProperty("snapshot.mode", "always") 21 | props.setProperty("database.hostname", self.SOURCEPGDB.CONTAINER.get_container_host_ip()) 22 | props.setProperty("database.port", 23 | self.SOURCEPGDB.CONTAINER.get_exposed_port(self.SOURCEPGDB.POSTGRES_PORT_DEFAULT)) 24 | props.setProperty("database.user", self.SOURCEPGDB.POSTGRES_USER) 25 | props.setProperty("database.password", self.SOURCEPGDB.POSTGRES_PASSWORD) 26 | props.setProperty("database.dbname", self.SOURCEPGDB.POSTGRES_DBNAME) 27 | props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector") 28 | props.setProperty("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore") 29 | props.setProperty("offset.storage.file.filename", offset_file_path.as_posix()) 30 | props.setProperty("poll.interval.ms", "10000") 31 | props.setProperty("converter.schemas.enable", "false") 32 | props.setProperty("offset.flush.interval.ms", "1000") 33 | props.setProperty("topic.prefix", "testc") 34 | props.setProperty("schema.whitelist", "inventory") 35 | props.setProperty("database.whitelist", "inventory") 36 | props.setProperty("table.whitelist", "inventory.products") 37 | props.setProperty("replica.identity.autoset.values", "inventory.*:FULL") 38 | 39 | if unwrap_messages: 40 | props.setProperty("transforms", "unwrap") 41 | props.setProperty("transforms.unwrap.type", "io.debezium.transforms.ExtractNewRecordState") 42 | props.setProperty("transforms.unwrap.add.fields", "op,table,source.ts_ms,sourcedb,ts_ms") 43 | props.setProperty("transforms.unwrap.delete.handling.mode", "rewrite") 44 | return props 45 | 46 | def clean_offset_file(self): 47 | if self.OFFSET_FILE.exists(): 48 | os.remove(self.OFFSET_FILE) 49 | 50 | def setUp(self): 51 | self.clean_offset_file() 52 | self.SOURCEPGDB.start() 53 | 54 | def tearDown(self): 55 | self.SOURCEPGDB.stop() 56 | self.clean_offset_file() -------------------------------------------------------------------------------- /tests/catalog_rest.py: -------------------------------------------------------------------------------- 1 | from testcontainers.core.config import testcontainers_config 2 | from testcontainers.core.container import DockerContainer 3 | from testcontainers.core.waiting_utils import wait_for_logs 4 | 5 | 6 | class CatalogRestContainer(DockerContainer): 7 | IMAGE = "apache/iceberg-rest-fixture:latest" 8 | REST_PORT = 8181 9 | READY_LOG_MESSAGE = "Server - Started" 10 | 11 | def __init__(self): 12 | super().__init__(self.IMAGE) 13 | self.with_exposed_ports(self.REST_PORT) 14 | # self.with_env("AWS_ACCESS_KEY_ID", S3Minio.AWS_ACCESS_KEY_ID) 15 | # self.with_env("AWS_SECRET_ACCESS_KEY", S3Minio.AWS_SECRET_ACCESS_KEY) 16 | # self.with_env("AWS_REGION", S3Minio.AWS_REGION) 17 | # self.with_env("CATALOG_WAREHOUSE", f"s3://{S3Minio.S3_WAREHOUSE_BUCKET}/") 18 | # self.with_env("CATALOG_IO__IMPL", "org.apache.iceberg.aws.s3.S3FileIO") 19 | # self.with_env("CATALOG_S3_PATH__STYLE__ACCESS", "true") 20 | 21 | def start(self, s3_endpoint:str): 22 | self.with_env("CATALOG_S3_ENDPOINT", s3_endpoint) 23 | testcontainers_config.ryuk_disabled = True 24 | super().start() 25 | wait_for_logs(self, self.READY_LOG_MESSAGE, timeout=60) 26 | print(f"Iceberg REST Catalog Started: {self.get_uri()}") 27 | return self 28 | 29 | def get_uri(self) -> str: 30 | host = self.get_container_host_ip() 31 | port = self.get_exposed_port(self.REST_PORT) 32 | return f"http://{host}:{port}" 33 | 34 | def get_catalog(self) -> 'Catalog': 35 | from pyiceberg.catalog import load_catalog 36 | catalog = load_catalog( 37 | "default", # Catalog name 38 | **{ 39 | "type": "rest", 40 | "uri": self.get_uri(), 41 | } 42 | ) 43 | return catalog 44 | 45 | def list_namespaces(self): 46 | catalog = self.get_catalog() 47 | namespaces = catalog.list_namespaces() 48 | print("Namespaces:", namespaces) 49 | -------------------------------------------------------------------------------- /tests/config/log4j2-test.properties: -------------------------------------------------------------------------------- 1 | #status = DEBUG 2 | # Root logger level 3 | rootLogger.level=INFO 4 | # Console appender configuration 5 | appender.console.type=Console 6 | appender.console.name=consoleLogger 7 | appender.console.direct=true 8 | appender.console.layout.type=PatternLayout 9 | appender.console.layout.pattern=%date [%level] [%threadName] %c{6} (%F:%L) - %m%n 10 | # Rotate log file 11 | appender.rolling.type=RollingFile 12 | appender.rolling.name=fileLogger 13 | appender.rolling.fileName=logs/pydbzengine.log 14 | appender.rolling.filePattern=logs/pydbzengine-%d{yyyy-MM-dd}.log.gz 15 | appender.rolling.layout.type=PatternLayout 16 | appender.rolling.layout.pattern=%date [%level] [%threadName] %c{6} (%F:%L) - %m%n 17 | appender.rolling.policies.type=Policies 18 | appender.rolling.policies.time.type=TimeBasedTriggeringPolicy 19 | appender.rolling.policies.size.type=SizeBasedTriggeringPolicy 20 | appender.rolling.policies.size.size=10MB 21 | appender.rolling.strategy.type=DefaultRolloverStrategy 22 | appender.rolling.strategy.max=10 23 | # package level log 24 | logger.dbzstorage.name=org.apache.kafka.connect.storage 25 | logger.dbzstorage.level=DEBUG 26 | # Root logger referring to console appender 27 | #rootLogger.additivity = false 28 | rootLogger.appenderRef.rolling.ref=fileLogger 29 | rootLogger.appenderRef.stdout.ref=consoleLogger -------------------------------------------------------------------------------- /tests/db_postgresql.py: -------------------------------------------------------------------------------- 1 | from testcontainers.core.config import testcontainers_config 2 | from testcontainers.core.waiting_utils import wait_for_logs 3 | from testcontainers.postgres import PostgresContainer 4 | 5 | 6 | def wait_for_pg_start(self) -> None: 7 | wait_for_logs(self, ".*database system is ready to accept connections.*") 8 | wait_for_logs(self, ".*PostgreSQL init process complete.*") 9 | 10 | 11 | class DbPostgresql: 12 | POSTGRES_USER = "postgres" 13 | POSTGRES_PASSWORD = "postgres" 14 | POSTGRES_DBNAME = "postgres" 15 | POSTGRES_IMAGE = "debezium/example-postgres:3.0.0.Final" 16 | POSTGRES_HOST = "localhost" 17 | POSTGRES_PORT_DEFAULT = 5432 18 | CONTAINER: PostgresContainer = (PostgresContainer(image=POSTGRES_IMAGE, 19 | port=POSTGRES_PORT_DEFAULT, 20 | username=POSTGRES_USER, 21 | password=POSTGRES_PASSWORD, 22 | dbname=POSTGRES_DBNAME, 23 | ) 24 | .with_exposed_ports(POSTGRES_PORT_DEFAULT) 25 | ) 26 | PostgresContainer._connect = wait_for_pg_start 27 | 28 | def start(self): 29 | testcontainers_config.ryuk_disabled = True 30 | self.CONTAINER.start() 31 | print(f"Postgresql Started: {self.CONTAINER.get_connection_url()}") 32 | 33 | def stop(self): 34 | try: 35 | self.CONTAINER.stop() 36 | except: 37 | pass 38 | 39 | def __exit__(self, exc_type, exc_value, traceback): 40 | self.stop() 41 | -------------------------------------------------------------------------------- /tests/s3_minio.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from testcontainers.core.config import testcontainers_config 4 | from testcontainers.minio import MinioContainer 5 | 6 | 7 | class S3Minio: 8 | AWS_ACCESS_KEY_ID = "admin" 9 | AWS_SECRET_ACCESS_KEY = "password" 10 | AWS_REGION = "us-east-1" 11 | S3_WAREHOUSE_BUCKET = "icebergdata" 12 | 13 | def __init__(self, image="minio/minio:RELEASE.2025-04-08T15-41-24Z"): 14 | self.minio = MinioContainer( 15 | image=image, 16 | access_key=self.AWS_ACCESS_KEY_ID, 17 | secret_key=self.AWS_SECRET_ACCESS_KEY, 18 | port=9000 19 | ).with_exposed_ports(9000).with_exposed_ports(9001) 20 | self._client = None 21 | 22 | def start(self): 23 | testcontainers_config.ryuk_disabled = True 24 | self.minio.start() 25 | self._client = self.minio.get_client() 26 | print(f"Minio Started: {self.endpoint()}") 27 | print(f"Minio Web: {self.web_url()}") 28 | self.setup_warehouse_bucket() 29 | return self 30 | 31 | def endpoint(self) -> str: 32 | host_ip = self.minio.get_container_host_ip() 33 | exposed_port = self.minio.get_exposed_port(self.minio.port) 34 | return f"http://{host_ip}:{exposed_port}" 35 | 36 | def web_url(self) -> str: 37 | host_ip = self.minio.get_container_host_ip() 38 | exposed_port = self.minio.get_exposed_port(9001) 39 | return f"http://{host_ip}:{exposed_port}" 40 | 41 | def setup_warehouse_bucket(self): 42 | bucket_name = self.S3_WAREHOUSE_BUCKET 43 | self.client.make_bucket(bucket_name=bucket_name) 44 | 45 | # Equivalent to `/usr/bin/mc policy set public minio/warehouse` 46 | policy = { 47 | "Version": "2012-10-17", 48 | "Statement": [ 49 | { 50 | "Sid": "PublicReadGetObject", 51 | "Effect": "Allow", 52 | "Principal": "*", 53 | "Action": ["s3:GetObject"], 54 | "Resource": [f"arn:aws:s3:::{bucket_name}/*"] 55 | } 56 | ] 57 | } 58 | self.client.set_bucket_policy( 59 | bucket_name=bucket_name, 60 | policy=json.dumps(policy) 61 | ) 62 | print(f"Bucket '{bucket_name}' created successfully.") 63 | 64 | def stop(self): 65 | """Stops the Minio container.""" 66 | if self.minio and self.minio.get_wrapped_container(): 67 | self.minio.stop() 68 | 69 | @property 70 | def client(self): 71 | if not self._client: 72 | raise RuntimeError( 73 | "Client not initialized. Call start() or use as a context manager first." 74 | ) 75 | return self._client 76 | 77 | def __enter__(self): 78 | return self.start() 79 | 80 | def __exit__(self, exc_type, exc_val, exc_tb): 81 | self.stop() 82 | -------------------------------------------------------------------------------- /tests/test_change_handler.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List 3 | 4 | from base_postgresql_test import BasePostgresqlTest 5 | from pydbzengine import ChangeEvent, BasePythonChangeHandler 6 | from pydbzengine import DebeziumJsonEngine 7 | 8 | from pydbzengine.helper import Utils 9 | 10 | 11 | class TestChangeHandler(BasePythonChangeHandler): 12 | """ 13 | An example implementation of a handler class, where we need to process the data received from java. 14 | Used for testing only. 15 | """ 16 | LOGGER_NAME = "TestChangeHandler" 17 | 18 | def handleJsonBatch(self, records: List[ChangeEvent]): 19 | logging.getLogger(self.LOGGER_NAME).info(f"Received {len(records)} records") 20 | print(f"Received {len(records)} records") 21 | # for record in records: 22 | # print(f"Event table: {record.destination()}") 23 | # print(f"Event key: {record.key()}") 24 | # print(f"Event value: {record.value()}") 25 | # print("--------------------------------------") 26 | 27 | 28 | class TestBasePythonChangeHandler(BasePostgresqlTest): 29 | def test_consuming_with_handler(self): 30 | props = self.debezium_engine_props() 31 | props.setProperty("database.server.name", "testc") 32 | props.setProperty("database.server.id", "1234") 33 | props.setProperty("max.batch.size", "5") 34 | 35 | with self.assertLogs(TestChangeHandler.LOGGER_NAME, level='INFO') as cm: 36 | # run async then interrupt after timeout! 37 | engine = DebeziumJsonEngine(properties=props, handler=TestChangeHandler()) 38 | Utils.run_engine_async(engine=engine) 39 | 40 | self.assertRegex(text=str(cm.output), expected_regex='.*Received.*records.*') 41 | -------------------------------------------------------------------------------- /tests/test_dlt_handler.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import dlt 4 | import duckdb 5 | 6 | from base_postgresql_test import BasePostgresqlTest 7 | from pydbzengine import DebeziumJsonEngine 8 | from pydbzengine.handlers.dlt import DltChangeHandler 9 | from pydbzengine.helper import Utils 10 | 11 | 12 | class TestDebeziumJsonEngine(BasePostgresqlTest): 13 | DUCK_DB = BasePostgresqlTest.CURRENT_DIR.joinpath("dbz_cdc_events.duckdb") 14 | 15 | def tearDown(self): 16 | if self.DUCK_DB.is_file() and self.DUCK_DB.exists(): 17 | os.remove(self.DUCK_DB) 18 | super().tearDown() 19 | 20 | def test_dlt_consuming(self): 21 | # get debezium engine configuration Properties 22 | props = self.debezium_engine_props() 23 | props.setProperty("database.server.name", "testdlt") 24 | props.setProperty("database.server.id", "2345") 25 | # create dlt pipeline to consume events to duckdb 26 | dlt_pipeline = dlt.pipeline( 27 | pipeline_name="dbz_cdc_events", 28 | destination="duckdb", 29 | dataset_name="dbz_data" 30 | ) 31 | # create handler class, which will process generated debezium events wih dlt 32 | handler = DltChangeHandler(dlt_pipeline=dlt_pipeline) 33 | with self.assertLogs(DltChangeHandler.LOGGER_NAME, level='INFO') as cm: 34 | # give the config and the handler class to the DebeziumJsonEngine 35 | engine = DebeziumJsonEngine(properties=props, handler=handler) 36 | # run async then interrupt after timeout time to test the result! 37 | Utils.run_engine_async(engine=engine, timeout_sec=120) 38 | 39 | self.assertRegex(text=str(cm.output), expected_regex='.*Consumed.*records.*') 40 | # print the data =========================== 41 | con = duckdb.connect(self.DUCK_DB.as_posix()) 42 | result = con.sql("SHOW ALL TABLES").fetchall() 43 | for r in result: 44 | database, schema, table = r[:3] 45 | if schema == "dbz_data": 46 | con.sql(f"select * from {database}.{schema}.{table}").show() 47 | -------------------------------------------------------------------------------- /tests/test_engine.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from pydbzengine import Properties, BasePythonChangeHandler, DebeziumJsonEngine 4 | 5 | 6 | class TestDebeziumJsonEngine(unittest.TestCase): 7 | 8 | def test_wrong_config_raises_error(self): 9 | props = Properties() 10 | props.setProperty("name", "my-connector") 11 | props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector") 12 | props.setProperty("transforms", "router") 13 | props.setProperty("transforms.router.type", "org.apache.kafka.connect.transforms.NotExists") 14 | 15 | with self.assertRaisesRegex(Exception, 16 | ".*Error.*while.*instantiating.*transformation.*router"): # Wrong message 17 | DebeziumJsonEngine(properties=props, handler=BasePythonChangeHandler()) 18 | 19 | # test engine arguments validated 20 | with self.assertRaisesRegex(Exception, 21 | ".*Please provide debezium config.*"): # Wrong message 22 | DebeziumJsonEngine(properties=None, handler=BasePythonChangeHandler()) 23 | with self.assertRaisesRegex(Exception, 24 | ".*Please provide handler.*"): # Wrong message 25 | DebeziumJsonEngine(properties=props, handler=None) 26 | -------------------------------------------------------------------------------- /tests/test_iceberg_handler.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from pyiceberg.catalog import load_catalog 4 | from pyiceberg.schema import Schema 5 | from pyiceberg.types import LongType, NestedField, StringType 6 | 7 | from base_postgresql_test import BasePostgresqlTest 8 | from catalog_rest import CatalogRestContainer 9 | from pydbzengine import DebeziumJsonEngine 10 | from pydbzengine.handlers.iceberg import IcebergChangeHandler 11 | from pydbzengine.helper import Utils 12 | from s3_minio import S3Minio 13 | 14 | 15 | class TestIcebergChangeHandler(BasePostgresqlTest): 16 | S3MiNIO = S3Minio() 17 | RESTCATALOG = CatalogRestContainer() 18 | 19 | def setUp(self): 20 | print("setUp") 21 | self.clean_offset_file() 22 | self.SOURCEPGDB.start() 23 | self.S3MiNIO.start() 24 | self.RESTCATALOG.start(s3_endpoint=self.S3MiNIO.endpoint()) 25 | 26 | def tearDown(self): 27 | self.SOURCEPGDB.stop() 28 | self.S3MiNIO.stop() 29 | self.clean_offset_file() 30 | 31 | @unittest.skip 32 | def test_iceberg_catalog(self): 33 | conf = { 34 | "uri": self.RESTCATALOG.get_uri(), 35 | # "s3.path-style.access": "true", 36 | "warehouse": "warehouse", 37 | "s3.endpoint": self.S3MiNIO.endpoint(), 38 | "s3.access-key-id": S3Minio.AWS_ACCESS_KEY_ID, 39 | "s3.secret-access-key": S3Minio.AWS_SECRET_ACCESS_KEY, 40 | } 41 | print(conf) 42 | catalog = load_catalog( 43 | name="rest", 44 | **conf 45 | ) 46 | catalog.create_namespace('my_warehouse') 47 | debezium_event_schema = Schema( 48 | NestedField(field_id=1, name="id", field_type=LongType(), required=True), 49 | NestedField(field_id=2, name="data", field_type=StringType(), required=False), 50 | ) 51 | table = catalog.create_table(identifier=("my_warehouse", "test_table",), schema=debezium_event_schema) 52 | print(f"Created iceberg table {table.refs()}") 53 | 54 | def test_iceberg_handler(self): 55 | dest_ns1_database="my_warehouse" 56 | dest_ns2_schema="dbz_cdc_data" 57 | conf = { 58 | "uri": self.RESTCATALOG.get_uri(), 59 | # "s3.path-style.access": "true", 60 | "warehouse": "warehouse", 61 | "s3.endpoint": self.S3MiNIO.endpoint(), 62 | "s3.access-key-id": S3Minio.AWS_ACCESS_KEY_ID, 63 | "s3.secret-access-key": S3Minio.AWS_SECRET_ACCESS_KEY, 64 | } 65 | catalog = load_catalog(name="rest",**conf) 66 | 67 | handler = IcebergChangeHandler(catalog=catalog, destination_namespace=(dest_ns1_database, dest_ns2_schema,)) 68 | 69 | dbz_props = self.debezium_engine_props(unwrap_messages=False) 70 | engine = DebeziumJsonEngine(properties=dbz_props, handler=handler) 71 | 72 | with self.assertLogs(IcebergChangeHandler.LOGGER_NAME, level='INFO') as cm: 73 | # run async then interrupt after timeout time to test the result! 74 | Utils.run_engine_async(engine=engine, timeout_sec=44) 75 | 76 | for t in cm.output: 77 | print(t) 78 | self.assertRegex(text=str(cm.output), expected_regex='.*Created iceberg table.*') 79 | self.assertRegex(text=str(cm.output), expected_regex='.*Appended.*records to table.*') 80 | 81 | # catalog.create_namespace(dest_ns1_database) 82 | namespaces = catalog.list_namespaces() 83 | self.assertIn((dest_ns1_database,) , namespaces, msg="Namespace not found in catalog") 84 | 85 | tables = catalog.list_tables((dest_ns1_database, dest_ns2_schema,)) 86 | print(tables) 87 | self.assertIn(('my_warehouse', 'dbz_cdc_data', 'testc_inventory_customers'), tables, msg="Namespace not found in catalog") 88 | 89 | tbl = catalog.load_table(identifier=('my_warehouse', 'dbz_cdc_data', 'testc_inventory_customers')) 90 | data = tbl.scan().to_arrow() 91 | self.assertIn("sally.thomas@acme.com", str(data)) 92 | self.assertIn("annek@noanswer.org", str(data)) 93 | print(data) 94 | self.assertEqual(data.num_rows, 4) --------------------------------------------------------------------------------