From d88f077a691d79400a8bf24fea52b49cf57623be Mon Sep 17 00:00:00 2001 From: Richan Fongdasen Date: Thu, 11 Apr 2024 11:50:25 +0700 Subject: [PATCH] Alpha release --- .github/CODEOWNERS | 1 + .github/CONTRIBUTING.md | 57 +++++ .github/FUNDING.yml | 2 +- .github/ISSUE_TEMPLATE/bug.yml | 116 +++++----- .github/ISSUE_TEMPLATE/config.yml | 6 +- .github/PULL_REQUEST_TEMPLATE.md | 22 ++ .github/SECURITY.md | 3 + .github/workflows/phpstan.yml | 8 +- .github/workflows/run-coverage-tests.yml | 64 ++++++ .github/workflows/run-tests.yml | 27 ++- .gitignore | 3 + CHANGELOG.md | 2 +- README.md | 82 +++---- composer.json | 29 ++- config/turso-laravel.php | 4 + config/turso.php | 6 - database/factories/ModelFactory.php | 19 -- .../migrations/create_turso_table.php.stub | 19 -- docker-compose.yml | 11 + phpstan-baseline.neon | 2 + phpstan.neon.dist | 1 - phpunit.xml.dist | 2 +- resources/views/.gitkeep | 0 src/Commands/LaravelTursoCommand.php | 21 -- src/Database/TursoConnection.php | 70 ++++++ src/Database/TursoConnector.php | 23 ++ src/Database/TursoPDO.php | 83 +++++++ src/Database/TursoPDOStatement.php | 206 ++++++++++++++++++ src/Database/TursoQueryGrammar.php | 11 + src/Database/TursoQueryProcessor.php | 11 + src/Database/TursoSchemaBuilder.php | 77 +++++++ src/Database/TursoSchemaGrammar.php | 37 ++++ src/Database/TursoSchemaState.php | 11 + .../FeatureNotSupportedException.php | 11 + src/Exceptions/TursoQueryException.php | 28 +++ src/Facades/LaravelTurso.php | 18 -- src/Facades/Turso.php | 21 ++ src/LaravelTurso.php | 9 - src/LaravelTursoServiceProvider.php | 27 --- src/TursoClient.php | 167 ++++++++++++++ src/TursoLaravelServiceProvider.php | 47 ++++ tests/ArchTest.php | 10 +- tests/ExampleTest.php | 33 +++ tests/Feature/EloquentCollectionTest.php | 26 +++ tests/Feature/EloquentDeleteTest.php | 48 ++++ .../HasManyThroughTest.php | 59 +++++ .../EloquentRelationship/ManyToManyTest.php | 70 ++++++ .../EloquentRelationship/OneToManyTest.php | 93 ++++++++ .../EloquentRelationship/OneToOneTest.php | 59 +++++ tests/Feature/EloquentSoftDeletesTest.php | 50 +++++ .../QueryBuilder/DatabaseQueriesTest.php | 102 +++++++++ .../QueryBuilder/DeleteStatementsTest.php | 41 ++++ .../QueryBuilder/InsertStatementsTest.php | 67 ++++++ .../QueryBuilder/RawExpressionsTest.php | 66 ++++++ .../QueryBuilder/SelectStatementsTest.php | 57 +++++ .../QueryBuilder/UpdateStatementTest.php | 76 +++++++ tests/Feature/TursoPDOStatementTest.php | 119 ++++++++++ tests/Feature/TursoPDOTest.php | 11 + tests/Feature/TursoSchemaBuilderTest.php | 127 +++++++++++ .../Fixtures/Factories/DeploymentFactory.php | 31 +++ .../Fixtures/Factories/EnvironmentFactory.php | 30 +++ tests/Fixtures/Factories/PhoneFactory.php | 30 +++ tests/Fixtures/Factories/PostFactory.php | 31 +++ tests/Fixtures/Factories/ProjectFactory.php | 28 +++ tests/Fixtures/Factories/RoleFactory.php | 28 +++ tests/Fixtures/Factories/UserFactory.php | 32 +++ .../Migrations/create_deployments_table.php | 34 +++ .../Migrations/create_environments_table.php | 34 +++ .../Migrations/create_phones_table.php | 34 +++ .../Migrations/create_posts_table.php | 35 +++ .../Migrations/create_projects_table.php | 28 +++ .../Migrations/create_roles_table.php | 29 +++ .../Migrations/create_user_roles_table.php | 38 ++++ .../Migrations/create_users_table.php | 31 +++ tests/Fixtures/Models/Deployment.php | 41 ++++ tests/Fixtures/Models/Environment.php | 47 ++++ tests/Fixtures/Models/Phone.php | 42 ++++ tests/Fixtures/Models/Post.php | 49 +++++ tests/Fixtures/Models/Project.php | 46 ++++ tests/Fixtures/Models/Role.php | 42 ++++ tests/Fixtures/Models/User.php | 71 ++++++ tests/Pest.php | 16 +- tests/TestCase.php | 23 +- tests/Unit/TursoClientTest.php | 79 +++++++ tests/Unit/TursoPDOTest.php | 35 +++ tests/Unit/TursoSchemaBuilderTest.php | 12 + 86 files changed, 3192 insertions(+), 262 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/CONTRIBUTING.md create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/SECURITY.md create mode 100644 .github/workflows/run-coverage-tests.yml create mode 100644 config/turso-laravel.php delete mode 100644 config/turso.php delete mode 100644 database/factories/ModelFactory.php delete mode 100644 database/migrations/create_turso_table.php.stub create mode 100644 docker-compose.yml delete mode 100644 resources/views/.gitkeep delete mode 100644 src/Commands/LaravelTursoCommand.php create mode 100644 src/Database/TursoConnection.php create mode 100644 src/Database/TursoConnector.php create mode 100644 src/Database/TursoPDO.php create mode 100644 src/Database/TursoPDOStatement.php create mode 100644 src/Database/TursoQueryGrammar.php create mode 100644 src/Database/TursoQueryProcessor.php create mode 100644 src/Database/TursoSchemaBuilder.php create mode 100644 src/Database/TursoSchemaGrammar.php create mode 100644 src/Database/TursoSchemaState.php create mode 100644 src/Exceptions/FeatureNotSupportedException.php create mode 100644 src/Exceptions/TursoQueryException.php delete mode 100644 src/Facades/LaravelTurso.php create mode 100644 src/Facades/Turso.php delete mode 100755 src/LaravelTurso.php delete mode 100644 src/LaravelTursoServiceProvider.php create mode 100755 src/TursoClient.php create mode 100644 src/TursoLaravelServiceProvider.php create mode 100644 tests/Feature/EloquentCollectionTest.php create mode 100644 tests/Feature/EloquentDeleteTest.php create mode 100644 tests/Feature/EloquentRelationship/HasManyThroughTest.php create mode 100644 tests/Feature/EloquentRelationship/ManyToManyTest.php create mode 100644 tests/Feature/EloquentRelationship/OneToManyTest.php create mode 100644 tests/Feature/EloquentRelationship/OneToOneTest.php create mode 100644 tests/Feature/EloquentSoftDeletesTest.php create mode 100644 tests/Feature/QueryBuilder/DatabaseQueriesTest.php create mode 100644 tests/Feature/QueryBuilder/DeleteStatementsTest.php create mode 100644 tests/Feature/QueryBuilder/InsertStatementsTest.php create mode 100644 tests/Feature/QueryBuilder/RawExpressionsTest.php create mode 100644 tests/Feature/QueryBuilder/SelectStatementsTest.php create mode 100644 tests/Feature/QueryBuilder/UpdateStatementTest.php create mode 100644 tests/Feature/TursoPDOStatementTest.php create mode 100644 tests/Feature/TursoPDOTest.php create mode 100644 tests/Feature/TursoSchemaBuilderTest.php create mode 100644 tests/Fixtures/Factories/DeploymentFactory.php create mode 100644 tests/Fixtures/Factories/EnvironmentFactory.php create mode 100644 tests/Fixtures/Factories/PhoneFactory.php create mode 100644 tests/Fixtures/Factories/PostFactory.php create mode 100644 tests/Fixtures/Factories/ProjectFactory.php create mode 100644 tests/Fixtures/Factories/RoleFactory.php create mode 100644 tests/Fixtures/Factories/UserFactory.php create mode 100644 tests/Fixtures/Migrations/create_deployments_table.php create mode 100644 tests/Fixtures/Migrations/create_environments_table.php create mode 100644 tests/Fixtures/Migrations/create_phones_table.php create mode 100644 tests/Fixtures/Migrations/create_posts_table.php create mode 100644 tests/Fixtures/Migrations/create_projects_table.php create mode 100644 tests/Fixtures/Migrations/create_roles_table.php create mode 100644 tests/Fixtures/Migrations/create_user_roles_table.php create mode 100644 tests/Fixtures/Migrations/create_users_table.php create mode 100644 tests/Fixtures/Models/Deployment.php create mode 100644 tests/Fixtures/Models/Environment.php create mode 100644 tests/Fixtures/Models/Phone.php create mode 100644 tests/Fixtures/Models/Post.php create mode 100644 tests/Fixtures/Models/Project.php create mode 100644 tests/Fixtures/Models/Role.php create mode 100644 tests/Fixtures/Models/User.php create mode 100644 tests/Unit/TursoClientTest.php create mode 100644 tests/Unit/TursoPDOTest.php create mode 100644 tests/Unit/TursoSchemaBuilderTest.php diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..79bc01b --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1 @@ +* @richan-fongdasen diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md new file mode 100644 index 0000000..73c4478 --- /dev/null +++ b/.github/CONTRIBUTING.md @@ -0,0 +1,57 @@ +# Contributing + +Contributions are **welcome** and will be fully **credited**. + +Please read and understand the contribution guide before creating an issue or pull request. + +## Etiquette + +This project is open source, and as such, the maintainers give their free time to build and maintain the source code +held within. They make the code freely available in the hope that it will be of use to other developers. It would be +extremely unfair for them to suffer abuse or anger for their hard work. + +Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the +world that developers are civilized and selfless people. + +It's the duty of the maintainer to ensure that all submissions to the project are of sufficient +quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. + +## Viability + +When requesting or submitting new features, first consider whether it might be useful to others. Open +source projects are used by many developers, who may have entirely different needs to your own. Think about +whether or not your feature is likely to be used by other users of the project. + +## Procedure + +Before filing an issue: + +- Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. +- Check to make sure your feature suggestion isn't already present within the project. +- Check the pull requests tab to ensure that the bug doesn't have a fix in progress. +- Check the pull requests tab to ensure that the feature isn't already in progress. + +Before submitting a pull request: + +- Check the codebase to ensure that your feature doesn't already exist. +- Check the pull requests to ensure that another person hasn't already submitted the feature or fix. + +## Requirements + +If the project maintainer has any additional requirements, you will find them listed here. + +- **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). + +- **Add tests!** - Your patch won't be accepted if it doesn't have tests. + +- **Pass The Code Quality Analysis** - This project uses Larastan which is a PHPStan wrapper for Laravel. Make sure your code passes the code quality analysis with level 8. + +- **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. + +- **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. + +- **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. + +- **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. + +**Happy coding**! diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index e1d546c..fdb4030 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1 @@ -github: Richan Fongdasen +github: richan-fongdasen diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index fe4cfe6..3ccc59c 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -3,64 +3,64 @@ description: Report an Issue or Bug with the Package title: "[Bug]: " labels: ["bug"] body: - - type: markdown - attributes: - value: | - We're sorry to hear you have a problem. Can you help us solve it by providing the following details. - - type: textarea - id: what-happened - attributes: - label: What happened? - description: What did you expect to happen? - placeholder: I cannot currently do X thing because when I do, it breaks X thing. - validations: - required: true - - type: textarea - id: how-to-reproduce - attributes: - label: How to reproduce the bug - description: How did this occur, please add any config values used and provide a set of reliable steps if possible. - placeholder: When I do X I see Y. - validations: - required: true - - type: input - id: package-version - attributes: - label: Package Version - description: What version of our Package are you running? Please be as specific as possible - placeholder: 2.0.0 - validations: - required: true - - type: input - id: php-version - attributes: - label: PHP Version - description: What version of PHP are you running? Please be as specific as possible - placeholder: 8.2.0 - validations: - required: true - - type: input - id: laravel-version - attributes: - label: Laravel Version - description: What version of Laravel are you running? Please be as specific as possible - placeholder: 9.0.0 - validations: - required: true - - type: dropdown - id: operating-systems - attributes: - label: Which operating systems does with happen with? - description: You may select more than one. - multiple: true - options: + - type: markdown + attributes: + value: | + We're sorry to hear you have a problem. Can you help us solve it by providing the following details. + - type: textarea + id: what-happened + attributes: + label: What happened? + description: What did you expect to happen? + placeholder: I cannot currently do X thing because when I do, it breaks X thing. + validations: + required: true + - type: textarea + id: how-to-reproduce + attributes: + label: How to reproduce the bug + description: How did this occur, please add any config values used and provide a set of reliable steps if possible. + placeholder: When I do X I see Y. + validations: + required: true + - type: input + id: package-version + attributes: + label: Package Version + description: What version of our Package are you running? Please be as specific as possible + placeholder: 1.0.0 + validations: + required: true + - type: input + id: php-version + attributes: + label: PHP Version + description: What version of PHP are you running? Please be as specific as possible + placeholder: 8.3.0 + validations: + required: true + - type: input + id: laravel-version + attributes: + label: Laravel Version + description: What version of Laravel are you running? Please be as specific as possible + placeholder: 11.0.0 + validations: + required: true + - type: dropdown + id: operating-systems + attributes: + label: Which operating systems does with happen with? + description: You may select more than one. + multiple: true + options: - macOS - Windows - Linux - - type: textarea - id: notes - attributes: - label: Notes - description: Use this field to provide any other notes that you feel might be relevant to the issue. - validations: - required: false + - type: textarea + id: notes + attributes: + label: Notes + description: Use this field to provide any other notes that you feel might be relevant to the issue. + validations: + required: false diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index cae76da..b6a952d 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Ask a question - url: https://github.com/Richan Fongdasen/laravel-turso/discussions/new?category=q-a + url: https://github.com/richan-fongdasen/turso-laravel/discussions/new?category=q-a about: Ask the community for help - name: Request a feature - url: https://github.com/Richan Fongdasen/laravel-turso/discussions/new?category=ideas + url: https://github.com/richan-fongdasen/turso-laravel/discussions/new?category=ideas about: Share ideas for new features - name: Report a security issue - url: https://github.com/Richan Fongdasen/laravel-turso/security/policy + url: https://github.com/richan-fongdasen/turso-laravel/security/policy about: Learn how to notify us for sensitive bugs diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..552f73d --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,22 @@ +## Changes In Code + + + +## Issue ticket number / Business Case + + + +## Checklist before requesting a review + +- [ ] I have written PHP tests. +- [ ] I have updated the documentation in the readme where needed. +- [ ] I have checked code styles, PHPStan etc. pass. +- [ ] I have provided an issue/business case. diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..803ae2f --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,3 @@ +# Security Policy + +If you discover any security related issues, please email richan.fongdasen@gmail.com instead of using the issue tracker. diff --git a/.github/workflows/phpstan.yml b/.github/workflows/phpstan.yml index f495e76..2ad603e 100644 --- a/.github/workflows/phpstan.yml +++ b/.github/workflows/phpstan.yml @@ -3,9 +3,9 @@ name: PHPStan on: push: paths: - - '**.php' - - 'phpstan.neon.dist' - - '.github/workflows/phpstan.yml' + - "**.php" + - "phpstan.neon.dist" + - ".github/workflows/phpstan.yml" jobs: phpstan: @@ -18,7 +18,7 @@ jobs: - name: Setup PHP uses: shivammathur/setup-php@v2 with: - php-version: '8.1' + php-version: "8.3" coverage: none - name: Install composer dependencies diff --git a/.github/workflows/run-coverage-tests.yml b/.github/workflows/run-coverage-tests.yml new file mode 100644 index 0000000..e0edd56 --- /dev/null +++ b/.github/workflows/run-coverage-tests.yml @@ -0,0 +1,64 @@ +name: run-coverage-tests + +on: + push: + paths: + - "**.php" + - ".github/workflows/run-tests.yml" + - "phpunit.xml.dist" + - "composer.json" + - "composer.lock" + pull_request: + branches: [main] + +jobs: + test: + runs-on: ${{ matrix.os }} + timeout-minutes: 5 + strategy: + fail-fast: true + matrix: + os: [ubuntu-latest] + php: [8.3] + laravel: [11.*] + stability: [prefer-stable] + include: + - laravel: 11.* + testbench: ^9.0 + carbon: ^2.63 + + name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + - name: Run Turso Local Database + run: docker-compose up -d + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: dom, curl, libxml, mbstring, zip, pcntl, pdo, sqlite, pdo_sqlite, bcmath, soap, intl, gd, exif, iconv, imagick, fileinfo + + - name: Setup problem matchers + run: | + echo "::add-matcher::${{ runner.tool_cache }}/php.json" + echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json" + + - name: Install dependencies + run: | + composer require "laravel/framework:${{ matrix.laravel }}" "orchestra/testbench:${{ matrix.testbench }}" "nesbot/carbon:${{ matrix.carbon }}" --no-interaction --no-update + composer update --${{ matrix.stability }} --prefer-dist --no-interaction + + - name: List Installed Dependencies + run: composer show -D + + - name: Execute coverage tests + run: vendor/bin/pest --coverage-clover coverage.xml + + - name: Upload test coverage report to codecov.io + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + run: bash <(curl -s https://codecov.io/bash) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index f7492c5..e68df5c 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -3,11 +3,15 @@ name: run-tests on: push: paths: - - '**.php' - - '.github/workflows/run-tests.yml' - - 'phpunit.xml.dist' - - 'composer.json' - - 'composer.lock' + - "**.php" + - ".github/workflows/run-tests.yml" + - "phpunit.xml.dist" + - "composer.json" + - "composer.lock" + pull_request: + branches: [main] + schedule: + - cron: "0 7 * * 1" jobs: test: @@ -16,13 +20,13 @@ jobs: strategy: fail-fast: true matrix: - os: [ubuntu-latest, windows-latest] - php: [8.3, 8.2, 8.1] - laravel: [10.*] + os: [ubuntu-latest] + php: [8.3, 8.2] + laravel: [11.*] stability: [prefer-lowest, prefer-stable] include: - - laravel: 10.* - testbench: 8.* + - laravel: 11.* + testbench: ^9.0 carbon: ^2.63 name: P${{ matrix.php }} - L${{ matrix.laravel }} - ${{ matrix.stability }} - ${{ matrix.os }} @@ -31,6 +35,9 @@ jobs: - name: Checkout code uses: actions/checkout@v4 + - name: Run Turso Local Database + run: docker-compose up -d + - name: Setup PHP uses: shivammathur/setup-php@v2 with: diff --git a/.gitignore b/.gitignore index d49cca9..96cda9d 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,6 @@ testbench.yaml vendor node_modules *.swp +*.sqlite +*.sqlite-shm +*.sqlite-wal diff --git a/CHANGELOG.md b/CHANGELOG.md index bb855f1..3b85801 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,3 @@ # Changelog -All notable changes to `laravel-turso` will be documented in this file. +All notable changes to `richan-fongdasen/turso-laravel` will be documented in this file. diff --git a/README.md b/README.md index 52851c1..89c12bc 100644 --- a/README.md +++ b/README.md @@ -1,65 +1,73 @@ -# This is my package laravel-turso +# A Turso database driver for Laravel -[![Latest Version on Packagist](https://img.shields.io/packagist/v/richan-fongdasen/laravel-turso.svg?style=flat-square)](https://packagist.org/packages/richan-fongdasen/laravel-turso) -[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/richan-fongdasen/laravel-turso/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/richan-fongdasen/laravel-turso/actions?query=workflow%3Arun-tests+branch%3Amain) -[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/richan-fongdasen/laravel-turso/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/richan-fongdasen/laravel-turso/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) -[![Total Downloads](https://img.shields.io/packagist/dt/richan-fongdasen/laravel-turso.svg?style=flat-square)](https://packagist.org/packages/richan-fongdasen/laravel-turso) +[![Latest Version on Packagist](https://img.shields.io/packagist/v/richan-fongdasen/turso-laravel.svg?style=flat-square)](https://packagist.org/packages/richan-fongdasen/turso-laravel) +[![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/richan-fongdasen/turso-laravel/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/richan-fongdasen/turso-laravel/actions?query=workflow%3Arun-tests+branch%3Amain) +[![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/richan-fongdasen/turso-laravel/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/richan-fongdasen/turso-laravel/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) +[![Total Downloads](https://img.shields.io/packagist/dt/richan-fongdasen/turso-laravel.svg?style=flat-square)](https://packagist.org/packages/richan-fongdasen/turso-laravel) -This is where your description should go. Limit it to a paragraph or two. Consider adding a small example. +This package provides a Turso database driver for Laravel. It allows you to use Turso database as your database driver in Laravel application. The database driver is implemented using HTTP client to communicate with the Turso database server. -## Support us +## Unsupported Features -[](https://spatie.be/github-ad-click/laravel-turso) +There are some features that are not supported by this package yet. Here are the list of unsupported features: -We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can support us by [buying one of our paid products](https://spatie.be/open-source/support-us). - -We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards on [our virtual postcard wall](https://spatie.be/open-source/postcards). +- Creating and dropping database +- [Database Transactions](https://turso.tech/blog/bring-your-own-sdk-with-tursos-http-api-ff4ccbed) +- [Turso Batch Request](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md#execute-a-batch) +- [Turso Sequence Request](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md#execute-a-sequence-of-sql-statements) +- [Turso Describe Request](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md#describe-a-statement) +- [Turso Store SQL Request](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md#store-an-sql-text-on-the-server) +- [Turso Close Stored SQL Request](https://github.com/tursodatabase/libsql/blob/main/docs/HTTP_V2_SPEC.md#close-a-stored-sql-text) ## Installation You can install the package via composer: ```bash -composer require richan-fongdasen/laravel-turso +composer require richan-fongdasen/turso-laravel ``` -You can publish and run the migrations with: +To use Turso as your database driver in Laravel, you need to append the following configuration to the `connections` array in your `config/database.php` file: -```bash -php artisan vendor:publish --tag="laravel-turso-migrations" -php artisan migrate +```php +'turso' => [ + 'driver' => 'turso', + 'turso_url' => env('DB_URL', 'http://localhost:8080'), + 'database' => null, + 'prefix' => env('DB_PREFIX', ''), + 'access_token' => env('DB_ACCESS_TOKEN', null), + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), +], ``` -You can publish the config file with: +## Configuration + +In Laravel application, The database driver configuration is stored in your `.env` file. Here is the list of available configuration for Turso database driver: ```bash -php artisan vendor:publish --tag="laravel-turso-config" +DB_CONNECTION=turso +DB_URL=http://localhost:8080 +DB_PREFIX= +DB_ACCESS_TOKEN= ``` -This is the contents of the published config file: +## Usage -```php -return [ -]; -``` +For local development, you can use the local Turso database server that is provided by the Turso database team for development purposes. You can find the instruction to run the local Turso database server in the [Turso CLI documentation](https://docs.turso.tech/local-development#turso-cli). -Optionally, you can publish the views using +The Turso database driver should work as expected with Laravel Query Builder and Eloquent ORM. -```bash -php artisan vendor:publish --tag="laravel-turso-views" -``` +## Debugging -## Usage +There is a way to debug the HTTP request and response that is sent and received by the Turso database client. Here is the example of how to enable the debugging feature: ```php -$laravelTurso = new RichanFongdasen\LaravelTurso(); -echo $laravelTurso->echoPhrase('Hello, RichanFongdasen!'); -``` +Turso::enableQueryLog(); -## Testing +DB::table('users')->get(); -```bash -composer test +// Get the query log +$logs = Turso::getQueryLog(); ``` ## Changelog @@ -68,7 +76,7 @@ Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed re ## Contributing -Please see [CONTRIBUTING](CONTRIBUTING.md) for details. +Please see [CONTRIBUTING](.github/CONTRIBUTING.md) for details. ## Security Vulnerabilities @@ -76,8 +84,8 @@ Please review [our security policy](../../security/policy) on how to report secu ## Credits -- [Richan Fongdasen](https://github.com/richan-fongdasen) -- [All Contributors](../../contributors) +- [Richan Fongdasen](https://github.com/richan-fongdasen) +- [All Contributors](../../contributors) ## License diff --git a/composer.json b/composer.json index 24fdda7..3fe0e97 100644 --- a/composer.json +++ b/composer.json @@ -1,12 +1,13 @@ { - "name": "richan-fongdasen/laravel-turso", - "description": "This is my package laravel-turso", + "name": "richan-fongdasen/turso-laravel", + "description": "A Turso/LibSQL database driver for Laravel", "keywords": [ "Richan Fongdasen", + "turso", "laravel", - "laravel-turso" + "turso-laravel" ], - "homepage": "https://github.com/richan-fongdasen/laravel-turso", + "homepage": "https://github.com/richan-fongdasen/turso-laravel", "license": "MIT", "authors": [ { @@ -17,8 +18,13 @@ ], "require": { "php": "^8.2", - "spatie/laravel-package-tools": "^1.16", - "illuminate/contracts": "^11.0" + "illuminate/contracts": "^11.0", + "illuminate/console": "^11.0", + "illuminate/database": "^11.0", + "illuminate/filesystem": "^11.0", + "illuminate/http": "^11.0", + "illuminate/support": "^11.0", + "spatie/laravel-package-tools": "^1.16" }, "require-dev": { "larastan/larastan": "^2.9", @@ -35,19 +41,18 @@ }, "autoload": { "psr-4": { - "RichanFongdasen\\LaravelTurso\\": "src/", - "RichanFongdasen\\LaravelTurso\\Database\\Factories\\": "database/factories/" + "RichanFongdasen\\Turso\\": "src/" } }, "autoload-dev": { "psr-4": { - "RichanFongdasen\\LaravelTurso\\Tests\\": "tests/", + "RichanFongdasen\\Turso\\Tests\\": "tests/", "Workbench\\App\\": "workbench/app/" } }, "scripts": { "post-autoload-dump": "@composer run prepare", - "clear": "@php vendor/bin/testbench package:purge-laravel-turso --ansi", + "clear": "@php vendor/bin/testbench package:purge-turso-laravel --ansi", "prepare": "@php vendor/bin/testbench package:discover --ansi", "build": [ "@composer run prepare", @@ -73,10 +78,10 @@ "extra": { "laravel": { "providers": [ - "RichanFongdasen\\LaravelTurso\\LaravelTursoServiceProvider" + "RichanFongdasen\\Turso\\TursoLaravelServiceProvider" ], "aliases": { - "LaravelTurso": "RichanFongdasen\\LaravelTurso\\Facades\\LaravelTurso" + "Turso": "RichanFongdasen\\Turso\\Facades\\Turso" } } }, diff --git a/config/turso-laravel.php b/config/turso-laravel.php new file mode 100644 index 0000000..41cc03e --- /dev/null +++ b/config/turso-laravel.php @@ -0,0 +1,4 @@ +id(); - - // add fields - - $table->timestamps(); - }); - } -}; diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..94c45d6 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,11 @@ +version: "3.6" + +services: + turso: + container_name: turso + restart: unless-stopped + image: "richan/turso-dev:latest" + environment: + - TURSO_DB_FILE=/var/lib/turso/turso.sqlite + ports: + - "8080:8080" diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index e69de29..eeafe7b 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -0,0 +1,2 @@ +parameters: + treatPhpDocTypesAsCertain: false diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 78ea0ea..a831ab0 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -6,7 +6,6 @@ parameters: paths: - src - config - - database tmpDir: build/phpstan checkOctaneCompatibility: true checkModelProperties: true diff --git a/phpunit.xml.dist b/phpunit.xml.dist index c361443..1ade1f6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -16,7 +16,7 @@ backupStaticProperties="false" > - + tests diff --git a/resources/views/.gitkeep b/resources/views/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/src/Commands/LaravelTursoCommand.php b/src/Commands/LaravelTursoCommand.php deleted file mode 100644 index 55cc9e5..0000000 --- a/src/Commands/LaravelTursoCommand.php +++ /dev/null @@ -1,21 +0,0 @@ -comment('All done'); - - return self::SUCCESS; - } -} diff --git a/src/Database/TursoConnection.php b/src/Database/TursoConnection.php new file mode 100644 index 0000000..0e46a86 --- /dev/null +++ b/src/Database/TursoConnection.php @@ -0,0 +1,70 @@ +setConnection($this); + + $this->withTablePrefix($grammar); + + return $grammar; + } + + /** + * Get a schema builder instance for the connection. + */ + public function getSchemaBuilder(): TursoSchemaBuilder + { + if (is_null($this->schemaGrammar)) { + $this->useDefaultSchemaGrammar(); + } + + return new TursoSchemaBuilder($this); + } + + /** + * Get the default schema grammar instance. + */ + protected function getDefaultSchemaGrammar(): TursoSchemaGrammar + { + $grammar = new TursoSchemaGrammar(); + $grammar->setConnection($this); + + $this->withTablePrefix($grammar); + + return $grammar; + } + + /** + * Get the schema state for the connection. + */ + public function getSchemaState(?Filesystem $files = null, ?callable $processFactory = null): TursoSchemaState + { + return new TursoSchemaState($this, $files, $processFactory); + } + + /** + * Get the default post processor instance. + */ + protected function getDefaultPostProcessor(): TursoQueryProcessor + { + return new TursoQueryProcessor(); + } +} diff --git a/src/Database/TursoConnector.php b/src/Database/TursoConnector.php new file mode 100644 index 0000000..4c8a319 --- /dev/null +++ b/src/Database/TursoConnector.php @@ -0,0 +1,23 @@ +getOptions($config); + + return new TursoPDO('sqlite::memory:', null, null, $options); + } +} diff --git a/src/Database/TursoPDO.php b/src/Database/TursoPDO.php new file mode 100644 index 0000000..9e2f524 --- /dev/null +++ b/src/Database/TursoPDO.php @@ -0,0 +1,83 @@ +prepare($queryStatement); + $statement->execute(); + + return $statement->getAffectedRows(); + } + + public function inTransaction(): bool + { + return false; + } + + public function lastInsertId(?string $name = null): string|false + { + if ($name === null) { + $name = 'id'; + } + + return (isset($this->lastInsertIds[$name])) + ? (string) $this->lastInsertIds[$name] + : false; + } + + public function prepare(string $query, array $options = []): TursoPDOStatement + { + return new TursoPDOStatement($this, $query, $options); + } + + public function rollBack(): bool + { + throw new FeatureNotSupportedException('Database transaction is not supported by the current Turso database driver.'); + } + + public function setLastInsertId(?string $name = null, ?int $value = null): void + { + if ($name === null) { + $name = 'id'; + } + + $this->lastInsertIds[$name] = $value; + } +} diff --git a/src/Database/TursoPDOStatement.php b/src/Database/TursoPDOStatement.php new file mode 100644 index 0000000..71de993 --- /dev/null +++ b/src/Database/TursoPDOStatement.php @@ -0,0 +1,206 @@ +responses = new Collection(); + } + + public function setFetchMode(int $mode, mixed ...$args): bool + { + $this->fetchMode = $mode; + + return true; + } + + public function bindValue(string|int $param, mixed $value, $type = PDO::PARAM_STR): bool + { + if ($value === null) { + $type = PDO::PARAM_NULL; + } + + $this->bindings[$param] = match ($type) { + PDO::PARAM_LOB => [ + 'type' => 'blob', + 'value' => base64_encode($value), + ], + PDO::PARAM_BOOL => [ + 'type' => 'boolean', + 'value' => (string) ((int) $value), + ], + PDO::PARAM_INT => [ + 'type' => 'integer', + 'value' => (string) $value, + ], + PDO::PARAM_NULL => [ + 'type' => 'null', + 'value' => 'null', + ], + default => [ + 'type' => 'text', + 'value' => (string) $value, + ], + }; + + return true; + } + + public function execute(?array $params = null): bool + { + collect((array) $params) + ->each(function (mixed $value, int $key) { + $type = match (gettype($value)) { + 'boolean' => PDO::PARAM_BOOL, + 'double', 'integer' => PDO::PARAM_INT, + 'resource' => PDO::PARAM_LOB, + 'NULL' => PDO::PARAM_NULL, + default => PDO::PARAM_STR, + }; + + $this->bindValue($key, $value, $type); + }); + + $rawResponse = Turso::query($this->query, array_values($this->bindings)); + $this->responses = $this->formatResponse($rawResponse); + + $lastId = (int) data_get($rawResponse, 'result.last_insert_rowid', 0); + + if ($lastId > 0) { + $this->pdo->setLastInsertId(value: $lastId); + } + + $this->affectedRows = (int) data_get($rawResponse, 'result.affected_row_count', 0); + + return true; + } + + public function fetch(int $mode = PDO::FETCH_DEFAULT, int $cursorOrientation = PDO::FETCH_ORI_NEXT, int $cursorOffset = 0): mixed + { + if ($mode === PDO::FETCH_DEFAULT) { + $mode = $this->fetchMode; + } + + $response = $this->responses?->shift(); + + if ($response === null) { + return false; + } + + return match ($mode) { + PDO::FETCH_BOTH => array_merge( + $response->toArray(), + $response->values()->toArray() + ), + PDO::FETCH_ASSOC, PDO::FETCH_NAMED => $response->toArray(), + PDO::FETCH_NUM => $response->values()->toArray(), + PDO::FETCH_OBJ => (object) $response->toArray(), + + default => throw new PDOException('Unsupported fetch mode.'), + }; + } + + public function fetchAll(int $mode = PDO::FETCH_DEFAULT, ...$args): array + { + if (! ($this->responses instanceof Collection)) { + return []; + } + + if ($mode === PDO::FETCH_DEFAULT) { + $mode = $this->fetchMode; + } + + $response = match ($mode) { + PDO::FETCH_BOTH => $this->responses->map(function (Collection $row) { + return array_merge($row->toArray(), $row->values()->toArray()); + })->toArray(), + PDO::FETCH_ASSOC, PDO::FETCH_NAMED => $this->responses->toArray(), + PDO::FETCH_NUM => $this->responses->map(function (Collection $row) { + return $row->values()->toArray(); + })->toArray(), + PDO::FETCH_OBJ => $this->responses->map(function (Collection $row) { + return (object) $row->toArray(); + })->toArray(), + + default => throw new PDOException('Unsupported fetch mode.'), + }; + + $this->responses = new Collection(); + + return $response; + } + + protected function formatResponse(array $originalResponse): Collection + { + $response = new Collection(); + $columns = collect((array) data_get($originalResponse, 'result.cols', [])) + ->keyBy('name') + ->keys() + ->all(); + + $rows = collect((array) data_get($originalResponse, 'result.rows', [])) + ->each(function (array $item) use (&$response, $columns) { + $row = new Collection(); + + collect($item) + ->each(function (array $column, int $index) use (&$row, $columns) { + $value = match ($column['type']) { + 'blob' => base64_decode((string) $column['value'], true), + 'integer' => (int) $column['value'], + 'float' => (float) $column['value'], + 'null' => null, + default => (string) $column['value'], + }; + + $row->put(data_get($columns, $index), $value); + }); + + $response->push($row); + }); + + return $response; + } + + public function getAffectedRows(): int + { + return $this->affectedRows; + } + + public function nextRowset(): bool + { + // TODO: Make sure if Turso database support multiple rowset. + return false; + } + + public function rowCount(): int + { + return $this->responses?->count() ?? 0; + } +} diff --git a/src/Database/TursoQueryGrammar.php b/src/Database/TursoQueryGrammar.php new file mode 100644 index 0000000..d948361 --- /dev/null +++ b/src/Database/TursoQueryGrammar.php @@ -0,0 +1,11 @@ +connection->getPdo()->prepare($this->grammar()->compileDropAllIndexes()); + $statement->execute(); + + collect($statement->fetchAll(\PDO::FETCH_NUM))->each(function (array $query) { + $this->connection->select($query[0]); + }); + } + + public function dropAllTables(): void + { + $this->dropAllTriggers(); + $this->dropAllIndexes(); + + $this->connection->select($this->grammar()->compileDisableForeignKeyConstraints()); + + $statement = $this->connection->getPdo()->prepare($this->grammar()->compileDropAllTables()); + $statement->execute(); + + collect($statement->fetchAll(\PDO::FETCH_NUM))->each(function (array $query) { + $this->connection->select($query[0]); + }); + + $this->connection->select($this->grammar()->compileEnableForeignKeyConstraints()); + } + + protected function dropAllTriggers(): void + { + $statement = $this->connection->getPdo()->prepare($this->grammar()->compileDropAllTriggers()); + $statement->execute(); + + collect($statement->fetchAll(\PDO::FETCH_NUM))->each(function (array $query) { + $this->connection->select($query[0]); + }); + } + + public function dropAllViews(): void + { + $statement = $this->connection->getPdo()->prepare($this->grammar()->compileDropAllViews()); + $statement->execute(); + + collect($statement->fetchAll(\PDO::FETCH_NUM))->each(function (array $query) { + $this->connection->select($query[0]); + }); + } + + protected function grammar(): TursoSchemaGrammar + { + if (! ($this->grammar instanceof TursoSchemaGrammar)) { + $this->grammar = new TursoSchemaGrammar(); + } + + return $this->grammar; + } +} diff --git a/src/Database/TursoSchemaGrammar.php b/src/Database/TursoSchemaGrammar.php new file mode 100644 index 0000000..2ace1ac --- /dev/null +++ b/src/Database/TursoSchemaGrammar.php @@ -0,0 +1,37 @@ +__toString()); + } + + public function __toString(): string + { + return sprintf( + '(%s) %s, while executing the following statement: %s', + $this->errorCode, + $this->errorMessage, + trim($this->statement) + ); + } +} diff --git a/src/Facades/LaravelTurso.php b/src/Facades/LaravelTurso.php deleted file mode 100644 index b9ea9ea..0000000 --- a/src/Facades/LaravelTurso.php +++ /dev/null @@ -1,18 +0,0 @@ -name('laravel-turso') - ->hasConfigFile() - ->hasViews() - ->hasMigration('create_laravel-turso_table') - ->hasCommand(LaravelTursoCommand::class); - } -} diff --git a/src/TursoClient.php b/src/TursoClient.php new file mode 100755 index 0000000..7b9b044 --- /dev/null +++ b/src/TursoClient.php @@ -0,0 +1,167 @@ +config = config('database.connections.turso', []); + + $this->queryLog = new Collection(); + + $this->disableQueryLog(); + $this->resetClientState(); + } + + public function __destruct() + { + $this->close(); + } + + public function close(): void + { + $this->request() + ->baseUrl($this->baseUrl) + ->post('/v3/pipeline', $this->createRequestBody('close')); + + $this->resetClientState(); + } + + protected function createRequest(): PendingRequest + { + $accessToken = data_get($this->config, 'access_token'); + + return Http::withHeaders([ + 'Content-Type' => 'application/json', + ])->connectTimeout(2) + ->timeout(5) + ->withToken($accessToken) + ->acceptJson(); + } + + protected function createRequestBody(string $type, ?string $statement = null, array $bindings = []): array + { + $requestBody = []; + + if (($this->baton !== null) && ($this->baton !== '')) { + $requestBody['baton'] = $this->baton; + } + + $requestBody['requests'] = ($type === 'close') + ? [['type' => 'close']] + : [[ + 'type' => 'execute', + 'stmt' => [ + 'sql' => $statement, + ], + ]]; + + if (($type !== 'close') && (count($bindings) > 0)) { + $requestBody['requests'][0]['stmt']['args'] = $bindings; + } + + return $requestBody; + } + + public function disableQueryLog(): void + { + $this->loggingQueries = false; + } + + public function enableQueryLog(): void + { + $this->loggingQueries = true; + } + + public function getBaseUrl(): ?string + { + return $this->baseUrl; + } + + public function getBaton(): ?string + { + return $this->baton; + } + + public function getQueryLog(): Collection + { + return $this->queryLog; + } + + public function query(string $statement, array $bindingValues = []): array + { + $response = $this->request() + ->baseUrl($this->baseUrl) + ->post('/v3/pipeline', $this->createRequestBody('execute', $statement, $bindingValues)); + + if ($response->failed()) { + $this->resetClientState(); + $response->throw(); + } + + $jsonResponse = $response->json(); + + if ($this->loggingQueries) { + $this->queryLog->push([ + 'statement' => $statement, + 'bindings' => $bindingValues, + 'response' => $jsonResponse, + ]); + } + + $this->baton = data_get($jsonResponse, 'baton', null); + $baseUrl = (string) data_get($jsonResponse, 'base_url', $this->baseUrl); + + if (($baseUrl !== '') && ($baseUrl !== $this->baseUrl)) { + $this->baseUrl = $baseUrl; + } + + $result = new Collection(data_get($jsonResponse, 'results.0', [])); + + if ($result->get('type') === 'error') { + $this->resetClientState(); + + $errorCode = (string) data_get($result, 'error.code', 'UNKNOWN_ERROR'); + $errorMessage = (string) data_get($result, 'error.message', 'Error: An unknown error has occurred'); + + throw new TursoQueryException($errorCode, $errorMessage, $statement); + } + + return data_get($result, 'response', []); + } + + public function request(): PendingRequest + { + if ($this->request === null) { + $this->request = $this->createRequest(); + } + + return $this->request; + } + + public function resetClientState(): void + { + $this->baton = null; + $this->baseUrl = data_get($this->config, 'turso_url'); + } +} diff --git a/src/TursoLaravelServiceProvider.php b/src/TursoLaravelServiceProvider.php new file mode 100644 index 0000000..45d0237 --- /dev/null +++ b/src/TursoLaravelServiceProvider.php @@ -0,0 +1,47 @@ +name('turso-laravel') + ->hasConfigFile(); + } + + public function register(): void + { + parent::register(); + + $this->app->scoped(TursoClient::class, function () { + return new TursoClient(); + }); + + $this->app->extend(DatabaseManager::class, function (DatabaseManager $manager) { + Connection::resolverFor('turso', function ($connection = null, ?string $database = null, string $prefix = '', array $config = []) { + $connector = new TursoConnector(); + $pdo = $connector->connect($config); + + return new TursoConnection($pdo, $database ?? ':memory:', $prefix, $config); + }); + + return $manager; + }); + } +} diff --git a/tests/ArchTest.php b/tests/ArchTest.php index 361ec52..08298ff 100644 --- a/tests/ArchTest.php +++ b/tests/ArchTest.php @@ -1,12 +1,16 @@ expect([ 'dd', 'debug_backtrace', 'die', 'dump', 'echo', 'eval', 'exec', 'exit', 'passthru', 'phpinfo', 'print_r', 'proc_open', 'ray', 'shell_exec', 'system', 'var_dump', ]) ->each->not->toBeUsed(); -arch('it will implement strict types') - ->expect('RichanFongdasen\\LaravelTurso') +arch('it should implement strict types') + ->expect('RichanFongdasen\\Turso') + ->toUseStrictTypes(); + +arch('test fixtures should implement strict types') + ->expect('RichanFongdasen\\Turso\\Tests\\Fixtures') ->toUseStrictTypes(); diff --git a/tests/ExampleTest.php b/tests/ExampleTest.php index 5d36321..027cb9e 100644 --- a/tests/ExampleTest.php +++ b/tests/ExampleTest.php @@ -1,5 +1,38 @@ toBeTrue(); + + // $grammar = DB::getSchemaGrammar(); + // dd($grammar->compileDropAllTables()); + + $query = <<<'END' + CREATE TABLE admins ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name char(255), + email char(255), + password char(255), + remember_token char(100), + deleted_at timestamp NULL DEFAULT NULL, + created_at timestamp NULL DEFAULT NULL, + updated_at timestamp NULL DEFAULT NULL + ) + END; + + // Turso::query($query); + + // dd(Turso::query("SELECT * FROM sqlite_schema WHERE type='table' AND NAME NOT LIKE 'sqlite_%'")); + + $query2 = <<<'END' + INSERT INTO `admins` VALUES (2,'Richan','richan@technovative.co.id','mypassword',NULL,NULL,'2022-05-15 10:28:30','2022-05-15 10:28:30'); + END; + + // dd(Http::tursoQuery($query2)->json(), $query2); + // dd(Http::tursoQuery('SELECT * FROM admins')->json()); + + // dd(Turso::query($query2)); }); diff --git a/tests/Feature/EloquentCollectionTest.php b/tests/Feature/EloquentCollectionTest.php new file mode 100644 index 0000000..4da2ef8 --- /dev/null +++ b/tests/Feature/EloquentCollectionTest.php @@ -0,0 +1,26 @@ +count(3)->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can perform the fresh() method', function () { + $collection = Project::all(); + + $collection->first()->delete(); + + $freshCollection = $collection->fresh(); + + expect($freshCollection)->toBeInstanceOf(Collection::class) + ->and($freshCollection->count())->toBe($collection->count() - 1); +})->group('EloquentCollectionTest', 'FeatureTest'); diff --git a/tests/Feature/EloquentDeleteTest.php b/tests/Feature/EloquentDeleteTest.php new file mode 100644 index 0000000..2dcc128 --- /dev/null +++ b/tests/Feature/EloquentDeleteTest.php @@ -0,0 +1,48 @@ +project1 = Project::create(['name' => 'Project 1']); + $this->project2 = Project::create(['name' => 'Project 2']); + $this->project3 = Project::create(['name' => 'Project 3']); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can delete a single record', function () { + $this->project2->delete(); + + expect(Project::count())->toBe(2) + ->and(Project::find($this->project2->getKey()))->toBeNull(); +})->group('EloquentDeleteTest', 'FeatureTest'); + +test('it can delete multiple records using query', function () { + Project::whereIn('id', [$this->project1->getKey(), $this->project3->getKey()])->delete(); + + expect(Project::count())->toBe(1) + ->and(Project::find($this->project1->getKey()))->toBeNull() + ->and(Project::find($this->project3->getKey()))->toBeNull(); +})->group('EloquentDeleteTest', 'FeatureTest'); + +test('it can delete multiple records using destroy method', function () { + Project::destroy([$this->project1->getKey(), $this->project3->getKey()]); + + expect(Project::count())->toBe(1) + ->and(Project::find($this->project1->getKey()))->toBeNull() + ->and(Project::find($this->project3->getKey()))->toBeNull(); +})->group('EloquentDeleteTest', 'FeatureTest'); + +test('it can truncate the whole table', function () { + Project::truncate(); + + expect(Project::count())->toBe(0) + ->and(Project::find($this->project1->getKey()))->toBeNull() + ->and(Project::find($this->project2->getKey()))->toBeNull() + ->and(Project::find($this->project3->getKey()))->toBeNull(); +})->group('EloquentDeleteTest', 'FeatureTest'); diff --git a/tests/Feature/EloquentRelationship/HasManyThroughTest.php b/tests/Feature/EloquentRelationship/HasManyThroughTest.php new file mode 100644 index 0000000..0798ea1 --- /dev/null +++ b/tests/Feature/EloquentRelationship/HasManyThroughTest.php @@ -0,0 +1,59 @@ +project = Project::factory()->create(); + $this->environment = Environment::factory()->create([ + 'project_id' => $this->project->getKey(), + ]); + + $this->deployment1 = Deployment::factory()->create([ + 'environment_id' => $this->environment->getKey(), + ]); + $this->deployment2 = Deployment::factory()->create([ + 'environment_id' => $this->environment->getKey(), + ]); + $this->deployment3 = Deployment::factory()->create([ + 'environment_id' => $this->environment->getKey(), + ]); +}); + +afterEach(function () { + DB::getSchemaBuilder()->dropAllTables(); +}); + +test('it can retrieve the related model in has many through relationship', function () { + $project = Project::findOrFail($this->project->getKey()); + $deployments = $project->deployments; + + expect($deployments)->not->toBeEmpty() + ->and($deployments)->toBeInstanceOf(Collection::class) + ->and($deployments->count())->toBe(3) + ->and($deployments->first()->getKey())->toBe($this->deployment1->getKey()) + ->and($deployments->last()->getKey())->toBe($this->deployment3->getKey()) + ->and($deployments->first()->environment->getKey())->toBe($this->environment->getKey()) + ->and($deployments->last()->environment->getKey())->toBe($this->environment->getKey()) + ->and($deployments->first()->environment->project->getKey())->toBe($this->project->getKey()) + ->and($deployments->last()->environment->project->getKey())->toBe($this->project->getKey()); +})->group('HasManyThroughTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in has many through relationship using eager loading', function () { + $project = Project::with('deployments')->findOrFail($this->project->getKey()); + $deployments = $project->deployments; + + expect($deployments)->not->toBeEmpty() + ->and($deployments)->toBeInstanceOf(Collection::class) + ->and($deployments->count())->toBe(3) + ->and($deployments->first()->getKey())->toBe($this->deployment1->getKey()) + ->and($deployments->last()->getKey())->toBe($this->deployment3->getKey()) + ->and($deployments->first()->environment->getKey())->toBe($this->environment->getKey()) + ->and($deployments->last()->environment->getKey())->toBe($this->environment->getKey()) + ->and($deployments->first()->environment->project->getKey())->toBe($this->project->getKey()) + ->and($deployments->last()->environment->project->getKey())->toBe($this->project->getKey()); +})->group('HasManyThroughTest', 'EloquentRelationship', 'FeatureTest'); diff --git a/tests/Feature/EloquentRelationship/ManyToManyTest.php b/tests/Feature/EloquentRelationship/ManyToManyTest.php new file mode 100644 index 0000000..ec6265f --- /dev/null +++ b/tests/Feature/EloquentRelationship/ManyToManyTest.php @@ -0,0 +1,70 @@ +user = User::factory()->create(); + $this->role1 = Role::factory()->create(); + $this->role2 = Role::factory()->create(); + $this->role3 = Role::factory()->create(); + + $this->user->roles()->attach($this->role1->getKey()); + $this->user->roles()->attach($this->role3->getKey()); +}); + +afterEach(function () { + DB::getSchemaBuilder()->dropAllTables(); +}); + +test('it can retrieve the related model in many to many relationship', function () { + $user = User::findOrFail($this->user->getKey()); + $roles = $user->roles; + + expect($roles)->not->toBeEmpty() + ->and($roles->count())->toBe(2) + ->and($roles->first()->getKey())->toBe($this->role1->getKey()) + ->and($roles->last()->getKey())->toBe($this->role3->getKey()); +})->group('ManyToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in many to many relationship using eager loading', function () { + $user = User::with('roles')->findOrFail($this->user->getKey()); + $roles = $user->roles; + + expect($roles)->not->toBeEmpty() + ->and($roles->count())->toBe(2) + ->and($roles->first()->getKey())->toBe($this->role1->getKey()) + ->and($roles->last()->getKey())->toBe($this->role3->getKey()); +})->group('ManyToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of many to many relationship', function () { + $role = Role::findOrFail($this->role1->getKey()); + $users = $role->users; + + expect($users)->not->toBeEmpty() + ->and($users)->toBeInstanceOf(Collection::class) + ->and($users->count())->toBe(1) + ->and($users->first()->getKey())->toBe($this->user->getKey()); +})->group('ManyToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of many to many relationship using eager loading', function () { + $role = Role::with('users')->findOrFail($this->role1->getKey()); + $users = $role->users; + + expect($users)->not->toBeEmpty() + ->and($users)->toBeInstanceOf(Collection::class) + ->and($users->count())->toBe(1) + ->and($users->first()->getKey())->toBe($this->user->getKey()); +})->group('ManyToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can filter the many to many relationship by specifying a column value', function () { + $user = User::findOrFail($this->user->getKey()); + $role = $user->roles()->where('name', $this->role3->name)->first(); + + expect($role)->not->toBeNull() + ->and($role->getKey())->toBe($this->role3->getKey()) + ->and($role->name)->toBe($this->role3->name); +})->group('ManyToManyTest', 'EloquentRelationship', 'FeatureTest'); diff --git a/tests/Feature/EloquentRelationship/OneToManyTest.php b/tests/Feature/EloquentRelationship/OneToManyTest.php new file mode 100644 index 0000000..bbbe364 --- /dev/null +++ b/tests/Feature/EloquentRelationship/OneToManyTest.php @@ -0,0 +1,93 @@ +user = User::factory()->create(); + $this->post1 = Post::factory()->create([ + 'user_id' => $this->user->getKey(), + ]); + $this->post2 = Post::factory()->create([ + 'user_id' => $this->user->getKey(), + ]); +}); + +afterEach(function () { + DB::getSchemaBuilder()->dropAllTables(); +}); + +test('it can retrieve the related model in one to many relationship', function () { + $user = User::findOrFail($this->user->getKey()); + $posts = $user->posts; + + expect($posts)->not->toBeEmpty() + ->and($posts)->toBeInstanceOf(Collection::class) + ->and($posts->count())->toBe(2) + ->and($posts->first()->getKey())->toBe($this->post1->getKey()) + ->and($posts->last()->getKey())->toBe($this->post2->getKey()) + ->and($posts->first()->user->getKey())->toBe($this->user->getKey()) + ->and($posts->last()->user->getKey())->toBe($this->user->getKey()); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in one to many relationship using eager loading', function () { + $user = User::with('posts')->findOrFail($this->user->getKey()); + $posts = $user->posts; + + expect($posts)->not->toBeEmpty() + ->and($posts)->toBeInstanceOf(Collection::class) + ->and($posts->count())->toBe(2) + ->and($posts->first()->getKey())->toBe($this->post1->getKey()) + ->and($posts->last()->getKey())->toBe($this->post2->getKey()) + ->and($posts->first()->user->getKey())->toBe($this->user->getKey()) + ->and($posts->last()->user->getKey())->toBe($this->user->getKey()); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of one to many relationship', function () { + $post = Post::findOrFail($this->post1->getKey()); + $user = $post->user; + + expect($user)->not->toBeNull() + ->and($user->getKey())->toBe($this->user->getKey()) + ->and($user->name)->toBe($this->user->name) + ->and($user->email)->toBe($this->user->email) + ->and($user->email_verified_at->format('Y-m-d H:i:s'))->toBe($this->user->email_verified_at->format('Y-m-d H:i:s')); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of one to many relationship using eager loading', function () { + $post = Post::with('user')->findOrFail($this->post1->getKey()); + $user = $post->user; + + expect($user)->not->toBeNull() + ->and($user->getKey())->toBe($this->user->getKey()) + ->and($user->name)->toBe($this->user->name) + ->and($user->email)->toBe($this->user->email) + ->and($user->email_verified_at->format('Y-m-d H:i:s'))->toBe($this->user->email_verified_at->format('Y-m-d H:i:s')); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can create a new Post record using eloquent relationship', function () { + $user = User::findOrFail($this->user->getKey()); + $post = $user->posts()->create([ + 'title' => 'New Post Title', + 'content' => 'New Post Content', + ]); + + expect($post)->not->toBeNull() + ->and($post->getKey())->not->toBeNull() + ->and($post->user->getKey())->toBe($user->getKey()) + ->and($post->title)->toBe('New Post Title') + ->and($post->content)->toBe('New Post Content'); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can filter the has many relationship by specifying column value', function () { + $user = User::findOrFail($this->user->getKey()); + $post = $user->posts()->where('title', $this->post1->title)->first(); + + expect($post)->not->toBeNull() + ->and($post->getKey())->toBe($this->post1->getKey()) + ->and($post->title)->toBe($this->post1->title) + ->and($post->content)->toBe($this->post1->content); +})->group('OneToManyTest', 'EloquentRelationship', 'FeatureTest'); diff --git a/tests/Feature/EloquentRelationship/OneToOneTest.php b/tests/Feature/EloquentRelationship/OneToOneTest.php new file mode 100644 index 0000000..06b96f7 --- /dev/null +++ b/tests/Feature/EloquentRelationship/OneToOneTest.php @@ -0,0 +1,59 @@ +user = User::factory()->create(); + $this->phone = Phone::factory()->create([ + 'user_id' => $this->user->getKey(), + ]); +}); + +afterEach(function () { + DB::getSchemaBuilder()->dropAllTables(); +}); + +test('it can retrieve the related model in one to one relationship', function () { + $user = User::findOrFail($this->user->getKey()); + $phone = $user->phone; + + expect($phone)->not->toBeNull() + ->and($phone->getKey())->toBe($this->phone->getKey()) + ->and($phone->user->getKey())->toBe($this->user->getKey()) + ->and($phone->phone_number)->toBe($this->phone->phone_number); +})->group('OneToOneTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in one to one relationship using eager loading', function () { + $user = User::with('phone')->findOrFail($this->user->getKey()); + $phone = $user->phone; + + expect($phone)->not->toBeNull() + ->and($phone->getKey())->toBe($this->phone->getKey()) + ->and($phone->user->getKey())->toBe($this->user->getKey()) + ->and($phone->phone_number)->toBe($this->phone->phone_number); +})->group('OneToOneTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of one to one relationship', function () { + $phone = Phone::findOrFail($this->phone->getKey()); + $user = $phone->user; + + expect($user)->not->toBeNull() + ->and($user->getKey())->toBe($this->user->getKey()) + ->and($user->name)->toBe($this->user->name) + ->and($user->email)->toBe($this->user->email) + ->and($user->email_verified_at->format('Y-m-d H:i:s'))->toBe($this->user->email_verified_at->format('Y-m-d H:i:s')); +})->group('OneToOneTest', 'EloquentRelationship', 'FeatureTest'); + +test('it can retrieve the related model in inverted way of one to one relationship using eager loading', function () { + $phone = Phone::with('user')->findOrFail($this->phone->getKey()); + $user = $phone->user; + + expect($user)->not->toBeNull() + ->and($user->getKey())->toBe($this->user->getKey()) + ->and($user->name)->toBe($this->user->name) + ->and($user->email)->toBe($this->user->email) + ->and($user->email_verified_at->format('Y-m-d H:i:s'))->toBe($this->user->email_verified_at->format('Y-m-d H:i:s')); +})->group('OneToOneTest', 'EloquentRelationship', 'FeatureTest'); diff --git a/tests/Feature/EloquentSoftDeletesTest.php b/tests/Feature/EloquentSoftDeletesTest.php new file mode 100644 index 0000000..69640e4 --- /dev/null +++ b/tests/Feature/EloquentSoftDeletesTest.php @@ -0,0 +1,50 @@ +role1 = Role::create(['name' => 'Role 1']); + $this->role2 = Role::create(['name' => 'Role 2']); + $this->role3 = Role::create(['name' => 'Role 3']); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can delete a single record', function () { + $this->role2->delete(); + + expect(Role::count())->toBe(2) + ->and(Role::withTrashed()->count())->toBe(3) + ->and(Role::find($this->role2->getKey()))->toBeNull(); +})->group('EloquentSoftDeleteTest', 'FeatureTest'); + +test('deleted record can be retrieved using soft deletes specific feature', function () { + $this->role2->delete(); + + $role = Role::withTrashed()->find($this->role2->getKey()); + + expect($role)->not->toBeNull() + ->and($role->getKey())->toBe($this->role2->getKey()) + ->and($role->name)->toBe($this->role2->name); +})->group('EloquentSoftDeleteTest', 'FeatureTest'); + +test('it can restore a soft deleted record', function () { + $this->role2->delete(); + + expect(Role::count())->toBe(2) + ->and(Role::withTrashed()->find($this->role2->getKey()))->not->toBeNull(); + + $role = Role::withTrashed()->find($this->role2->getKey()); + $role->restore(); + + $role = Role::find($this->role2->getKey()); + + expect(Role::count())->toBe(3) + ->and(Role::whereNotNull('deleted_at')->count())->toBe(0) + ->and(Role::find($this->role2->getKey()))->not->toBeNull(); +})->group('EloquentSoftDeleteTest', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/DatabaseQueriesTest.php b/tests/Feature/QueryBuilder/DatabaseQueriesTest.php new file mode 100644 index 0000000..2174a5b --- /dev/null +++ b/tests/Feature/QueryBuilder/DatabaseQueriesTest.php @@ -0,0 +1,102 @@ +project1 = Project::factory()->create(); + $this->project2 = Project::factory()->create(); + $this->project3 = Project::factory()->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can get all rows from the table', function () { + $projects = DB::table('projects')->get(); + + expect($projects)->toHaveCount(3) + ->and($projects[0]->name)->toEqual($this->project1->name) + ->and($projects[1]->name)->toEqual($this->project2->name) + ->and($projects[2]->name)->toEqual($this->project3->name); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can retrieve a single row from the table with first() method', function () { + $project = DB::table('projects')->where('name', $this->project2->name)->first(); + + expect($project)->not->toBeNull() + ->and($project)->toBeObject() + ->and($project->id)->toEqual($this->project2->id) + ->and($project->name)->toEqual($this->project2->name); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can retrieve a single row from the table with find() method', function () { + $project = DB::table('projects')->find($this->project2->getKey()); + + expect($project)->not->toBeNull() + ->and($project)->toBeObject() + ->and($project->id)->toEqual($this->project2->id) + ->and($project->name)->toEqual($this->project2->name); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it will return null if there was no record with the given id to be found', function () { + $project = DB::table('projects')->find(999); + + expect($project)->toBeNull(); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can retrieve a list of column values', function () { + $expectation = [ + $this->project1->name, + $this->project2->name, + $this->project3->name, + ]; + + $projects = DB::table('projects')->pluck('name')->toArray(); + + expect($projects)->toBeArray() + ->and($projects)->toHaveCount(3) + ->and($projects)->toEqual($expectation); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can stream the results lazily', function () { + $expectations = [ + $this->project1, + $this->project2, + $this->project3, + ]; + + DB::table('projects') + ->orderBy('id') + ->lazy() + ->each(function (object $project, int $index) use ($expectations) { + expect($project)->toBeObject() + ->and($project->id)->toEqual($expectations[$index]->id) + ->and($project->name)->toEqual($expectations[$index]->name); + }); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can count the records count', function () { + expect(DB::table('projects')->count())->toEqual(3); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can return the maximum value of a column from the table', function () { + expect(DB::table('projects')->max('id'))->toEqual(3); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can return the minimum value of a column from the table', function () { + expect(DB::table('projects')->min('id'))->toEqual(1); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can return the average value of a column from the table', function () { + expect(DB::table('projects')->avg('id'))->toEqual(2); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); + +test('it can determine if a record exists in the table', function () { + expect(DB::table('projects')->where('name', $this->project2->name)->exists())->toBeTrue() + ->and(DB::table('projects')->where('name', 'unknown')->doesntExist())->toBeTrue(); +})->group('DatabaseQueriesTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/DeleteStatementsTest.php b/tests/Feature/QueryBuilder/DeleteStatementsTest.php new file mode 100644 index 0000000..3c0015a --- /dev/null +++ b/tests/Feature/QueryBuilder/DeleteStatementsTest.php @@ -0,0 +1,41 @@ +user1 = User::factory()->create(); + $this->user2 = User::factory()->create(); + $this->user3 = User::factory()->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can delete multiple records', function () { + DB::table('users')->where('id', '>', 1)->delete(); + + expect(DB::table('users')->count())->toBe(1); +})->group('DeleteStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can truncate the whole table content', function () { + DB::table('users')->truncate(); + + expect(DB::table('users')->count())->toBe(0); +})->group('DeleteStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can delete a single record', function () { + DB::table('users')->where('id', $this->user2->getKey())->delete(); + + expect(DB::table('users')->count())->toBe(2); +})->group('DeleteStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can delete all records', function () { + DB::table('users')->delete(); + + expect(DB::table('users')->count())->toBe(0); +})->group('DeleteStatementsTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/InsertStatementsTest.php b/tests/Feature/QueryBuilder/InsertStatementsTest.php new file mode 100644 index 0000000..4bc9716 --- /dev/null +++ b/tests/Feature/QueryBuilder/InsertStatementsTest.php @@ -0,0 +1,67 @@ +insert([ + 'name' => 'John Doe', + 'email' => 'john.doe@gmail.com', + ]); + + $user = DB::table('users')->first(); + + expect($result)->toBeTrue() + ->and(DB::table('users')->count())->toBe(1) + ->and($user->name)->toBe('John Doe') + ->and($user->email)->toBe('john.doe@gmail.com'); +})->group('InsertStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can insert multiple records', function () { + $result = DB::table('users')->insert([ + [ + 'name' => 'John Doe', + 'email' => 'john.doe@gmail.com', + ], + [ + 'name' => 'June Monroe', + 'email' => 'june.monroe@gmail.com', + ], + ]); + + $users = DB::table('users')->get(); + + expect($result)->toBeTrue() + ->and(DB::table('users')->count())->toBe(2) + ->and($users->first()->name)->toBe('John Doe') + ->and($users->first()->email)->toBe('john.doe@gmail.com') + ->and($users->last()->name)->toBe('June Monroe') + ->and($users->last()->email)->toBe('june.monroe@gmail.com'); +})->group('InsertStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can get the auto increment id as the result of insert command', function () { + User::factory()->create(); + + $expectation = User::factory()->make(); + + $result = DB::table('users')->insertGetId([ + 'name' => $expectation->name, + 'email' => $expectation->email, + ]); + + $newUser = DB::table('users')->find($result); + + expect(DB::table('users')->count())->toBe(2) + ->and($result)->toBe(2) + ->and($newUser->name)->toBe($expectation->name) + ->and($newUser->email)->toBe($expectation->email); +})->group('InsertStatementsTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/RawExpressionsTest.php b/tests/Feature/QueryBuilder/RawExpressionsTest.php new file mode 100644 index 0000000..7dc5f75 --- /dev/null +++ b/tests/Feature/QueryBuilder/RawExpressionsTest.php @@ -0,0 +1,66 @@ +user1 = User::factory()->create(); + $this->user2 = User::factory()->create(); + $this->user3 = User::factory()->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can perform raw column selection', function () { + $result = DB::table('users') + ->select(DB::raw('count (*) as user_count')) + ->get(); + + expect($result->first()->user_count)->toBe(3); +})->group('RawExpressionsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can perform selectRaw query', function () { + $result = DB::table('users') + ->selectRaw('id, id * ? as multiplied_id', [3]) + ->orderBy('id') + ->get(); + + expect($result->count())->toBe(3) + ->and($result[0]->multiplied_id)->toBe((int) $this->user1->getKey() * 3) + ->and($result[1]->multiplied_id)->toBe((int) $this->user2->getKey() * 3) + ->and($result[2]->multiplied_id)->toBe((int) $this->user3->getKey() * 3); +})->group('RawExpressionsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can perform whereRaw query', function () { + $newUser = User::factory()->create([ + 'created_at' => Carbon::parse('1945-08-17 00:00:00'), + ]); + + $selectedUser = DB::table('users') + ->whereRaw("strftime('%Y-%m', created_at) = '1945-08'") + ->first(); + + expect($selectedUser)->not->toBeNull() + ->and($selectedUser->id)->toBe($newUser->id) + ->and($selectedUser->name)->toBe($newUser->name); +})->group('RawExpressionsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can perform orderByRaw query', function () { + $newUser = User::factory()->create([ + 'created_at' => Carbon::parse('1945-08-17 00:00:00'), + ]); + + $result = DB::table('users') + ->orderByRaw('updated_at - created_at DESC') + ->first(); + + expect($result)->not->toBeNull() + ->and($result->id)->toBe($newUser->id) + ->and($result->name)->toBe($newUser->name); +})->group('RawExpressionsTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/SelectStatementsTest.php b/tests/Feature/QueryBuilder/SelectStatementsTest.php new file mode 100644 index 0000000..b3d77b0 --- /dev/null +++ b/tests/Feature/QueryBuilder/SelectStatementsTest.php @@ -0,0 +1,57 @@ +user1 = User::factory()->create(); + $this->user2 = User::factory()->create(); + $this->user3 = User::factory()->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can specify a select clause', function () { + $users = DB::table('users')->select('name', 'email as user_email')->get(); + + expect($users)->toHaveCount(3) + ->and($users[0]->name)->toEqual($this->user1->name) + ->and($users[0]->user_email)->toEqual($this->user1->email) + ->and($users[1]->name)->toEqual($this->user2->name) + ->and($users[1]->user_email)->toEqual($this->user2->email) + ->and($users[2]->name)->toEqual($this->user3->name) + ->and($users[2]->user_email)->toEqual($this->user3->email); +})->group('SelectStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can return distinct result', function () { + $newUser = User::factory()->create([ + 'name' => $this->user2->name, + ]); + + $users = DB::table('users')->select('name')->distinct()->get(); + + expect($users)->toHaveCount(3) + ->and(DB::table('users')->count())->toEqual(4) + ->and($users[0]->name)->toEqual($this->user1->name) + ->and($users[1]->name)->toEqual($this->user2->name) + ->and($users[2]->name)->toEqual($this->user3->name); +})->group('SelectStatementsTest', 'QueryBuilder', 'FeatureTest'); + +test('it can add another column selection', function () { + $query = DB::table('users')->select('name'); + + $users = $query->addSelect('email')->get(); + + expect($users)->toHaveCount(3) + ->and($users[0]->name)->toEqual($this->user1->name) + ->and($users[0]->email)->toEqual($this->user1->email) + ->and($users[1]->name)->toEqual($this->user2->name) + ->and($users[1]->email)->toEqual($this->user2->email) + ->and($users[2]->name)->toEqual($this->user3->name) + ->and($users[2]->email)->toEqual($this->user3->email); +})->group('SelectStatementsTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/QueryBuilder/UpdateStatementTest.php b/tests/Feature/QueryBuilder/UpdateStatementTest.php new file mode 100644 index 0000000..7834c62 --- /dev/null +++ b/tests/Feature/QueryBuilder/UpdateStatementTest.php @@ -0,0 +1,76 @@ +user = User::factory()->create(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can update the user\'s email address', function () { + DB::table('users') + ->where('id', $this->user->getKey()) + ->update([ + 'email' => 'richan.fongdasen@gmail.com', + ]); + + $updatedUser = DB::table('users')->find($this->user->getKey()); + + expect($updatedUser->email)->toBe('richan.fongdasen@gmail.com'); +})->group('UpdateStatementTest', 'QueryBuilder', 'FeatureTest'); + +test('it can insert a new record with updateOrInsert method', function () { + DB::table('users') + ->updateOrInsert( + [ + 'name' => 'John Doe', + 'email' => 'john.doe@gmail.com', + ], + [ + 'remember_token' => '1234567890', + ] + ); + + $user = DB::table('users') + ->where('name', 'John Doe') + ->where('email', 'john.doe@gmail.com') + ->first(); + + expect($user->id)->toBe(2) + ->and($user->remember_token)->toBe('1234567890'); +})->group('UpdateStatementTest', 'QueryBuilder', 'FeatureTest'); + +test('it can update an existing record with updateOrInsert method', function () { + DB::table('users') + ->updateOrInsert( + [ + 'name' => $this->user->name, + 'email' => $this->user->email, + ], + [ + 'remember_token' => '1234567890', + ] + ); + + $updatedUser = DB::table('users')->find($this->user->getKey()); + + expect(DB::table('users')->count())->toBe(1) + ->and($updatedUser->remember_token)->toBe('1234567890'); +})->group('UpdateStatementTest', 'QueryBuilder', 'FeatureTest'); + +test('it can increment and decrement a column value', function () { + DB::table('users')->increment('id', 5); + + expect(DB::table('users')->first()->id)->toBe(6); + + DB::table('users')->decrement('id', 3); + + expect(DB::table('users')->first()->id)->toBe(3); +})->group('UpdateStatementTest', 'QueryBuilder', 'FeatureTest'); diff --git a/tests/Feature/TursoPDOStatementTest.php b/tests/Feature/TursoPDOStatementTest.php new file mode 100644 index 0000000..a247792 --- /dev/null +++ b/tests/Feature/TursoPDOStatementTest.php @@ -0,0 +1,119 @@ +connection = DB::connection(); + $this->pdo = $this->connection->getPdo(); +}); + +afterEach(function () { + Schema::dropAllTables(); +}); + +test('it can fetch all row sets of a simple select query result in associative array format', function () { + $expectation = [ + [ + 'type' => 'table', + 'name' => 'migrations', + 'tbl_name' => 'migrations', + 'sql' => 'CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)', + ], + ]; + + $statement = $this->pdo->prepare('SELECT * FROM sqlite_schema WHERE type = ? AND name NOT LIKE ?'); + $this->connection->bindValues($statement, $this->connection->prepareBindings(['table', 'sqlite_%'])); + + $statement->execute(); + + $statement->setFetchMode(\PDO::FETCH_ASSOC); + $response = $statement->fetchAll(); + + expect(count($response))->toBe(1) + ->and($response[0]['type'])->toBe($expectation[0]['type']) + ->and($response[0]['name'])->toBe($expectation[0]['name']) + ->and($response[0]['tbl_name'])->toBe($expectation[0]['tbl_name']) + ->and($response[0]['sql'])->toBe($expectation[0]['sql']); +})->group('TursoPDOStatementTest', 'FeatureTest'); + +test('it can fetch all row sets of a simple select query result in both array format', function () { + $expectation = [ + [ + 'type' => 'table', + 'name' => 'migrations', + 'tbl_name' => 'migrations', + 'sql' => 'CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)', + 0 => 'table', + 1 => 'migrations', + 2 => 'migrations', + 4 => 'CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)', + ], + ]; + + $statement = $this->pdo->prepare('SELECT * FROM sqlite_schema WHERE type = ? AND name NOT LIKE ?'); + $this->connection->bindValues($statement, $this->connection->prepareBindings(['table', 'sqlite_%'])); + + $statement->execute(); + + $statement->setFetchMode(\PDO::FETCH_BOTH); + $response = $statement->fetchAll(); + + expect(count($response))->toBe(1) + ->and($response[0]['type'])->toBe($expectation[0]['type']) + ->and($response[0]['name'])->toBe($expectation[0]['name']) + ->and($response[0]['tbl_name'])->toBe($expectation[0]['tbl_name']) + ->and($response[0]['sql'])->toBe($expectation[0]['sql']) + ->and($response[0][0])->toBe($expectation[0][0]) + ->and($response[0][1])->toBe($expectation[0][1]) + ->and($response[0][2])->toBe($expectation[0][2]) + ->and($response[0][4])->toBe($expectation[0][4]); +})->group('TursoPDOStatementTest', 'FeatureTest'); + +test('it can fetch each row set of a simple select query result in associative array format', function () { + $expectation = [ + 'type' => 'table', + 'name' => 'migrations', + 'tbl_name' => 'migrations', + 'sql' => 'CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)', + ]; + + $statement = $this->pdo->prepare('SELECT * FROM sqlite_schema WHERE type = ? AND name NOT LIKE ?'); + $this->connection->bindValues($statement, $this->connection->prepareBindings(['table', 'sqlite_%'])); + + $statement->execute(); + + $statement->setFetchMode(\PDO::FETCH_ASSOC); + $response = $statement->fetch(); + + expect($response['type'])->toBe($expectation['type']) + ->and($response['name'])->toBe($expectation['name']) + ->and($response['tbl_name'])->toBe($expectation['tbl_name']) + ->and($response['sql'])->toBe($expectation['sql']) + ->and($statement->fetch())->toBeFalse(); +})->group('TursoPDOStatementTest', 'FeatureTest'); + +test('it can count the rows of query result set', function () { + $statement = $this->pdo->prepare('SELECT * FROM sqlite_schema WHERE type = ? AND name NOT LIKE ?'); + $this->connection->bindValues($statement, $this->connection->prepareBindings(['table', 'sqlite_%'])); + + $statement->execute(); + + expect($statement->rowCount())->toBe(1); +})->group('TursoPDOStatementTest', 'FeatureTest'); + +test('it can perform query execution with binding values', function () { + DB::statement('INSERT INTO "migrations" ("migration", "batch") VALUES (?, ?)', ['CreateUsersTable', 1]); + + $statement = $this->pdo->prepare('SELECT * FROM "migrations" WHERE "migration" = ? AND "batch" = ?'); + $statement->execute(['CreateUsersTable', 1]); + + expect($statement->rowCount())->toBe(1); + + $result = $statement->fetch(); + + expect($result['migration'])->toBe('CreateUsersTable') + ->and($result['batch'])->toBe(1); +})->group('TursoPDOStatementTest', 'FeatureTest'); diff --git a/tests/Feature/TursoPDOTest.php b/tests/Feature/TursoPDOTest.php new file mode 100644 index 0000000..723d05b --- /dev/null +++ b/tests/Feature/TursoPDOTest.php @@ -0,0 +1,11 @@ +pdo = DB::connection()->getPdo(); +}); + +test('it can execute SQL command', function () { + expect($this->pdo->exec('PRAGMA foreign_keys = ON;'))->toBe(0); +})->group('TursoPDOTest', 'FeatureTest'); diff --git a/tests/Feature/TursoSchemaBuilderTest.php b/tests/Feature/TursoSchemaBuilderTest.php new file mode 100644 index 0000000..62d4ba3 --- /dev/null +++ b/tests/Feature/TursoSchemaBuilderTest.php @@ -0,0 +1,127 @@ +toBe([]); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); + +test('it can retrieve all of the table information in the database', function () { + DB::select('CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)'); + + $result = Schema::getTables()[0]; + + expect($result['name'])->toBe('migrations') + ->and($result['schema'])->toBeNull() + ->and($result['comment'])->toBeNull() + ->and($result['collation'])->toBeNull() + ->and($result['engine'])->toBeNull(); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); + +test('it can retrieve all of the column information in the table', function () { + DB::select('CREATE TABLE "migrations" ("id" integer primary key autoincrement not null, "migration" varchar not null, "batch" integer not null)'); + + $result = collect(Schema::getColumns('migrations'))->keyBy('name'); + + expect($result->count())->toBe(3) + ->and($result->has('id'))->toBeTrue() + ->and($result->has('migration'))->toBeTrue() + ->and($result->has('batch'))->toBeTrue() + ->and($result->get('id'))->toBe([ + 'name' => 'id', + 'type_name' => 'integer', + 'type' => 'integer', + 'collation' => null, + 'nullable' => false, + 'default' => null, + 'auto_increment' => true, + 'comment' => null, + 'generation' => null, + ]) + ->and($result->get('migration'))->toBe([ + 'name' => 'migration', + 'type_name' => 'varchar', + 'type' => 'varchar', + 'collation' => null, + 'nullable' => false, + 'default' => null, + 'auto_increment' => false, + 'comment' => null, + 'generation' => null, + ]) + ->and($result->get('batch'))->toBe([ + 'name' => 'batch', + 'type_name' => 'integer', + 'type' => 'integer', + 'collation' => null, + 'nullable' => false, + 'default' => null, + 'auto_increment' => false, + 'comment' => null, + 'generation' => null, + ]); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); + +test('it can create a new table', function () { + Schema::create('users', function (Blueprint $table) { + $table->id(); + $table->string('name'); + }); + + $result = Schema::getTables()[0]; + + expect($result['name'])->toBe('users') + ->and($result['schema'])->toBeNull() + ->and($result['comment'])->toBeNull() + ->and($result['collation'])->toBeNull() + ->and($result['engine'])->toBeNull(); + + $columns = collect(Schema::getColumns('users'))->keyBy('name')->keys()->all(); + + expect($columns)->toBe(['id', 'name']); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); + +test('it can alter an existing table.', function () { + Schema::create('users', function (Blueprint $table) { + $table->id(); + $table->string('name'); + }); + + Schema::table('users', function (Blueprint $table) { + $table->string('email')->after('name'); + }); + + expect(Schema::hasColumn('users', 'email'))->toBeTrue() + ->and(Schema::hasColumns('users', ['id', 'name', 'email']))->toBeTrue() + ->and(Schema::getColumnType('users', 'email'))->toBe('varchar') + ->and(Schema::getColumnListing('users'))->toBe(['id', 'name', 'email']); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); + +test('it can drop all views from the database', function () { + $createSql = 'CREATE VIEW foo (id) AS SELECT 1'; + + DB::statement($createSql); + + $view = collect(Schema::getViews())->first(); + + expect($view['name'])->toBe('foo') + ->and($view['schema'])->toBeNull() + ->and($view['definition'])->toBe($createSql); + + Schema::dropAllViews(); + + expect(Schema::getViews())->toBe([]); +})->group('TursoSchemaBuilderTest', 'FeatureTest'); diff --git a/tests/Fixtures/Factories/DeploymentFactory.php b/tests/Fixtures/Factories/DeploymentFactory.php new file mode 100644 index 0000000..f9998c9 --- /dev/null +++ b/tests/Fixtures/Factories/DeploymentFactory.php @@ -0,0 +1,31 @@ + + */ + public function definition(): array + { + return [ + 'environment_id' => Environment::factory(), + 'commit_hash' => sha1(Str::random(40)), + ]; + } + + public function modelName(): string + { + return Deployment::class; + } +} diff --git a/tests/Fixtures/Factories/EnvironmentFactory.php b/tests/Fixtures/Factories/EnvironmentFactory.php new file mode 100644 index 0000000..ec707ce --- /dev/null +++ b/tests/Fixtures/Factories/EnvironmentFactory.php @@ -0,0 +1,30 @@ + + */ + public function definition(): array + { + return [ + 'project_id' => Project::factory(), + 'name' => fake()->text(rand(5, 10)), + ]; + } + + public function modelName(): string + { + return Environment::class; + } +} diff --git a/tests/Fixtures/Factories/PhoneFactory.php b/tests/Fixtures/Factories/PhoneFactory.php new file mode 100644 index 0000000..3bb5efc --- /dev/null +++ b/tests/Fixtures/Factories/PhoneFactory.php @@ -0,0 +1,30 @@ + + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'phone_number' => fake()->phoneNumber(), + ]; + } + + public function modelName(): string + { + return Phone::class; + } +} diff --git a/tests/Fixtures/Factories/PostFactory.php b/tests/Fixtures/Factories/PostFactory.php new file mode 100644 index 0000000..4d540ad --- /dev/null +++ b/tests/Fixtures/Factories/PostFactory.php @@ -0,0 +1,31 @@ + + */ + public function definition(): array + { + return [ + 'user_id' => User::factory(), + 'title' => fake()->text(rand(10, 30)), + 'content' => fake()->paragraph(), + ]; + } + + public function modelName(): string + { + return Post::class; + } +} diff --git a/tests/Fixtures/Factories/ProjectFactory.php b/tests/Fixtures/Factories/ProjectFactory.php new file mode 100644 index 0000000..aebb84c --- /dev/null +++ b/tests/Fixtures/Factories/ProjectFactory.php @@ -0,0 +1,28 @@ + + */ + public function definition(): array + { + return [ + 'name' => fake()->text(rand(5, 10)), + ]; + } + + public function modelName(): string + { + return Project::class; + } +} diff --git a/tests/Fixtures/Factories/RoleFactory.php b/tests/Fixtures/Factories/RoleFactory.php new file mode 100644 index 0000000..704b586 --- /dev/null +++ b/tests/Fixtures/Factories/RoleFactory.php @@ -0,0 +1,28 @@ + + */ + public function definition(): array + { + return [ + 'name' => fake()->text(rand(5, 10)), + ]; + } + + public function modelName(): string + { + return Role::class; + } +} diff --git a/tests/Fixtures/Factories/UserFactory.php b/tests/Fixtures/Factories/UserFactory.php new file mode 100644 index 0000000..c7bf255 --- /dev/null +++ b/tests/Fixtures/Factories/UserFactory.php @@ -0,0 +1,32 @@ + + */ + public function definition(): array + { + return [ + 'name' => fake()->name(), + 'email' => fake()->unique()->safeEmail(), + 'email_verified_at' => now(), + 'remember_token' => Str::random(10), + ]; + } + + public function modelName(): string + { + return User::class; + } +} diff --git a/tests/Fixtures/Migrations/create_deployments_table.php b/tests/Fixtures/Migrations/create_deployments_table.php new file mode 100644 index 0000000..2ebd75a --- /dev/null +++ b/tests/Fixtures/Migrations/create_deployments_table.php @@ -0,0 +1,34 @@ +id(); + $table->unsignedBigInteger('environment_id'); + $table->string('commit_hash'); + $table->timestamps(); + + $table->foreign('environment_id') + ->references('id') + ->on('environments') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('deployments'); + } +}; diff --git a/tests/Fixtures/Migrations/create_environments_table.php b/tests/Fixtures/Migrations/create_environments_table.php new file mode 100644 index 0000000..1990982 --- /dev/null +++ b/tests/Fixtures/Migrations/create_environments_table.php @@ -0,0 +1,34 @@ +id(); + $table->unsignedBigInteger('project_id'); + $table->string('name'); + $table->timestamps(); + + $table->foreign('project_id') + ->references('id') + ->on('projects') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('environments'); + } +}; diff --git a/tests/Fixtures/Migrations/create_phones_table.php b/tests/Fixtures/Migrations/create_phones_table.php new file mode 100644 index 0000000..ce38024 --- /dev/null +++ b/tests/Fixtures/Migrations/create_phones_table.php @@ -0,0 +1,34 @@ +id(); + $table->unsignedBigInteger('user_id'); + $table->string('phone_number'); + $table->timestamps(); + + $table->foreign('user_id') + ->references('id') + ->on('users') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('phones'); + } +}; diff --git a/tests/Fixtures/Migrations/create_posts_table.php b/tests/Fixtures/Migrations/create_posts_table.php new file mode 100644 index 0000000..82871f0 --- /dev/null +++ b/tests/Fixtures/Migrations/create_posts_table.php @@ -0,0 +1,35 @@ +id(); + $table->unsignedBigInteger('user_id'); + $table->string('title'); + $table->text('content'); + $table->timestamps(); + + $table->foreign('user_id') + ->references('id') + ->on('users') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('posts'); + } +}; diff --git a/tests/Fixtures/Migrations/create_projects_table.php b/tests/Fixtures/Migrations/create_projects_table.php new file mode 100644 index 0000000..efbd99f --- /dev/null +++ b/tests/Fixtures/Migrations/create_projects_table.php @@ -0,0 +1,28 @@ +id(); + $table->string('name'); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('projects'); + } +}; diff --git a/tests/Fixtures/Migrations/create_roles_table.php b/tests/Fixtures/Migrations/create_roles_table.php new file mode 100644 index 0000000..e6ad011 --- /dev/null +++ b/tests/Fixtures/Migrations/create_roles_table.php @@ -0,0 +1,29 @@ +id(); + $table->string('name'); + $table->timestamps(); + $table->softDeletes(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('roles'); + } +}; diff --git a/tests/Fixtures/Migrations/create_user_roles_table.php b/tests/Fixtures/Migrations/create_user_roles_table.php new file mode 100644 index 0000000..3be5f2d --- /dev/null +++ b/tests/Fixtures/Migrations/create_user_roles_table.php @@ -0,0 +1,38 @@ +id(); + $table->unsignedBigInteger('user_id'); + $table->unsignedBigInteger('role_id'); + + $table->foreign('user_id') + ->references('id') + ->on('users') + ->onDelete('cascade'); + + $table->foreign('role_id') + ->references('id') + ->on('roles') + ->onDelete('cascade'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('user_roles'); + } +}; diff --git a/tests/Fixtures/Migrations/create_users_table.php b/tests/Fixtures/Migrations/create_users_table.php new file mode 100644 index 0000000..e5b4cc8 --- /dev/null +++ b/tests/Fixtures/Migrations/create_users_table.php @@ -0,0 +1,31 @@ +id(); + $table->string('name'); + $table->string('email')->unique(); + $table->timestamp('email_verified_at')->nullable(); + $table->rememberToken(); + $table->timestamps(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('users'); + } +}; diff --git a/tests/Fixtures/Models/Deployment.php b/tests/Fixtures/Models/Deployment.php new file mode 100644 index 0000000..1329401 --- /dev/null +++ b/tests/Fixtures/Models/Deployment.php @@ -0,0 +1,41 @@ + + */ + protected $fillable = [ + 'commit_hash', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + 'environment_id' => 'integer', + ]; + } + + public function environment(): BelongsTo + { + return $this->belongsTo(Environment::class); + } +} diff --git a/tests/Fixtures/Models/Environment.php b/tests/Fixtures/Models/Environment.php new file mode 100644 index 0000000..de94820 --- /dev/null +++ b/tests/Fixtures/Models/Environment.php @@ -0,0 +1,47 @@ + + */ + protected $fillable = [ + 'name', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + 'project_id' => 'integer', + ]; + } + + public function deployments(): HasMany + { + return $this->hasMany(Deployment::class); + } + + public function project(): BelongsTo + { + return $this->belongsTo(Project::class); + } +} diff --git a/tests/Fixtures/Models/Phone.php b/tests/Fixtures/Models/Phone.php new file mode 100644 index 0000000..ffaf1d3 --- /dev/null +++ b/tests/Fixtures/Models/Phone.php @@ -0,0 +1,42 @@ + + */ + protected $fillable = [ + 'user_id', + 'phone_number', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + 'user_id' => 'integer', + ]; + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/tests/Fixtures/Models/Post.php b/tests/Fixtures/Models/Post.php new file mode 100644 index 0000000..6c31cb9 --- /dev/null +++ b/tests/Fixtures/Models/Post.php @@ -0,0 +1,49 @@ + + */ + protected $fillable = [ + 'user_id', + 'title', + 'content', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + 'user_id' => 'integer', + ]; + } + + public function comments(): HasMany + { + return $this->hasMany(Comment::class); + } + + public function user(): BelongsTo + { + return $this->belongsTo(User::class); + } +} diff --git a/tests/Fixtures/Models/Project.php b/tests/Fixtures/Models/Project.php new file mode 100644 index 0000000..43959bc --- /dev/null +++ b/tests/Fixtures/Models/Project.php @@ -0,0 +1,46 @@ + + */ + protected $fillable = [ + 'name', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + ]; + } + + public function environments(): HasMany + { + return $this->hasMany(Environment::class); + } + + public function deployments(): HasManyThrough + { + return $this->hasManyThrough(Deployment::class, Environment::class); + } +} diff --git a/tests/Fixtures/Models/Role.php b/tests/Fixtures/Models/Role.php new file mode 100644 index 0000000..3366cc0 --- /dev/null +++ b/tests/Fixtures/Models/Role.php @@ -0,0 +1,42 @@ + + */ + protected $fillable = [ + 'name', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + ]; + } + + public function users(): BelongsToMany + { + return $this->belongsToMany(User::class, 'user_roles'); + } +} diff --git a/tests/Fixtures/Models/User.php b/tests/Fixtures/Models/User.php new file mode 100644 index 0000000..4178941 --- /dev/null +++ b/tests/Fixtures/Models/User.php @@ -0,0 +1,71 @@ + + */ + protected $fillable = [ + 'name', + 'email', + ]; + + /** + * The attributes that should be hidden for serialization. + * + * @var array + */ + protected $hidden = [ + 'remember_token', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'id' => 'integer', + 'email_verified_at' => 'datetime', + ]; + } + + public function comments(): HasManyThrough + { + return $this->hasManyThrough(Comment::class, Post::class); + } + + public function phone(): HasOne + { + return $this->hasOne(Phone::class); + } + + public function posts(): HasMany + { + return $this->hasMany(Post::class); + } + + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class, 'user_roles'); + } +} diff --git a/tests/Pest.php b/tests/Pest.php index e594a5a..afacdef 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -1,5 +1,17 @@ in(__DIR__); +uses( + TestCase::class, +)->in(__DIR__); + +function migrateTables(...$tableNames): void +{ + collect($tableNames) + ->each(function (string $tableName) { + $migration = include __DIR__ . '/Fixtures/Migrations/create_' . Str::snake(Str::plural($tableName)) . '_table.php'; + $migration->up(); + }); +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 6efa341..321275d 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -1,10 +1,10 @@ 'RichanFongdasen\\LaravelTurso\\Database\\Factories\\' . class_basename($modelName) . 'Factory' + fn (string $modelName) => 'RichanFongdasen\\Turso\\Tests\\Fixtures\\Factories\\' . class_basename($modelName) . 'Factory' ); } protected function getPackageProviders($app) { return [ - LaravelTursoServiceProvider::class, + TursoLaravelServiceProvider::class, ]; } public function getEnvironmentSetUp($app) { - config()->set('database.default', 'testing'); - - /* - $migration = include __DIR__.'/../database/migrations/create_laravel-turso_table.php.stub'; - $migration->up(); - */ + config()->set('database.connections.turso', [ + 'driver' => 'turso', + 'turso_url' => env('DB_URL', 'http://127.0.0.1:8080'), + 'database' => null, + 'prefix' => env('DB_PREFIX', ''), + 'access_token' => 'your-access-token', + 'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true), + ]); + config()->set('database.default', 'turso'); } } diff --git a/tests/Unit/TursoClientTest.php b/tests/Unit/TursoClientTest.php new file mode 100644 index 0000000..0fadf1e --- /dev/null +++ b/tests/Unit/TursoClientTest.php @@ -0,0 +1,79 @@ +toBe('http://127.0.0.1:8080') + ->and(Turso::getBaton())->toBeNull(); +})->group('TursoClient', 'UnitTest'); + +test('it can log queries', function () { + Http::fake(); + + $query = [ + 'statement' => 'SELECT * FROM "users" WHERE "id" = ?', + 'bindings' => [ + [ + 'type' => 'integer', + 'value' => 1, + ], + ], + 'response' => null, + ]; + + Turso::enableQueryLog(); + + Turso::query($query['statement'], $query['bindings']); + + expect(Turso::getQueryLog()->count())->toBe(1) + ->and(Turso::getQueryLog()->first())->toBe($query); +})->group('TursoClient', 'UnitTest'); + +test('it raises exception on any HTTP errors', function () { + Http::fake([ + '*' => Http::response(['message' => 'Internal Server Error'], 500), + ]); + + Turso::query('SELECT * FROM "users"'); +})->throws(RequestException::class)->group('TursoClient', 'UnitTest'); + +test('it raises TursoQueryException when the query response has any response in it', function () { + Http::fake([ + '*' => Http::response( + [ + 'results' => [ + [ + 'type' => 'error', + 'error' => [ + 'code' => 'QUERY_ERROR', + 'message' => 'Error: An unknown error has occurred', + ], + ], + ], + ], + 200 + ), + ]); + + Turso::query('SELECT * FROM "users"'); +})->throws(TursoQueryException::class)->group('TursoClient', 'UnitTest'); + +test('it can replace the base url with the one that suggested by turso response', function () { + Http::fake([ + '*' => Http::response( + [ + 'base_url' => 'http://base-url-example.turso.io', + ], + 200 + ), + ]); + + Turso::query('SELECT * FROM "users"'); + + expect(Turso::getBaseUrl())->toBe('http://base-url-example.turso.io'); +})->group('TursoClient', 'UnitTest'); diff --git a/tests/Unit/TursoPDOTest.php b/tests/Unit/TursoPDOTest.php new file mode 100644 index 0000000..2c7aaef --- /dev/null +++ b/tests/Unit/TursoPDOTest.php @@ -0,0 +1,35 @@ +pdo = DB::connection()->getPdo(); +}); + +test('it should be an instance of TursoPDO', function () { + expect($this->pdo)->toBeInstanceOf(TursoPDO::class); +})->group('TursoPDOTest', 'UnitTest'); + +test('it raises exception on beginning a database transaction', function () { + $this->pdo->beginTransaction(); +})->throws(FeatureNotSupportedException::class)->group('TursoPDOTest', 'UnitTest'); + +test('it raises exception on committing a database transaction', function () { + $this->pdo->commit(); +})->throws(FeatureNotSupportedException::class)->group('TursoPDOTest', 'UnitTest'); + +test('it raises exception on rolling back a database transaction', function () { + $this->pdo->rollBack(); +})->throws(FeatureNotSupportedException::class)->group('TursoPDOTest', 'UnitTest'); + +test('database transaction status should always be false', function () { + expect($this->pdo->inTransaction())->toBeFalse(); +})->group('TursoPDOTest', 'UnitTest'); + +test('it can manage the last insert id value', function () { + $this->pdo->setLastInsertId(value: 123); + + expect($this->pdo->lastInsertId())->toBe('123'); +})->group('TursoPDOTest', 'UnitTest'); diff --git a/tests/Unit/TursoSchemaBuilderTest.php b/tests/Unit/TursoSchemaBuilderTest.php new file mode 100644 index 0000000..3b3e1c2 --- /dev/null +++ b/tests/Unit/TursoSchemaBuilderTest.php @@ -0,0 +1,12 @@ +throws(FeatureNotSupportedException::class)->group('TursoSchemaBuilderTest', 'UnitTest'); + +test('it raises exception on dropping database.', function () { + Schema::dropDatabaseIfExists('test'); +})->throws(FeatureNotSupportedException::class)->group('TursoSchemaBuilderTest', 'UnitTest');