gpt4 book ai didi

sql - 在 PostgreSQL 查询中获取大对象的大小?

转载 作者:行者123 更新时间:2023-11-29 11:12:45 26 4
gpt4 key购买 nike

我想获取一个 blob 的字节大小。

我正在使用 Postgresql 并希望使用 SQL 查询获取大小。像这样:

SELECT sizeof(field) FROM table;

这在 Postgresql 中可能吗?

更新:我已阅读 postgresql 手册,但找不到合适的函数来计算文件大小。此外,blob 存储为一个大对象。

最佳答案

不是说我用过大对象,而是看文档:http://www.postgresql.org/docs/current/interactive/lo-interfaces.html#LO-TELL

我认为您必须使用与某些文件系统 API 所要求的技术相同的技术:查找到末尾,然后告诉位置。 PostgreSQL 具有似乎包装内部 C 函数的 SQL 函数。我找不到太多文档,但这很有效:

CREATE OR REPLACE FUNCTION get_lo_size(oid) RETURNS bigint
VOLATILE STRICT
LANGUAGE 'plpgsql'
AS $$
DECLARE
fd integer;
sz bigint;
BEGIN
-- Open the LO; N.B. it needs to be in a transaction otherwise it will close immediately.
-- Luckily a function invocation makes its own transaction if necessary.
-- The mode x'40000'::int corresponds to the PostgreSQL LO mode INV_READ = 0x40000.
fd := lo_open($1, x'40000'::int);
-- Seek to the end. 2 = SEEK_END.
PERFORM lo_lseek(fd, 0, 2);
-- Fetch the current file position; since we're at the end, this is the size.
sz := lo_tell(fd);
-- Remember to close it, since the function may be called as part of a larger transaction.
PERFORM lo_close(fd);
-- Return the size.
RETURN sz;
END;
$$;

测试它:

-- Make a new LO, returns an OID e.g. 1234567
SELECT lo_create(0);

-- Populate it with data somehow
...

-- Get the length.
SELECT get_lo_size(1234567);

看起来 LO 功能主要设计为通过客户端或通过低级服务器编程使用,但至少他们为它提供了一些 SQL 可见函数,这使得上述成为可能。我查询了 SELECT relname FROM pg_proc where relname LIKE 'lo%' 让我自己开始。 C 编程的模糊内存以及对模式 x'40000'::intSEEK_END = 2 值的一些研究是其余部分所需要的!

关于sql - 在 PostgreSQL 查询中获取大对象的大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10169309/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com