4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

一度しか実行できないPL/pgSQL関数

Last updated at Posted at 2019-04-21

はじめに

1回しか実行できないSQL関数なんてものがあると面白いかな、と思ってPL/pgSQL関数を作って試してみた。

検証環境

PostgreSQL 12-develで確認。

定義

例えば、以下のようなsuicide()というPL/pgSQL関数をCREATE FUNCTIONを使って作成してみる。

testdb=# CREATE OR REPLACE FUNCTION suicide( )
 RETURNS INTEGER
 LANGUAGE plpgsql

AS $function$
DECLARE
  sql TEXT;
BEGIN
  --
  -- なにか処理を書く
  --
  sql := 'DROP FUNCTION suicide()';
  EXECUTE sql;
  RETURN 0;
END
$function$

;
CREATE FUNCTION
testdb=#

実行してみる

まず、さきほど作成したSQL関数が存在するか\dメタコマンドで確認してみる。

testdb=# \df
                        List of functions
 Schema |  Name   | Result data type | Argument data types | Type
--------+---------+------------------+---------------------+------
 public | suicide | integer          |                     | func
(1 row)

testdb=#

SELECT文を使って、sucide()を実行する。

testdb=# SELECT suicide();
 suicide
---------
       0
(1 row)

testdb=#

とくに何もエラーにもならず、関数は実行された。

再び、\dfメタコマンドで確認する。

testdb=# \df
                       List of functions
 Schema | Name | Result data type | Argument data types | Type
--------+------+------------------+---------------------+------
(0 rows)

testdb=#

suicide()関数は消えてしまった。消えてしまったので、再度実行しようとしてもエラーになる。

testdb=# SELECT suicide();
psql: ERROR:  function suicide() does not exist
LINE 1: SELECT suicide();
               ^
HINT:  No function matches the given name and argument types. You might need to add explicit type casts.
testdb=#

おわりに

一度しか実行できない、SQL関数ができた。
これが何の役に立つのかは、作った自分にもわからない。

つか、実行中の関数だから削除できないと思ったのに・・・

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?