php / php-src

The PHP Interpreter
https://www.php.net
Other
37.91k stars 7.72k forks source link

Binary type for PDO #11462

Open NattyNarwhal opened 1 year ago

NattyNarwhal commented 1 year ago

Description

As part of supporting multiple users, I've found that they have difficulty with dealing with binary columns with PDO drivers.

Notably, these aren't necessarily LOBs - they can be (relatively) small, users don't (want to) deal with them in terms of streams on the PHP side (as PHP strings can represent binary data just fine), etc. Treating them as strings isn't right, because they can be subject to unwanted and inappropriate encoding conversions or an inefficient representation over the wire.

Proposal

Extend the PDO constants to have a PARAM_BINARY binding type, and use it in drivers. For things like ODBC (where I'm most familiar), this would map to an SQL_C_BINARY binding type, with the equivalent in other drivers when possible.

User code could look something like:

<?php

$SQL1 = "select id, my_blob from calvin.blob_stream";

$connstring = 'odbc:*LOCAL';
$dbconn = new PDO($connstring);
$stmt = $dbconn->prepare($SQL1);
$stmt->execute();
$lob = "";
$stmt->bindColumn(2, $lob, PDO::PARAM_BINARY);
$stmt->fetch(PDO::FETCH_BOUND);

echo "PDO: $lob\n";

Basically looks like using PARAM_STR, and would maintain a string interface unlike PARAM_LOB.

Possible problems/alternatives

I'm not committed to the proposed interface; I just know there is a problem dealing with binaries. If there's another way to solve this, I'd like to hear it.

acerbis commented 1 year ago

This feature is extremely important. I've seen this behaviour in production, where I just wanted to fetch a BLOB on and IBMi via PDO/ODBC and an hex string was returned (sometimes even with a weird truncation behaviour). Resorted to using straight ODBC interface to more idiomatically fetch the binary.