ydb-platform / ydb-platform/ydb-php-sdk

Невозможно использовать null в параметрах подготовленного запроса

Open
#17 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
PHP
Stars
39
Forks
19
Avg merge
1d 15h
Merged PRs (30d)
2

Description

Есть таблица в YDB:
CREATE TABLE sensors (id Uint32,
device String,
name Utf8,
description Utf8,
PRIMARY KEY (id));

Ниже код облачной функции, которая вставляет очередную запись в эту таблицу, используя значения параметров в виде JSON объекта с полями "device", "name" и "description", ключевое поле же имитируется автоинкрементальным.
Если параметр передается как null, то возникает ошибка. Т.е. обработка значения null в массиве параметров неверна!

Вариант входных значений:
{
"device": "123456",
"name": "name1",
"description": null
}

Ошибка:
"YDB Table ExecuteDataQuery (400010 BAD_REQUEST): Failed to parse query parameters.:"

<?php
use YandexCloud\Ydb\Ydb;

function handler($event, $context) {
    try {
        $config = [
            // Database path
            'database' => '/ru-central1/******',
            // Database endpoint
            'endpoint'=> 'ydb.serverless.yandexcloud.net:2135',
            // Auto discovery (dedicated server only)
            'discovery' => false,
            // IAM config
            'iam_config' => [
                'use_metadata' => true
            ],
        ];
        $ydb = new Ydb($config);
        $session = $ydb->table()->session();
        if (isset($event['device']) && isset($event['name'])) {
            $query = $session->prepare('DECLARE $device AS String;
                DECLARE $name AS Utf8;
                DECLARE $description AS Utf8;
                INSERT INTO `sensors` (`id`, `device`, `name`, `description`)
                SELECT CAST(COALESCE(MAX(`id`), 0) + 1 AS Uint32), $device, $name, $description
                FROM `sensors`;');
            $params = [
                'device' => $event['device'],
                'name' => $event['name'],
                'description' => $event['description']
            ];
            $result = $session->transaction(function($session) use ($query, $params) {
                return $query->execute($params);
            });
            $code = 200;
            $body = 'OK';
        } else {
            $code = 400;
            $body = 'Missing parameters!';
        }
    } catch (Exception $e) {
        $code = 500;
        $body = $e->getMessage();
    }

    return [
        "statusCode" => $code,
        "body" => $body,
    ];
}

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the PHP example's prepared query and $query->execute($params) call, then trace how the declared Utf8 $description value is converted when the input is null. Reproduce the shown request against the YDB table and inspect the parameter-handling entry point. Done means a null description is accepted without the BAD_REQUEST parse error and non-null values still work.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
database
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
55/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.