├── .github └── workflows │ ├── django_3.2_test.yml │ ├── django_4.0_test.yml │ ├── django_4.1_test.yml │ └── django_test.yml ├── .gitignore ├── LICENSE ├── README.rst ├── django_test_suite.sh ├── django_yugabytedb ├── __init__.py ├── base.py ├── client.py ├── creation.py ├── features.py ├── introspection.py ├── operations.py └── schema.py ├── requirements.txt ├── setup.cfg ├── setup.py └── yugabyte_settings.py /.github/workflows/django_3.2_test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '30 8 1,15 * *' 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | name: django-3.2-tests 11 | jobs: 12 | system-tests: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | 19 | - name: Setup Python 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: 3.8 23 | 24 | - name: Start YugabyteDB on docker 25 | run: docker run -d --name yugabyte1 -p5435:5433 yugabytedb/yugabyte:latest bin/yugabyted start --daemon=false --tserver_flags='enable_pg_savepoints=true' 26 | 27 | - name: Run Django 3.2 tests 28 | run: sh django_test_suite.sh 29 | env: 30 | DJANGO_VERSION: 3.2 31 | DJANGO_BRANCH: stable/3.2.x 32 | PORT: 5435 33 | DJANGO_TEST_APPS: absolute_url_overrides admin_autodiscover admin_checks admin_default_site admin_registration admin_scripts app_loading apps async bash_completion builtin_server cache check_framework conditional_processing constraints context_processors csrf_tests custom_lookups custom_methods datatypes db_typecasts db_utils dbshell.test_postgresql decorators deprecation dispatch empty empty_models field_deconstruction field_defaults field_subclassing file_storage files fixtures_model_package from_db_value handlers httpwrappers humanize_tests i18n invalid_models_tests logging_tests m2o_recursive mail max_lengths messages_tests middleware middleware_exceptions migrate_signals migrations migration_test_data_persistence migrations2 model_enums model_indexes model_meta model_utils no_models or_lookups pagination project_template properties requests reserved_names resolve_url responses save_delete_hooks schema servers sessions_tests settings_tests shell shortcuts signed_cookies_tests signing sitemaps_tests sites_tests staticfiles_tests str template_backends template_loader test_client test_client_regress test_exceptions test_runner transaction_hooks transactions urlpatterns urlpatterns_reverse user_commands utils_tests validators version wsgi 34 | 35 | - name: Stop YugabyteDB on docker 36 | run: docker stop yugabyte1 37 | 38 | - name: Remove YugabyteDB on docker 39 | run: docker rm yugabyte1 40 | -------------------------------------------------------------------------------- /.github/workflows/django_4.0_test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '30 8 1,15 * *' 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | name: django-4.0-tests 11 | jobs: 12 | system-tests: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | 19 | - name: Setup Python 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: 3.8 23 | 24 | - name: Start YugabyteDB on docker 25 | run: docker run -d --name yugabyte2 -p5431:5433 yugabytedb/yugabyte:latest bin/yugabyted start --daemon=false --tserver_flags='enable_pg_savepoints=true' 26 | 27 | - name: Run Django 4.0 tests 28 | run: sh django_test_suite.sh 29 | env: 30 | DJANGO_VERSION: 4.0 31 | DJANGO_BRANCH: stable/4.0.x 32 | PORT: 5431 33 | DJANGO_TEST_APPS: absolute_url_overrides admin_autodiscover admin_checks admin_default_site admin_registration admin_scripts app_loading apps async bash_completion builtin_server cache check_framework conditional_processing constraints context_processors csrf_tests custom_lookups custom_methods datatypes db_typecasts db_utils dbshell.test_postgresql decorators deprecation dispatch empty empty_models field_deconstruction field_defaults field_subclassing file_storage files fixtures_model_package from_db_value handlers httpwrappers humanize_tests i18n invalid_models_tests logging_tests m2o_recursive mail max_lengths messages_tests middleware middleware_exceptions migrate_signals migrations migration_test_data_persistence migrations2 model_enums model_indexes model_meta model_utils no_models or_lookups pagination project_template properties requests reserved_names resolve_url responses save_delete_hooks schema servers sessions_tests settings_tests shell shortcuts signed_cookies_tests signing sitemaps_tests sites_tests staticfiles_tests str template_backends template_loader test_client test_client_regress test_exceptions test_runner transaction_hooks transactions urlpatterns urlpatterns_reverse user_commands utils_tests validators version wsgi 34 | 35 | - name: Stop YugabyteDB on docker 36 | run: docker stop yugabyte2 37 | 38 | - name: Remove YugabyteDB on docker 39 | run: docker rm yugabyte2 40 | -------------------------------------------------------------------------------- /.github/workflows/django_4.1_test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '30 8 1,15 * *' 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | name: django-4.1-tests 11 | jobs: 12 | system-tests: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | 19 | - name: Setup Python 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: 3.8 23 | 24 | - name: Start YugabyteDB on docker 25 | run: docker run -d --name yugabyte3 -p5440:5433 yugabytedb/yugabyte:latest bin/yugabyted start --daemon=false --tserver_flags='enable_pg_savepoints=true' 26 | 27 | - name: Run Django 4.1 tests 28 | run: sh django_test_suite.sh 29 | env: 30 | DJANGO_VERSION: 4.1 31 | DJANGO_BRANCH: stable/4.1.x 32 | PORT: 5440 33 | DJANGO_TEST_APPS: absolute_url_overrides admin_autodiscover admin_checks admin_default_site admin_registration admin_scripts app_loading apps async bash_completion builtin_server cache check_framework conditional_processing constraints context_processors csrf_tests custom_lookups custom_methods datatypes db_typecasts db_utils dbshell.test_postgresql decorators deprecation dispatch empty empty_models field_deconstruction field_defaults field_subclassing file_storage files fixtures_model_package from_db_value handlers httpwrappers humanize_tests i18n invalid_models_tests logging_tests m2o_recursive mail max_lengths messages_tests middleware middleware_exceptions migrate_signals migrations migration_test_data_persistence migrations2 model_enums model_indexes model_meta model_utils no_models or_lookups pagination project_template properties requests reserved_names resolve_url responses save_delete_hooks schema servers sessions_tests settings_tests shell shortcuts signed_cookies_tests signing sitemaps_tests sites_tests staticfiles_tests str template_backends template_loader test_client test_client_regress test_exceptions test_runner transaction_hooks transactions urlpatterns urlpatterns_reverse user_commands utils_tests validators version wsgi 34 | 35 | - name: Stop YugabyteDB on docker 36 | run: docker stop yugabyte3 37 | 38 | - name: Remove YugabyteDB on docker 39 | run: docker rm yugabyte3 40 | -------------------------------------------------------------------------------- /.github/workflows/django_test.yml: -------------------------------------------------------------------------------- 1 | on: 2 | schedule: 3 | - cron: '30 8 1,15 * *' 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | name: django-tests 11 | jobs: 12 | system-tests: 13 | runs-on: ubuntu-latest 14 | 15 | steps: 16 | - name: Checkout code 17 | uses: actions/checkout@v2 18 | 19 | - name: Setup Python 20 | uses: actions/setup-python@v3 21 | with: 22 | python-version: 3.8 23 | 24 | - name: Start YugabyteDB on docker 25 | run: docker run -d --name yugabyte -p5437:5433 yugabytedb/yugabyte:latest bin/yugabyted start --daemon=false --tserver_flags='enable_pg_savepoints=true' 26 | 27 | - name: Run Django tests 28 | run: sh django_test_suite.sh 29 | env: 30 | DJANGO_VERSION: latest 31 | DJANGO_BRANCH: main 32 | PORT: 5437 33 | DJANGO_TEST_APPS: absolute_url_overrides admin_autodiscover admin_checks admin_default_site admin_registration admin_scripts app_loading apps asgi async bash_completion builtin_server cache check_framework conditional_processing constraints context_processors csrf_tests custom_lookups custom_methods datatypes db_typecasts db_utils dbshell.test_postgresql decorators deprecation dispatch empty empty_models field_deconstruction field_defaults field_subclassing file_storage files fixtures_model_package from_db_value handlers httpwrappers humanize_tests i18n invalid_models_tests logging_tests m2o_recursive mail max_lengths messages_tests middleware middleware_exceptions migrate_signals migrations migration_test_data_persistence migrations2 model_enums model_indexes model_meta model_utils no_models or_lookups pagination project_template properties requests reserved_names resolve_url responses save_delete_hooks schema servers sessions_tests settings_tests shell shortcuts signed_cookies_tests signing sitemaps_tests sites_tests staticfiles_tests str template_backends template_loader test_client test_client_regress test_exceptions test_runner transaction_hooks transactions urlpatterns urlpatterns_reverse user_commands utils_tests validators version wsgi 34 | 35 | - name: Stop YugabyteDB on docker 36 | run: docker stop yugabyte 37 | 38 | - name: Remove YugabyteDB on docker 39 | run: docker rm yugabyte 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /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.rst: -------------------------------------------------------------------------------- 1 | Django backend for YugabyteDB 2 | ============================= 3 | 4 | Prerequisites 5 | ------------- 6 | 7 | * GCC 8 | * Python 3.8 and above 9 | * Psycopg2-yugabytedb (recommended) 10 | * Django 3.2 or above 11 | 12 | Need for Django Backend for YugabyteDB 13 | --------------------------------------- 14 | 15 | YugabyteDB needs a separate backend for Django. This is because of mainly 3 reasons. 16 | 17 | * Django tries to create Inet data types as primary keys in Django test suites. Since this is not supported, we map Inet types to varchar(15) and varchar(39) in the YB backend. 18 | * We also need it to support type change from int to BigInt and numeric(m,n) to double precision. This is required for Django DB migrations. For now, the YB backend ignores these type changes. 19 | * The Django PostgreSQL Backend does not support the Load Balance, even when used with YugabyteDB smart driver. 20 | 21 | Installing from Pypi 22 | --------------------- 23 | 24 | Install the django-yugabytedb package with the command: 25 | 26 | .. code-block:: console 27 | 28 | $ pip install django-yugabytedb 29 | 30 | 31 | Installing in Python Virtual Environment From Source 32 | --------------------------------------------------------- 33 | 34 | The django-yugabytedb package can also be installed from source: 35 | 36 | .. code-block:: console 37 | 38 | $ git clone https://github.com/yugabyte/yb-django.git 39 | 40 | $ python -m pip install -r /yb-django/requirements.txt 41 | 42 | $ python -m pip install -e /yb-django/ 43 | 44 | Check if it is installed correctly: 45 | 46 | .. code-block:: console 47 | 48 | $ pip list —local 49 | 50 | Use the backend with your Application 51 | ------------------------------------- 52 | 53 | Update the ``DATABASES`` setting in your Django project's settings to point to YB server using Django YB backend: 54 | 55 | .. code-block:: python 56 | 57 | DATABASES = { 58 | 'default': { 59 | 'ENGINE': 'django_yugabytedb', 60 | 'NAME': 'yugabyte', 61 | 'HOST': 'localhost', 62 | 'PORT': 5433, 63 | 'USER': 'yugabyte', 64 | } 65 | } 66 | 67 | To use Cluster Aware Load Balance: 68 | 69 | .. code-block:: python 70 | 71 | DATABASES = { 72 | 'default': { 73 | 'ENGINE': 'django_yugabytedb', 74 | 'NAME': 'yugabyte', 75 | 'HOST': 'localhost', 76 | 'PORT': 5433, 77 | 'USER': 'yugabyte', 78 | 'LOAD_BALANCE': 'True' 79 | } 80 | } 81 | 82 | To use Topology Aware Load Balance: 83 | 84 | .. code-block:: python 85 | 86 | DATABASES = { 87 | 'default': { 88 | 'ENGINE': 'django_yugabytedb', 89 | 'NAME': 'yugabyte', 90 | 'HOST': 'localhost', 91 | 'PORT': 5433, 92 | 'USER': 'yugabyte', 93 | 'LOAD_BALANCE': 'True', 94 | 'TOPOLOGY_KEYS': 'cloud1.region1.zone1' 95 | } 96 | } 97 | 98 | Known bugs and issues 99 | ----------------------- 100 | 101 | * The creation of indexes in YugabyteDB is a little slow. 102 | * Since Inet is mapped to varchar in the backend, comparison between data in the inet column wth Inet type will fail. 103 | * For YugabyteDB verions earlier than 2.9, the savepoint feature is not supported. 104 | * Dropping of Primary keys are not supported 105 | * Alter table Add column Unique is not yet supported. 106 | * Backfilling of existing rows when new column is added with default value is not yet implemented in yugabytedb. 107 | * Type change from int to BigInt and numeric(m,n) to double precision is not yet supported. 108 | * ALTER INDEX not supported yet. -------------------------------------------------------------------------------- /django_test_suite.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # Copyright (c) 2020 Google LLC. All rights reserved. 4 | # Use of this source code is governed by a BSD-style 5 | # license that can be found in the LICENSE file. 6 | 7 | set -x pipefail 8 | 9 | sudo apt-get update -y 10 | sudo apt-get install -y libmemcached-dev 11 | 12 | # Disable buffering, so that the logs stream through. 13 | export PYTHONUNBUFFERED=1 14 | 15 | export DJANGO_TESTS_DIR="django_tests_dir" 16 | mkdir -p $DJANGO_TESTS_DIR 17 | 18 | pip3 install -r requirements.txt 19 | pip3 install -e . 20 | git clone https://github.com/django/django.git --branch $DJANGO_BRANCH $DJANGO_TESTS_DIR/django-$DJANGO_VERSION 21 | 22 | # Install dependencies for Django tests. 23 | sudo apt-get update 24 | sudo apt-get install -y libffi-dev libjpeg-dev zlib1g-devel 25 | 26 | cd $DJANGO_TESTS_DIR/django-$DJANGO_VERSION && pip3 install -e . && pip3 install -r tests/requirements/py3.txt; cd ../../ 27 | 28 | create_settings() { 29 | cat << ! > "test_yugabyte.py" 30 | DATABASES = { 31 | 'default': { 32 | 'ENGINE': 'django_yugabytedb', 33 | 'NAME': 'yugabyte', 34 | 'HOST': 'localhost', 35 | 'PORT': $PORT, 36 | 'USER': 'yugabyte' 37 | }, 38 | 'other': { 39 | 'ENGINE': 'django_yugabytedb', 40 | 'NAME': 'other', 41 | 'HOST': 'localhost', 42 | 'PORT': $PORT, 43 | 'USER': 'yugabyte' 44 | }, 45 | } 46 | SECRET_KEY = 'django_tests_secret_key' 47 | PASSWORD_HASHERS = [ 48 | 'django.contrib.auth.hashers.MD5PasswordHasher', 49 | ] 50 | DEFAULT_AUTO_FIELD = 'django.db.models.AutoField' 51 | 52 | USE_TZ = False 53 | ! 54 | } 55 | 56 | cd $DJANGO_TESTS_DIR/django-$DJANGO_VERSION/tests 57 | create_settings 58 | 59 | EXIT_STATUS=0 60 | for DJANGO_TEST_APP in $DJANGO_TEST_APPS 61 | do 62 | echo "===========================================================================================" 63 | echo $DJANGO_TEST_APP 64 | echo "===========================================================================================" 65 | python3 runtests.py --settings=test_yugabyte -v 3 $DJANGO_TEST_APP --noinput || EXIT_STATUS=$? 66 | done 67 | exit $EXIT_STATUS -------------------------------------------------------------------------------- /django_yugabytedb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yugabyte/yb-django/92b51b1a7f4809cd917fa849d6811cbb8aaa5fd2/django_yugabytedb/__init__.py -------------------------------------------------------------------------------- /django_yugabytedb/base.py: -------------------------------------------------------------------------------- 1 | from django.core.exceptions import ImproperlyConfigured 2 | from django.utils.version import get_version_tuple 3 | from django.utils.functional import cached_property 4 | 5 | 6 | try: 7 | import psycopg2 as Database 8 | import psycopg2.extensions 9 | import psycopg2.extras 10 | except ImportError as e: 11 | raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) 12 | 13 | 14 | def psycopg2_version(): 15 | version = psycopg2.__version__.split(' ', 1)[0] 16 | return get_version_tuple(version) 17 | 18 | 19 | PSYCOPG2_VERSION = psycopg2_version() 20 | 21 | if PSYCOPG2_VERSION < (2, 5, 4): 22 | raise ImproperlyConfigured("psycopg2_version 2.5.4 or newer is required; you have %s" % psycopg2.__version__) 23 | 24 | from .client import DatabaseClient # NOQA 25 | from .creation import DatabaseCreation # NOQA 26 | from .features import DatabaseFeatures # NOQA 27 | from .introspection import DatabaseIntrospection # NOQA 28 | from .operations import DatabaseOperations # NOQA 29 | from .schema import DatabaseSchemaEditor # NOQA 30 | 31 | 32 | from django.db.backends.postgresql.base import ( 33 | DatabaseWrapper as PGDatabaseWrapper, 34 | ) 35 | 36 | 37 | class DatabaseWrapper(PGDatabaseWrapper): 38 | vendor = 'yugabyte' 39 | display_name = 'YugabyteDB' 40 | # Override some types from the postgresql adapter. 41 | # Refer https://github.com/yugabyte/yugabyte-db/issues/7761 42 | data_types = dict( 43 | PGDatabaseWrapper.data_types, 44 | IPAddressField = 'varchar(15)', 45 | GenericIPAddressField = 'varchar(39)', 46 | ) 47 | SchemaEditorClass = DatabaseSchemaEditor 48 | creation_class = DatabaseCreation 49 | features_class = DatabaseFeatures 50 | introspection_class = DatabaseIntrospection 51 | ops_class = DatabaseOperations 52 | client_class = DatabaseClient 53 | 54 | @cached_property 55 | def yugabytedb_version(self): 56 | with self.temporary_connection() as cur: 57 | cur.execute("Select * from version()") 58 | row = cur.fetchone() 59 | version_part = row[0].split('-YB-')[1].split('-')[0] # "2.20.7.0" 60 | version_tuple = tuple(map(int, version_part.split('.')[:2])) # (2, 20) 61 | return version_tuple 62 | 63 | def get_database_version(self): 64 | return self.yugabytedb_version 65 | 66 | 67 | # def savepoint(self): 68 | # We override savepoint function to overcome the issue mentioned here 69 | # https://code.djangoproject.com/ticket/28263 70 | # https://code.djangoproject.com/ticket/32527 71 | # https://github.com/yugabyte/yugabyte-db/issues/7760 72 | #return 1 73 | 74 | def get_connection_params(self): 75 | conn_params = super().get_connection_params() 76 | settings_dict = self.settings_dict 77 | load_balance = settings_dict.get("LOAD_BALANCE") 78 | topology_keys = settings_dict.get("TOPOLOGY_KEYS") 79 | if load_balance: 80 | conn_params["load_balance"] = load_balance 81 | if topology_keys: 82 | conn_params["topology_keys"] = topology_keys 83 | 84 | return conn_params 85 | 86 | -------------------------------------------------------------------------------- /django_yugabytedb/client.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.base.client import BaseDatabaseClient 2 | 3 | 4 | class DatabaseClient(BaseDatabaseClient): 5 | executable_name = 'yugabyte' 6 | 7 | -------------------------------------------------------------------------------- /django_yugabytedb/creation.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.postgresql.creation import ( 2 | DatabaseCreation as PGDatabaseCreation, 3 | ) 4 | 5 | 6 | class DatabaseCreation(PGDatabaseCreation): 7 | pass -------------------------------------------------------------------------------- /django_yugabytedb/features.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.postgresql.features import ( 2 | DatabaseFeatures as PGDatabaseFeatures, 3 | ) 4 | from django.utils.functional import cached_property 5 | from django import __version__ as _ver 6 | import os 7 | 8 | class DatabaseFeatures(PGDatabaseFeatures): 9 | 10 | # Minimum version of yugabytedb 11 | minimum_database_version = (2,14) 12 | 13 | # Refer https://github.com/yugabyte/yugabyte-db/issues/7764 14 | 15 | allows_group_by_lob = False 16 | supports_deferrable_unique_constraints = False 17 | uses_savepoints = True 18 | can_release_savepoints = True 19 | 20 | # With YB, transactions may start generating conflicts if one transaction does 21 | # "select for update". While in Postgres, the transactions wait. To overcome 22 | # this, YB users should implement a retry logic 23 | has_select_for_update = True 24 | has_select_for_update_of = True 25 | has_select_for_no_key_update = True 26 | supports_select_for_update_with_limit = True 27 | 28 | has_select_for_update_nowait = False 29 | has_select_for_update_skip_locked = False 30 | can_introspect_materialized_views = False 31 | can_rollback_ddl = False 32 | indexes_foreign_keys = True 33 | can_clone_databases = False 34 | supports_ignore_conflicts = True 35 | supports_covering_indexes = True 36 | 37 | supports_collation_on_charfield = False 38 | supports_collation_on_textfield = False 39 | supports_non_deterministic_collations = False 40 | supports_tablespaces = False 41 | 42 | @cached_property 43 | def django_test_expected_failures(self): 44 | base_expected_failures = super().django_test_expected_failures 45 | base_expected_failures.update({ 46 | # Deferrable constraints not honoured in child table deferred UPDATE scenario. 47 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/9288 48 | 'migrations.test_operations.OperationTests.test_add_field_m2m', 49 | 'migrations.test_operations.OperationTests.test_create_model_m2m', 50 | 51 | # Lack of Pessimistic Locking support which will need app to retry the transaction. 52 | 'migrations.test_operations.OperationTests.test_run_sql', 53 | 54 | # INDEX on column of type 'JSONB' not yet supported 55 | 'schema.tests.SchemaTests.test_func_index_json_key_transform', 56 | 'schema.tests.SchemaTests.test_func_index_json_key_transform_cast', 57 | 58 | }) 59 | 60 | 61 | if float(_ver[0:3]) <= 4.0 : 62 | base_expected_failures.update({ 63 | 64 | # YB does not allow changing the column type from integer to serial 65 | 'schema.tests.SchemaTests.test_alter_int_pk_to_autofield_pk', 66 | # YB does not allow changing the column type from serial to integer 67 | 'schema.tests.SchemaTests.test_alter_auto_field_to_integer_field', 68 | 69 | }) 70 | 71 | expected_failures = base_expected_failures 72 | 73 | yb_version = os.getenv('YB_VERSION') 74 | yb_version_major = yb_version.split('.')[0] 75 | yb_version_minor = yb_version.split('.')[1] 76 | 77 | if float(yb_version[0:4]) <= 2.18: 78 | expected_failures.update({ 79 | # Backfilling of existing rows when new column is added with default value is not yet implemented in yugabytedb. 80 | # The test inserts data and then tries to add columns with default value. 81 | # GH Issue : https://github.com/yugabyte/yugabyte-db/issues/4415 82 | 'migrations.test_operations.OperationTests.test_add_binaryfield', 83 | 'migrations.test_operations.OperationTests.test_add_charfield', 84 | 'migrations.test_operations.OperationTests.test_add_textfield', 85 | 'migrations.test_operations.OperationTests.test_alter_order_with_respect_to', 86 | 'schema.tests.SchemaTests.test_add_datefield_and_datetimefield_use_effective_default', 87 | 'schema.tests.SchemaTests.test_add_field_default_dropped', 88 | 'schema.tests.SchemaTests.test_add_field_default_transform', 89 | 'schema.tests.SchemaTests.test_add_field_use_effective_default', 90 | 91 | 92 | # Yugabyte does not allow changing column type from integer to bigint. 93 | 'migrations.test_operations.OperationTests.test_alter_fk_non_fk', 94 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/7762 95 | 'migrations.test_operations.OperationTests.test_autofield__bigautofield_foreignfield_growth', 96 | 97 | # YB does not allow changing the column test_blog.Blog.id type from smallint to integer 98 | 'migrations.test_operations.OperationTests.test_smallfield_autofield_foreignfield_growth', 99 | 'migrations.test_operations.OperationTests.test_smallfield_bigautofield_foreignfield_growth', 100 | 101 | # Yugabyte does not allow changing the column type from varchar(255) to text 102 | 'schema.tests.SchemaTests.test_alter', 103 | 104 | # CREATE TABLE "INTEGERPK" ("i" integer NOT NULL PRIMARY KEY, "j" integer NOT NULL UNIQUE); 105 | # INSERT INTO "INTEGERPK" ("j") VALUES (1) RETURNING "INTEGERPK"."i"; 106 | # Does not work with yugabytedb without the PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY clause. 107 | 'schema.tests.SchemaTests.test_alter_int_pk_to_bigautofield_pk', 108 | 109 | # Yugabyte does not allow changing the column type from varchar(31) to integer 110 | 'schema.tests.SchemaTests.test_char_field_with_db_index_to_fk', 111 | 112 | # The test is renaming the column 'name' to 'display_name'. 113 | # The size of column 'name' is varchar(255). 114 | # The column 'display_name' is getting renamed with varchar(254) in the test. 115 | # Yugabyte does not support changing the column type from varchar(255) to varchar(254). Hence the column is not getting renamed to 'display_name' 116 | 'schema.tests.SchemaTests.test_rename', 117 | 118 | # Yugabyte does not allow changing the column type from text to integer 119 | 'schema.tests.SchemaTests.test_text_field_with_db_index_to_fk', 120 | 121 | 122 | }) 123 | 124 | if float(_ver[0:3]) >= 4.2: 125 | expected_failures.update({ 126 | # Backfilling of existing rows when new column is added with default value is not yet implemented in yugabytedb. 127 | # The test inserts data and then tries to add columns with default value. 128 | # GH Issue : https://github.com/yugabyte/yugabyte-db/issues/4415 129 | 'schema.tests.SchemaTests.test_add_db_comment_and_default_charfield', 130 | }) 131 | 132 | if (yb_version_major == '2024' and yb_version_minor == '1') or float(yb_version[0:4]) < 2.23: 133 | expected_failures.update({ 134 | # Alter table Add column Unique is not yet supported. 135 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/1124 136 | 'schema.tests.SchemaTests.test_add_field_o2o_nullable', 137 | 138 | # ALTER TABLE name ADD [COLUMN] [IF NOT EXISTS] colname integer GENERATED ALWAYS AS IDENTITY [PRIMARY KEY] is not supported. 139 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/1124 140 | 'schema.tests.SchemaTests.test_add_auto_field', 141 | 142 | # Dropping a primary key constraint is not yet supported 143 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/8735 144 | 'schema.tests.SchemaTests.test_alter_not_unique_field_to_primary_key', 145 | 'schema.tests.SchemaTests.test_primary_key', 146 | 147 | # Alter table Add column Unique is not yet supported. 148 | # GH Issue: https://github.com/yugabyte/yugabyte-db/issues/1124 149 | 'schema.tests.SchemaTests.test_indexes', 150 | 151 | }) 152 | 153 | 154 | return expected_failures 155 | -------------------------------------------------------------------------------- /django_yugabytedb/introspection.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.postgresql.introspection import ( 2 | DatabaseIntrospection as PGDatabaseIntrospection, 3 | ) 4 | 5 | 6 | class DatabaseIntrospection(PGDatabaseIntrospection): 7 | # The default access method for Yugabyte is lsm as compared to postgres btree 8 | index_default_access_method = "lsm" -------------------------------------------------------------------------------- /django_yugabytedb/operations.py: -------------------------------------------------------------------------------- 1 | from django.db.backends.postgresql.operations import ( 2 | DatabaseOperations as PGDatabaseOperations, 3 | ) 4 | 5 | 6 | class DatabaseOperations(PGDatabaseOperations): 7 | pass 8 | -------------------------------------------------------------------------------- /django_yugabytedb/schema.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | from django.db.backends.postgresql.schema import ( 4 | DatabaseSchemaEditor as PGDatabaseSchemaEditor, 5 | ) 6 | logger = logging.getLogger('yb_backend.schema') 7 | 8 | class DatabaseSchemaEditor(PGDatabaseSchemaEditor): 9 | def _alter_field(self, model, old_field, new_field, old_type, new_type, 10 | old_db_params, new_db_params, strict=False): 11 | 12 | if self.connection.yugabytedb_version <= (2,18): 13 | 14 | # Refer https://github.com/yugabyte/yugabyte-db/issues/7762 15 | if old_type != new_type: 16 | # Increasing the size of varchar is supported 17 | if old_type.lower().startswith("varchar(") and new_type.lower().startswith("varchar("): 18 | conv = lambda i: i or 8 19 | o_len = int(old_type[8:conv(old_type.index(")"))]) 20 | n_len = int(new_type[8:conv(new_type.index(")"))]) 21 | if o_len > n_len: 22 | logger.warning("Warning: YB does not allow changing the column %s type from %s to %s " % ( 23 | old_field, old_type, new_type)) 24 | return 25 | else: 26 | logger.warning("Warning: YB does not allow changing the column %s type from %s to %s " % (old_field, old_type, new_type)) 27 | return 28 | super()._alter_field(model, old_field, new_field, old_type, new_type, 29 | old_db_params, new_db_params, strict) 30 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | setuptools>=42 2 | wheel 3 | asgiref>=3.3.1 4 | Django>=3.1.6 5 | pytz>=2021.1 6 | sqlparse>=0.4.1 7 | psycopg2-yugabytedb~=2.9.3.post0 8 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | license_files=LICENSE 3 | 4 | [flake8] 5 | max-line-length = 119 6 | 7 | [options] 8 | python_requires = >=3.8 9 | 10 | [isort] 11 | combine_as_imports = true 12 | default_section = THIRDPARTY 13 | include_trailing_comma = true 14 | known_first_party = yugabyte 15 | line_length = 79 16 | multi_line_output = 5 17 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | import os 4 | import sys 5 | from distutils.sysconfig import get_python_lib 6 | 7 | from setuptools import setup 8 | 9 | CURRENT_PYTHON = sys.version_info[:2] 10 | REQUIRED_PYTHON = (3, 8) 11 | 12 | # This check and everything above must remain compatible with Python 2.7. 13 | if CURRENT_PYTHON < REQUIRED_PYTHON: 14 | sys.stderr.write(""" 15 | ========================== 16 | Unsupported Python version 17 | ========================== 18 | 19 | This version of Django requires Python {}.{}, but you're trying to 20 | install it on Python {}.{}. 21 | 22 | This may be because you are using a version of pip that doesn't 23 | understand the python_requires classifier. Make sure you 24 | have pip >= 9.0 and setuptools >= 24.2, then try again: 25 | 26 | $ python -m pip install --upgrade pip setuptools 27 | $ python -m pip install django 28 | 29 | This will install the latest version of Django which works on your 30 | version of Python. If you can't upgrade your pip (or Python), request 31 | an older version of Django: 32 | 33 | $ python -m pip install "django<2" 34 | """.format(*(REQUIRED_PYTHON + CURRENT_PYTHON))) 35 | sys.exit(1) 36 | 37 | classifiers = """\ 38 | Development Status :: 5 - Production/Stable 39 | Environment :: Web Environment 40 | Framework :: Django 41 | Framework :: Django :: 3.2 42 | Framework :: Django :: 4.0 43 | Intended Audience :: Developers 44 | Operating System :: OS Independent 45 | Programming Language :: Python :: 3.8 46 | Programming Language :: Python :: 3.9 47 | Topic :: Internet :: WWW/HTTP 48 | Topic :: Internet :: WWW/HTTP :: Dynamic Content 49 | Topic :: Internet :: WWW/HTTP :: WSGI 50 | Topic :: Software Development :: Libraries :: Application Frameworks 51 | Topic :: Software Development :: Libraries :: Python Modules 52 | """ 53 | try: 54 | f = open("README.rst") 55 | readme = f.read() 56 | f.close() 57 | except Exception: 58 | print("failed to read readme: ignoring...") 59 | readme = __doc__ 60 | setup(name="django-yugabytedb", 61 | version = "4.2.0.1", 62 | url = 'https://www.yugabyte.com/', 63 | author = 'Yugabyte', 64 | author_email = 'hbhanawat@yugabyte.com', 65 | maintainer="Sfurti Sarah", 66 | maintainer_email="ssarah@yugabyte.com", 67 | description=readme.split("\n")[0], 68 | long_description="\n".join(readme.split("\n")[2:]).lstrip(), 69 | license = 'Apache', 70 | classifiers =[x for x in classifiers.split("\n") if x], 71 | project_urls ={ 72 | 'Documentation' : 'https://docs.yugabyte.com/', 73 | 'Code': 'https://github.com/yugabyte/yb-django' 74 | } 75 | ) 76 | -------------------------------------------------------------------------------- /yugabyte_settings.py: -------------------------------------------------------------------------------- 1 | DATABASES = { 2 | 'default': { 3 | 'ENGINE': 'django_yugabytedb', 4 | 'NAME': 'yugabyte', 5 | 'HOST': 'localhost', 6 | 'PORT': 5433, 7 | 'USER': 'yugabyte' 8 | }, 9 | 'other': { 10 | 'ENGINE': 'django_yugabytedb', 11 | 'NAME': 'yugabyte', 12 | 'HOST': 'localhost', 13 | 'PORT': 5433, 14 | 'USER': 'yugabyte' 15 | }, 16 | } 17 | SECRET_KEY = 'yb_secret_key' 18 | --------------------------------------------------------------------------------