├── .devcontainer ├── Dockerfile └── devcontainer.json ├── .github └── workflows │ ├── style.yml │ └── tests.yml ├── .gitignore ├── .styleci.yml ├── .vscode └── launch.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── composer.json ├── phpunit.xml.dist ├── pint.json ├── src ├── Connect │ ├── SingleStoreConnection.php │ └── SingleStoreConnector.php ├── Exceptions │ ├── SingleStoreDriverException.php │ └── UnsupportedFunctionException.php ├── Fluency │ └── SpatialIndexCommand.php ├── Query │ ├── SingleStoreQueryBuilder.php │ └── SingleStoreQueryGrammar.php ├── Schema │ ├── Blueprint.php │ ├── Blueprint │ │ ├── AddsTableFlags.php │ │ ├── InlinesIndexes.php │ │ └── ModifiesIndexes.php │ ├── Grammar │ │ ├── CompilesKeys.php │ │ └── ModifiesColumns.php │ ├── SingleStoreSchemaBuilder.php │ └── SingleStoreSchemaGrammar.php └── SingleStoreProvider.php └── tests ├── BaseTest.php ├── Hybrid ├── ChangeColumnTest.php ├── CreateTable │ ├── ComputedColumnsTest.php │ ├── IncrementWithoutPrimaryKeyTest.php │ ├── MiscCreateTest.php │ ├── SeriesTimestampTest.php │ ├── ShardKeysTest.php │ ├── SortKeysTest.php │ ├── SparseModifiersTest.php │ ├── SpatialTest.php │ ├── TableModifiersTest.php │ └── UniqueKeysTest.php ├── DropAllTablesTest.php ├── FulltextTest.php ├── GroupLimitTest.php ├── HybridTestHelpers.php ├── Json │ ├── JsonContainsTest.php │ ├── JsonKeypathsTest.php │ ├── JsonUpdateTest.php │ └── JsonWhereTest.php ├── OptionTest.php ├── OrderByTest.php ├── OverridesGetConnection.php ├── RenameTest.php ├── TransactionsTest.php └── UnionTest.php ├── Integration └── .gitkeep └── Unit └── .gitkeep /.devcontainer/Dockerfile: -------------------------------------------------------------------------------- 1 | ARG VARIANT="0-8" 2 | FROM mcr.microsoft.com/devcontainers/php:${VARIANT} 3 | 4 | ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/ 5 | RUN chmod +x /usr/local/bin/install-php-extensions 6 | RUN install-php-extensions pdo_mysql -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the README at: 2 | // https://github.com/microsoft/vscode-dev-containers/tree/v0.231.6/containers/php 3 | { 4 | "name": "PHP", 5 | "build": { 6 | "dockerfile": "Dockerfile", 7 | "args": { 8 | // Update VARIANT to pick a PHP version: 8, 8.1, 8.0, 7, 7.4 9 | // Append -bullseye or -buster to pin to an OS version. 10 | // Use -bullseye variants on local on arm64/Apple Silicon. 11 | "VARIANT": "8.2" 12 | } 13 | }, 14 | // Set *default* container specific settings.json values on container create. 15 | "customizations": { 16 | "vscode": { 17 | "settings": { 18 | "php.validate.executablePath": "/usr/local/bin/php" 19 | }, 20 | // Add the IDs of extensions you want installed when the container is created. 21 | "extensions": [ 22 | "xdebug.php-debug", 23 | "bmewburn.vscode-intelephense-client", 24 | "emallin.phpunit" 25 | ] 26 | } 27 | }, 28 | // Use 'postCreateCommand' to run commands after the container is created. 29 | "postCreateCommand": "composer install", 30 | "forwardPorts": [] 31 | } -------------------------------------------------------------------------------- /.github/workflows/style.yml: -------------------------------------------------------------------------------- 1 | name: Fix Code Styling 2 | 3 | on: [push] 4 | 5 | jobs: 6 | lint: 7 | runs-on: ubuntu-22.04 8 | 9 | steps: 10 | - name: Checkout code 11 | uses: actions/checkout@v3 12 | 13 | - name: Setup PHP 14 | uses: shivammathur/setup-php@v2 15 | with: 16 | php-version: "8.1" 17 | extensions: json, dom, curl, libxml, mbstring 18 | coverage: none 19 | 20 | - name: Install Pint 21 | run: composer global require laravel/pint 22 | 23 | - name: Run Pint 24 | run: pint 25 | 26 | - name: Commit linted files 27 | run: | 28 | git config user.name "github-actions[bot]" 29 | git config user.email "github-actions[bot]@users.noreply.github.com" 30 | git add . 31 | if git diff --cached --quiet; then 32 | echo "No changes to commit." 33 | else 34 | git commit -m "Fix code styling" 35 | git push 36 | fi 37 | -------------------------------------------------------------------------------- /.github/workflows/tests.yml: -------------------------------------------------------------------------------- 1 | name: tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | types: [opened, synchronize, reopened] 9 | 10 | schedule: 11 | - cron: "0 0 * * *" 12 | 13 | jobs: 14 | test: 15 | runs-on: ubuntu-22.04 16 | if: "!contains(github.event.head_commit.message, 'ci skip')" 17 | strategy: 18 | fail-fast: false 19 | matrix: 20 | php: [8.2, 8.3, 8.4] 21 | laravel: [12.*] 22 | dependency-version: [prefer-lowest, prefer-stable] 23 | include: 24 | - laravel: 12.* 25 | testbench: 10.* 26 | 27 | name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.dependency-version }} 28 | 29 | services: 30 | singlestore: 31 | image: ghcr.io/singlestore-labs/singlestoredb-dev:latest 32 | ports: 33 | - "3306:3306" 34 | env: 35 | # this license key is only authorized for use in SingleStore laravel tests and is heavily restricted 36 | # if you want a free SingleStore license for your own use please visit https://www.singlestore.com/cloud-trial/ 37 | SINGLESTORE_LICENSE: BGIxODZiYTg1YWUxYjRlODRhYzRjMGFmYTA1OTkxYzgyAAAAAAAAAAABAAAAAAAAACgwNQIZANx4NIXJ7CWvKYYb3wIyRXxBY7fdAnLeSwIYLy2Q0jA124GAkl04yuGrD59Zpv85DVYXAA== 38 | ROOT_PASSWORD: "test" 39 | 40 | steps: 41 | - name: Checkout code 42 | uses: actions/checkout@v3 43 | 44 | - name: Cache dependencies 45 | uses: actions/cache@v3 46 | with: 47 | path: ~/.composer/cache/files 48 | key: dependencies-laravel-${{ matrix.laravel }}-php-${{ matrix.php }}-composer-${{ hashFiles('composer.json') }} 49 | 50 | - name: Setup PHP 51 | uses: shivammathur/setup-php@v2 52 | with: 53 | php-version: ${{ matrix.php }} 54 | extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick 55 | coverage: none 56 | 57 | - name: Install dependencies 58 | run: | 59 | composer self-update 60 | composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" --no-interaction --no-update 61 | composer update --${{ matrix.dependency-version }} --prefer-dist --no-interaction 62 | 63 | - name: Execute Unit Tests 64 | run: vendor/bin/phpunit 65 | 66 | - name: SingleStore Container Logs 67 | run: docker logs $(docker ps -ql) 68 | 69 | - name: Create Test Database 70 | run: | 71 | mysql -h 127.0.0.1 -u root -ptest -e "create database test" 72 | 73 | - name: Execute Integration Tests 74 | run: vendor/bin/phpunit 75 | env: 76 | HYBRID_INTEGRATION: 1 77 | DB_DATABASE: test 78 | DB_USERNAME: root 79 | DB_PASSWORD: test 80 | DB_HOST: 127.0.0.1 81 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .env 2 | /vendor/ 3 | .phpunit.result.cache 4 | composer.lock 5 | .idea 6 | -------------------------------------------------------------------------------- /.styleci.yml: -------------------------------------------------------------------------------- 1 | preset: laravel 2 | 3 | disabled: 4 | - concat_without_spaces 5 | - not_operator_with_successor_space 6 | - cast_spaces 7 | - trailing_comma_in_multiline_array 8 | - heredoc_to_nowdoc 9 | - phpdoc_summary 10 | 11 | risky: false -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "0.2.0", 3 | "configurations": [ 4 | { 5 | "name": "Listen for Xdebug", 6 | "type": "php", 7 | "request": "launch", 8 | "port": 9000 9 | } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for 6 | everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity 7 | and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, 8 | or sexual identity and orientation. 9 | 10 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to a positive environment for our community include: 15 | 16 | * Demonstrating empathy and kindness toward other people 17 | * Being respectful of differing opinions, viewpoints, and experiences 18 | * Giving and gracefully accepting constructive feedback 19 | * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 20 | * Focusing on what is best not just for us as individuals, but for the overall community 21 | 22 | Examples of unacceptable behavior include: 23 | 24 | * The use of sexualized language or imagery, and sexual attention or advances of any kind 25 | * Trolling, insulting or derogatory comments, and personal or political attacks 26 | * Public or private harassment 27 | * Publishing others' private information, such as a physical or email address, without their explicit permission 28 | * Other conduct which could reasonably be considered inappropriate in a professional setting 29 | 30 | ## Enforcement Responsibilities 31 | 32 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take 33 | appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, 34 | or harmful. 35 | 36 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, 37 | issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for 38 | moderation decisions when appropriate. 39 | 40 | ## Scope 41 | 42 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing 43 | the community in public spaces. Examples of representing our community include using an official e-mail address, posting 44 | via an official social media account, or acting as an appointed representative at an online or offline event. 45 | 46 | ## Enforcement 47 | 48 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible 49 | for enforcement at bhayes@singlestore.com. All complaints will be reviewed and investigated promptly and fairly. 50 | 51 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 52 | 53 | ## Enforcement Guidelines 54 | 55 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem 56 | in violation of this Code of Conduct: 57 | 58 | ### 1. Correction 59 | 60 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the 61 | community. 62 | 63 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation 64 | and an explanation of why the behavior was inappropriate. A public apology may be requested. 65 | 66 | ### 2. Warning 67 | 68 | **Community Impact**: A violation through a single incident or series of actions. 69 | 70 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including 71 | unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding 72 | interactions in community spaces as well as external channels like social media. Violating these terms may lead to a 73 | temporary or permanent ban. 74 | 75 | ### 3. Temporary Ban 76 | 77 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 78 | 79 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified 80 | period of time. No public or private interaction with the people involved, including unsolicited interaction with those 81 | enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 82 | 83 | ### 4. Permanent Ban 84 | 85 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate 86 | behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 87 | 88 | **Consequence**: A permanent ban from any sort of public interaction within the community. 89 | 90 | ## Attribution 91 | 92 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at 93 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 94 | 95 | Community Impact Guidelines were inspired 96 | by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 97 | 98 | [homepage]: https://www.contributor-covenant.org 99 | 100 | For answers to common questions about this code of conduct, see the FAQ at 101 | https://www.contributor-covenant.org/faq. Translations are available at 102 | https://www.contributor-covenant.org/translations. -------------------------------------------------------------------------------- /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 2021 SingleStore 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SingleStore Driver for Laravel 2 | 3 | [![Latest Stable Version](https://poser.pugx.org/singlestoredb/singlestoredb-laravel/v)](https://packagist.org/packages/singlestoredb/singlestoredb-laravel) [![Total Downloads](https://poser.pugx.org/singlestoredb/singlestoredb-laravel/downloads)](https://packagist.org/packages/singlestoredb/singlestoredb-laravel) [![License](https://poser.pugx.org/singlestoredb/singlestoredb-laravel/license)](https://packagist.org/packages/singlestoredb/singlestoredb-laravel) [![PHP Version Require](https://poser.pugx.org/singlestoredb/singlestoredb-laravel/require/php)](https://packagist.org/packages/singlestoredb/singlestoredb-laravel) [![Github Actions status image](https://github.com/singlestore-labs/singlestoredb-laravel-driver/actions/workflows/tests.yml/badge.svg)](https://github.com/singlestore-labs/singlestoredb-laravel-driver/actions) 4 | 5 | This repository contains the official SingleStoreDB Driver for Laravel. This driver wraps the official MySQL support in Laravel in order to make it work nicer with SingleStoreDB. Specifically, this driver provides the following advantages over vanilla Laravel MySQL support: 6 | 7 | - Extensions to Eloquent allowing specific SingleStoreDB features to be specified through the Eloquent api. See [Migrations](#migrations) for supported features. 8 | - Integration tested against SingleStoreDB across a matrix of PHP and Laravel versions. 9 | - JSON column support 10 | - Other compatibility fixes in query generation 11 | 12 | ## TOC 13 | 14 | - [Install](#install) 15 | - [Usage](#usage) 16 | - [Issues connecting to SingleStore Managed Service](#issues-connecting-to-singlestore-managed-service) 17 | - [Persistent Connections (performance optimization)](#persistent-connections-performance-optimization) 18 | - [Order by in delete and update](#order-by-in-delete-and-update) 19 | - [PHP Versions before 8.1](#php-versions-before-81) 20 | - [Migrations](#migrations) 21 | - [Universal Storage Tables (Columnstore)](#universal-storage-tables-columnstore) 22 | - [Rowstore Tables](#rowstore-tables) 23 | - [Reference Tables](#reference-tables) 24 | - [Global Temporary Tables](#global-temporary-tables) 25 | - [Sparse Columns](#sparse-columns) 26 | - [Sparse Tables](#sparse-tables) 27 | - [Shard Keys](#shard-keys) 28 | - [Sort Keys](#sort-keys) 29 | - [Unique Keys](#unique-keys) 30 | - [Hash Keys](#hash-keys) 31 | - [Series Timestamps](#series-timestamps) 32 | - [Computed Columns](#computed-columns) 33 | - [Increment Columns without Primary Key](#increment-columns-without-primary-key) 34 | - [Full-text search using FULLTEXT indexes](#full-text-search-using-fulltext-indexes) 35 | - [Testing](#testing) 36 | - [License](#license) 37 | - [Resources](#resources) 38 | - [User agreement](#user-agreement) 39 | 40 | ## Install 41 | 42 | You can install the package via composer: 43 | 44 | ```shell 45 | composer require singlestoredb/singlestoredb-laravel 46 | ``` 47 | 48 | **This package requires pdo_mysql** to be installed. If you aren't sure check to see if `pdo_mysql` is listed when you run `php -i`. 49 | 50 | ## Usage 51 | 52 | To enable the driver, head to your `config/database.php` file and create a new entry for SingleStore in your `connections`, and update your `default` to point to that new connection: 53 | 54 | ```php 55 | [ 56 | 'default' => env('DB_CONNECTION', 'singlestore'), 57 | 58 | 'connections' => [ 59 | 'singlestore' => [ 60 | 'driver' => 'singlestore', 61 | 'url' => env('DATABASE_URL'), 62 | 'host' => env('DB_HOST'), 63 | 'port' => env('DB_PORT'), 64 | 'database' => env('DB_DATABASE'), 65 | 'username' => env('DB_USERNAME'), 66 | 'password' => env('DB_PASSWORD'), 67 | 'unix_socket' => env('DB_SOCKET'), 68 | 'charset' => 'utf8mb4', 69 | 'collation' => 'utf8mb4_unicode_ci', 70 | 'prefix' => '', 71 | 'prefix_indexes' => true, 72 | 'strict' => true, 73 | 'engine' => null, 74 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 75 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 76 | PDO::ATTR_EMULATE_PREPARES => true, 77 | ]) : [], 78 | ], 79 | ] 80 | ] 81 | ``` 82 | 83 | > The SingleStore driver is an extension of the MySQL driver, so you could also just change your `driver` from `mysql` to `singlestore`. 84 | 85 | In case you want to store failed jobs in SingleStore, then make sure you also set it as the `database` in your `config/queue.php` file. At which point, you may actually prefer to set `DB_CONNECTION='singlestore'` in your environment variables. 86 | 87 | ```php 88 | 'failed' => [ 89 | 'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'), 90 | 'database' => env('DB_CONNECTION', 'singlestore'), 91 | 'table' => 'failed_jobs', 92 | ], 93 | ``` 94 | 95 | ## Issues connecting to SingleStore Managed Service 96 | 97 | If you are encountering issues connecting to the SingleStore Managed Service, it may be due to your environment not being able to verify the SSL certificate used to secure connections. You can fix this by downloading and manually specifying the SingleStore certificate file. 98 | 99 | * [Download the file here][singlestore-pem] 100 | * In the Laravel SingleStore connection configuration, point the variable `PDO::MYSQL_ATTR_SSL_CA` at `singlestore_bundle.pem`: 101 | 102 | ```php 103 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 104 | PDO::MYSQL_ATTR_SSL_CA => 'path/to/singlestore_bundle.pem', 105 | PDO::ATTR_EMULATE_PREPARES => true, 106 | ]) : [], 107 | ``` 108 | 109 | ## Persistent Connections (performance optimization) 110 | 111 | In general, we recommend enabling `PDO::ATTR_PERSISTENT` when connecting to SingleStoreDB. This is because opening new connections to SingleStoreDB is very expensive compared to running many transactional queries. By using `PDO::ATTR_PERSISTENT`, you can greatly improve the performance of transactional workloads. 112 | 113 | The only downside to using persistent connections is that you need to ensure that transactions are correctly cleaned up as well as being careful when changing session variables or the context database. [You can read more about this feature in the official documentation on php.net][attr_persistent]. 114 | 115 | Also, note that SingleStoreDB in it's default configuration can handle very large numbers of idle connections with no performance impact. The default is roughly 100,000 idle connections per aggregator, but that can be set much higher if your server can handle it. 116 | 117 | To enable this feature, simply update your options to include `PDO::ATTR_PERSISTENT => true`: 118 | 119 | ```php 120 | 'options' => extension_loaded('pdo_mysql') ? array_filter([ 121 | PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'), 122 | PDO::ATTR_EMULATE_PREPARES => true, 123 | PDO::ATTR_PERSISTENT => true, 124 | ]) : [], 125 | ``` 126 | 127 | ## `ORDER BY` Clause in `DELETE` and `UPDATE` Queries 128 | 129 | SingleStore does not support the `ORDER BY` clause in the `DELETE` and `UPDATE` queries. 130 | Issuing queries similar to the following will return an error. 131 | 132 | ```php 133 | DB::table('test')->orderBy('id', 'asc')->update(['id' => 1, 'a' => 'b']); 134 | DB::table('test')->orderBy('id', 'asc')->delete(); 135 | ``` 136 | 137 | You can configure the driver to ignore `orderBy` in `delete()` and `update()` requests by enabling `ignore_order_by_in_deletes` and 138 | `ignore_order_by_in_updates` in the connection configuration, respectively. For example: 139 | 140 | ```php 141 | [ 142 | 'default' => env('DB_CONNECTION', 'singlestore'), 143 | 144 | 'connections' => [ 145 | 'singlestore' => [ 146 | 'driver' => 'singlestore', 147 | 'ignore_order_by_in_deletes' => true, 148 | 'ignore_order_by_in_updates' => true, 149 | ... 150 | ], 151 | ] 152 | ] 153 | ``` 154 | 155 | Note that when `orderBy` is ignored, it may result in deletion/update of different rows if query contains LIMIT or OFFSET. 156 | 157 | Example: 158 | ```php 159 | DB::table('user')->orderBy('score', 'asc')->limit(5)->delete(); 160 | ``` 161 | In the following query when ORDER BY is ignored - 5 random users will be deleted instead of 5 users with the lowest score. 162 | 163 | ## PHP Versions before 8.1 164 | 165 | In PHP versions before 8.1, the flag `PDO::ATTR_EMULATE_PREPARES` results in a bug by which all attributes returned by MySQL (and 166 | SingleStoreDB) are returned as strings. 167 | 168 | For example, a table with a column named `user_id` and a type of `int(10)`, if the row value is `5423` we would 169 | get a string like `"5423"` in PHP. 170 | 171 | This is a historic and known bug: 172 | 173 | - https://stackoverflow.com/a/58830039/3275796 174 | - https://github.com/php/php-src/blob/7b34db0659dda933b1146a0ff249f25acca1d669/UPGRADING#L130-L134 175 | 176 | The best method to solve this is to upgrade to PHP 8.1 or higher. If that's not possible, [Eloquent's attribute casting] is the next best solution. 177 | 178 | ## Migrations 179 | 180 | This driver provides many SingleStore specific methods for creating or modifying tables. They are listed below. For more information see the [create table] docs on SingleStore. 181 | 182 | ### Universal Storage Tables (Columnstore) 183 | 184 | By default, tables created by this driver will use [SingleStoreDB Universal Storage][columnstore]. Universal Storage leverages both column and row oriented data structures to automatically optimize storage for transactional and analytical workloads. In general, you should use this table type for all tables unless you profile your workload and determine that another table type is better. 185 | 186 | To create a table, you can simply use `Schema::create`: 187 | 188 | ```php 189 | Schema::create('table', function (Blueprint $table) { 190 | // ... column definitions, indexes, table options 191 | }); 192 | ``` 193 | 194 | ### Rowstore Tables 195 | 196 | To create a [rowstore] table, use the `rowstore` method. Rowstore tables are optimized for low-latency transactional workloads with high concurrency at the expense of memory. In general, we recommend using Universal Storage (see above) and benchmarking your workload before using a rowstore table. 197 | 198 | ```php 199 | Schema::create('table', function (Blueprint $table) { 200 | $table->rowstore(); 201 | 202 | // ... 203 | }); 204 | ``` 205 | 206 | ### Reference Tables 207 | 208 | To create a [reference table], you may use the `reference` method. Reference tables are fully replicated to every node in the cluster. This means that if you store 1000 rows in a reference table, those 1000 rows will be copied many times. Because of this you should only store small amounts of data in reference tables, and only when you need to reference that data via joins against non-collocated data in other tables. Inserts and updates to reference tables will also run slower due to the high replication overhead. 209 | 210 | ```php 211 | Schema::create('table', function (Blueprint $table) { 212 | $table->reference(); 213 | 214 | // ... 215 | }); 216 | ``` 217 | 218 | ### Global Temporary Tables 219 | 220 | To create a [global temporary table], you may use the `global` method on the table. 221 | 222 | ```php 223 | Schema::create('table', function (Blueprint $table) { 224 | $table->rowstore(); 225 | $table->temporary(); 226 | $table->global(); 227 | 228 | // ... 229 | }); 230 | ``` 231 | 232 | You may also use either of the following two methods: 233 | 234 | ```php 235 | // Fluent 236 | $table->rowstore()->temporary()->global(); 237 | 238 | // As an argument to `temporary`. 239 | $table->temporary($global = true); 240 | ``` 241 | 242 | ### Sparse Columns 243 | 244 | You can mark particular columns as [sparse] fluently by appending `sparse` to the column's definition. This only applies to Rowstore tables. 245 | 246 | ```php 247 | Schema::create('table', function (Blueprint $table) { 248 | $table->rowstore(); 249 | 250 | $table->string('name')->nullable()->sparse(); 251 | }); 252 | ``` 253 | 254 | ### Sparse Tables 255 | 256 | You can mark particular entire tables as [sparse] fluently by appending `sparse` to the column's definition. This only applies to Rowstore tables. 257 | 258 | ```php 259 | Schema::create('table', function (Blueprint $table) { 260 | $table->rowstore(); 261 | 262 | $table->string('name'); 263 | 264 | $table->sparse(); 265 | }); 266 | ``` 267 | 268 | ### Shard Keys 269 | 270 | You can add a [shard key] to your tables using the standalone `shardKey` method, or fluently by appending `shardKey` to the column definition. 271 | 272 | ```php 273 | Schema::create('table', function (Blueprint $table) { 274 | $table->string('name'); 275 | 276 | $table->shardKey('name'); 277 | }); 278 | 279 | Schema::create('table', function (Blueprint $table) { 280 | $table->string('name')->shardKey(); 281 | }); 282 | 283 | Schema::create('table', function (Blueprint $table) { 284 | $table->string('f_name'); 285 | $table->string('l_name'); 286 | 287 | $table->shardKey(['f_name', 'l_name']); 288 | }); 289 | ``` 290 | 291 | ### Sort Keys 292 | 293 | You can add a [sort key] to your tables using the standalone `sortKey` method, or fluently by appending `sortKey` to the column definition. 294 | 295 | ```php 296 | Schema::create('table', function (Blueprint $table) { 297 | $table->string('name'); 298 | 299 | $table->sortKey('name'); 300 | }); 301 | 302 | Schema::create('table', function (Blueprint $table) { 303 | $table->string('name')->sortKey(); 304 | }); 305 | 306 | Schema::create('table', function (Blueprint $table) { 307 | $table->string('f_name'); 308 | $table->string('l_name'); 309 | 310 | $table->sortKey(['f_name', 'l_name']); 311 | }); 312 | ``` 313 | 314 | Sort keys sort in ascending order by default. If you would like to create a sort key which sorts descending you can set the key direction to `desc`. 315 | 316 | ```php 317 | Schema::create('table', function (Blueprint $table) { 318 | $table->string('name'); 319 | 320 | $table->sortKey('name', 'desc'); 321 | }); 322 | 323 | Schema::create('table', function (Blueprint $table) { 324 | $table->string('name')->sortKey('desc'); 325 | }); 326 | ``` 327 | 328 | You may also define the sort key direction per-column using the following syntax: 329 | 330 | ```php 331 | Schema::create('table', function (Blueprint $table) { 332 | $table->string('f_name'); 333 | $table->string('l_name'); 334 | 335 | $table->sortKey([['f_name', 'asc'], ['l_name', 'desc']]); 336 | }); 337 | ``` 338 | 339 | Sometimes you may want to tune [columnstore][columnstore-tuning] per table. You can do it by appending `with` fluently to the `sortKey` definition. 340 | 341 | ```php 342 | Schema::create('table', function (Blueprint $table) { 343 | $table->string('name'); 344 | 345 | $table->sortKey('name')->with(['columnstore_segment_rows' => 100000]); 346 | }); 347 | 348 | Schema::create('table', function (Blueprint $table) { 349 | $table->string('name')->sortKey()->with(['columnstore_segment_rows' => 100000]); 350 | }); 351 | ``` 352 | 353 | However, you may want to tune it without setting a column as sort key. You can do that by creating an empty `sortKey` definition: 354 | 355 | ```php 356 | Schema::create('table', function (Blueprint $table) { 357 | $table->string('name'); 358 | 359 | $table->sortKey()->with(['columnstore_segment_rows' => 100000]); 360 | }); 361 | ``` 362 | 363 | ### Unique Keys 364 | 365 | You can add an `unique key` to your tables using the standalone `unique` method, or fluently by appending `unique` to the column definition. 366 | 367 | > **Note** 368 | > SingleStore requires that the shard key is contained within an unique key. This means that in most cases you can't use the fluent api as you will likely need to specify more than one column. This restriction does not apply to reference tables. 369 | 370 | ```php 371 | Schema::create('table', function (Blueprint $table) { 372 | $table->string('key'); 373 | $table->string('val'); 374 | 375 | $table->shardKey('key'); 376 | $table->unique(['key', 'val']); 377 | }); 378 | 379 | Schema::create('table', function (Blueprint $table) { 380 | $table->reference(); 381 | $table->string('name')->unique(); 382 | }); 383 | ``` 384 | 385 | ### Hash Keys 386 | 387 | You can add a `hash key` to your tables using the third argument to the `index` 388 | function. Note that by default, indexes on Universal Storage Tables 389 | (Columnstore) are always hash indexes, so a simple `.index(foo)` is usually 390 | sufficient. On Rowstore tables this syntax is needed to create a hash index. 391 | 392 | ```php 393 | Schema::create('table', function (Blueprint $table) { 394 | $table->string('name'); 395 | $table->index('name', 'name_idx', 'hash'); 396 | }); 397 | ``` 398 | 399 | ### Series Timestamps 400 | To denote a column as a series timestamp, use the `seriesTimestamp` column modifier. 401 | 402 | ```php 403 | Schema::create('table', function (Blueprint $table) { 404 | $table->datetime('created_at')->seriesTimestamp(); 405 | 406 | // Or make it sparse 407 | $table->datetime('deleted_at')->nullable()->seriesTimestamp()->sparse(); 408 | }); 409 | ``` 410 | 411 | ### Computed Columns 412 | 413 | SingleStore does not support virtual computed columns. You must use Laravel's [`storedAs`] method to create a [persisted computed column]. 414 | 415 | ```php 416 | Schema::create('test', function (Blueprint $table) { 417 | $table->integer('a'); 418 | $table->integer('b'); 419 | $table->integer('c')->storedAs('a + b'); 420 | }); 421 | ``` 422 | 423 | ### Increment Columns without Primary Key 424 | 425 | Sometimes you may want to set a custom primary key. However if your table has an int `increment` column, Laravel, by default, always sets this column as the primary key. Even if you manually set another one. This behavior can be disabled using the `withoutPrimaryKey` method. 426 | 427 | ```php 428 | Schema::create('test', function (Blueprint $table) { 429 | $table->id()->withoutPrimaryKey(); 430 | $table->uuid('uuid'); 431 | 432 | $table->primary(['id', 'uuid']); 433 | }); 434 | ``` 435 | 436 | ### Full-text search using FULLTEXT indexes 437 | 438 | SingleStoreDB supports full-text search across text columns in a columnstore table using the `FULLTEXT` index type. 439 | 440 | Keep in mind that `FULLTEXT` is only supported when using the `utf8_unicode_ci` collation. An exception will be thrown if you try to add the index to a column with an unsupported collation. 441 | 442 | ```php 443 | Schema::create('test', function (Blueprint $table) { 444 | $table->id(); 445 | $table->text('first_name')->collation('utf8_unicode_ci'); 446 | 447 | $table->fullText(['first_name']); 448 | }); 449 | ``` 450 | 451 | ## Testing 452 | 453 | Execute the tests using PHPUnit 454 | ``` 455 | ./vendor/bin/phpunit 456 | ``` 457 | 458 | To test against an active SingleStore database, create a `.env` file and populate the following variables: 459 | 460 | ``` 461 | DB_DATABASE= 462 | DB_USERNAME= 463 | DB_PASSWORD= 464 | DB_HOST= 465 | ``` 466 | 467 | Now when executing your tests, enable the integration tests by running 468 | 469 | ```shell 470 | HYBRID_INTEGRATION=1 ./vendor/bin/phpunit 471 | ``` 472 | 473 | ## Compatibility matrix 474 | 475 | 476 | 477 | 478 | 479 | 480 | 481 | 482 | 483 | 484 | 485 | 486 | 487 | 488 | 489 | 490 | 491 | 492 | 493 | 494 | 495 | 496 | 497 | 498 | 499 | 500 | 501 | 502 | 503 | 504 | 505 | 506 | 507 | 508 | 509 | 510 | 511 | 512 | 513 | 514 | 515 |
Driver versionLaravel versionPHP version
0.0 - 1.487.3 - 8.0
98.0 - 8.1
1.587.3 - 8.0
98.0 - 8.4
108.1 - 8.4
118.2 - 8.4
2.0128.2 - 8.4
516 | 517 | ## License 518 | 519 | This library is licensed under the Apache 2.0 License. 520 | 521 | ## Resources 522 | 523 | * [SingleStore](https://singlestore.com) 524 | * [Laravel](https://laravel.com) 525 | * [Full-text search documentation](https://docs.singlestore.com/managed-service/en/reference/sql-reference/data-definition-language-ddl/create-table.html#fulltext-behavior) 526 | 527 | ## User agreement 528 | 529 | SINGLESTORE, INC. ("SINGLESTORE") AGREES TO GRANT YOU AND YOUR COMPANY ACCESS TO THIS OPEN SOURCE SOFTWARE CONNECTOR ONLY IF (A) YOU AND YOUR COMPANY REPRESENT AND WARRANT THAT YOU, ON BEHALF OF YOUR COMPANY, HAVE THE AUTHORITY TO LEGALLY BIND YOUR COMPANY AND (B) YOU, ON BEHALF OF YOUR COMPANY ACCEPT AND AGREE TO BE BOUND BY ALL OF THE OPEN SOURCE TERMS AND CONDITIONS APPLICABLE TO THIS OPEN SOURCE CONNECTOR AS SET FORTH BELOW (THIS “AGREEMENT”), WHICH SHALL BE DEFINITIVELY EVIDENCED BY ANY ONE OF THE FOLLOWING MEANS: YOU, ON BEHALF OF YOUR COMPANY, CLICKING THE “DOWNLOAD, “ACCEPTANCE” OR “CONTINUE” BUTTON, AS APPLICABLE OR COMPANY’S INSTALLATION, ACCESS OR USE OF THE OPEN SOURCE CONNECTOR AND SHALL BE EFFECTIVE ON THE EARLIER OF THE DATE ON WHICH THE DOWNLOAD, ACCESS, COPY OR INSTALL OF THE CONNECTOR OR USE ANY SERVICES (INCLUDING ANY UPDATES OR UPGRADES) PROVIDED BY SINGLESTORE. 530 | BETA SOFTWARE CONNECTOR 531 | 532 | Customer Understands and agrees that it is being granted access to pre-release or “beta” versions of SingleStore’s open source software connector (“Beta Software Connector”) for the limited purposes of non-production testing and evaluation of such Beta Software Connector. Customer acknowledges that SingleStore shall have no obligation to release a generally available version of such Beta Software Connector or to provide support or warranty for such versions of the Beta Software Connector for any production or non-evaluation use. 533 | 534 | NOTWITHSTANDING ANYTHING TO THE CONTRARY IN ANY DOCUMENTATION, AGREEMENT OR IN ANY ORDER DOCUMENT, SINGLESTORE WILL HAVE NO WARRANTY, INDEMNITY, SUPPORT, OR SERVICE LEVEL, OBLIGATIONS WITH 535 | RESPECT TO THIS BETA SOFTWARE CONNECTOR (INCLUDING TOOLS AND UTILITIES). 536 | 537 | APPLICABLE OPEN SOURCE LICENSE: Apache 2.0 538 | 539 | IF YOU OR YOUR COMPANY DO NOT AGREE TO THESE TERMS AND CONDITIONS, DO NOT CHECK THE ACCEPTANCE BOX, AND DO NOT DOWNLOAD, ACCESS, COPY, INSTALL OR USE THE SOFTWARE OR THE SERVICES. 540 | 541 | [reference table]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/concepts-of-physical-database-schema-design/other-schema-concepts.html#reference-tables-654455 542 | [global temporary table]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/concepts-of-physical-database-schema-design/other-schema-concepts.html#global-temporary-tables 543 | [columnstore]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/concepts-of-physical-database-schema-design/columnstore.html 544 | [rowstore]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/concepts-of-physical-database-schema-design/rowstore.html 545 | [sparse]: https://docs.singlestore.com/managed-service/en/reference/sql-reference/data-definition-language-ddl/create-table.html#compression---sparse-and-sparse-behavior 546 | [shard key]: https://docs.singlestore.com/managed-service/en/developer-resources/porting-tables-to-singlestoredb-cloud/shard-keys.html 547 | [sort key]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/procedures-for-physical-database-schema-design/creating-a-columnstore-table.html 548 | [columnstore-tuning]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/procedures-for-physical-database-schema-design/configuring-the-columnstore-to-work-effectively.html 549 | [`storedAs`]: https://laravel.com/docs/9.x/migrations#column-modifiers 550 | [persisted computed column]: https://docs.singlestore.com/managed-service/en/create-a-database/physical-database-schema-design/procedures-for-physical-database-schema-design/using-persistent-computed-columns.html 551 | [singlestore-pem]: https://portal.singlestore.com/static/ca/singlestore_bundle.pem 552 | [Eloquent's attribute casting]: https://laravel.com/docs/9.x/eloquent-mutators#attribute-casting 553 | [create table]: https://docs.singlestore.com/managed-service/en/reference/sql-reference/data-definition-language-ddl/create-table.html 554 | [attr_persistent]: https://www.php.net/manual/en/features.persistent-connections.php 555 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "singlestoredb/singlestoredb-laravel", 3 | "description": "A SingleStoreDB database driver for Laravel.", 4 | "type": "library", 5 | "license": "Apache-2.0", 6 | "autoload": { 7 | "psr-4": { 8 | "SingleStore\\Laravel\\": "src/" 9 | } 10 | }, 11 | "autoload-dev": { 12 | "psr-4": { 13 | "SingleStore\\Laravel\\Tests\\": "tests/" 14 | } 15 | }, 16 | "authors": [ 17 | { 18 | "name": "Aaron Francis", 19 | "email": "aarondfrancis@gmail.com" 20 | }, 21 | { 22 | "name": "Carl Sverre", 23 | "email": "carl@singlestore.com" 24 | } 25 | ], 26 | "require": { 27 | "php": "^8.2", 28 | "illuminate/container": "^12.0", 29 | "illuminate/database": "^12.0", 30 | "illuminate/events": "^12.0", 31 | "illuminate/support": "^12.0" 32 | }, 33 | "require-dev": { 34 | "mockery/mockery": "^1.6.10", 35 | "orchestra/testbench": "^10.0.0", 36 | "phpunit/phpunit": "^10.5.35|^11.5.3|^12.0.1" 37 | }, 38 | "config": { 39 | "sort-packages": true 40 | }, 41 | "extra": { 42 | "laravel": { 43 | "providers": [ 44 | "SingleStore\\Laravel\\SingleStoreProvider" 45 | ] 46 | } 47 | }, 48 | "minimum-stability": "dev", 49 | "prefer-stable": true 50 | } -------------------------------------------------------------------------------- /phpunit.xml.dist: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 9 | tests/Unit 10 | 11 | 12 | tests/Hybrid 13 | 14 | 15 | tests/Integration 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /pint.json: -------------------------------------------------------------------------------- 1 | { 2 | "preset": "laravel" 3 | } -------------------------------------------------------------------------------- /src/Connect/SingleStoreConnection.php: -------------------------------------------------------------------------------- 1 | schemaGrammar === null) { 16 | $this->useDefaultSchemaGrammar(); 17 | } 18 | 19 | return new SingleStoreSchemaBuilder($this); 20 | } 21 | 22 | /** 23 | * Get the default query grammar instance. 24 | * 25 | * @return SingleStoreQueryGrammar 26 | */ 27 | protected function getDefaultQueryGrammar() 28 | { 29 | return new SingleStoreQueryGrammar( 30 | connection: $this, 31 | ignoreOrderByInDeletes: $this->getConfig('ignore_order_by_in_deletes'), 32 | ignoreOrderByInUpdates: $this->getConfig('ignore_order_by_in_updates') 33 | ); 34 | } 35 | 36 | /** 37 | * Get the default schema grammar instance. 38 | * 39 | * @return SingleStoreSchemaGrammar 40 | */ 41 | protected function getDefaultSchemaGrammar() 42 | { 43 | return new SingleStoreSchemaGrammar($this); 44 | } 45 | 46 | /** 47 | * Get a new query builder instance. 48 | */ 49 | public function query() 50 | { 51 | return new SingleStoreQueryBuilder( 52 | $this, 53 | $this->getQueryGrammar(), 54 | $this->getPostProcessor() 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/Connect/SingleStoreConnector.php: -------------------------------------------------------------------------------- 1 | options = $options; 14 | 15 | return $this; 16 | } 17 | 18 | public function toSql() 19 | { 20 | $sql = parent::toSql(); 21 | 22 | if (! empty($this->options)) { 23 | $sql .= ' '.$this->grammar->compileOptions($this->options); 24 | } 25 | 26 | return $sql; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/Query/SingleStoreQueryGrammar.php: -------------------------------------------------------------------------------- 1 | ignoreOrderByInDeletes = $ignoreOrderByInDeletes; 22 | $this->ignoreOrderByInUpdates = $ignoreOrderByInUpdates; 23 | } 24 | 25 | public function compileOptions(array $options): string 26 | { 27 | $optionString = ''; 28 | foreach ($options as $key => $value) { 29 | if (! empty($optionString)) { 30 | $optionString .= ','; 31 | } 32 | $optionString .= $key.'='.$value; 33 | } 34 | 35 | return "OPTION ({$optionString})"; 36 | } 37 | 38 | public function compileDelete(Builder $query) 39 | { 40 | // TODO: allow order by in the case when table has unique column 41 | if (isset($query->orders)) { 42 | if ($this->ignoreOrderByInDeletes) { 43 | if (env('APP_ENV') !== 'production') { 44 | Log::warning('SingleStore does not support the "ORDER BY" clause in a "DELETE" statement. The "ORDER BY" clause will be ignored.'); 45 | } 46 | $query->orders = []; 47 | } else { 48 | throw new Exception('SingleStore does not support the "ORDER BY" clause in a "DELETE" statement. Enable the "ignore_order_by_in_deletes" configuration to ignore "orderBy" in "delete" operations.'); 49 | } 50 | } 51 | 52 | return parent::compileDelete($query); 53 | } 54 | 55 | public function compileUpdate(Builder $query, array $values) 56 | { 57 | // TODO: allow order by in the case when table has unique column 58 | if (isset($query->orders)) { 59 | if ($this->ignoreOrderByInUpdates) { 60 | if (env('APP_ENV') !== 'production') { 61 | Log::warning('SingleStore does not support the "ORDER BY" clause in an "UPDATE" statement. The "ORDER BY" clause will be ignored.'); 62 | } 63 | $query->orders = []; 64 | } else { 65 | throw new Exception('SingleStore does not support the "ORDER BY" clause in an update statement. Enable the "ignore_order_by_in_updates" configuration to ignore "orderBy" in "update" operations.'); 66 | } 67 | } 68 | 69 | return parent::compileUpdate($query, $values); 70 | } 71 | 72 | /** 73 | * Compile a "where fulltext" clause. 74 | * 75 | * @param array $where 76 | * @return string 77 | */ 78 | public function whereFullText(Builder $query, $where) 79 | { 80 | $columns = $this->columnize($where['columns']); 81 | 82 | $value = $this->parameter($where['value']); 83 | 84 | return "MATCH ({$columns}) AGAINST ({$value})"; 85 | } 86 | 87 | /** 88 | * @return string 89 | */ 90 | protected function compileJsonContains($column, $value) 91 | { 92 | [$field, $path] = $this->wrapJsonFieldAndPath($column); 93 | 94 | // JSON_ARRAY_CONTAINS_[TYPE] doesn't support paths, so 95 | // we have to pass it through JSON_EXTRACT_JSON first. 96 | if ($path) { 97 | $field = "JSON_EXTRACT_JSON($field$path)"; 98 | } 99 | 100 | return "JSON_ARRAY_CONTAINS_JSON($field, $value)"; 101 | } 102 | 103 | protected function compileJsonUpdateColumn($key, $value) 104 | { 105 | if (is_bool($value)) { 106 | $value = $value ? "'true'" : "'false'"; 107 | } else { 108 | $value = $this->parameter($value); 109 | } 110 | 111 | // Break apart the column name from the JSON keypath. 112 | [$field, $path] = $this->wrapJsonFieldAndPath($key); 113 | 114 | return "$field = JSON_SET_JSON($field$path, $value)"; 115 | } 116 | 117 | public function prepareBindingsForUpdate(array $bindings, array $values) 118 | { 119 | // We need to encode strings for JSON columns, but we'll 120 | // let the parent class handle everything else. 121 | $values = collect($values)->map(function ($value, $column) { 122 | return $this->isJsonSelector($column) && is_string($value) ? json_encode($value) : $value; 123 | })->all(); 124 | 125 | return parent::prepareBindingsForUpdate($bindings, $values); 126 | } 127 | 128 | /** 129 | * Transforms expressions to their scalar types. 130 | * 131 | * @param \Illuminate\Contracts\Database\Query\Expression|string|int|float $expression 132 | * @return string|int|float 133 | */ 134 | public function getValue($expression) 135 | { 136 | if ($this->isExpression($expression)) { 137 | return $this->getValue($expression->getValue($this)); 138 | } 139 | 140 | return $expression; 141 | } 142 | 143 | protected function whereNull(Builder $query, $where) 144 | { 145 | $columnValue = (string) $this->getValue($where['column']); 146 | if ($this->isJsonSelector($columnValue)) { 147 | [$field, $path] = $this->wrapJsonFieldAndPath($where['column']); 148 | 149 | return '(JSON_EXTRACT_JSON('.$field.$path.') IS NULL OR JSON_GET_TYPE(JSON_EXTRACT_JSON('.$field.$path.')) = \'NULL\')'; 150 | } 151 | 152 | return $this->wrap($where['column']).' is null'; 153 | } 154 | 155 | protected function whereNotNull(Builder $query, $where) 156 | { 157 | $columnValue = (string) $this->getValue($where['column']); 158 | if ($this->isJsonSelector($columnValue)) { 159 | [$field, $path] = $this->wrapJsonFieldAndPath($where['column']); 160 | 161 | return '(JSON_EXTRACT_JSON('.$field.$path.') IS NOT NULL AND JSON_GET_TYPE(JSON_EXTRACT_JSON('.$field.$path.')) != \'NULL\')'; 162 | } 163 | 164 | return $this->wrap($where['column']).' is not null'; 165 | } 166 | 167 | protected function wrapJsonSelector($value) 168 | { 169 | // Break apart the column name from the JSON keypath. 170 | [$field, $path] = $this->wrapJsonFieldAndPath($value); 171 | 172 | if (! $path) { 173 | return $field; 174 | } 175 | 176 | return "JSON_EXTRACT_STRING($field$path)"; 177 | } 178 | 179 | protected function wrapJsonBooleanSelector($value) 180 | { 181 | return str_replace( 182 | 'JSON_EXTRACT_STRING', 183 | 'JSON_EXTRACT_DOUBLE', 184 | $this->wrapJsonSelector($value) 185 | ); 186 | } 187 | 188 | protected function wrapJsonFieldAndPath($column) 189 | { 190 | // Matches numbers surrounded by brackets. 191 | $arrayAccessPattern = "/\\[(\d+)\\]/"; 192 | 193 | // Turn all array access e.g. `data[0]` into `data->[0]` 194 | $column = preg_replace_callback($arrayAccessPattern, function ($matches) { 195 | return "->[$matches[1]]"; 196 | }, $column); 197 | 198 | $parts = explode('->', $column); 199 | 200 | // The field must be unquoted, so shift it off first. 201 | $field = array_shift($parts); 202 | 203 | $parts = array_map(function ($part) use ($arrayAccessPattern) { 204 | // Array access indexes need to be real numbers, not strings. 205 | if (preg_match($arrayAccessPattern, $part, $matches)) { 206 | return (int) $matches[1]; 207 | } 208 | 209 | // Named keys need to be strings. 210 | return "'$part'"; 211 | }, $parts); 212 | 213 | $path = count($parts) ? ', '.implode(', ', $parts) : ''; 214 | 215 | return [$field, $path]; 216 | } 217 | 218 | /** 219 | * Wrap a union subquery in parentheses. 220 | * 221 | * @param string $sql 222 | * @return string 223 | */ 224 | protected function wrapUnion($sql) 225 | { 226 | return 'SELECT * FROM ('.$sql.')'; 227 | } 228 | 229 | /** 230 | * Compile the "union" queries attached to the main query. 231 | * 232 | * @return string 233 | */ 234 | protected function compileUnions(Builder $query) 235 | { 236 | $sql = ''; 237 | 238 | foreach ($query->unions as $union) { 239 | $sql .= $this->compileUnion($union); 240 | } 241 | 242 | return ltrim($sql); 243 | } 244 | 245 | /** 246 | * Compile a single union statement. 247 | * 248 | * @return string 249 | */ 250 | protected function compileUnion(array $union) 251 | { 252 | $conjunction = $union['all'] ? ' union all ' : ' union '; 253 | 254 | return $conjunction.'('.$union['query']->toSql().')'; 255 | } 256 | 257 | /** 258 | * Compile a select query into SQL. 259 | * 260 | * @return string 261 | */ 262 | public function compileSelect(Builder $query) 263 | { 264 | $isAggregateWithUnionOrHaving = (($query->unions || $query->havings) && $query->aggregate); 265 | 266 | $sql = parent::compileSelect($query); 267 | 268 | if ($isAggregateWithUnionOrHaving) { 269 | return ltrim($sql); 270 | } 271 | 272 | if (! empty($query->unionOrders) || isset($query->unionLimit) || isset($query->unionOffset)) { 273 | $sql = 'SELECT * FROM ('.$sql.') '; 274 | 275 | if (! empty($query->unionOrders)) { 276 | $sql .= ' '.$this->compileOrders($query, $query->unionOrders); 277 | } 278 | 279 | if (isset($query->unionLimit)) { 280 | $sql .= ' '.$this->compileLimit($query, $query->unionLimit); 281 | } 282 | 283 | if (isset($query->unionOffset)) { 284 | $sql .= ' '.$this->compileUnionOffset($query, $query->unionOffset); 285 | } 286 | } 287 | 288 | return ltrim($sql); 289 | } 290 | 291 | /** 292 | * Compile the "offset" portions of the query. 293 | * 294 | * @return string 295 | */ 296 | protected function compileOffset(Builder $query, $offset) 297 | { 298 | return $this->compileOffsetWithLimit($offset, $query->limit); 299 | } 300 | 301 | /** 302 | * Compile the "offset" portions of the final union query. 303 | */ 304 | protected function compileUnionOffset(Builder $query, $offset): string 305 | { 306 | return $this->compileOffsetWithLimit($offset, $query->unionLimit); 307 | } 308 | 309 | /** 310 | * Compile the "offset" portions of the query taking into account "limit" portion. 311 | */ 312 | private function compileOffsetWithLimit($offset, $limit): string 313 | { 314 | // OFFSET is not valid without LIMIT 315 | // Add a huge LIMIT clause 316 | if (! isset($limit)) { 317 | // 9223372036854775807 - max 64-bit integer 318 | return ' LIMIT 9223372036854775807 OFFSET '.(int) $offset; 319 | } 320 | 321 | return ' OFFSET '.(int) $offset; 322 | } 323 | 324 | /** 325 | * Compile a delete statement with joins into SQL. 326 | * 327 | * @param string $table 328 | * @param string $where 329 | */ 330 | protected function compileDeleteWithJoins(Builder $query, $table, $where): string 331 | { 332 | $joins = $this->compileJoins($query, $query->joins); 333 | 334 | // SingleStore does not support "database.table" in a delete statement when the delete statement contains a join 335 | // strip the database name from the table, if it exists 336 | $deleteTable = last(explode('.', $table)); 337 | 338 | return "delete {$deleteTable} from {$table} {$joins} {$where}"; 339 | } 340 | 341 | public function useLegacyGroupLimit(Builder $query) 342 | { 343 | return false; 344 | } 345 | } 346 | -------------------------------------------------------------------------------- /src/Schema/Blueprint.php: -------------------------------------------------------------------------------- 1 | addColumn('geography', $column); 29 | } 30 | 31 | public function geographyPoint($column) 32 | { 33 | return $this->point($column); 34 | } 35 | 36 | /** 37 | * Create a new point column on the table. 38 | * 39 | * @param string $column 40 | * @param int|null $srid 41 | * @return \Illuminate\Database\Schema\ColumnDefinition 42 | */ 43 | public function point($column, $srid = null) 44 | { 45 | return $this->addColumn('point', $column); 46 | } 47 | 48 | /** 49 | * Execute the blueprint against the database. 50 | * 51 | * @return void 52 | */ 53 | public function build() 54 | { 55 | try { 56 | parent::build(); 57 | } catch (QueryException $exception) { 58 | if (str_contains($exception->getMessage(), 'FULLTEXT KEY with unsupported type')) { 59 | throw new Exception('FULLTEXT is not supported when using the utf8mb4 collation.'); 60 | } 61 | 62 | throw $exception; 63 | } 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Schema/Blueprint/AddsTableFlags.php: -------------------------------------------------------------------------------- 1 | rowstore = true; 30 | 31 | return $this; 32 | } 33 | 34 | public function reference() 35 | { 36 | $this->reference = true; 37 | 38 | return $this; 39 | } 40 | 41 | public function temporary($global = false) 42 | { 43 | $this->global = $global; 44 | $this->temporary = true; 45 | 46 | return $this; 47 | } 48 | 49 | public function global() 50 | { 51 | $this->global = true; 52 | 53 | return $this; 54 | } 55 | 56 | public function sparse() 57 | { 58 | $this->sparse = true; 59 | 60 | return $this; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/Schema/Blueprint/InlinesIndexes.php: -------------------------------------------------------------------------------- 1 | name, array_merge( 75 | $this->singleStoreIndexes, 76 | $this->mysqlIndexes 77 | )); 78 | } 79 | 80 | /** 81 | * @return void 82 | */ 83 | protected function addFluentSingleStoreIndexes() 84 | { 85 | // This is modeled from the parent class, but with one major difference. In the 86 | // parent class, after an index is found `continue 2` is called, eliminating 87 | // the possibility that a single column has two fluent keys on it. For us, 88 | // a column can be a combination of primary key, shard key, or sort key. 89 | foreach ($this->columns as $column) { 90 | foreach ($this->singleStoreIndexes as $index) { 91 | if (isset($column->{$index})) { 92 | if ($column->{$index} === true) { 93 | $command = $this->{$index}($column->name); 94 | } else { 95 | $command = $this->{$index}($column->name, $column->{$index}); 96 | } 97 | 98 | // Forward with attributes if sortKey 99 | if ($index === 'sortKey' && isset($column->with)) { 100 | $command->with($column->with); 101 | $column->with = null; 102 | } 103 | 104 | $column->{$index} = false; 105 | } 106 | } 107 | } 108 | } 109 | 110 | public function toSql() 111 | { 112 | $this->addImpliedCommands(); 113 | $this->addFluentSingleStoreIndexes(); 114 | 115 | $statements = []; 116 | $indexStatementKeys = []; 117 | 118 | foreach ($this->commands as $command) { 119 | if ($command->shouldBeSkipped) { 120 | continue; 121 | } 122 | 123 | $method = 'compile'.ucfirst($command->name); 124 | $isIndex = $this->isIndexCommand($command); 125 | 126 | if (method_exists($this->grammar, $method) || $this->grammar::hasMacro($method)) { 127 | if (! is_null($sql = $this->grammar->$method($this, $command))) { 128 | $statements = array_merge($statements, (array) $sql); 129 | 130 | if ($isIndex) { 131 | array_push($indexStatementKeys, count($statements) - 1); 132 | } 133 | } 134 | } 135 | } 136 | 137 | return $this->creating() ? $this->inlineCreateIndexStatements($statements, $indexStatementKeys) : $statements; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/Schema/Blueprint/ModifiesIndexes.php: -------------------------------------------------------------------------------- 1 | indexCommand('shardKey', $columns, 'shardKeyDummyName'); 15 | } 16 | 17 | /** 18 | * @return \Illuminate\Support\Fluent 19 | */ 20 | public function sortKey($columns = null, $direction = 'asc') 21 | { 22 | $command = $this->indexCommand('sortKey', $columns, 'sortKeyDummyName'); 23 | $command->direction = $direction; 24 | 25 | return $command; 26 | } 27 | 28 | /** 29 | * @return SpatialIndexCommand 30 | */ 31 | public function spatialIndex($columns, $name = null) 32 | { 33 | parent::spatialIndex($columns, $name); 34 | 35 | return $this->recastLastCommand(SpatialIndexCommand::class); 36 | } 37 | 38 | /** 39 | * Recast the last fluent command into a different class, 40 | * which is helpful for IDE completion. 41 | * 42 | * @template T 43 | * 44 | * @param class-string $class 45 | * @return T 46 | */ 47 | protected function recastLastCommand($class) 48 | { 49 | return $this->commands[] = new $class(array_pop($this->commands)->getAttributes()); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/Schema/Grammar/CompilesKeys.php: -------------------------------------------------------------------------------- 1 | columnize($command->columns)})"; 13 | } 14 | 15 | public function compileSortKey(Blueprint $blueprint, Fluent $command) 16 | { 17 | if (is_array($command->with)) { 18 | $compiled = collect($command->with)->map(function ($value, $variable) { 19 | return "{$variable}={$value}"; 20 | })->join(','); 21 | 22 | return "sort key({$this->columnizeWithDirection($command->columns, $command->direction)}) with ({$compiled})"; 23 | } 24 | 25 | return "sort key({$this->columnizeWithDirection($command->columns, $command->direction)})"; 26 | } 27 | 28 | public function compileSpatialIndex(Blueprint $blueprint, Fluent $command) 29 | { 30 | // SingleStore's spatial indexes just use the keyword `index`, not `spatial index`. 31 | $compiled = $this->compileKey($blueprint, $command, 'index'); 32 | 33 | if ($command->resolution) { 34 | $compiled .= " with (resolution = $command->resolution)"; 35 | } 36 | 37 | return $compiled; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/Schema/Grammar/ModifiesColumns.php: -------------------------------------------------------------------------------- 1 | singleStoreModifiersAdded) { 25 | // We need to insert all of our modifiers before the "after" modifier, 26 | // otherwise things like "sparse" will come after "after", which is 27 | // invalid SQL. So we find the position of the "after" modifier in 28 | // the parent, and then slot our modifiers in before it. 29 | $index = array_search('After', $this->modifiers); 30 | 31 | $this->modifiers = array_merge( 32 | array_slice($this->modifiers, 0, $index), 33 | $this->singleStoreModifiers, 34 | array_slice($this->modifiers, $index) 35 | ); 36 | 37 | $this->singleStoreModifiersAdded = true; 38 | } 39 | } 40 | 41 | public function modifySparse(Blueprint $blueprint, Fluent $column) 42 | { 43 | if (! is_null($column->sparse)) { 44 | return ' sparse'; 45 | } 46 | } 47 | 48 | public function modifySeriesTimestamp(Blueprint $blueprint, Fluent $column) 49 | { 50 | if (! is_null($column->seriesTimestamp)) { 51 | return ' series timestamp'; 52 | } 53 | } 54 | 55 | public function modifyOption(Blueprint $blueprint, Fluent $column) 56 | { 57 | if (! is_null($column->option)) { 58 | // @TODO docs? 59 | return " option '$column->option'"; 60 | } 61 | } 62 | 63 | protected function modifyStoredAs(Blueprint $blueprint, Fluent $column) 64 | { 65 | // This is handled in the `getType` method of the Grammar, since 66 | // SingleStore requires it come before the column type. 67 | } 68 | 69 | protected function modifyVirtualAs(Blueprint $blueprint, Fluent $column) 70 | { 71 | if (! is_null($column->virtualAs)) { 72 | throw new Exception('SingleStore does not support virtual computed columns. Use `storedAs` instead.'); 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/Schema/SingleStoreSchemaBuilder.php: -------------------------------------------------------------------------------- 1 | blueprintResolver(function ($table, $callback, $prefix) { 21 | return new Blueprint($table, $callback, $prefix); 22 | }); 23 | 24 | return parent::createBlueprint($table, $callback); 25 | } 26 | 27 | public function getAllTables() 28 | { 29 | return $this->connection->select( 30 | 'SHOW FULL TABLES WHERE table_type = \'BASE TABLE\'' 31 | ); 32 | } 33 | 34 | /** 35 | * Drop all tables from the database. 36 | * 37 | * @return void 38 | */ 39 | public function dropAllTables() 40 | { 41 | $tables = []; 42 | 43 | foreach ($this->getAllTables() as $row) { 44 | $row = (array) $row; 45 | 46 | $tables[] = reset($row); 47 | } 48 | 49 | if (empty($tables)) { 50 | return; 51 | } 52 | 53 | foreach ($tables as $table) { 54 | $this->connection->statement( 55 | $this->grammar->compileDropAllTables([$table]) 56 | ); 57 | } 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/Schema/SingleStoreSchemaGrammar.php: -------------------------------------------------------------------------------- 1 | addSingleStoreModifiers(); 28 | } 29 | 30 | /** 31 | * Compile a change column command into a series of SQL statements. 32 | * 33 | * @return array|string 34 | * 35 | * @throws \RuntimeException 36 | */ 37 | public function compileChange(Blueprint $blueprint, Fluent $command) 38 | { 39 | $prefix = method_exists($blueprint, 'getPrefix') 40 | ? $blueprint->getPrefix() 41 | : (function () { 42 | return $this->prefix; 43 | })->call($blueprint); 44 | 45 | $isColumnstoreTable = $this->connection->scalar(sprintf( 46 | "select exists (select 1 from information_schema.tables where table_schema = %s and table_name = %s and storage_type = 'COLUMNSTORE') as is_columnstore", 47 | $this->quoteString($this->connection->getDatabaseName()), 48 | $this->quoteString($prefix.$blueprint->getTable()) 49 | )); 50 | 51 | if (! $isColumnstoreTable) { 52 | return parent::compileChange($blueprint, $command); 53 | } 54 | 55 | $tempCommand = clone $command; 56 | $tempCommand->column = clone $command->column; 57 | $tempCommand->column->change = false; 58 | $tempCommand->column->name = '__temp__'.$command->column->name; 59 | $tempCommand->column->after = is_null($command->column->after) && is_null($command->column->first) 60 | ? $command->column->name 61 | : $command->column->after; 62 | 63 | return [ 64 | $this->compileAdd($blueprint, $tempCommand), 65 | sprintf( 66 | 'update %s set %s = %s', 67 | $this->wrapTable($blueprint), 68 | $this->wrap($tempCommand->column), 69 | $this->wrap($command->column) 70 | ), 71 | $this->compileDropColumn($blueprint, new Fluent([ 72 | 'columns' => [$command->column->name], 73 | ])), 74 | $this->compileRenameColumn($blueprint, new Fluent([ 75 | 'from' => $tempCommand->column->name, 76 | 'to' => $command->column->name, 77 | ])), 78 | ]; 79 | } 80 | 81 | /** 82 | * Compile a primary key command. 83 | * 84 | * @return string 85 | */ 86 | public function compilePrimary(Blueprint $blueprint, Fluent $command) 87 | { 88 | $command->name(null); 89 | 90 | return $this->compileKey($blueprint, $command, 'primary key'); 91 | } 92 | 93 | /** 94 | * Create the column definition for a spatial Geography type. 95 | * 96 | * @return string 97 | */ 98 | public function typeGeography(Fluent $column) 99 | { 100 | return 'geography'; 101 | } 102 | 103 | /** 104 | * Create the column definition for a spatial Point type. 105 | * 106 | * @return string 107 | */ 108 | public function typePoint(Fluent $column) 109 | { 110 | // For SingleStore, `point` is invalid. It uses `geographypoint` instead. 111 | return 'geographypoint'; 112 | } 113 | 114 | /** 115 | * Create the main create table clause. 116 | * 117 | * @param Blueprint $blueprint 118 | * @param \Illuminate\Support\Fluent $command 119 | * @param \Illuminate\Database\Connection $connection 120 | * 121 | * @throws Exception 122 | */ 123 | protected function compileCreateTable($blueprint, $command): string 124 | { 125 | // We want to do as little as possible ourselves, so we rely on the parent 126 | // to compile everything and then potentially sneak some modifiers in. 127 | return $this->insertCreateTableModifiers( 128 | $blueprint, 129 | parent::compileCreateTable($blueprint, $command) 130 | ); 131 | } 132 | 133 | /** 134 | * @return string 135 | */ 136 | protected function getType(Fluent $column) 137 | { 138 | $type = parent::getType($column); 139 | 140 | if (! is_null($column->storedAs)) { 141 | // MySQL's syntax for stored columns is ` as () stored`, 142 | // but for SingleStore it's ` as () persisted `. Here 143 | // we sneak the expression in as a part of the type definition, so that it will 144 | // end up in the right spot. `modifyStoredAs` is a noop to account for this. 145 | $type = "as ($column->storedAs) persisted $type"; 146 | } 147 | 148 | return $type; 149 | } 150 | 151 | /** 152 | * Append the engine specifications to a command. 153 | * 154 | * @param string $sql 155 | * @return string 156 | */ 157 | protected function compileCreateEngine($sql, Blueprint $blueprint) 158 | { 159 | $sql = parent::compileCreateEngine($sql, $blueprint); 160 | 161 | // We're not actually messing with the engine part at all, this is just 162 | // a good place to add `compression = sparse` if it's called for. 163 | if ($blueprint->sparse) { 164 | $sql .= ' compression = sparse'; 165 | } 166 | 167 | return $sql; 168 | } 169 | 170 | /** 171 | * @return string 172 | * 173 | * @throws Exception 174 | */ 175 | protected function insertCreateTableModifiers($blueprint, $compiled) 176 | { 177 | $replacement = 'create'; 178 | 179 | if ($blueprint->rowstore) { 180 | $replacement .= ' rowstore'; 181 | } 182 | 183 | if ($blueprint->reference) { 184 | $replacement .= ' reference'; 185 | } 186 | 187 | if ($blueprint->global) { 188 | $replacement .= ' global'; 189 | } 190 | 191 | return Str::replaceFirst('create ', "$replacement ", $compiled); 192 | } 193 | 194 | /** 195 | * @return array 196 | * 197 | * @throws Exception 198 | */ 199 | protected function getColumns(Blueprint $blueprint) 200 | { 201 | $columns = parent::getColumns($blueprint); 202 | 203 | if ($blueprint->creating()) { 204 | // Because all keys *must* be added at the time of table creation, we can't rely on 205 | // the normal ALTER TABLE commands that Laravel generates. Instead we add a fake 206 | // column so that it ends up in the right spot (last) inside the SQL statement. 207 | $columns[] = SingleStoreBlueprint::INDEX_PLACEHOLDER; 208 | } 209 | 210 | return $columns; 211 | } 212 | 213 | /** 214 | * @return array|string|string[] 215 | */ 216 | protected function compileKey(Blueprint $blueprint, Fluent $command, $type) 217 | { 218 | $compiled = parent::compileKey($blueprint, $command, $type); 219 | 220 | // We don't mess with ALTER statements at all. 221 | if (! $blueprint->creating()) { 222 | return $compiled; 223 | } 224 | 225 | // All keys are added as a part of the CREATE TABLE statement. Completely 226 | // removing the `alter table %s add` gives us the right syntax for 227 | // creating the indexes as a part of the create statement. 228 | return str_replace(sprintf('alter table %s add ', $this->wrapTable($blueprint)), '', $compiled); 229 | } 230 | 231 | /** 232 | * Convert an array of column names into a delimited string (with direction parameter). 233 | * 234 | * @return string 235 | */ 236 | protected function columnizeWithDirection(array $columns, string $direction) 237 | { 238 | if ($columns === array_filter($columns, 'is_array')) { 239 | $columnNames = array_map(function ($column) { 240 | return $this->wrap($column[0]); 241 | }, $columns); 242 | 243 | $columnDirections = array_map(function ($column) { 244 | return $column[1]; 245 | }, $columns); 246 | 247 | return implode(', ', array_map(function ($column, $direction) { 248 | return "$column $direction"; 249 | }, $columnNames, $columnDirections)); 250 | } 251 | 252 | if (array_filter($columns, 'is_array') !== []) { 253 | throw new InvalidArgumentException('You must set the direction for each sort key column or use the second parameter to set the direction for all sort key columns'); 254 | } 255 | 256 | $wrapped = array_map([$this, 'wrap'], $columns); 257 | 258 | return implode(', ', array_map(function ($column) use ($direction) { 259 | return $column.' '.$direction; 260 | }, $wrapped)); 261 | } 262 | 263 | /** 264 | * Get the SQL for an auto-increment column modifier. 265 | * 266 | * @return string|null 267 | */ 268 | protected function modifyIncrement(Blueprint $blueprint, Fluent $column) 269 | { 270 | if (in_array($column->type, $this->serials) && $column->autoIncrement) { 271 | return ($column->withoutPrimaryKey === true) 272 | ? ' auto_increment' 273 | : ' auto_increment primary key'; 274 | } 275 | } 276 | 277 | /** 278 | * Compile a rename table command. 279 | * 280 | * @return string 281 | */ 282 | public function compileRename(Blueprint $blueprint, Fluent $command) 283 | { 284 | $from = $this->wrapTable($blueprint); 285 | 286 | return "alter table {$from} rename to ".$this->wrapTable($command->to); 287 | } 288 | 289 | /** 290 | * Compile a rename column command. 291 | * 292 | * @return array|string 293 | */ 294 | public function compileRenameColumn(Blueprint $blueprint, Fluent $command) 295 | { 296 | return sprintf( 297 | 'alter table %s change %s %s', 298 | $this->wrapTable($blueprint), 299 | $this->wrap($command->from), 300 | $this->wrap($command->to) 301 | ); 302 | } 303 | 304 | /** 305 | * Compile the query to determine the columns. 306 | * 307 | * @param string $database 308 | * @param string $table 309 | * @return string 310 | */ 311 | public function compileColumns($database, $table) 312 | { 313 | return sprintf( 314 | 'select column_name as `name`, data_type as `type_name`, column_type as `type`, ' 315 | .'collation_name as `collation`, is_nullable as `nullable`, ' 316 | .'column_default as `default`, column_comment as `comment`, ' 317 | .'"" as `expression`, extra as `extra` ' 318 | .'from information_schema.columns where table_schema = %s and table_name = %s ' 319 | .'order by ordinal_position asc', 320 | $database ? $this->quoteString($database) : 'database()', 321 | $this->quoteString($table) 322 | ); 323 | } 324 | } 325 | -------------------------------------------------------------------------------- /src/SingleStoreProvider.php: -------------------------------------------------------------------------------- 1 | app->bind('db.connector.singlestore', SingleStoreConnector::class); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /tests/BaseTest.php: -------------------------------------------------------------------------------- 1 | useEnvironmentPath(dirname(__DIR__)); 21 | } 22 | 23 | protected function getPackageProviders($app) 24 | { 25 | return [ 26 | SingleStoreProvider::class, 27 | ]; 28 | } 29 | 30 | public function getEnvironmentSetUp($app) 31 | { 32 | // Use the default MySQL configuration from Laravel, but switch the driver 33 | // to `singlestore`. This ensures that we're doing the least amount of 34 | // configuration possible, making for the ideal developer experience. 35 | $app['config']->set('database.default', 'mysql'); 36 | $app['config']->set('database.connections.mysql.driver', 'singlestore'); 37 | $app['config']->set('database.connections.mysql.options.'.PDO::ATTR_EMULATE_PREPARES, true); 38 | $app['config']->set('database.connections.mysql.ignore_order_by_in_deletes', true); 39 | $app['config']->set('database.connections.mysql.ignore_order_by_in_updates', true); 40 | } 41 | 42 | public function singlestoreVersion() 43 | { 44 | return DB::select('SELECT @@memsql_version AS version')[0]->version; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Hybrid/ChangeColumnTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 20 | $cached = $this->mockDatabaseConnection; 21 | 22 | $this->mockDatabaseConnection = false; 23 | 24 | if (method_exists(SingleStoreSchemaBuilder::class, 'useNativeSchemaOperationsIfPossible')) { 25 | Schema::useNativeSchemaOperationsIfPossible(); 26 | } 27 | 28 | $this->createTable(function (Blueprint $table) { 29 | $table->rowstore(); 30 | $table->id(); 31 | $table->string('data'); 32 | }); 33 | 34 | Schema::table('test', function (Blueprint $table) { 35 | $table->text('data')->nullable()->change(); 36 | }); 37 | 38 | $this->assertEquals(['id', 'data'], Schema::getColumnListing('test')); 39 | $this->assertEquals('text', Schema::getColumnType('test', 'data')); 40 | 41 | $this->mockDatabaseConnection = $cached; 42 | } 43 | 44 | $connection = $this->getConnection(); 45 | $grammar = new SingleStoreSchemaGrammar($connection); 46 | 47 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 48 | $connection->shouldReceive('getDatabaseName')->andReturn('database'); 49 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 50 | $connection->shouldReceive('scalar') 51 | ->with("select exists (select 1 from information_schema.tables where table_schema = 'database' and table_name = 'test' and storage_type = 'COLUMNSTORE') as is_columnstore") 52 | ->andReturn(0); 53 | $connection->shouldReceive('usingNativeSchemaOperations')->andReturn(true); 54 | 55 | $blueprint = new Blueprint($connection, 'test'); 56 | $blueprint->text('data')->nullable()->change(); 57 | 58 | $statements = $blueprint->toSql(); 59 | 60 | $this->assertCount(1, $statements); 61 | $this->assertEquals('alter table `test` modify `data` text null', $statements[0]); 62 | } 63 | 64 | #[Test] 65 | public function change_column_of_columnstore_table() 66 | { 67 | if ($this->runHybridIntegrations()) { 68 | $cached = $this->mockDatabaseConnection; 69 | 70 | $this->mockDatabaseConnection = false; 71 | 72 | $this->createTable(function (Blueprint $table) { 73 | $table->id(); 74 | $table->string('data'); 75 | }); 76 | 77 | Schema::table('test', function (Blueprint $table) { 78 | $table->text('data')->nullable()->change(); 79 | }); 80 | 81 | $this->assertEquals(['id', 'data'], Schema::getColumnListing('test')); 82 | $this->assertEquals('text', Schema::getColumnType('test', 'data')); 83 | 84 | $this->mockDatabaseConnection = $cached; 85 | } 86 | 87 | $connection = $this->getConnection('test'); 88 | $grammar = new SingleStoreSchemaGrammar($connection); 89 | 90 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 91 | $connection->shouldReceive('getDatabaseName')->andReturn('database'); 92 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 93 | $connection->shouldReceive('scalar') 94 | ->with("select exists (select 1 from information_schema.tables where table_schema = 'database' and table_name = 'test' and storage_type = 'COLUMNSTORE') as is_columnstore") 95 | ->andReturn(1); 96 | 97 | $blueprint = new Blueprint($connection, 'test'); 98 | $blueprint->text('data')->nullable()->change(); 99 | 100 | $statements = $blueprint->toSql($connection, $this->getGrammar()); 101 | 102 | $this->assertCount(4, $statements); 103 | $this->assertEquals([ 104 | 'alter table `test` add `__temp__data` text null after `data`', 105 | 'update `test` set `__temp__data` = `data`', 106 | 'alter table `test` drop `data`', 107 | 'alter table `test` change `__temp__data` `data`', 108 | ], $statements); 109 | } 110 | } 111 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/ComputedColumnsTest.php: -------------------------------------------------------------------------------- 1 | expectException(Exception::class); 19 | $this->expectExceptionMessage('SingleStore does not support virtual computed columns. Use `storedAs` instead.'); 20 | 21 | $blueprint = $this->createTable(function (Blueprint $table) { 22 | $table->string('name')->virtualAs('1'); 23 | }); 24 | 25 | $this->assertCreateStatement($blueprint, 'Argument is moot, exception will be thrown.'); 26 | } 27 | 28 | #[Test] 29 | public function computed_stored() 30 | { 31 | $blueprint = $this->createTable(function (Blueprint $table) { 32 | $table->integer('a'); 33 | $table->integer('b'); 34 | $table->integer('c')->storedAs('a + b'); 35 | }); 36 | 37 | $this->assertCreateStatement( 38 | $blueprint, 39 | 'create table `test` (`a` int not null, `b` int not null, `c` as (a + b) persisted int)' 40 | ); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/IncrementWithoutPrimaryKeyTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->bigIncrements('id')->withoutPrimaryKey(); 19 | $table->uuid('uuid'); 20 | 21 | $table->primary(['id', 'uuid']); 22 | }); 23 | 24 | $this->assertCreateStatement( 25 | $blueprint, 26 | 'create table `test` (`id` bigint unsigned not null auto_increment, `uuid` char(36) not null, primary key (`id`, `uuid`))' 27 | ); 28 | } 29 | 30 | #[Test] 31 | public function it_adds_an_id_without_primary_key() 32 | { 33 | $blueprint = $this->createTable(function (Blueprint $table) { 34 | $table->id()->withoutPrimaryKey(); 35 | $table->uuid('uuid'); 36 | 37 | $table->primary(['id', 'uuid']); 38 | }); 39 | 40 | $this->assertCreateStatement( 41 | $blueprint, 42 | 'create table `test` (`id` bigint unsigned not null auto_increment, `uuid` char(36) not null, primary key (`id`, `uuid`))' 43 | ); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/MiscCreateTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->string('primary')->primary('name1'); 19 | $table->string('index')->index('name2'); 20 | $table->string('foo'); 21 | $table->index('foo', 'name3', 'hash'); 22 | }); 23 | 24 | $this->assertCreateStatement( 25 | $blueprint, 26 | 'create table `test` (`primary` varchar(255) not null, `index` varchar(255) not null, `foo` varchar(255) not null, index `name3` using hash(`foo`), index `name2`(`index`), primary key (`primary`))' 27 | ); 28 | } 29 | 30 | #[Test] 31 | public function all_keys_are_added_in_create_rowstore() 32 | { 33 | $blueprint = $this->createTable(function (Blueprint $table) { 34 | $table->rowstore(); 35 | $table->string('primary')->primary('name1'); 36 | $table->string('index')->index('name2'); 37 | $table->geography('georegion')->spatialIndex('name3'); 38 | }); 39 | 40 | $this->assertCreateStatement( 41 | $blueprint, 42 | 'create rowstore table `test` (`primary` varchar(255) not null, `index` varchar(255) not null, `georegion` geography not null, index `name2`(`index`), index `name3`(`georegion`), primary key (`primary`))' 43 | ); 44 | } 45 | 46 | #[Test] 47 | public function medium_integer_id() 48 | { 49 | $blueprint = $this->createTable(function (Blueprint $table) { 50 | $table->mediumInteger('id', true, true); 51 | }); 52 | 53 | $this->assertCreateStatement( 54 | $blueprint, 55 | 'create table `test` (`id` mediumint unsigned not null auto_increment primary key)' 56 | ); 57 | } 58 | 59 | #[Test] 60 | public function discussion_53() 61 | { 62 | $blueprint = $this->createTable(function (Blueprint $table) { 63 | $table->bigIncrements('id')->withoutPrimaryKey()->index(); 64 | $table->unsignedBigInteger('user_id')->shardKey(); 65 | $table->string('template_id'); 66 | $table->longText('data'); 67 | $table->string('response_status_code'); 68 | $table->longText('response_message'); 69 | $table->timestamps(); 70 | }); 71 | 72 | $this->assertCreateStatement( 73 | $blueprint, 74 | 'create table `test` (`id` bigint unsigned not null auto_increment, `user_id` bigint unsigned not null, `template_id` varchar(255) not null, `data` longtext not null, `response_status_code` varchar(255) not null, `response_message` longtext not null, `created_at` timestamp null, `updated_at` timestamp null, index `test_id_index`(`id`), shard key(`user_id`))' 75 | ); 76 | } 77 | 78 | #[Test] 79 | public function json_column() 80 | { 81 | $blueprint = $this->createTable(function (Blueprint $table) { 82 | $table->id(); 83 | $table->json('data'); 84 | }); 85 | 86 | $this->assertCreateStatement( 87 | $blueprint, 88 | 'create table `test` (`id` bigint unsigned not null auto_increment primary key, `data` json not null)' 89 | ); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/SeriesTimestampTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->date('created_at')->seriesTimestamp(); 19 | }); 20 | 21 | $this->assertCreateStatement( 22 | $blueprint, 23 | 'create table `test` (`created_at` date not null series timestamp)' 24 | ); 25 | } 26 | 27 | #[Test] 28 | public function series_timestamp_sparse() 29 | { 30 | $blueprint = $this->createTable(function (Blueprint $table) { 31 | $table->rowstore(); 32 | 33 | $table->date('created_at')->nullable()->seriesTimestamp()->sparse(); 34 | }); 35 | 36 | $this->assertCreateStatement( 37 | $blueprint, 38 | 'create rowstore table `test` (`created_at` date null sparse series timestamp)' 39 | ); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/ShardKeysTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->string('name'); 19 | 20 | $table->shardKey('name'); 21 | }); 22 | 23 | $this->assertCreateStatement( 24 | $blueprint, 25 | 'create table `test` (`name` varchar(255) not null, shard key(`name`))' 26 | ); 27 | } 28 | 29 | #[Test] 30 | public function it_adds_a_shard_key_fluent() 31 | { 32 | $blueprint = $this->createTable(function (Blueprint $table) { 33 | $table->string('name')->shardKey(); 34 | }); 35 | 36 | $this->assertCreateStatement( 37 | $blueprint, 38 | 'create table `test` (`name` varchar(255) not null, shard key(`name`))' 39 | ); 40 | } 41 | 42 | #[Test] 43 | public function it_adds_a_dual_shard_key() 44 | { 45 | $blueprint = $this->createTable(function (Blueprint $table) { 46 | $table->string('f_name'); 47 | $table->string('l_name'); 48 | 49 | $table->shardKey(['f_name', 'l_name']); 50 | }); 51 | 52 | $this->assertCreateStatement( 53 | $blueprint, 54 | 'create table `test` (`f_name` varchar(255) not null, `l_name` varchar(255) not null, shard key(`f_name`, `l_name`))' 55 | ); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/SortKeysTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 19 | $table->string('name'); 20 | $table->sortKey('name'); 21 | }); 22 | 23 | $this->assertCreateStatement( 24 | $blueprint, 25 | 'create table `test` (`name` varchar(255) not null, sort key(`name` asc))' 26 | ); 27 | } 28 | 29 | #[Test] 30 | public function it_adds_a_sort_key_with_desc_direction_standalone() 31 | { 32 | $blueprint = $this->createTable(function (Blueprint $table) { 33 | $table->string('name'); 34 | $table->sortKey('name', 'desc'); 35 | }); 36 | 37 | $this->assertCreateStatement( 38 | $blueprint, 39 | 'create table `test` (`name` varchar(255) not null, sort key(`name` desc))' 40 | ); 41 | } 42 | 43 | #[Test] 44 | public function it_adds_a_sort_key_fluent() 45 | { 46 | $blueprint = $this->createTable(function (Blueprint $table) { 47 | $table->string('name')->sortKey(); 48 | }); 49 | 50 | $this->assertCreateStatement( 51 | $blueprint, 52 | 'create table `test` (`name` varchar(255) not null, sort key(`name` asc))' 53 | ); 54 | } 55 | 56 | #[Test] 57 | public function it_adds_a_sort_key_with_desc_direction_fluent() 58 | { 59 | $blueprint = $this->createTable(function (Blueprint $table) { 60 | $table->string('name')->sortKey('desc'); 61 | }); 62 | 63 | $this->assertCreateStatement( 64 | $blueprint, 65 | 'create table `test` (`name` varchar(255) not null, sort key(`name` desc))' 66 | ); 67 | } 68 | 69 | #[Test] 70 | public function it_adds_a_dual_sort_key() 71 | { 72 | $blueprint = $this->createTable(function (Blueprint $table) { 73 | $table->string('f_name'); 74 | $table->string('l_name'); 75 | $table->sortKey(['f_name', 'l_name']); 76 | }); 77 | 78 | $this->assertCreateStatement( 79 | $blueprint, 80 | 'create table `test` (`f_name` varchar(255) not null, `l_name` varchar(255) not null, sort key(`f_name` asc, `l_name` asc))' 81 | ); 82 | } 83 | 84 | #[Test] 85 | public function it_adds_a_dual_sort_key_with_desc_direction() 86 | { 87 | $blueprint = $this->createTable(function (Blueprint $table) { 88 | $table->string('f_name'); 89 | $table->string('l_name'); 90 | $table->sortKey(['f_name', 'l_name'], 'desc'); 91 | }); 92 | 93 | $this->assertCreateStatement( 94 | $blueprint, 95 | 'create table `test` (`f_name` varchar(255) not null, `l_name` varchar(255) not null, sort key(`f_name` desc, `l_name` desc))' 96 | ); 97 | } 98 | 99 | #[Test] 100 | public function it_adds_a_dual_sort_key_with_different_directions() 101 | { 102 | $blueprint = $this->createTable(function (Blueprint $table) { 103 | $table->string('f_name'); 104 | $table->string('l_name'); 105 | $table->sortKey([['f_name', 'asc'], ['l_name', 'desc']]); 106 | }); 107 | 108 | $this->assertCreateStatement( 109 | $blueprint, 110 | 'create table `test` (`f_name` varchar(255) not null, `l_name` varchar(255) not null, sort key(`f_name` asc, `l_name` desc))' 111 | ); 112 | } 113 | 114 | #[Test] 115 | public function it_cannot_add_a_dual_sort_key_with_only_one_direction() 116 | { 117 | $this->expectException(InvalidArgumentException::class); 118 | 119 | $blueprint = $this->createTable(function (Blueprint $table) { 120 | $table->string('f_name'); 121 | $table->string('l_name'); 122 | $table->sortKey(['f_name', ['l_name', 'desc']]); 123 | }); 124 | 125 | $blueprint->toSql($this->getConnection(), $this->getGrammar()); 126 | } 127 | 128 | #[Test] 129 | public function it_cannot_add_a_dual_sort_key_with_only_one_direction_desc() 130 | { 131 | $this->expectException(InvalidArgumentException::class); 132 | 133 | $blueprint = $this->createTable(function (Blueprint $table) { 134 | $table->string('f_name'); 135 | $table->string('l_name'); 136 | $table->sortKey(['f_name', ['l_name', 'asc']], 'desc'); 137 | }); 138 | 139 | $blueprint->toSql($this->getConnection(), $this->getGrammar()); 140 | } 141 | 142 | #[Test] 143 | public function shard_and_sort_keys() 144 | { 145 | $blueprint = $this->createTable(function (Blueprint $table) { 146 | $table->string('name')->sortKey()->shardKey(); 147 | }); 148 | 149 | $this->assertCreateStatement( 150 | $blueprint, 151 | 'create table `test` (`name` varchar(255) not null, shard key(`name`), sort key(`name` asc))' 152 | ); 153 | } 154 | 155 | #[Test] 156 | public function it_adds_a_sort_key_with_with_statement() 157 | { 158 | $blueprint = $this->createTable(function (Blueprint $table) { 159 | $table->string('name'); 160 | $table->sortKey('name')->with(['columnstore_segment_rows' => 100000]); 161 | }); 162 | 163 | $this->assertCreateStatement( 164 | $blueprint, 165 | 'create table `test` (`name` varchar(255) not null, sort key(`name` asc) with (columnstore_segment_rows=100000))' 166 | ); 167 | } 168 | 169 | #[Test] 170 | public function it_adds_an_empty_sort_key_with_with_statement() 171 | { 172 | $blueprint = $this->createTable(function (Blueprint $table) { 173 | $table->string('name'); 174 | $table->sortKey()->with(['columnstore_segment_rows' => 100000]); 175 | }); 176 | 177 | $this->assertCreateStatement( 178 | $blueprint, 179 | 'create table `test` (`name` varchar(255) not null, sort key() with (columnstore_segment_rows=100000))' 180 | ); 181 | } 182 | 183 | #[Test] 184 | public function it_adds_a_sort_key_fluent_with_with_statement() 185 | { 186 | $blueprint = $this->createTable(function (Blueprint $table) { 187 | $table->string('name')->sortKey()->with(['columnstore_segment_rows' => 100000]); 188 | }); 189 | 190 | $this->assertCreateStatement( 191 | $blueprint, 192 | 'create table `test` (`name` varchar(255) not null, sort key(`name` asc) with (columnstore_segment_rows=100000))' 193 | ); 194 | } 195 | 196 | #[Test] 197 | public function it_adds_a_sort_key_fluent_with_dual_with_statement() 198 | { 199 | $blueprint = $this->createTable(function (Blueprint $table) { 200 | $table->string('name')->sortKey()->with([ 201 | 'columnstore_segment_rows' => 100000, 202 | 'columnstore_flush_bytes' => 4194304, 203 | ]); 204 | }); 205 | 206 | $this->assertCreateStatement( 207 | $blueprint, 208 | 'create table `test` (`name` varchar(255) not null, sort key(`name` asc) with (columnstore_segment_rows=100000,columnstore_flush_bytes=4194304))' 209 | ); 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/SparseModifiersTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 19 | $table->rowstore(); 20 | 21 | $table->string('name')->nullable()->sparse(); 22 | }); 23 | 24 | $this->assertCreateStatement( 25 | $blueprint, 26 | 'create rowstore table `test` (`name` varchar(255) null sparse)' 27 | ); 28 | } 29 | 30 | #[Test] 31 | public function sparse_table() 32 | { 33 | $blueprint = $this->createTable(function (Blueprint $table) { 34 | $table->rowstore(); 35 | 36 | $table->string('name'); 37 | 38 | $table->sparse(); 39 | }); 40 | 41 | $this->assertCreateStatement( 42 | $blueprint, 43 | 'create rowstore table `test` (`name` varchar(255) not null) compression = sparse' 44 | ); 45 | } 46 | 47 | #[Test] 48 | public function sparse_with_after() 49 | { 50 | // See https://github.com/singlestore-labs/singlestoredb-laravel-driver/issues/18 51 | $connection = $this->getConnection('test'); 52 | $grammar = new SingleStoreSchemaGrammar($connection); 53 | 54 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 55 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 56 | $connection->shouldReceive('getDatabaseName')->andReturn('database'); 57 | 58 | $blueprint = new Blueprint($connection, 'test'); 59 | 60 | $blueprint->string('two_factor_secret') 61 | ->after('password') 62 | ->nullable() 63 | ->sparse(); 64 | 65 | $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); 66 | 67 | $this->assertEquals( 68 | 'alter table `test` add `two_factor_secret` varchar(255) null sparse after `password`', 69 | $statements[0] 70 | ); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/SpatialTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->rowstore(); 19 | 20 | $table->geography('shape')->spatialIndex('idx'); 21 | }); 22 | 23 | $this->assertCreateStatement( 24 | $blueprint, 25 | 'create rowstore table `test` (`shape` geography not null, index `idx`(`shape`))' 26 | ); 27 | } 28 | 29 | #[Test] 30 | public function geography_with_resolution() 31 | { 32 | $blueprint = $this->createTable(function (Blueprint $table) { 33 | $table->rowstore(); 34 | 35 | $table->geography('shape'); 36 | 37 | $table->spatialIndex('shape', 'idx')->resolution(8); 38 | }); 39 | 40 | $this->assertCreateStatement( 41 | $blueprint, 42 | 'create rowstore table `test` (`shape` geography not null, index `idx`(`shape`) with (resolution = 8))' 43 | ); 44 | } 45 | 46 | #[Test] 47 | public function geography_point() 48 | { 49 | $blueprint = $this->createTable(function (Blueprint $table) { 50 | $table->rowstore(); 51 | 52 | $table->point('point1'); 53 | $table->geographyPoint('point2'); 54 | }); 55 | 56 | $this->assertCreateStatement( 57 | $blueprint, 58 | 'create rowstore table `test` (`point1` geographypoint not null, `point2` geographypoint not null)' 59 | ); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/TableModifiersTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 21 | // $table->rowstore(); 22 | // $table->temporary(); 23 | // $table->global(); 24 | // $table->reference(); 25 | // 26 | // $table->string('name'); 27 | // }); 28 | // 29 | // $this->assertCreateStatement( 30 | // $blueprint, 31 | // "create rowstore reference global temporary table `test` (`name` varchar(255) not null)" 32 | // ); 33 | // } 34 | 35 | #[Test] 36 | public function it_creates_a_standard_temp() 37 | { 38 | $blueprint = $this->createTable(function (Blueprint $table) { 39 | $table->temporary(); 40 | 41 | $table->string('name'); 42 | }); 43 | 44 | $this->assertCreateStatement( 45 | $blueprint, 46 | 'create temporary table `test` (`name` varchar(255) not null)' 47 | ); 48 | } 49 | 50 | #[Test] 51 | public function it_creates_a_global_temp() 52 | { 53 | $blueprint = $this->createTable(function (Blueprint $table) { 54 | $table->rowstore(); 55 | $table->temporary(); 56 | $table->global(); 57 | 58 | $table->string('name'); 59 | }); 60 | 61 | $this->assertCreateStatement( 62 | $blueprint, 63 | 'create rowstore global temporary table `test` (`name` varchar(255) not null)' 64 | ); 65 | } 66 | 67 | #[Test] 68 | public function it_creates_a_global_temp_chained() 69 | { 70 | $blueprint = $this->createTable(function (Blueprint $table) { 71 | $table->rowstore()->temporary()->global(); 72 | 73 | $table->string('name'); 74 | }); 75 | 76 | $this->assertCreateStatement( 77 | $blueprint, 78 | 'create rowstore global temporary table `test` (`name` varchar(255) not null)' 79 | ); 80 | } 81 | 82 | #[Test] 83 | public function it_creates_a_global_temp_style_two() 84 | { 85 | $blueprint = $this->createTable(function (Blueprint $table) { 86 | $table->temporary($global = true); 87 | $table->rowstore(); 88 | 89 | $table->string('name'); 90 | }); 91 | 92 | $this->assertCreateStatement( 93 | $blueprint, 94 | 'create rowstore global temporary table `test` (`name` varchar(255) not null)' 95 | ); 96 | } 97 | 98 | #[Test] 99 | public function it_creates_a_global_temp_rowstore() 100 | { 101 | $blueprint = $this->createTable(function (Blueprint $table) { 102 | $table->rowstore(); 103 | $table->temporary(); 104 | $table->global(); 105 | 106 | $table->string('name'); 107 | }); 108 | 109 | $this->assertCreateStatement( 110 | $blueprint, 111 | 'create rowstore global temporary table `test` (`name` varchar(255) not null)' 112 | ); 113 | } 114 | 115 | #[Test] 116 | public function it_creates_a_reference() 117 | { 118 | $blueprint = $this->createTable(function (Blueprint $table) { 119 | $table->reference(); 120 | 121 | $table->string('name'); 122 | }); 123 | 124 | $this->assertCreateStatement( 125 | $blueprint, 126 | 'create reference table `test` (`name` varchar(255) not null)' 127 | ); 128 | } 129 | 130 | #[Test] 131 | public function it_creates_a_rowstore_reference() 132 | { 133 | $blueprint = $this->createTable(function (Blueprint $table) { 134 | $table->reference(); 135 | $table->rowstore(); 136 | 137 | $table->id(); 138 | $table->string('name'); 139 | }); 140 | 141 | $this->assertCreateStatement( 142 | $blueprint, 143 | 'create rowstore reference table `test` (`id` bigint unsigned not null auto_increment primary key, `name` varchar(255) not null)' 144 | ); 145 | } 146 | 147 | #[Test] 148 | public function it_creates_a_default() 149 | { 150 | $blueprint = $this->createTable(function (Blueprint $table) { 151 | // Just to ensure we haven't messed up the default case with all our modifier logic. 152 | $table->string('name'); 153 | }); 154 | 155 | $this->assertCreateStatement( 156 | $blueprint, 157 | 'create table `test` (`name` varchar(255) not null)' 158 | ); 159 | } 160 | } 161 | -------------------------------------------------------------------------------- /tests/Hybrid/CreateTable/UniqueKeysTest.php: -------------------------------------------------------------------------------- 1 | createTable(function (Blueprint $table) { 18 | $table->string('key'); 19 | $table->string('val'); 20 | 21 | $table->shardKey('key'); 22 | $table->unique(['key', 'val']); 23 | }); 24 | 25 | $this->assertCreateStatement( 26 | $blueprint, 27 | 'create table `test` (`key` varchar(255) not null, `val` varchar(255) not null, shard key(`key`), unique `test_key_val_unique`(`key`, `val`))' 28 | ); 29 | } 30 | 31 | #[Test] 32 | public function it_adds_a_unique_key_reference_fluent() 33 | { 34 | $blueprint = $this->createTable(function (Blueprint $table) { 35 | $table->reference(); 36 | $table->string('name')->unique(); 37 | }); 38 | 39 | $this->assertCreateStatement( 40 | $blueprint, 41 | 'create reference table `test` (`name` varchar(255) not null, unique `test_name_unique`(`name`))' 42 | ); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/Hybrid/DropAllTablesTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 18 | return; 19 | } 20 | 21 | $this->mockDatabaseConnection = false; 22 | 23 | Schema::dropIfExists('test_drop_1'); 24 | Schema::dropIfExists('test_drop_2'); 25 | 26 | $this->assertFalse(Schema::hasTable('test_drop_1')); 27 | $this->assertFalse(Schema::hasTable('test_drop_2')); 28 | 29 | Schema::create('test_drop_1', function (Blueprint $table) { 30 | $table->id(); 31 | }); 32 | 33 | Schema::create('test_drop_2', function (Blueprint $table) { 34 | $table->id(); 35 | }); 36 | 37 | $this->assertTrue(Schema::hasTable('test_drop_1')); 38 | $this->assertTrue(Schema::hasTable('test_drop_2')); 39 | 40 | $this->getConnection()->getSchemaBuilder()->dropAllTables(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /tests/Hybrid/FulltextTest.php: -------------------------------------------------------------------------------- 1 | whereFullText('title', 'performance'); 19 | 20 | $this->assertEquals( 21 | 'select * from `test` where MATCH (`title`) AGAINST (?)', 22 | $query->toSql() 23 | ); 24 | 25 | $this->assertSame('performance', $query->getBindings()[0]); 26 | 27 | if (! $this->runHybridIntegrations()) { 28 | return; 29 | } 30 | 31 | $this->createTable(function (Blueprint $table) { 32 | $table->id(); 33 | $table->text('title')->collation('utf8_unicode_ci'); 34 | 35 | $table->fullText(['title']); 36 | }); 37 | 38 | DB::table('test')->insert([[ 39 | 'title' => 'Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems', 40 | ], [ 41 | 'title' => 'Data Pipelines Pocket Reference: Moving and Processing Data for Analytics', 42 | ], [ 43 | 'title' => 'Data Quality Fundamentals', 44 | ], [ 45 | 'title' => 'High Performance MySQL: Optimization, Backups, and Replication', 46 | ]]); 47 | 48 | // Force the index to be updated immediately, as it may happen async a little later 49 | DB::statement('OPTIMIZE TABLE test FLUSH'); 50 | 51 | $this->assertSame( 52 | 'High Performance MySQL: Optimization, Backups, and Replication', 53 | $query->get()[0]->title 54 | ); 55 | } 56 | 57 | #[Test] 58 | public function fulltext_multicolumn() 59 | { 60 | $query = DB::table('test')->whereFullText(['name', 'race'], 'Laika'); 61 | 62 | $this->assertEquals( 63 | 'select * from `test` where MATCH (`name`, `race`) AGAINST (?)', 64 | $query->toSql() 65 | ); 66 | 67 | $this->assertSame('Laika', $query->getBindings()[0]); 68 | 69 | if (! $this->runHybridIntegrations()) { 70 | return; 71 | } 72 | 73 | $this->createTable(function (Blueprint $table) { 74 | $table->id(); 75 | $table->text('name')->collation('utf8_unicode_ci'); 76 | $table->text('race')->collation('utf8_unicode_ci'); 77 | 78 | $table->fullText(['name', 'race']); 79 | }); 80 | 81 | DB::table('test')->insert([[ 82 | 'name' => 'Laika', 83 | 'race' => 'Dog', 84 | ], [ 85 | 'name' => 'Ham', 86 | 'race' => 'Monkey', 87 | ]]); 88 | 89 | // Force the index to be updated immediately, as it may happen async a little later 90 | DB::statement('OPTIMIZE TABLE test FLUSH'); 91 | 92 | $this->assertSame('Laika', $query->get()[0]->name); 93 | } 94 | 95 | #[Test] 96 | public function throws_exception_when_using_an_unsupported_collation() 97 | { 98 | if (! $this->runHybridIntegrations()) { 99 | return; 100 | } 101 | 102 | if (version_compare(parent::singlestoreVersion(), '8.1.0', '>=')) { 103 | // fulltext with utf8mb4_general_ci is supported in newer SingleStore 104 | $this->markTestSkipped('requires lower SingleStore version'); 105 | 106 | return; 107 | } 108 | 109 | try { 110 | // The default collation is utf8mb4_general_ci, which is unsupported for FULLTEXT 111 | $this->createTable(function (Blueprint $table) { 112 | $table->id(); 113 | $table->text('name'); 114 | 115 | $table->fullText(['name']); 116 | }); 117 | } catch (\Exception $exception) { 118 | $this->assertEquals( 119 | 'FULLTEXT is not supported when using the utf8mb4 collation.', 120 | $exception->getMessage() 121 | ); 122 | 123 | return; 124 | } 125 | 126 | $this->fail('Did not throw exception when using an unsupported collation'); 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /tests/Hybrid/GroupLimitTest.php: -------------------------------------------------------------------------------- 1 | orderBy('id')->groupLimit(2, 'group'); 18 | $this->assertEquals( 19 | 'select * from (select *, row_number() over (partition by `group` order by `id` asc) as `laravel_row` from `test`) as `laravel_table` where `laravel_row` <= 2 order by `laravel_row`', 20 | $query->toSql() 21 | ); 22 | 23 | if (! $this->runHybridIntegrations()) { 24 | return; 25 | } 26 | 27 | $this->createTable(function (Blueprint $table) { 28 | $table->id(); 29 | $table->integer('group'); 30 | }); 31 | 32 | DB::table('test')->insert([ 33 | ['id' => 1, 'group' => 1], 34 | ['id' => 2, 'group' => 1], 35 | ['id' => 3, 'group' => 1], 36 | ['id' => 4, 'group' => 2], 37 | ['id' => 5, 'group' => 3], 38 | ['id' => 6, 'group' => 3], 39 | ['id' => 7, 'group' => 3], 40 | ['id' => 8, 'group' => 3], 41 | ]); 42 | 43 | $ids = $query->get(['id'])->pluck('id')->toArray(); 44 | sort($ids); 45 | $this->assertEquals($ids, [1, 2, 4, 5, 6]); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /tests/Hybrid/HybridTestHelpers.php: -------------------------------------------------------------------------------- 1 | getConnection($connection, $table)); 25 | } 26 | 27 | protected function runHybridIntegrations() 28 | { 29 | return env('HYBRID_INTEGRATION') == 1; 30 | } 31 | 32 | protected function getDatabaseConnection($connection = null, $table = null) 33 | { 34 | return $this->mockDatabaseConnection 35 | ? $this->mockedConnection() 36 | : parent::getConnection($connection, $table); 37 | } 38 | 39 | protected function mockedConnection() 40 | { 41 | $connection = Mockery::mock(SingleStoreConnection::class); 42 | $grammar = new SingleStoreSchemaGrammar($connection); 43 | 44 | $connection->shouldReceive('getConfig')->atMost()->once()->with('charset')->andReturn(null); 45 | $connection->shouldReceive('getConfig')->atMost()->once()->with('collation')->andReturn(null); 46 | $connection->shouldReceive('getConfig')->atMost()->once()->with('engine')->andReturn(null); 47 | $connection->shouldReceive('getConfig')->atMost()->once()->with('prefix_indexes')->andReturn(null); 48 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 49 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 50 | $connection->shouldReceive('getSchemaBuilder')->andReturn(new SingleStoreSchemaBuilder($connection)); 51 | 52 | return $connection; 53 | } 54 | 55 | protected function tearDown(): void 56 | { 57 | parent::tearDown(); 58 | 59 | Mockery::close(); 60 | } 61 | 62 | protected function assertCreateStatement($blueprint, $sql) 63 | { 64 | $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()); 65 | 66 | $this->assertCount(1, $statements); 67 | $this->assertEquals($sql, $statements[0]); 68 | 69 | return $statements; 70 | } 71 | 72 | protected function createTable($fn) 73 | { 74 | if ($this->runHybridIntegrations()) { 75 | $cached = $this->mockDatabaseConnection; 76 | 77 | $this->mockDatabaseConnection = false; 78 | 79 | Schema::dropIfExists('test'); 80 | $this->assertFalse(Schema::hasTable('test')); 81 | Schema::create('test', $fn); 82 | 83 | // Can't assert table exists, because some tables are temp. If the table 84 | // wasn't successfully created, this will throw an error, so we're 85 | // just asserting a blank set of results comes back. 86 | $this->assertTrue(DB::table('test')->select('*')->get() instanceof Collection); 87 | 88 | $this->mockDatabaseConnection = $cached; 89 | } 90 | 91 | $blueprint = new Blueprint($this->getConnection(), 'test'); 92 | $blueprint->create(); 93 | 94 | call_user_func($fn, $blueprint); 95 | 96 | return $blueprint; 97 | } 98 | 99 | protected function insertJsonData($records) 100 | { 101 | $this->createTable(function (Blueprint $table) { 102 | $table->id(); 103 | $table->json('data'); 104 | }); 105 | 106 | $ids = []; 107 | 108 | foreach ($records as $record) { 109 | DB::table('test')->insert([ 110 | 'id' => static::$counter, 111 | 'data' => json_encode($record), 112 | ]); 113 | 114 | $ids[] = static::$counter++; 115 | } 116 | 117 | return $ids; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /tests/Hybrid/Json/JsonContainsTest.php: -------------------------------------------------------------------------------- 1 | whereJsonContains('data->array', 'en'); 24 | 25 | $this->assertEquals( 26 | "select * from `test` where JSON_ARRAY_CONTAINS_JSON(JSON_EXTRACT_JSON(data, 'array'), ?)", 27 | $query->toSql() 28 | ); 29 | 30 | $this->assertSame('"en"', $query->getBindings()[0]); 31 | 32 | if (! $this->runHybridIntegrations()) { 33 | return; 34 | } 35 | 36 | [$id1] = $this->insertJsonData([ 37 | ['array' => ['en', 1, true, ['a' => 'b']]], 38 | ['array' => ['es', 2, false, ['c' => 'd']]], 39 | ]); 40 | 41 | $this->assertEquals($id1, $query->first()->id); 42 | $this->assertEquals(1, $query->count()); 43 | } 44 | 45 | #[Test] 46 | public function json_contains_double() 47 | { 48 | $query = DB::table('test')->whereJsonContains('data->array', 1.5); 49 | 50 | $this->assertEquals( 51 | "select * from `test` where JSON_ARRAY_CONTAINS_JSON(JSON_EXTRACT_JSON(data, 'array'), ?)", 52 | $query->toSql() 53 | ); 54 | 55 | $this->assertSame('1.5', $query->getBindings()[0]); 56 | 57 | if (! $this->runHybridIntegrations()) { 58 | return; 59 | } 60 | 61 | [$id1] = $this->insertJsonData([ 62 | ['array' => ['en', 1.5, true, ['a' => 'b']]], 63 | ['array' => ['es', 2.5, false, ['c' => 'd']]], 64 | ]); 65 | 66 | $this->assertEquals($id1, $query->first()->id); 67 | $this->assertEquals(1, $query->count()); 68 | } 69 | 70 | #[Test] 71 | public function json_contains_int() 72 | { 73 | $query = DB::table('test')->whereJsonContains('data->array', 1); 74 | 75 | $this->assertEquals( 76 | "select * from `test` where JSON_ARRAY_CONTAINS_JSON(JSON_EXTRACT_JSON(data, 'array'), ?)", 77 | $query->toSql() 78 | ); 79 | 80 | $this->assertSame('1', $query->getBindings()[0]); 81 | 82 | if (! $this->runHybridIntegrations()) { 83 | return; 84 | } 85 | 86 | [$id1] = $this->insertJsonData([ 87 | ['array' => ['en', 1, true, ['a' => 'b']]], 88 | ['array' => ['es', 2, false, ['c' => 'd']]], 89 | ]); 90 | 91 | $this->assertEquals($id1, $query->first()->id); 92 | $this->assertEquals(1, $query->count()); 93 | } 94 | 95 | #[Test] 96 | public function json_contains_bool() 97 | { 98 | $query = DB::table('test')->whereJsonContains('data->array', true); 99 | 100 | $this->assertEquals( 101 | "select * from `test` where JSON_ARRAY_CONTAINS_JSON(JSON_EXTRACT_JSON(data, 'array'), ?)", 102 | $query->toSql() 103 | ); 104 | 105 | $this->assertSame('true', $query->getBindings()[0]); 106 | 107 | if (! $this->runHybridIntegrations()) { 108 | return; 109 | } 110 | 111 | [$id1] = $this->insertJsonData([ 112 | ['array' => ['en', 1, true, ['a' => 'b']]], 113 | ['array' => ['es', 2, false, ['c' => 'd']]], 114 | ]); 115 | 116 | $this->assertEquals($id1, $query->first()->id); 117 | $this->assertEquals(1, $query->count()); 118 | } 119 | 120 | #[Test] 121 | public function json_contains_json() 122 | { 123 | $query = DB::table('test')->whereJsonContains('data->array', ['a' => 'b']); 124 | 125 | $this->assertEquals( 126 | "select * from `test` where JSON_ARRAY_CONTAINS_JSON(JSON_EXTRACT_JSON(data, 'array'), ?)", 127 | $query->toSql() 128 | ); 129 | 130 | $this->assertEquals('{"a":"b"}', $query->getBindings()[0]); 131 | 132 | if (! $this->runHybridIntegrations()) { 133 | return; 134 | } 135 | 136 | [$id1] = $this->insertJsonData([ 137 | ['array' => ['en', 1, true, ['a' => 'b']]], 138 | ['array' => ['es', 2, false, ['c' => 'd']]], 139 | ]); 140 | 141 | $this->assertEquals($id1, $query->first()->id); 142 | $this->assertEquals(1, $query->count()); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /tests/Hybrid/Json/JsonKeypathsTest.php: -------------------------------------------------------------------------------- 1 | where('data', '[]'); 18 | 19 | $this->assertEquals( 20 | 'select * from `test` where `data` = ?', 21 | $query->toSql() 22 | ); 23 | 24 | if (! $this->runHybridIntegrations()) { 25 | return; 26 | } 27 | 28 | [$id1] = $this->insertJsonData([[ 29 | // 30 | ], [ 31 | 1, 32 | ]]); 33 | 34 | $this->assertEquals($id1, $query->first()->id); 35 | $this->assertEquals(1, $query->count()); 36 | } 37 | 38 | #[Test] 39 | public function it_compiles_nested_json_path() 40 | { 41 | $query = DB::table('test')->where('data->value1->value2->value3->value4', 2); 42 | 43 | $this->assertEquals( 44 | "select * from `test` where JSON_EXTRACT_STRING(data, 'value1', 'value2', 'value3', 'value4') = ?", 45 | $query->toSql() 46 | ); 47 | 48 | if (! $this->runHybridIntegrations()) { 49 | return; 50 | } 51 | 52 | [, $id2] = $this->insertJsonData([[ 53 | 'value1' => ['value2' => ['value3' => ['value4' => 1]]], 54 | ], [ 55 | 'value1' => ['value2' => ['value3' => ['value4' => 2]]], 56 | ], [ 57 | 'value1' => ['value2' => ['value3' => ['value4' => 3]]], 58 | ]]); 59 | 60 | $this->assertEquals($id2, $query->first()->id); 61 | $this->assertEquals(1, $query->count()); 62 | } 63 | 64 | #[Test] 65 | public function it_compiles_nested_json_path_with_array_access() 66 | { 67 | $query = DB::table('test')->where('data->value1[0]->value2[2][0]', 1); 68 | 69 | $this->assertEquals( 70 | "select * from `test` where JSON_EXTRACT_STRING(data, 'value1', 0, 'value2', 2, 0) = ?", 71 | $query->toSql() 72 | ); 73 | 74 | if (! $this->runHybridIntegrations()) { 75 | return; 76 | } 77 | 78 | [$id1] = $this->insertJsonData([[ 79 | 'value1' => [['value2' => [[], [], [1]]]], 80 | ], [ 81 | 'value1' => [['value2' => [[], [], [2]]]], 82 | ]]); 83 | 84 | $this->assertEquals($id1, $query->first()->id); 85 | $this->assertEquals(1, $query->count()); 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /tests/Hybrid/Json/JsonUpdateTest.php: -------------------------------------------------------------------------------- 1 | table('test')->update([ 19 | 'data->value1' => true, 20 | ]); 21 | }); 22 | 23 | $this->assertEquals( 24 | "update `test` set data = JSON_SET_JSON(data, 'value1', 'true')", 25 | $logs['query'] 26 | ); 27 | } 28 | 29 | #[Test] 30 | public function set_boolean_execution() 31 | { 32 | if (! $this->runHybridIntegrations()) { 33 | return; 34 | } 35 | 36 | $this->insertJsonData([ 37 | ['value1' => false], 38 | ]); 39 | 40 | $this->assertEquals(1, DB::table('test')->where('data->value1', false)->count()); 41 | 42 | DB::table('test')->update([ 43 | 'data->value1' => true, 44 | ]); 45 | 46 | $this->assertEquals(0, DB::table('test')->where('data->value1', false)->count()); 47 | $this->assertEquals(1, DB::table('test')->where('data->value1', true)->count()); 48 | } 49 | 50 | #[Test] 51 | public function set_string_syntax() 52 | { 53 | if (! $this->runHybridIntegrations()) { 54 | return; 55 | } 56 | 57 | [$logs] = DB::pretend(function ($database) { 58 | $database->table('test')->update([ 59 | 'data->value1' => 'foo', 60 | ]); 61 | }); 62 | 63 | $this->assertEquals( 64 | "update `test` set data = JSON_SET_JSON(data, 'value1', '\\\"foo\\\"')", 65 | $logs['query'] 66 | ); 67 | 68 | $this->assertSame('"foo"', $logs['bindings'][0]); 69 | } 70 | 71 | #[Test] 72 | public function set_string_execution() 73 | { 74 | if (! $this->runHybridIntegrations()) { 75 | return; 76 | } 77 | 78 | $this->insertJsonData([ 79 | ['value1' => 'foo'], 80 | ]); 81 | 82 | $this->assertEquals(1, DB::table('test')->where('data->value1', 'foo')->count()); 83 | 84 | DB::table('test')->update([ 85 | 'data->value1' => 'bar', 86 | ]); 87 | 88 | $this->assertEquals(0, DB::table('test')->where('data->value1', 'foo')->count()); 89 | $this->assertEquals(1, DB::table('test')->where('data->value1', 'bar')->count()); 90 | } 91 | 92 | #[Test] 93 | public function set_double_syntax() 94 | { 95 | [$logs] = DB::pretend(function ($database) { 96 | $database->table('test')->update([ 97 | 'data->value1' => 1.3, 98 | ]); 99 | }); 100 | 101 | $this->assertEquals( 102 | "update `test` set data = JSON_SET_JSON(data, 'value1', 1.3)", 103 | $logs['query'] 104 | ); 105 | 106 | $this->assertSame(1.3, $logs['bindings'][0]); 107 | } 108 | 109 | #[Test] 110 | public function set_double_execution() 111 | { 112 | if (! $this->runHybridIntegrations()) { 113 | return; 114 | } 115 | 116 | $this->insertJsonData([ 117 | ['value1' => 1.3], 118 | ]); 119 | 120 | $this->assertEquals(1, DB::table('test')->where('data->value1', 1.3)->count()); 121 | 122 | DB::table('test')->update([ 123 | 'data->value1' => 1.5, 124 | ]); 125 | 126 | $this->assertEquals(0, DB::table('test')->where('data->value1', 1.3)->count()); 127 | $this->assertEquals(1, DB::table('test')->where('data->value1', 1.5)->count()); 128 | } 129 | 130 | #[Test] 131 | public function set_json_syntax() 132 | { 133 | if (! $this->runHybridIntegrations()) { 134 | return; 135 | } 136 | 137 | [$logs] = DB::pretend(function ($database) { 138 | $database->table('test')->update([ 139 | 'data->value1' => ['foo' => 'bar'], 140 | ]); 141 | }); 142 | 143 | $this->assertEquals( 144 | "update `test` set data = JSON_SET_JSON(data, 'value1', '{\\\"foo\\\":\\\"bar\\\"}')", 145 | $logs['query'] 146 | ); 147 | 148 | $this->assertSame('{"foo":"bar"}', $logs['bindings'][0]); 149 | } 150 | 151 | #[Test] 152 | public function set_json_execution() 153 | { 154 | if (! $this->runHybridIntegrations()) { 155 | return; 156 | } 157 | 158 | $this->insertJsonData([ 159 | ['value1' => ['foo' => 'bar']], 160 | ]); 161 | 162 | $this->assertEquals(1, DB::table('test')->where('data->value1', json_encode(['foo' => 'bar']))->count()); 163 | 164 | DB::table('test')->update([ 165 | 'data->value1' => ['foo' => 'baz'], 166 | ]); 167 | 168 | $this->assertEquals(0, DB::table('test')->where('data->value1', json_encode(['foo' => 'bar']))->count()); 169 | 170 | $this->assertEquals(1, DB::table('test')->where('data->value1', json_encode(['foo' => 'baz']))->count()); 171 | } 172 | } 173 | -------------------------------------------------------------------------------- /tests/Hybrid/Json/JsonWhereTest.php: -------------------------------------------------------------------------------- 1 | where('data->value1->value2', 1); 18 | 19 | $this->assertEquals( 20 | "select * from `test` where JSON_EXTRACT_STRING(data, 'value1', 'value2') = ?", 21 | $query->toSql() 22 | ); 23 | 24 | $this->assertSame(1, $query->getBindings()[0]); 25 | } 26 | 27 | #[Test] 28 | public function singlestore_will_cast_all_types() 29 | { 30 | $query1 = DB::table('test')->where('data->value1->value2', 'string'); 31 | $query2 = DB::table('test')->where('data->value1->value2', 1); 32 | $query3 = DB::table('test')->where('data->value1->value2', 1.5); 33 | $query4 = DB::table('test')->where('data->value1->value2', json_encode(['a' => 'b'])); 34 | 35 | if (! $this->runHybridIntegrations()) { 36 | return; 37 | } 38 | 39 | [$id1, $id2, $id3, $id4] = $this->insertJsonData([ 40 | ['value1' => ['value2' => 'string']], 41 | ['value1' => ['value2' => 1]], 42 | ['value1' => ['value2' => 1.5]], 43 | ['value1' => ['value2' => ['a' => 'b']]], 44 | ]); 45 | 46 | $this->assertEquals($id1, $query1->first()->id); 47 | $this->assertEquals(1, $query1->count()); 48 | 49 | $this->assertEquals($id2, $query2->first()->id); 50 | $this->assertEquals(1, $query2->count()); 51 | 52 | $this->assertEquals($id3, $query3->first()->id); 53 | $this->assertEquals(1, $query3->count()); 54 | 55 | $this->assertEquals($id4, $query4->first()->id); 56 | $this->assertEquals(1, $query4->count()); 57 | } 58 | 59 | #[Test] 60 | public function json_boolean() 61 | { 62 | $query1 = DB::table('test')->where('data->value1->value2', true); 63 | $query2 = DB::table('test')->where('data->value1->value2', false); 64 | 65 | $this->assertEquals( 66 | "select * from `test` where JSON_EXTRACT_DOUBLE(data, 'value1', 'value2') = true", 67 | $query1->toSql() 68 | ); 69 | 70 | $this->assertEquals( 71 | "select * from `test` where JSON_EXTRACT_DOUBLE(data, 'value1', 'value2') = false", 72 | $query2->toSql() 73 | ); 74 | 75 | if (! $this->runHybridIntegrations()) { 76 | return; 77 | } 78 | 79 | [$id1, $id2] = $this->insertJsonData([ 80 | ['value1' => ['value2' => true]], 81 | ['value1' => ['value2' => false]], 82 | ]); 83 | 84 | $this->assertEquals($id1, $query1->first()->id); 85 | $this->assertEquals(1, $query1->count()); 86 | 87 | $this->assertEquals($id2, $query2->first()->id); 88 | $this->assertEquals(1, $query1->count()); 89 | } 90 | 91 | #[Test] 92 | public function nested_where() 93 | { 94 | $query = DB::table('test')->where(function ($query) { 95 | $query->where('data->value1', 'foo')->orWhere(function ($query) { 96 | $query->where('data->value2', 1); 97 | }); 98 | }); 99 | 100 | $this->assertEquals( 101 | "select * from `test` where (JSON_EXTRACT_STRING(data, 'value1') = ? or (JSON_EXTRACT_STRING(data, 'value2') = ?))", 102 | $query->toSql() 103 | ); 104 | } 105 | 106 | #[Test] 107 | public function where_null() 108 | { 109 | $query = DB::table('test')->whereNull('data->value1')->orderBy('id'); 110 | 111 | $this->assertEquals( 112 | // @TODO check docs 113 | "select * from `test` where (JSON_EXTRACT_JSON(data, 'value1') IS NULL OR JSON_GET_TYPE(JSON_EXTRACT_JSON(data, 'value1')) = 'NULL') order by `id` asc", 114 | $query->toSql() 115 | ); 116 | 117 | if (! $this->runHybridIntegrations()) { 118 | return; 119 | } 120 | 121 | [, $id2, $id3] = $this->insertJsonData([ 122 | ['value1' => ['value2' => 'string']], 123 | ['value1' => null], 124 | [null], 125 | ['value1' => ['value2' => 1]], 126 | ]); 127 | 128 | $this->assertEquals($id2, $query->get()[0]->id); 129 | $this->assertEquals($id3, $query->get()[1]->id); 130 | } 131 | 132 | #[Test] 133 | public function where_null_raw() 134 | { 135 | $query = DB::table('test')->whereNull(DB::raw('(SELECT NULL)'))->orderBy('id'); 136 | 137 | $this->assertEquals( 138 | 'select * from `test` where (SELECT NULL) is null order by `id` asc', 139 | $query->toSql() 140 | ); 141 | 142 | if (! $this->runHybridIntegrations()) { 143 | return; 144 | } 145 | 146 | [$id1, $id2, $id3, $id4] = $this->insertJsonData([ 147 | ['value1' => ['value2' => 'string']], 148 | ['value1' => null], 149 | [null], 150 | ['value1' => ['value2' => 1]], 151 | ]); 152 | 153 | $this->assertEquals($id1, $query->get()[0]->id); 154 | $this->assertEquals($id2, $query->get()[1]->id); 155 | $this->assertEquals($id3, $query->get()[2]->id); 156 | $this->assertEquals($id4, $query->get()[3]->id); 157 | } 158 | 159 | #[Test] 160 | public function where_not_null() 161 | { 162 | $query = DB::table('test')->whereNotNull('data->value1')->orderBy('id'); 163 | 164 | $this->assertEquals( 165 | // @TODO check docs 166 | "select * from `test` where (JSON_EXTRACT_JSON(data, 'value1') IS NOT NULL AND JSON_GET_TYPE(JSON_EXTRACT_JSON(data, 'value1')) != 'NULL') order by `id` asc", 167 | $query->toSql() 168 | ); 169 | 170 | if (! $this->runHybridIntegrations()) { 171 | return; 172 | } 173 | 174 | [$id1,,, $id4] = $this->insertJsonData([ 175 | ['value1' => ['value2' => 'string']], 176 | ['value1' => null], 177 | [null], 178 | ['value1' => ['value2' => 1]], 179 | ]); 180 | 181 | $this->assertEquals($id1, $query->get()[0]->id); 182 | $this->assertEquals($id4, $query->get()[1]->id); 183 | } 184 | 185 | #[Test] 186 | public function where_not_null_raw() 187 | { 188 | $query = DB::table('test')->whereNotNull(DB::raw('(SELECT 1)'))->orderBy('id'); 189 | 190 | $this->assertEquals( 191 | 'select * from `test` where (SELECT 1) is not null order by `id` asc', 192 | $query->toSql() 193 | ); 194 | 195 | if (! $this->runHybridIntegrations()) { 196 | return; 197 | } 198 | 199 | [$id1, $id2, $id3, $id4] = $this->insertJsonData([ 200 | ['value1' => ['value2' => 'string']], 201 | ['value1' => null], 202 | [null], 203 | ['value1' => ['value2' => 1]], 204 | ]); 205 | 206 | $this->assertEquals($id1, $query->get()[0]->id); 207 | $this->assertEquals($id2, $query->get()[1]->id); 208 | $this->assertEquals($id3, $query->get()[2]->id); 209 | $this->assertEquals($id4, $query->get()[3]->id); 210 | } 211 | } 212 | -------------------------------------------------------------------------------- /tests/Hybrid/OptionTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 19 | $this->createTable(function (Blueprint $table) { 20 | $table->id(); 21 | }); 22 | } 23 | } 24 | 25 | #[Test] 26 | public function single_option() 27 | { 28 | $query = DB::table('test')->options(['interpreter_mode' => 'compile']); 29 | echo get_class($query); 30 | $this->assertEquals('select * from `test` OPTION (interpreter_mode=compile)', $query->toSql()); 31 | 32 | if ($this->runHybridIntegrations()) { 33 | $query->get(); 34 | } 35 | } 36 | 37 | #[Test] 38 | public function empty_option() 39 | { 40 | $query = DB::table('test')->options([]); 41 | echo get_class($query); 42 | $this->assertEquals('select * from `test`', $query->toSql()); 43 | 44 | if ($this->runHybridIntegrations()) { 45 | $query->get(); 46 | } 47 | } 48 | 49 | #[Test] 50 | public function multi_option() 51 | { 52 | $query = DB::table('test')->options(['interpreter_mode' => 'compile', 'resource_pool' => 'default_pool']); 53 | echo get_class($query); 54 | $this->assertEquals('select * from `test` OPTION (interpreter_mode=compile,resource_pool=default_pool)', $query->toSql()); 55 | 56 | if ($this->runHybridIntegrations()) { 57 | $query->get(); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /tests/Hybrid/OrderByTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 18 | return; 19 | } 20 | 21 | $this->createTable(function (Blueprint $table) { 22 | $table->id(); 23 | }); 24 | 25 | DB::table('test')->insert([ 26 | ['id' => 1], 27 | ]); 28 | 29 | DB::table('test')->orderBy('id', 'asc')->delete(); 30 | } 31 | 32 | #[Test] 33 | public function ignores_order_by_in_update() 34 | { 35 | if (! $this->runHybridIntegrations()) { 36 | return; 37 | } 38 | 39 | $this->createTable(function (Blueprint $table) { 40 | $table->id(); 41 | $table->string('a'); 42 | }); 43 | 44 | DB::table('test')->insert([ 45 | ['id' => 1, 'a' => 'a'], 46 | ]); 47 | 48 | DB::table('test')->orderBy('id', 'asc')->update(['id' => 1, 'a' => 'b']); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /tests/Hybrid/OverridesGetConnection.php: -------------------------------------------------------------------------------- 1 | getDatabaseConnection($connection, $table); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tests/Hybrid/RenameTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 20 | $this->createTable(function (Blueprint $table) { 21 | $table->id(); 22 | }); 23 | } 24 | } 25 | 26 | protected function tearDown(): void 27 | { 28 | if ($this->runHybridIntegrations()) { 29 | Schema::dropIfExists('test_renamed'); 30 | } 31 | 32 | parent::tearDown(); 33 | } 34 | 35 | #[Test] 36 | public function rename_table() 37 | { 38 | if ($this->runHybridIntegrations()) { 39 | $cached = $this->mockDatabaseConnection; 40 | 41 | $this->mockDatabaseConnection = false; 42 | 43 | $this->assertFalse(Schema::hasTable('test_renamed')); 44 | Schema::rename('test', 'test_renamed'); 45 | 46 | $this->assertTrue(Schema::hasTable('test_renamed')); 47 | 48 | $this->mockDatabaseConnection = $cached; 49 | } 50 | 51 | $connection = $this->getConnection('test'); 52 | $grammar = new SingleStoreSchemaGrammar($connection); 53 | 54 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 55 | $connection->shouldReceive('getDatabaseName')->andReturn('database'); 56 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 57 | 58 | $blueprint = new Blueprint($connection, 'test'); 59 | $blueprint->rename('test_renamed'); 60 | 61 | $statements = $blueprint->toSql(); 62 | 63 | $this->assertCount(1, $statements); 64 | $this->assertEquals('alter table `test` rename to `test_renamed`', $statements[0]); 65 | } 66 | 67 | #[Test] 68 | public function rename_column() 69 | { 70 | if ($this->runHybridIntegrations()) { 71 | $cached = $this->mockDatabaseConnection; 72 | 73 | $this->mockDatabaseConnection = false; 74 | 75 | $this->createTable(function (Blueprint $table) { 76 | $table->id(); 77 | $table->string('data'); 78 | }); 79 | 80 | Schema::table('test', function (Blueprint $table) { 81 | $table->renameColumn('data', 'data1'); 82 | }); 83 | 84 | $columnNames = Schema::getColumnListing('test'); 85 | $this->assertEquals(['id', 'data1'], $columnNames); 86 | 87 | $this->mockDatabaseConnection = $cached; 88 | } 89 | 90 | $connection = $this->getConnection('test'); 91 | $grammar = new SingleStoreSchemaGrammar($connection); 92 | 93 | $connection->shouldReceive('getSchemaGrammar')->andReturn($grammar); 94 | $connection->shouldReceive('getDatabaseName')->andReturn('database'); 95 | $connection->shouldReceive('getTablePrefix')->andReturn(''); 96 | 97 | $blueprint = new Blueprint($connection, 'test'); 98 | $blueprint->renameColumn('data', 'data1'); 99 | 100 | $statements = $blueprint->toSql(); 101 | 102 | $this->assertCount(1, $statements); 103 | $this->assertEquals('alter table `test` change `data` `data1`', $statements[0]); 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /tests/Hybrid/TransactionsTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 19 | $this->createTable(function (Blueprint $table) { 20 | $table->id(); 21 | }); 22 | } 23 | } 24 | 25 | #[Test] 26 | public function multiple_begin() 27 | { 28 | if (! $this->runHybridIntegrations()) { 29 | return; 30 | } 31 | 32 | DB::beginTransaction(); 33 | DB::rollBack(); 34 | DB::beginTransaction(); 35 | DB::rollBack(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /tests/Hybrid/UnionTest.php: -------------------------------------------------------------------------------- 1 | runHybridIntegrations()) { 19 | $this->createTable(function (Blueprint $table) { 20 | $table->id(); 21 | }); 22 | 23 | DB::table('test')->insert([ 24 | ['id' => 1], 25 | ['id' => 2], 26 | ['id' => 3], 27 | ['id' => 4], 28 | ['id' => 100], 29 | ]); 30 | } 31 | } 32 | 33 | #[Test] 34 | public function union() 35 | { 36 | if (! $this->runHybridIntegrations()) { 37 | return; 38 | } 39 | 40 | $first = DB::table('test')->where('id', '<', 3); 41 | $second = DB::table('test')->where('id', '>', 5); 42 | $res = $first->union($second)->get(); 43 | 44 | $indexes = array_map(function ($value): int { 45 | return $value->id; 46 | }, $res->toArray()); 47 | sort($indexes); 48 | 49 | $this->assertEquals([1, 2, 100], $indexes); 50 | } 51 | 52 | #[Test] 53 | public function union_all() 54 | { 55 | if (! $this->runHybridIntegrations()) { 56 | return; 57 | } 58 | 59 | $first = DB::table('test')->where('id', '<', 4); 60 | $second = DB::table('test')->where('id', '>', 2); 61 | $res = $first->unionAll($second)->get(); 62 | 63 | $indexes = array_map(function ($value): int { 64 | return $value->id; 65 | }, $res->toArray()); 66 | sort($indexes); 67 | 68 | $this->assertEquals([1, 2, 3, 3, 4, 100], $indexes); 69 | } 70 | 71 | #[Test] 72 | public function union_with_order_by_limit_and_offset() 73 | { 74 | if (! $this->runHybridIntegrations()) { 75 | return; 76 | } 77 | 78 | $first = DB::table('test')->where('id', '<', 3); 79 | $second = DB::table('test')->where('id', '>', 5); 80 | $res = $first->union($second)->orderBy('id')->limit(1)->offset(1)->get(); 81 | 82 | $indexes = array_map(function ($value): int { 83 | return $value->id; 84 | }, $res->toArray()); 85 | 86 | $this->assertEquals([2], $indexes); 87 | } 88 | 89 | #[Test] 90 | public function union_with_order_by() 91 | { 92 | if (! $this->runHybridIntegrations()) { 93 | return; 94 | } 95 | 96 | $first = DB::table('test')->where('id', '<', 3); 97 | $second = DB::table('test')->where('id', '>', 5); 98 | $res = $first->union($second)->orderBy('id')->get(); 99 | 100 | $indexes = array_map(function ($value): int { 101 | return $value->id; 102 | }, $res->toArray()); 103 | 104 | $this->assertEquals([1, 2, 100], $indexes); 105 | } 106 | 107 | #[Test] 108 | public function union_with_limit() 109 | { 110 | if (! $this->runHybridIntegrations()) { 111 | return; 112 | } 113 | 114 | $first = DB::table('test')->where('id', '<', 3); 115 | $second = DB::table('test')->where('id', '>', 5); 116 | $res = $first->union($second)->limit(2)->get(); 117 | 118 | $this->assertCount(2, $res); 119 | } 120 | 121 | #[Test] 122 | public function union_with_offset() 123 | { 124 | if (! $this->runHybridIntegrations()) { 125 | return; 126 | } 127 | 128 | $first = DB::table('test')->where('id', '<', 3); 129 | $second = DB::table('test')->where('id', '>', 5); 130 | $res = $first->union($second)->offset(1)->get(); 131 | 132 | $this->assertCount(2, $res); 133 | } 134 | 135 | #[Test] 136 | public function union_with_inner_offset() 137 | { 138 | if (! $this->runHybridIntegrations()) { 139 | return; 140 | } 141 | 142 | $first = DB::table('test')->where('id', '<', 3)->offset(1)->orderBy('id'); 143 | $second = DB::table('test')->where('id', '>', 5); 144 | $res = $first->union($second)->get(); 145 | 146 | $indexes = array_map(function ($value): int { 147 | return $value->id; 148 | }, $res->toArray()); 149 | sort($indexes); 150 | 151 | $this->assertEquals([2, 100], $indexes); 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /tests/Integration/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singlestore-labs/singlestoredb-laravel-driver/113b337d286b323aaf63911612b6da030ea5d6b7/tests/Integration/.gitkeep -------------------------------------------------------------------------------- /tests/Unit/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/singlestore-labs/singlestoredb-laravel-driver/113b337d286b323aaf63911612b6da030ea5d6b7/tests/Unit/.gitkeep --------------------------------------------------------------------------------