efureev/laravel-support-db

Laravel DB 的 PHP 支持包

v2.1.0 2024-07-22 14:05 UTC

README

Codacy Badge PHP Database Laravel Package Latest Stable Version Total Downloads Maintainability Test Coverage

描述

安装

composer require efureev/laravel-support-db "^2.0"

内容

扩展列类型

位字符串。 文档.

$table->bit(string $column, int $length = 1);

地理点

点是几何类型的基本二维构建块。 文档.

$table->geoPoint(string $column);

地理路径

路径由一系列连接点表示。 文档.

$table->geoPoint(string $column);

IP 网络类型

IP 网络数据类型以 CIDR 表示法存储 IP 网络。 文档.

IPv4 = 7 字节
IPv6 = 19 字节

$table->ipNetwork(string $column);

范围

范围数据类型存储具有可选起始值和结束值的值范围。例如,可以用来描述会议室预订的时间。 文档.

$table->dateRange(string $column);
$table->tsRange(string $column);
$table->timestampRange(string $column);

UUID

可以使用 primaryUUID 将 UUID 类型存储为主键。

$table->primaryUUID(); // create PK UUID-column with name `id`
$table->primaryUUID('custom_name'); // create PK UUID-column with name `custom_name`

可以使用 generateUUID 存储带有/不带索引(或外键)的 UUID 类型。

在创建行时,通过扩展 uuid-ossp 使用 uuid_generate_v4() 生成值。

// create UUID-column with name `id`. Generate UUID-value by DB.
$table->generateUUID();

// create UUID-column with name `cid`. Generate UUID-value by DB.
$table->generateUUID('cid');

// create UUID-column with name `cid`. NOT generate UUID-value by DB. Set `nullable`. Default value: `NULL`. 
$table->generateUUID('id', null);

// create UUID-column with name `cid`. NOT generate UUID-value by DB. Set `nullable`. Default value: `NULL`. Create Index by this column.
$table->generateUUID('fk_id', null)->index();

 // create UUID-column with name `fk_id`. NOT generate UUID-value by DB.
$table->generateUUID('fk_id', false);

// create UUID-column with name `fk_id`. Generate UUID-value by DB with custom value.
$table->generateUUID('fk_id', fn($column)=>'uuid_generate_v5()');

// create UUID-column with name `fk_id`. Generate UUID-value by DB with custom value.
$table->generateUUID('fk_id', new Expression('uuid_generate_v2()'));

XML

XML 数据类型可以用来存储 XML 文档。 文档.

$table->xml(string $column);

UUID 数组

UUID 数据类型数组可以用来存储 ID 数组(uuid 类型)。

$table->uuidArray(string $column);

整数数组

整数数据类型数组可以用来存储整数列表。

$table->intArray(string $column);

文本数组

文本数据类型数组可以用来存储字符串列表。

$table->textArray(string $column);

列选项

压缩

PostgreSQL 14 引入了指定可 toast 数据类型压缩方法的可能性。您可以选择默认方法 pglz、最近添加的 lz4 算法或使用 default 以使用服务器的默认设置。 文档.

$table->string('col')->compression('lz4');

视图

创建视图

// Facade methods:
Schema::createView('active_users', "SELECT * FROM users WHERE active = 1");
Schema::createView('active_users', "SELECT * FROM users WHERE active = 1", true) ;
Schema::createViewOrReplace('active_users', "SELECT * FROM users WHERE active = 1");

// Schema methods:
use \Php\Support\Laravel\Database\Schema\Postgres\Blueprint;

Schema::create('users', function (Blueprint $table) {
    $table
        ->createView('active_users', "SELECT * FROM users WHERE active = 1")
        ->materialize();
});

删除视图

// Facade methods:
Schema::dropView('active_users');
Schema::dropViewIfExists('active_users');

索引

部分索引

参见:https://postgresql.ac.cn/docs/current/indexes-partial.html

示例

use \Php\Support\Laravel\Database\Schema\Postgres\Blueprint;
Schema::create('table', static function (Blueprint $table) {
    $table->string('code'); 
    $table->softDeletes();
    $table
        ->partial('code')
        ->whereNull('deleted_at');
});

如果您想删除部分索引,请使用此方法

use \Php\Support\Laravel\Database\Schema\Postgres\Blueprint;

Schema::create('table', static function (Blueprint $table) {
    $table->dropPartial(['code']);
});

唯一部分索引

示例

use \Php\Support\Laravel\Database\Schema\Postgres\Blueprint;
Schema::create('table', static function (Blueprint $table) {
    $table->string('code'); 
    $table->softDeletes();
    $table
        ->uniquePartial('code')
        ->whereNull('deleted_at');
});

如果您想删除部分唯一索引,请使用此方法

use \Php\Support\Laravel\Database\Schema\Postgres\Blueprint;

Schema::create('table', static function (Blueprint $table) {
    $table->dropUniquePartial(['code']);
});

$table->dropUnique() 对于部分唯一索引不起作用,因为 PostgreSQL 没有定义部分(即条件)唯一约束。如果您尝试删除此类部分唯一索引,将会收到错误。

CREATE UNIQUE INDEX CONCURRENTLY examples_new_col_idx ON examples (new_col);
ALTER TABLE examples
    ADD CONSTRAINT examples_unique_constraint USING INDEX examples_new_col_idx;

当您创建一个无条件的唯一索引时,PostgreSQL 会自动为您创建唯一约束,当您尝试删除这样的索引时,约束将被首先删除,然后才是唯一索引。

扩展模式

创建与另一张表相同

从源表创建一个表。只创建结构。
includingAll 会复制源表的所有依赖关系。

创建将不包含数据。

Schema::create('target_table', function (Blueprint $table) {
    $table->like('source_table')->includingAll(); 
    $table->ifNotExists();
});

创建与另一张表相同的完整数据

从源表复制一个表。只复制列和数据。不包括索引等...

Schema::create('target_table', function (Blueprint $table) {
    $table->fromTable('source_table'); 
});

创建与另一张表相同的查询选择数据

从选择查询创建一个表。只复制列和数据。不包括索引等...

Schema::create('target_table', function (Blueprint $table) {
    $table->fromSelect('select id, name from source_table');
});

// or

Schema::create('target_table', function (Blueprint $table) {
    $table->fromSelect(
        'select t1.id, t2.enabled, t2.extra from source_table t1 ' .
        'join source_table_2 t2 on t1.id = t2.src_id ' .
        'where t2.enabled = true'
    );
});

// or

$tbl = 'source_table';
Schema::create(
    $tbl,
    static function (Blueprint $table) {
        $table->string('key', 16)->primary();
        $table->string('title');
        $table->integer('sort')->index();
    }
);

// or

Schema::create(self::TGT_TABLE, function (Blueprint $table) use ($tbl) {
    Schema::createExtensionIfNotExists('uuid-ossp');

    $table->fromSelect(
        'select uuid_generate_v4() as id, key, title, sort from ' . $tbl
    );
});

// or

Schema::create(self::TGT_TABLE, function (Blueprint $table) use ($tbl) {
    Schema::createExtensionIfNotExists('uuid-ossp');

    $table->fromSelect(
        'select uuid_generate_v4() as id, * ' . $tbl
    );
});

如果存在则级联删除

自动删除依赖于表的对象(如视图、索引、序列等),以及反过来依赖于这些对象的所有对象。

Schema::dropIfExistsCascade('table');

扩展查询构建器

更新记录并返回更新记录的列

$list = Model::toBase()->updateAndReturn(['deleted_at' => now()], 'id', 'name');
$list = Model::where(['enabled' => true])->updateAndReturn(['enabled' => false], 'id');

删除记录并返回已删除记录的列

$list = Model::toBase()->deleteAndReturn('id', 'name');
$list = Model::where(['enabled' => true])->deleteAndReturn('id');

扩展

创建扩展

Schema 门面支持使用 createExtensioncreateExtensionIfNotExists 方法创建扩展

Schema::createExtension('uuid-ossp');
Schema::createExtensionIfNotExists('uuid-ossp');

删除扩展

要删除扩展,您可以使用 Schema 门面提供的 dropExtensionIfExists 方法

Schema::dropExtensionIfExists('tablefunc');

您可以通过传递多个扩展名称一次删除多个扩展

Schema::dropExtensionIfExists('tablefunc', 'fuzzystrmatch');

用法

简单示例

<?php

use Illuminate\Support\Facades\Schema;
use Php\Support\Laravel\Database\Schema\Postgres\Blueprint;

Schema::create(
    'test_table',
    static function (Blueprint $table) {
        $table->primaryUUID();
        $table->generateUUID('id', null);
        $table->tsRange('range');
        $table->numeric('num');
        
    }
);

测试

composer test
composer test-cover # with coverage