Code Monkey home page Code Monkey logo

turso-laravel's Introduction

A Turso database driver for Laravel

Latest Version on Packagist License: MIT PHPStan Unit Tests Code Style codecov Total Downloads

This package provides a Turso database driver for Laravel, allowing you to use Turso as your database backend in Laravel applications. The driver communicates with the Turso database server using an HTTP client.

You can find a demo application that uses this Turso database driver in the richan-fongdasen/pingcrm repository.

Requirements

  • PHP 8.2 or higher
  • Laravel 11.0 or higher
  • Node.js 16 or higher

Installation

You can install the package via Composer:

composer require richan-fongdasen/turso-laravel

To use Turso as your database driver in Laravel, append the following configuration to the connections array in your config/database.php file:

'turso' => [
    'driver'                  => 'turso',
    'db_url'                  => env('DB_URL', 'http://localhost:8080'),
    'access_token'            => env('DB_ACCESS_TOKEN'),
    'db_replica'              => env('DB_REPLICA'),
    'database'                => null, // Leave this null
    'prefix'                  => env('DB_PREFIX', ''),
    'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
    'sticky'                  => env('DB_STICKY', true),
],

Publishing Configuration and Sync Script

Publish the configuration file and sync script by running the following command:

php artisan vendor:publish --provider="RichanFongdasen\Turso\TursoLaravelServiceProvider"

The above command publishes the following files:

  • config/turso-laravel.php
  • turso-sync.mjs

The content of the config/turso-laravel.php file should look like this:

return [
    'client' => [
        'connect_timeout' => env('TURSO_CONNECT_TIMEOUT', 2),
        'timeout'         => env('TURSO_REQUEST_TIMEOUT', 5),
    ],

    'sync_command' => [
        'node_path'       => env('NODE_PATH'), // Full path to the node executable. E.g: /usr/bin/node
        'script_filename' => 'turso-sync.mjs',
        'script_path'     => realpath(__DIR__ . '/..'),
        'timeout'         => 60,
    ],
];

You may need to set the NODE_PATH environment variable to the path of your Node.js executable. This is required to run the sync script.

Installing Node.js Dependencies

The Turso database driver requires Node.js to run the sync script. Install the Node.js dependencies by running the following command:

npm install @libsql/client

Configuration

In Laravel applications, the database driver configuration is stored in your .env file. Here are the available configurations for the Turso database driver:

DB_CONNECTION=turso
DB_URL=http://localhost:8080
DB_ACCESS_TOKEN=
DB_REPLICA=
DB_PREFIX=
DB_FOREIGN_KEYS=true
DB_STICKY=true
ENV Variable Name Description
DB_URL The Turso database server URL. E.g: https://[databaseName]-[organizationName].turso.io
DB_ACCESS_TOKEN (Optional) The access token to access the Turso database server.
DB_REPLICA (Optional) The full path to the local embedded replica database file. E.g: /tmp/turso.sqlite
DB_PREFIX (Optional) The database table prefix.
DB_FOREIGN_KEYS Enable or disable foreign key constraints, default is true.
DB_STICKY Enable or disable sticky connections while performing write operations, default is true.

Usage

For local development, you can use the local Turso database server provided by the Turso team. Refer to the Turso CLI documentation for instructions on running the local Turso database server.

The Turso database driver should work as expected with Laravel's Query Builder and Eloquent ORM. Here are some examples:

use App\Models\User;
use Illuminate\Support\Facades\DB;

// Using Query Builder
$users = DB::table('users')->orderBy('name')->get();

// Using Eloquent ORM
$users = User::with('posts')->orderBy('name')->get();

Embedded Replica Support

The driver supports the embedded replica feature. If you're unfamiliar with this feature, refer to the Turso embedded replica article for more information.

Running the sync script from artisan command

Run the sync script manually using the following Artisan command:

php artisan turso:sync

You may encounter an error if the path to the replica database does not exist. This is expected when the replica database has not been created yet.

Running the sync script programmatically

Run the sync script programmatically using the following code:

use Illuminate\Support\Facades\DB;
use RichanFongdasen\Turso\Facades\Turso;

if ( DB::hasModifiedRecords() ) {
    // Run the sync script immediately
    Turso::sync();

    // Run the sync script in the background
    Turso::backgroundSync();
}

Debugging

To debug the HTTP requests and responses sent and received by the Turso database client, enable the debugging feature as follows:

Turso::enableQueryLog();

DB::table('users')->get();

// Get the query log
$logs = Turso::getQueryLog();

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

turso-laravel's People

Contributors

dependabot[bot] avatar github-actions[bot] avatar richan-fongdasen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

turso-laravel's Issues

[Bug]: Blob data storage not working

What happened?

Blob storage doesn't work:
GuzzleHttp\Exception\InvalidArgumentException: json_encode error: Malformed UTF-8 characters, possibly incorrectly encoded

How to reproduce the bug

Schema::create('blob', function (\Illuminate\Database\Schema\Blueprint $table) {
    $table->binary('blob');
});

$data = random_bytes(50);
$result = DB::table('blob')->insert([
    'blob' => $data,
]);

$newData = DB::table('blob')->first();

expect($result)->toBeTrue()
    ->and(DB::table('blob')->count())->toBe(1)
    ->and($newData->blob)->toBe($data);

Package Version

0.6

PHP Version

8.3

Laravel Version

11.0

Which operating systems does with happen with?

macOS

Notes

No response

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.