2012-04-16 98 views
9

我想獲得一個blob的字節大小。在PostgreSQL查詢中獲取大對象的大小?

我正在使用Postgresql並希望使用SQL查詢獲取大小。這樣的事情:

SELECT sizeof(field) FROM table; 

這是可能在Postgresql?

更新:我已閱讀postgresql手冊,並找不到合適的函數來計算文件大小。另外,blob被存儲爲一個大對象。

+0

請張貼這樣的問題之前閱讀手冊:http://www.postgresql.org/docs/current/static/functions.html – 2012-04-16 06:51:38

+2

定義「BLOB數據」。一個bytea列?或者存儲在'pg_largeobject'中的大對象?顯示你的表格定義。 – 2012-04-16 06:55:55

+0

的重複【獲得lobject的大小在PostgreSQL的](http://stackoverflow.com/questions/9248738/obtaining-the-size-of-lobject-in-postgressql)? – 2012-04-17 01:19:24

回答

12

這並不是說我用過大的物體,但在看文檔: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值得研究!

3

嘗試length()octet_length()

10

您可以在創建大對象時更改應用程序以存儲大小。否則,你可以使用查詢,如:

select sum(length(lo.data)) from pg_largeobject lo 
where lo.loid=XXXXXX 

您還可以使用大對象的API函數,如在以前的文章中提出,他們的工作好了,但幅度慢於選擇方法上面建議的順序。

+0

這是最乾淨的解決方案。由於 – MarekM 2016-05-14 12:03:12

+1

不幸的是,'pg_largeobject'目錄是因爲PostgreSQL的9.0不再公開訪問:https://www.postgresql.org/docs/current/static/catalog-pg-largeobject.html。 – ochedru 2017-08-11 16:52:16

4
select pg_column_size(lo_get(lo_oid)) from table; 

以字節爲單位給出您的大小。

如果你想漂亮的印刷:

select pg_size_pretty(pg_column_size(lo_get(lo_oid))::numeric) from table;