├── .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
├── debeziumdlt.py
├── examples
│ └── dlt_consuming.py
├── helper.py
├── install_libs.sh
└── pom.xml
├── pyproject.toml
└── tests
├── DbPostgresql.py
├── base_postgresql_test.py
├── config
└── log4j2-test.properties
├── test_change_handler.py
├── test_debeziumdlt.py
└── test_engine.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]
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 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
--------------------------------------------------------------------------------
/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 | [](http://www.apache.org/licenses/LICENSE-2.0.html)
2 | 
3 | [](https://github.com/memiiso/pydbzengine/actions/workflows/release.yml)
4 | # pydbzengine
5 |
6 | A Python module to use [Debezium Engine](https://debezium.io/) in python. Consume Database CDC events using python.
7 |
8 | Java integration is using [Pyjnius](https://pyjnius.readthedocs.io/en/latest/), It is a Python library for accessing
9 | Java classes
10 |
11 | ## Installation
12 |
13 | Python+Java integration requires a Java Development Kit (JDK). Ensure a JDK is installed on environment.
14 |
15 | install:
16 |
17 | ```shell
18 | pip install pydbzengine
19 | # install from github:
20 | pip install https://github.com/memiiso/pydbzengine/archive/master.zip --upgrade --user
21 | ```
22 |
23 | ## How to Use
24 |
25 | First install the packages, `pip install pydbzengine[dev]`
26 |
27 | ```python
28 | from typing import List
29 | from pydbzengine import ChangeEvent, BasePythonChangeHandler
30 | from pydbzengine import Properties, DebeziumJsonEngine
31 |
32 |
33 | class PrintChangeHandler(BasePythonChangeHandler):
34 | """
35 | A custom change event handler class.
36 |
37 | This class processes batches of Debezium change events received from the engine.
38 | The `handleJsonBatch` method is where you implement your logic for consuming
39 | and processing these events. Currently, it prints basic information about
40 | each event to the console.
41 | """
42 |
43 | def handleJsonBatch(self, records: List[ChangeEvent]):
44 | """
45 | Handles a batch of Debezium change events.
46 |
47 | This method is called by the Debezium engine with a list of ChangeEvent objects.
48 | Change this method to implement your desired processing logic. For example,
49 | you might parse the event data, transform it, and load it into a database or
50 | other destination.
51 |
52 | Args:
53 | records: A list of ChangeEvent objects representing the changes captured by Debezium.
54 | """
55 | print(f"Received {len(records)} records")
56 | for record in records:
57 | print(f"destination: {record.destination()}")
58 | print(f"key: {record.key()}")
59 | print(f"value: {record.value()}")
60 | print("--------------------------------------")
61 |
62 |
63 | if __name__ == '__main__':
64 | props = Properties()
65 | props.setProperty("name", "engine")
66 | props.setProperty("snapshot.mode", "initial_only")
67 | # Add further Debezium connector configuration properties here. For example:
68 | # props.setProperty("connector.class", "io.debezium.connector.mysql.MySqlConnector")
69 | # props.setProperty("database.hostname", "your_database_host")
70 | # props.setProperty("database.port", "3306")
71 |
72 | # Create a DebeziumJsonEngine instance, passing the configuration properties and the custom change event handler.
73 | engine = DebeziumJsonEngine(properties=props, handler=PrintChangeHandler())
74 |
75 | # Start the Debezium engine to begin consuming and processing change events.
76 | engine.run()
77 |
78 | ```
79 | #### How to consume events with dlt
80 | For the full code please see [dlt_consuming.py](pydbzengine/examples/dlt_consuming.py)
81 |
82 | https://github.com/memiiso/pydbzengine/blob/c4a88228aa66a2dc41b3dcc192615b1357326b66/pydbzengine/examples/dlt_consuming.py#L92-L153
83 |
84 | ### Contributors
85 |
86 |
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/activation-1.1.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/antlr4-runtime-4.10.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/antlr4-runtime-4.10.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/aopalliance-repackaged-2.6.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/aopalliance-repackaged-2.6.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/bson-5.2.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/bson-5.2.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/bson-record-codec-5.2.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/checker-qual-3.31.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/commons-lang3-3.12.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/commons-lang3-3.12.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/connect-api-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/connect-api-3.9.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/connect-file-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/connect-file-3.9.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/connect-json-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/connect-json-3.9.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/connect-runtime-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/connect-runtime-3.9.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/connect-transforms-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/hk2-api-2.6.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/hk2-locator-2.6.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/hk2-locator-2.6.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/hk2-utils-2.6.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/hk2-utils-2.6.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jackson-annotations-2.16.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jackson-annotations-2.16.2.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jackson-core-2.16.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jackson-core-2.16.2.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jackson-databind-2.16.2.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jaxb-api-2.3.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jersey-client-2.39.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jersey-client-2.39.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jersey-common-2.39.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jersey-hk2-2.39.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jersey-server-2.39.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jetty-util-9.4.56.v20240826.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/jose4j-0.9.4.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/jose4j-0.9.4.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/kafka-clients-3.9.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/kafka-clients-3.9.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/log4j-api-2.24.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/log4j-api-2.24.3.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/log4j-core-2.24.3.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/lz4-java-1.8.0.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/maven-artifact-3.9.6.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/plexus-utils-3.5.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/postgresql-42.6.1.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/postgresql-42.6.1.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/protobuf-java-3.25.5.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/protobuf-java-3.25.5.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/reflections-0.9.12.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/reflections-0.9.12.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/reload4j-1.2.25.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/reload4j-1.2.25.jar
--------------------------------------------------------------------------------
/pydbzengine/debezium/libs/slf4j-api-2.0.16.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/memiiso/pydbzengine/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/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/ac6f148c5ab9cb09d192435dac767a653f9f4c52/pydbzengine/debezium/libs/zstd-jni-1.5.6-4.jar
--------------------------------------------------------------------------------
/pydbzengine/debeziumdlt.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/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.debeziumdlt 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 | # cleanup
20 | if OFFSET_FILE.exists():
21 | os.remove(OFFSET_FILE)
22 | if DUCKDB_FILE.exists():
23 | os.remove(DUCKDB_FILE)
24 |
25 | def wait_for_postgresql_to_start(self) -> None:
26 | wait_for_logs(self, ".*database system is ready to accept connections.*")
27 | wait_for_logs(self, ".*PostgreSQL init process complete.*")
28 |
29 |
30 | class DbPostgresql:
31 | POSTGRES_USER = "postgres"
32 | POSTGRES_PASSWORD = "postgres"
33 | POSTGRES_DBNAME = "postgres"
34 | POSTGRES_IMAGE = "debezium/example-postgres:3.0.0.Final"
35 | POSTGRES_HOST = "localhost"
36 | POSTGRES_PORT_DEFAULT = 5432
37 | CONTAINER: PostgresContainer = (PostgresContainer(image=POSTGRES_IMAGE,
38 | port=POSTGRES_PORT_DEFAULT,
39 | username=POSTGRES_USER,
40 | password=POSTGRES_PASSWORD,
41 | dbname=POSTGRES_DBNAME,
42 | )
43 | .with_exposed_ports(POSTGRES_PORT_DEFAULT)
44 | )
45 | PostgresContainer._connect = wait_for_postgresql_to_start
46 |
47 | def start(self):
48 | testcontainers_config.ryuk_disabled = True
49 | print("Starting Postgresql Db...")
50 | self.CONTAINER.start()
51 |
52 | def stop(self):
53 | print("Stopping Postgresql Db...")
54 | self.CONTAINER.stop()
55 |
56 | def __exit__(self, exc_type, exc_value, traceback):
57 | self.stop()
58 |
59 |
60 | def debezium_engine_props(sourcedb: DbPostgresql):
61 | props = Properties()
62 | props.setProperty("name", "engine")
63 | props.setProperty("snapshot.mode", "initial_only")
64 | props.setProperty("database.hostname", sourcedb.CONTAINER.get_container_host_ip())
65 | props.setProperty("database.port",
66 | sourcedb.CONTAINER.get_exposed_port(sourcedb.POSTGRES_PORT_DEFAULT))
67 | props.setProperty("database.user", sourcedb.POSTGRES_USER)
68 | props.setProperty("database.password", sourcedb.POSTGRES_PASSWORD)
69 | props.setProperty("database.dbname", sourcedb.POSTGRES_DBNAME)
70 | props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector")
71 | props.setProperty("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore")
72 | props.setProperty("offset.storage.file.filename", OFFSET_FILE.as_posix())
73 | props.setProperty("max.batch.size", "5")
74 | props.setProperty("poll.interval.ms", "10000")
75 | props.setProperty("converter.schemas.enable", "false")
76 | props.setProperty("offset.flush.interval.ms", "1000")
77 | props.setProperty("database.server.name", "testc")
78 | props.setProperty("database.server.id", "1234")
79 | props.setProperty("topic.prefix", "testc")
80 | props.setProperty("schema.whitelist", "inventory")
81 | props.setProperty("database.whitelist", "inventory")
82 | props.setProperty("table.whitelist", "inventory.*")
83 | props.setProperty("replica.identity.autoset.values", "inventory.*:FULL")
84 | # // debezium unwrap message
85 | props.setProperty("transforms", "unwrap")
86 | props.setProperty("transforms.unwrap.type", "io.debezium.transforms.ExtractNewRecordState")
87 | props.setProperty("transforms.unwrap.add.fields", "op,table,source.ts_ms,sourcedb,ts_ms")
88 | props.setProperty("transforms.unwrap.delete.handling.mode", "rewrite")
89 | # props.setProperty("debezium.transforms.unwrap.drop.tombstones", "true")
90 | return props
91 |
92 | def main():
93 | """
94 | Demonstrates capturing change data from PostgreSQL using Debezium and loading
95 | it into DuckDB using dlt.
96 |
97 | This example starts a PostgreSQL container, configures Debezium to capture changes,
98 | processes the change events with a custom handler using dlt, and finally queries
99 | the DuckDB database to display the loaded data.
100 | """
101 |
102 | # Start the PostgreSQL container that will serve as the replication source.
103 | sourcedb = DbPostgresql()
104 | sourcedb.start()
105 |
106 | # Get Debezium engine configuration properties, including connection details
107 | # for the PostgreSQL database. This function debezium_engine_props returns all the properties
108 | props = debezium_engine_props(sourcedb=sourcedb)
109 |
110 | # Create a dlt pipeline to load the change events into DuckDB.
111 | dlt_pipeline = dlt.pipeline(
112 | pipeline_name="dbz_cdc_events_example",
113 | destination="duckdb",
114 | dataset_name="dbz_data"
115 | )
116 |
117 | # Instantiate change event handler (DltChangeHandler) that uses the dlt pipeline
118 | # to process and load the Debezium events. This handler has
119 | # the logic for transforming and loading the events.
120 | handler = DltChangeHandler(dlt_pipeline=dlt_pipeline)
121 |
122 | # Create a DebeziumJsonEngine instance, providing the configuration properties
123 | # and the custom event handler.
124 | engine = DebeziumJsonEngine(properties=props, handler=handler)
125 |
126 | # Run the Debezium engine asynchronously with a timeout. This allows the example
127 | # to run for a limited time and then terminate automatically.
128 | Utils.run_engine_async(engine=engine, timeout_sec=60)
129 | # engine.run() # This would be used for synchronous execution (without timeout)
130 |
131 | # ================ PRINT THE CONSUMED DATA FROM DUCKDB ===========================
132 | # Connect to the DuckDB database.
133 | con = duckdb.connect(DUCKDB_FILE.as_posix())
134 |
135 | # Retrieve a list of all tables in the DuckDB database.
136 | result = con.sql("SHOW ALL TABLES").fetchall()
137 |
138 | # Iterate through the tables and display the data from tables within the 'dbz_data' schema.
139 | for r in result:
140 | database, schema, table = r[:3] # Extract database, schema, and table names.
141 | if schema == "dbz_data": # Only show data from the schema where Debezium loaded the data.
142 | print(f"Data in table {table}:")
143 | con.sql(f"select * from {database}.{schema}.{table} limit 5").show() # Display table data
144 |
145 |
146 | if __name__ == "__main__":
147 | """
148 | Main entry point for the script.
149 |
150 | Before running, ensure you have installed the necessary dependencies:
151 | `pip install pydbzengine[dev]`
152 | """
153 | main()
--------------------------------------------------------------------------------
/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 | "dlt>=1.5.0"
27 | ]
28 | [project.optional-dependencies]
29 | dev = [
30 | "testcontainers>=4.9.1",
31 | "dlt[duckdb]>=1.5.0",
32 | "apache-airflow>=2.10.4"
33 | ]
34 | #[project.scripts]
35 | #debezium = "pydbzengine.__main__:main"
36 |
37 | [project.urls]
38 | Homepage = "https://github.com/memiiso/pydbzengine"
39 | Documentation = "https://github.com/memiiso/pydbzengine"
40 | Repository = "https://github.com/memiiso/pydbzengine"
41 |
--------------------------------------------------------------------------------
/tests/DbPostgresql.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 | print("Starting Postgresql Db...")
30 | testcontainers_config.ryuk_disabled = True
31 | self.CONTAINER.start()
32 |
33 | def stop(self):
34 | print("Stopping Postgresql Db...")
35 | self.CONTAINER.stop()
36 |
37 | def __exit__(self, exc_type, exc_value, traceback):
38 | self.stop()
39 |
--------------------------------------------------------------------------------
/tests/base_postgresql_test.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 | from pathlib import Path
4 |
5 | from DbPostgresql 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 | SOURCEDB = DbPostgresql()
13 |
14 | def debezium_engine_props(self):
15 | props = Properties()
16 | props.setProperty("name", "engine")
17 | props.setProperty("snapshot.mode", "always")
18 | props.setProperty("database.hostname", self.SOURCEDB.CONTAINER.get_container_host_ip())
19 | props.setProperty("database.port",
20 | self.SOURCEDB.CONTAINER.get_exposed_port(self.SOURCEDB.POSTGRES_PORT_DEFAULT))
21 | props.setProperty("database.user", self.SOURCEDB.POSTGRES_USER)
22 | props.setProperty("database.password", self.SOURCEDB.POSTGRES_PASSWORD)
23 | props.setProperty("database.dbname", self.SOURCEDB.POSTGRES_DBNAME)
24 | props.setProperty("connector.class", "io.debezium.connector.postgresql.PostgresConnector")
25 | props.setProperty("offset.storage", "org.apache.kafka.connect.storage.FileOffsetBackingStore")
26 | props.setProperty("offset.storage.file.filename", self.OFFSET_FILE.as_posix())
27 | props.setProperty("poll.interval.ms", "10000")
28 | props.setProperty("converter.schemas.enable", "false")
29 | props.setProperty("offset.flush.interval.ms", "1000")
30 | props.setProperty("topic.prefix", "testc")
31 | props.setProperty("schema.whitelist", "inventory")
32 | props.setProperty("database.whitelist", "inventory")
33 | props.setProperty("table.whitelist", "inventory.*")
34 | props.setProperty("replica.identity.autoset.values", "inventory.*:FULL")
35 | # // debezium unwrap message
36 | props.setProperty("transforms", "unwrap")
37 | props.setProperty("transforms.unwrap.type", "io.debezium.transforms.ExtractNewRecordState")
38 | props.setProperty("transforms.unwrap.add.fields", "op,table,source.ts_ms,sourcedb,ts_ms")
39 | props.setProperty("transforms.unwrap.delete.handling.mode", "rewrite")
40 | # props.setProperty("debezium.transforms.unwrap.drop.tombstones", "true")
41 | return props
42 |
43 | def setUp(self):
44 | print("setUp")
45 | if self.OFFSET_FILE.exists():
46 | os.remove(self.OFFSET_FILE)
47 | self.SOURCEDB.start()
48 |
49 | def tearDown(self):
50 | self.tearDownClass()
51 |
52 | @classmethod
53 | def tearDownClass(cls):
54 | print("tearDown")
55 | if cls.OFFSET_FILE.exists():
56 | os.remove(cls.OFFSET_FILE)
57 | try:
58 | cls.SOURCEDB.stop()
59 | except:
60 | pass
61 |
--------------------------------------------------------------------------------
/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/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_debeziumdlt.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.debeziumdlt 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 |
--------------------------------------------------------------------------------