intaro/custom-index-bundle

控制实体自定义索引的注解和命令

安装次数: 475,358

依赖项: 0

建议者: 0

安全性: 0

星标: 27

关注者: 14

分支: 15

开放问题: 1

类型:symfony-bundle

v1.0.3 2024-09-20 14:54 UTC

README

CustomIndexBundle 允许使用实体定义中的属性和命令行创建 doctrine 实体的索引。

安装

CustomIndexBundle 需要 Symfony 5 或更高版本。仅适用于 PostgreSQL。

在您的项目目录中运行

$ composer require intaro/custom-index-bundle

config/bundles.php 中注册该捆绑包

<?php

return [
   ...
    Intaro\CustomIndexBundle\IntaroCustomIndexBundle::class => ['all' => true],
];

如果您的项目在单个数据库中拥有多个模式,并且命令必须只为一个模式生成自定义索引,则请将以下内容添加到您的 config.yml

intaro_custom_index:
    search_in_all_schemas: false
    allowed_index_types: ['gin', 'gist', 'btree', 'hash']

search_in_all_schemas 的默认值为 true。如果您在不同模式中拥有不同的实体,并且需要一次性更新所有模式中的自定义索引,则必须将 search_in_all_schemas 设置为 true 或省略此配置。如果您的数据库只有公共模式,则 search_in_all_schemas 的值无关紧要。

allowed_index_types 参数有助于排除某些索引类型。如果有人尝试使用排除的类型,命令 intaro:doctrine:index:update 将返回错误。
默认值为 ['gin', 'gist', 'btree', 'hash']

用法

  1. 在您的实体中添加属性
<?php

namespace Acme\MyBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Intaro\CustomIndexBundle\Metadata\Attribute\CustomIndex;

#[ORM\Table(name:'my_entity')]
#[ORM\Entity]
#[CustomIndex(columns: ['my_property1'])]
#[CustomIndex(columns: ['lower(my_property1)', 'lower(my_property2)'])]
class MyEntity
{
    #[ORM\Column(type:'string', length: 256)]
    private $myProperty1;
    #[ORM\Column(type:'string', length: 256)]
    private $myProperty2;
}

可用的 CustomIndex 属性

  • columns - 表列的数组
  • name - 索引名称(默认 = 'i_cindex_<所有 CustomIndex 属性的 MD5 哈希>')。
  • unique - 索引是唯一的(默认 = false)。
  • using - 对应于 PostgreSQL CREATE INDEX 命令中的 USING 指令。
  • where - 对应于 PostgreSQL CREATE INDEX 命令中的 WHERE 指令。

仅需要 columns 属性。

  1. 使用 intaro:doctrine:index:update 命令来更新数据库。
php app/console intaro:doctrine:index:update

您可以使用 dump-sql 参数以包含 DROP/CREATE INDEX 命令的方式转储 SQL。

php app/console intaro:doctrine:index:update --dump-sql

示例

使用 pg_trgm 扩展创建索引

<?php

#[CustomIndex(columns: ['lower(my_column) gist_trgm_ops'], using: 'gist')]

使用 PostgreSQL 函数创建唯一索引

<?php

#[CustomIndex(columns: ['lower(my_column1)', 'nullif(true, not my_column2 isnull)'], unique: true)]

创建部分索引

<?php

#[CustomIndex(columns: ['site_id'], where: 'product_id IS NULL')]