Some of our clients keep their data in Snowflake. Their analysts use it for reports, and their Laravel applications must read and write the same data. For this work, we use two packages:

  • Laravel Snowflake is a database driver. With it, the query builder, Eloquent and migrations work on Snowflake.
  • Laravel Snowflake Sync copies your Eloquent models to Snowflake tables. It writes the changes in batches.

The driver

Laravel Snowflake started as a fork of laravel-pdo-odbc by Yoram de Langen. We thank Yoram and the other contributors for this good base. We then added much more Snowflake support to it.

The driver connects in two ways:

  • With the pdo_snowflake PHP extension from Snowflake. We recommend this.
  • With the Snowflake ODBC driver.

It also works as a general ODBC driver for other data sources.

Install the driver

composer require bernskiold/laravel-snowflake

Add a connection to config/database.php:

'snowflake' => [
    'driver' => 'snowflake_native',
    'account' => '{account_name}.eu-west-1',
    'username' => env('SNOWFLAKE_USERNAME'),
    'password' => env('SNOWFLAKE_PASSWORD'),
    'database' => env('SNOWFLAKE_DATABASE'),
    'warehouse' => env('SNOWFLAKE_WAREHOUSE'),
    'schema' => 'PUBLIC',
],

The driver also supports key-pair authentication. Set authenticator to key_pair, and give the path to the private key or the key itself.

Use the query builder and Eloquent

Use the connection as you use a different database:

$books = DB::connection('snowflake')
    ->table('books')
    ->where('author', 'Abram Andrea')
    ->get();

The driver changes Laravel features into Snowflake SQL:

  • upsert() and updateOrCreate() become a MERGE INTO statement.
  • $table->json() makes a VARIANT column. The JSON helpers, such as whereJsonContains(), use the Snowflake functions for semi-structured data.
  • whereFullText() uses the Snowflake SEARCH() function.
  • The atTimestamp() and beforeStatement() macros read a table as it was at an earlier time.

To write JSON into a VARIANT column, Snowflake needs PARSE_JSON(). Use the AsVariant cast on the model, and the driver adds it for you:

use Bernskiold\LaravelSnowflake\Casts\AsVariant;

protected function casts(): array
{
    return [
        'settings' => AsVariant::class,
    ];
}

Uppercase column names

Snowflake keeps unquoted names in uppercase. Thus, a row comes back with the keys ID and NAME. Eloquent looks for id and name, and it finds nothing. Each attribute is then null, and Eloquent does not show an error.

To prevent this, set lowercase_result_keys on the connection. The names stay in uppercase in Snowflake, and PHP gets them in lowercase.

'options' => [
    'lowercase_result_keys' => true,
],

The sync package

The second package copies your models to Snowflake. Add the SyncsToSnowflake trait, and tell the trait which table and which values to write:

use Bernskiold\LaravelSnowflakeSync\Concerns\SyncsToSnowflake;

class Brand extends Model
{
    use SyncsToSnowflake;

    public function snowflakeTable(): string
    {
        return 'brands';
    }

    public function toSnowflake(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'updated_at' => $this->updated_at?->toDateTimeString(),
        ];
    }
}

Why the package writes in batches

Snowflake locks the full table for each write. If you send one job for each saved row, the jobs wait for each other. Many workers are not faster than one worker.

Thus, the package does not write on each save. When you save a model, the package adds its key to a buffer in Redis. A second save of the same row does not add a second key. Then a flush job reads the rows from your database and writes them with one MERGE for each batch. A bulk change of fifty thousand rows becomes a small number of statements.

Live or periodic

In live mode, each change starts a flush job after a short delay. All saves in that period go into one write.

In periodic mode, the package only fills the buffer. You schedule the flush command yourself:

Schedule::command('snowflake:flush')->everyFifteenMinutes();

You can also schedule this command in live mode. If a flush job is lost, the command writes its rows.

Fill a new table

Use snowflake:import to copy a full table. This command also removes the rows that were deleted outside of Eloquent.

php artisan snowflake:import "App\Models\Brand"

Limits to know

Snowflake is an analytical database. It is very good for large reads, totals and reports. It is slow for single-row reads and writes. Each query also keeps the warehouse running, and this costs money. Eager-load your relations, and write many rows in one statement.

Some other limits:

  • Snowflake does not have a lastInsertId. After an insert, insertGetId() reads the highest key. When many processes write to the same table, this value can be wrong. Use UUID keys for these tables.
  • Snowflake does not use transactions for schema changes. If a migration fails, the completed part of it stays.
  • insertOrIgnore() does not work. Use upsert().
  • For millions of rows, COPY INTO from a file is faster than MERGE. You can replace the write engine of the sync package for this.

Get the packages

Both packages are open source, with the MIT license. The code and the full documentation are on GitHub: Laravel Snowflake and Laravel Snowflake Sync. If you find a problem or have an idea, open an issue. We are happy to hear from you.