SQLAnywhereStatement.php 10.1 KB
Newer Older
1 2 3 4
<?php

namespace Doctrine\DBAL\Driver\SQLAnywhere;

5
use Doctrine\DBAL\Driver\Statement;
6
use Doctrine\DBAL\Driver\StatementIterator;
7 8
use Doctrine\DBAL\FetchMode;
use Doctrine\DBAL\ParameterType;
9
use IteratorAggregate;
10 11 12 13
use PDO;
use ReflectionClass;
use ReflectionObject;
use stdClass;
14

15
use function array_key_exists;
16
use function assert;
17 18 19 20
use function func_get_args;
use function func_num_args;
use function gettype;
use function is_array;
Sergei Morozov's avatar
Sergei Morozov committed
21
use function is_int;
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
use function is_object;
use function is_resource;
use function is_string;
use function sasql_fetch_array;
use function sasql_fetch_assoc;
use function sasql_fetch_object;
use function sasql_fetch_row;
use function sasql_prepare;
use function sasql_stmt_affected_rows;
use function sasql_stmt_bind_param_ex;
use function sasql_stmt_errno;
use function sasql_stmt_error;
use function sasql_stmt_execute;
use function sasql_stmt_field_count;
use function sasql_stmt_reset;
use function sasql_stmt_result_metadata;
use function sprintf;
39

Grégoire Paris's avatar
Grégoire Paris committed
40
use const SASQL_BOTH;
41 42 43 44 45 46

/**
 * SAP SQL Anywhere implementation of the Statement interface.
 */
class SQLAnywhereStatement implements IteratorAggregate, Statement
{
47
    /** @var resource The connection resource. */
48
    private $conn;
Steve Müller's avatar
Steve Müller committed
49

50
    /** @var string Name of the default class to instantiate when fetching class instances. */
51
    private $defaultFetchClass = '\stdClass';
Steve Müller's avatar
Steve Müller committed
52

53
    /** @var mixed[] Constructor arguments for the default class to instantiate when fetching class instances. */
54
    private $defaultFetchClassCtorArgs = [];
Steve Müller's avatar
Steve Müller committed
55

56
    /** @var int Default fetch mode to use. */
57
    private $defaultFetchMode = FetchMode::MIXED;
Steve Müller's avatar
Steve Müller committed
58

59
    /** @var resource The result set resource to fetch. */
60
    private $result;
Steve Müller's avatar
Steve Müller committed
61

62
    /** @var resource The prepared SQL statement to execute. */
63 64
    private $stmt;

65 66 67
    /** @var mixed[] The references to bound parameter values. */
    private $boundValues = [];

68 69 70 71 72 73 74 75 76 77
    /**
     * Prepares given statement for given connection.
     *
     * @param resource $conn The connection resource to use.
     * @param string   $sql  The SQL statement to prepare.
     *
     * @throws SQLAnywhereException
     */
    public function __construct($conn, $sql)
    {
78
        if (! is_resource($conn)) {
79 80 81 82 83 84
            throw new SQLAnywhereException('Invalid SQL Anywhere connection resource: ' . $conn);
        }

        $this->conn = $conn;
        $this->stmt = sasql_prepare($conn, $sql);

85
        if (! is_resource($this->stmt)) {
86 87 88 89 90 91 92 93 94
            throw SQLAnywhereException::fromSQLAnywhereError($conn);
        }
    }

    /**
     * {@inheritdoc}
     *
     * @throws SQLAnywhereException
     */
95
    public function bindParam($param, &$variable, $type = ParameterType::STRING, $length = null)
96
    {
97
        assert(is_int($param));
98

99
        switch ($type) {
100 101
            case ParameterType::INTEGER:
            case ParameterType::BOOLEAN:
102 103
                $type = 'i';
                break;
104 105

            case ParameterType::LARGE_OBJECT:
106 107
                $type = 'b';
                break;
108 109 110

            case ParameterType::NULL:
            case ParameterType::STRING:
111
            case ParameterType::BINARY:
112 113
                $type = 's';
                break;
114

115 116 117 118
            default:
                throw new SQLAnywhereException('Unknown type: ' . $type);
        }

119
        $this->boundValues[$param] =& $variable;
120

121
        if (! sasql_stmt_bind_param_ex($this->stmt, $param - 1, $variable, $type, $variable === null)) {
122 123 124 125 126 127 128 129 130
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
131
    public function bindValue($param, $value, $type = ParameterType::STRING)
132
    {
133 134
        assert(is_int($param));

135 136 137 138 139 140 141 142 143 144
        return $this->bindParam($param, $value, $type);
    }

    /**
     * {@inheritdoc}
     *
     * @throws SQLAnywhereException
     */
    public function closeCursor()
    {
145
        if (! sasql_stmt_reset($this->stmt)) {
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
        }

        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function columnCount()
    {
        return sasql_stmt_field_count($this->stmt);
    }

    /**
     * {@inheritdoc}
     */
    public function errorCode()
    {
        return sasql_stmt_errno($this->stmt);
    }

    /**
     * {@inheritdoc}
     */
    public function errorInfo()
    {
        return sasql_stmt_error($this->stmt);
    }

    /**
     * {@inheritdoc}
     *
     * @throws SQLAnywhereException
     */
    public function execute($params = null)
    {
Steve Müller's avatar
Steve Müller committed
183
        if (is_array($params)) {
184
            $hasZeroIndex = array_key_exists(0, $params);
Steve Müller's avatar
Steve Müller committed
185

186
            foreach ($params as $key => $val) {
Sergei Morozov's avatar
Sergei Morozov committed
187 188 189 190 191
                if ($hasZeroIndex && is_int($key)) {
                    $this->bindValue($key + 1, $val);
                } else {
                    $this->bindValue($key, $val);
                }
192 193 194
            }
        }

195
        if (! sasql_stmt_execute($this->stmt)) {
196 197 198 199 200 201 202 203 204 205 206 207 208
            throw SQLAnywhereException::fromSQLAnywhereError($this->conn, $this->stmt);
        }

        $this->result = sasql_stmt_result_metadata($this->stmt);

        return true;
    }

    /**
     * {@inheritdoc}
     *
     * @throws SQLAnywhereException
     */
209
    public function fetch($fetchMode = null, $cursorOrientation = PDO::FETCH_ORI_NEXT, $cursorOffset = 0)
210
    {
211
        if (! is_resource($this->result)) {
212 213 214 215 216 217
            return false;
        }

        $fetchMode = $fetchMode ?: $this->defaultFetchMode;

        switch ($fetchMode) {
218
            case FetchMode::COLUMN:
219 220
                return $this->fetchColumn();

221
            case FetchMode::ASSOCIATIVE:
222
                return sasql_fetch_assoc($this->result);
223 224

            case FetchMode::MIXED:
225
                return sasql_fetch_array($this->result, SASQL_BOTH);
226 227

            case FetchMode::CUSTOM_OBJECT:
228
                $className = $this->defaultFetchClass;
Steve Müller's avatar
Steve Müller committed
229
                $ctorArgs  = $this->defaultFetchClassCtorArgs;
230 231

                if (func_num_args() >= 2) {
Steve Müller's avatar
Steve Müller committed
232
                    $args      = func_get_args();
233
                    $className = $args[1];
234
                    $ctorArgs  = $args[2] ?? [];
235 236 237 238
                }

                $result = sasql_fetch_object($this->result);

239
                if ($result instanceof stdClass) {
240 241 242 243
                    $result = $this->castObject($result, $className, $ctorArgs);
                }

                return $result;
244 245

            case FetchMode::NUMERIC:
246
                return sasql_fetch_row($this->result);
247 248

            case FetchMode::STANDARD_OBJECT:
249
                return sasql_fetch_object($this->result);
250

251 252 253 254 255 256 257 258
            default:
                throw new SQLAnywhereException('Fetch mode is not supported: ' . $fetchMode);
        }
    }

    /**
     * {@inheritdoc}
     */
259
    public function fetchAll($fetchMode = null, $fetchArgument = null, $ctorArgs = null)
260
    {
261
        $rows = [];
262 263

        switch ($fetchMode) {
264
            case FetchMode::CUSTOM_OBJECT:
265
                while (($row = $this->fetch(...func_get_args())) !== false) {
266 267
                    $rows[] = $row;
                }
Grégoire Paris's avatar
Grégoire Paris committed
268

269
                break;
270 271

            case FetchMode::COLUMN:
272
                while (($row = $this->fetchColumn()) !== false) {
273 274
                    $rows[] = $row;
                }
Grégoire Paris's avatar
Grégoire Paris committed
275

276
                break;
277

278
            default:
279
                while (($row = $this->fetch($fetchMode)) !== false) {
280 281 282 283 284 285 286 287 288 289 290 291
                    $rows[] = $row;
                }
        }

        return $rows;
    }

    /**
     * {@inheritdoc}
     */
    public function fetchColumn($columnIndex = 0)
    {
292
        $row = $this->fetch(FetchMode::NUMERIC);
293

294
        if ($row === false) {
295
            return false;
296 297
        }

298
        return $row[$columnIndex] ?? null;
299 300 301 302 303 304 305
    }

    /**
     * {@inheritdoc}
     */
    public function getIterator()
    {
306
        return new StatementIterator($this);
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    }

    /**
     * {@inheritdoc}
     */
    public function rowCount()
    {
        return sasql_stmt_affected_rows($this->stmt);
    }

    /**
     * {@inheritdoc}
     */
    public function setFetchMode($fetchMode, $arg2 = null, $arg3 = null)
    {
Steve Müller's avatar
Steve Müller committed
322
        $this->defaultFetchMode          = $fetchMode;
323
        $this->defaultFetchClass         = $arg2 ?: $this->defaultFetchClass;
324
        $this->defaultFetchClassCtorArgs = $arg3 ? (array) $arg3 : $this->defaultFetchClassCtorArgs;
325 326

        return true;
327 328 329 330 331
    }

    /**
     * Casts a stdClass object to the given class name mapping its' properties.
     *
332
     * @param stdClass      $sourceObject     Object to cast from.
333
     * @param string|object $destinationClass Name of the class or class instance to cast to.
334
     * @param mixed[]       $ctorArgs         Arguments to use for constructing the destination class instance.
335 336 337 338 339
     *
     * @return object
     *
     * @throws SQLAnywhereException
     */
340
    private function castObject(stdClass $sourceObject, $destinationClass, array $ctorArgs = [])
341
    {
342 343
        if (! is_string($destinationClass)) {
            if (! is_object($destinationClass)) {
344
                throw new SQLAnywhereException(sprintf(
345 346
                    'Destination class has to be of type string or object, %s given.',
                    gettype($destinationClass)
347 348 349
                ));
            }
        } else {
350
            $destinationClass = new ReflectionClass($destinationClass);
351 352 353
            $destinationClass = $destinationClass->newInstanceArgs($ctorArgs);
        }

354 355
        $sourceReflection           = new ReflectionObject($sourceObject);
        $destinationClassReflection = new ReflectionObject($destinationClass);
356 357 358

        foreach ($sourceReflection->getProperties() as $sourceProperty) {
            $sourceProperty->setAccessible(true);
Steve Müller's avatar
Steve Müller committed
359 360

            $name  = $sourceProperty->getName();
361 362 363 364
            $value = $sourceProperty->getValue($sourceObject);

            if ($destinationClassReflection->hasProperty($name)) {
                $destinationProperty = $destinationClassReflection->getProperty($name);
Steve Müller's avatar
Steve Müller committed
365

366 367 368 369 370 371 372 373 374 375
                $destinationProperty->setAccessible(true);
                $destinationProperty->setValue($destinationClass, $value);
            } else {
                $destinationClass->$name = $value;
            }
        }

        return $destinationClass;
    }
}