Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 saving file to Oracle BLOB

Problem is that i can't save file to blob. It works without any error, temp file is created and i can read from it. I checked if it goes to bind - yes it goes with right resource value and with \PDO::PARAM_LOB data type.

I have an ActiveRecord class:

class News extends ActiveRecord
{
    public function rules()
    {
        return [
            [
                ['image'],
                'image',
                'extensions' => 'png jpg',
                'maxSize' => 1024 * 300,
            ]
        ];
    }

    public function beforeSave($insert)
    {
        $fileInfo = UploadedFile::getInstance($this, 'image');
        $this->image = fopen($fileInfo->tempName, 'r+');
        return parent::beforeSave($insert);
    }

}

Table:

CREATE TABLE NEWS
(
    RN NUMBER(17,0) PRIMARY KEY NOT NULL,
    IMAGE BLOB
);

Logs showing this query:

INSERT INTO "NEWS" ("IMAGE") VALUES (:qp4) RETURNING "RN" INTO :qp8

So it didn't actually bind it or what?

like image 778
UnstableFractal Avatar asked Sep 11 '15 11:09

UnstableFractal


2 Answers

You should simply use image data instead of resource pointer, e.g. :

$this->image = file_get_contents($fileInfo->tempName);

EDIT: sorry you are right, you need to provide a resource pointer to be able to bind this param using PARAM_LOB.

As stated on php doc, you should try using a transaction, e.g. :

News::getDb()->transaction(function($db) use ($model) {
    $model->save();
});
like image 138
soju Avatar answered Sep 30 '22 03:09

soju


It appears that PDO_OCI is working with Oracle in old-style way, so you need to start a transaction insert EMPTY_BLOB() first, then bind variable with pointer to file, execute statement and commit.

I've done it with update, because i don't want to make full query manually. First i write pointer to file into $this->file in save() method and call $model->save && $model->saveImage() in controller.

public function saveImage()
{
    if (!$this->file) {
        return true;
    }
    $table = self::tableName();
    $rn = $this->rn;
    $command = Yii::$app->getDb()->createCommand(
        "UPDATE $table SET IMAGE=EMPTY_BLOB() WHERE RN=:rn RETURNING IMAGE INTO :image"
    );
    $command->bindParam(':rn', $rn, \PDO::PARAM_STR);
    $command->prepare();
    $command->bindParam(':image', $this->file, \PDO::PARAM_LOB);
    return $command->execute();
}
like image 44
UnstableFractal Avatar answered Sep 30 '22 02:09

UnstableFractal