相关疑难解决方法(0)

如何避免 PostgreSQL 中的隐式类型转换?

我刚刚发现我可以将任何类型的值插入到 PostgreSQL (9.6) 类型的列中text

drop table if exists d cascade;
create table d ( a text );
insert into d values ( 42 );
insert into d values ( true );
select a, pg_typeof( a ) from d;

  a   | pg_typeof
------+-----------
 42   | text
 true | text
(2 rows)
Run Code Online (Sandbox Code Playgroud)

这是故意的功能吗?我做错了什么吗?有没有设置可以避免这种情况?这是否违反了 RDBMS 应该是类型安全的假设?

我知道这text在 PostgreSQL 中就像一个包罗万象的东西,这通常很方便,因为您可以编写任意类型的字符串表示。但是有时您肯定希望确保只有字符串被插入到给定的列中,以排除隐式转换值。

我能做些什么来避免“随意”类型转换?

postgresql datatypes type-conversion

6
推荐指数
2
解决办法
6161
查看次数

IS NULL 上的 Postgres 部分索引不起作用

Postgres 版本

使用 PostgreSQL 10.3。

表定义

CREATE TABLE tickets (
  id bigserial primary key,
  state character varying,
  closed timestamp
);

CREATE INDEX  "state_index" ON "tickets" ("state")
  WHERE ((state)::text = 'open'::text));
Run Code Online (Sandbox Code Playgroud)

基数

该表包含 1027616 行,其中 51533 行具有state = 'open'closed IS NULL或 5%。

条件为 on 的查询state按预期使用索引扫描执行良好:

explain analyze select * from tickets where state = 'open';

Index Scan using state_index on tickets  (cost=0.29..16093.57 rows=36599 width=212) (actual time=0.025..22.875 rows=37346 loops=1)
Planning time: 0.212 ms
Execution time: 25.697 …
Run Code Online (Sandbox Code Playgroud)

postgresql performance index postgresql-10 postgresql-performance

3
推荐指数
1
解决办法
3231
查看次数