メインコンテンツへスキップ
見出し画像

Tsurugi DBでgRPCを使う

    DBからサーバにアクセスできるのは当たり前ですが(LAMP環境はMySQL<->Apache)そういう重い感じではなくて、関数定義で操作したいと思う方いますよね

    TsurugiからgRPC使えます。はい

    では一先ずgRPCフレームワークのおさらいです。

    用意する物

    Protocol Buffers (hello.proto)

    syntax = "proto3";
    package hello;
    service Greeter {
    rpc SayHello(HelloRequest) returns (HelloReply);
    }
    message HelloRequest {
    string name = 1;
    }
    message HelloReply {
    string message = 1;
    }

    Pythonサーバ(server.py)

    from concurrent import futures
    import grpc
    
    import hello_pb2
    import hello_pb2_grpc
    
    
    class Greeter(hello_pb2_grpc.GreeterServicer):
        def SayHello(self, request, context):
            return hello_pb2.HelloReply(message=f"Hello, {request.name}!")
    
    
    def serve():
        server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
        hello_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
        server.add_insecure_port("[::]:50051")
        server.start()
        print("gRPC server started on port 50051")
        server.wait_for_termination()
    
    
    if __name__ == "__main__":
        serve()

    Pythonクライアント(client.py)

    import grpc
    
    import hello_pb2
    import hello_pb2_grpc
    
    
    def run():
        with grpc.insecure_channel("localhost:50051") as channel:
            stub = hello_pb2_grpc.GreeterStub(channel)
            response = stub.SayHello(hello_pb2.HelloRequest(name="World"))
            print("Response:", response.message)
    
    
    if __name__ == "__main__":
        run()

    まずhello.protoからhello_pb2.pyとhello_pb2_grpc.pyを作ります

    pip install grpcio grpcio-tools
    python3 -m grpc_tools.protoc \
      -I. \
      --python_out=. \
      --grpc_python_out=. \
      hello.proto

    その後serverを起動

    python3 server.py
    gRPC server started on port 50051

    でclient.pyを起動させると

    python3 client.py
    Response: Hello, World!

    serverから返事が返ってきます。

    じゃあ何か?Tsurugiのシステムを使うと以下のSQL関数が返事を返す?

    drop table if exists t_char;
    create table t_char (v char(30));
    insert into t_char values ('World');
    select sayhello(v) from t_char;

    はい。"Response: Hello, World!"を返します。

    gRPCサーバに接続するために1.8.0でリリースされたTsurugi UDFを使います

    読めばわかる、、、けどガチに読む人は既にTsurugi使っている人なんで全くの初心者にもわかるようにどういう機能か?というのを説明します。

    Tsurugi内部でselect sayhello(v) from t_char;を記述したらとしたら内部で定義されたsayhello関数を呼び出すんだろうなと推測しますよね?それは正しいです

    でも、当然ですがTsurugi内部でsayhello関数は無いので失敗してしまいます。

    じゃあ予めsayhelloのルーチンを作ってTsurugiに渡しておけばできるんじゃね?という発想しますよね?それがTsurugi UDF機能です。

    Tsurugi が読めるようにhello.protoをベースにTsurugi用のデータに変換するツールの出番です。それがudf-plugin-builderです。

    どうすれば使えるのか?下のコマンドで使えます

     git clone https://github.com/project-tsurugi/tsurugi-udf.git
    
    cd tsurugi-udf/udf-plugin
    
    pip install .

    入れたら、下記コマンドを入力してください

    udf-plugin-builder --proto-file hello.proto

    libhello.soとlibhello.iniが生成されます。生成されましたがこのままではTsurugiはそれがどこにあるのかわかりません。

    教えるためにtsurugi.ini(構成ファイル)に生成されたフォルダのPathを記述しなければなりません。

    tsurugi.iniについて

    Tsurugiがlibhello.soとlibhello.iniを調べる場所は、udf sectionのplugin_directoryです

    具体的な記述は

    [udf]
        plugin_directory=/home/sample/grpc
        endpoint=localhost:50051
        secure=false

    上の設定をした後Tsurugiを起動すると

    drop table if exists t_char;
    create table t_char (v char(30));
    insert into t_char values ('World');
    select sayhello(v) from t_char;

    "Response: Hello, World!"が帰ってきます。

    Pythonサーバを工夫してLLMに接続したりするとAIとSQLの融合もできますよー

    あなたへのおすすめ