db-dao.md 12 KB
Newer Older
1 2 3
Database basics
===============

4
> Note: This section is under development.
Qiang Xue committed
5

6
Yii has a database access layer built on top of PHP's [PDO](http://www.php.net/manual/en/book.pdo.php). It provides
7 8 9
uniform API and solves some inconsistencies between different DBMS. By default Yii supports the following DBMS:

- [MySQL](http://www.mysql.com/)
10
- [MariaDB](https://mariadb.com/)
11 12
- [SQLite](http://sqlite.org/)
- [PostgreSQL](http://www.postgresql.org/)
Qiang Xue committed
13
- [CUBRID](http://www.cubrid.org/): version 9.1.0 or higher.
14
- [Oracle](http://www.oracle.com/us/products/database/overview/index.html)
Qiang Xue committed
15 16
- [MSSQL](https://www.microsoft.com/en-us/sqlserver/default.aspx): version 2012 or above is required if you
  want to use LIMIT/OFFSET.
17

18

19 20 21 22 23 24 25
Configuration
-------------

In order to start using database you need to configure database connection component first by adding `db` component
to application configuration (for "basic" web application it's `config/web.php`) like the following:

```php
Alexander Makarov committed
26
return [
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
    // ...
    'components' => [
        // ...
        'db' => [
            'class' => 'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=mydatabase', // MySQL, MariaDB
            //'dsn' => 'sqlite:/path/to/database/file', // SQLite
            //'dsn' => 'pgsql:host=localhost;port=5432;dbname=mydatabase', // PostgreSQL
            //'dsn' => 'cubrid:dbname=demodb;host=localhost;port=33000', // CUBRID
            //'dsn' => 'sqlsrv:Server=localhost;Database=mydatabase', // MS SQL Server, sqlsrv driver
            //'dsn' => 'dblib:host=localhost;dbname=mydatabase', // MS SQL Server, dblib driver
            //'dsn' => 'mssql:host=localhost;dbname=mydatabase', // MS SQL Server, mssql driver
            //'dsn' => 'oci:dbname=//localhost:1521/mydatabase', // Oracle
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8',
        ],
    ],
    // ...
Alexander Makarov committed
46
];
47
```
48

49 50 51 52 53 54
There is a peculiarity when you want to work with the database through the `ODBC` layer. When using `ODBC`,
connection `DSN` doesn't indicate uniquely what database type is being used. That's why you have to override
`driverName` property of [[yii\db\Connection]] class to disambiguate that:

```php
'db' => [
55 56 57 58 59
    'class' => 'yii\db\Connection',
    'driverName' => 'mysql',
    'dsn' => 'odbc:Driver={MySQL};Server=localhost;Database=test',
    'username' => 'root',
    'password' => '',
60 61 62
],
```

63 64
Please refer to the [PHP manual](http://www.php.net/manual/en/function.PDO-construct.php) for more details
on the format of the DSN string.
65

66
After the connection component is configured you can access it using the following syntax:
67 68 69 70 71

```php
$connection = \Yii::$app->db;
```

72
You can refer to [[yii\db\Connection]] for a list of properties you can configure. Also note that you can define more
73
than one connection component and use both at the same time if needed:
74 75 76 77 78 79

```php
$primaryConnection = \Yii::$app->db;
$secondaryConnection = \Yii::$app->secondDb;
```

80
If you don't want to define the connection as an application component you can instantiate it directly:
81 82

```php
Alexander Makarov committed
83
$connection = new \yii\db\Connection([
84 85 86
    'dsn' => $dsn,
     'username' => $username,
     'password' => $password,
Alexander Makarov committed
87
]);
88 89 90
$connection->open();
```

91

92 93 94 95 96
> **Tip**: if you need to execute additional SQL queries right after establishing a connection you can add the
> following to your application configuration file:
>
```php
return [
97 98 99 100 101 102 103 104 105 106 107 108
    // ...
    'components' => [
        // ...
        'db' => [
            'class' => 'yii\db\Connection',
            // ...
            'on afterOpen' => function($event) {
                $event->sender->createCommand("SET time_zone = 'UTC'")->execute();
            }
        ],
    ],
    // ...
109 110 111
];
```

112 113 114
Basic SQL queries
-----------------

115
Once you have a connection instance you can execute SQL queries using [[yii\db\Command]].
116 117 118 119 120 121

### SELECT

When query returns a set of rows:

```php
122
$command = $connection->createCommand('SELECT * FROM post');
123 124 125 126 127 128
$posts = $command->queryAll();
```

When only a single row is returned:

```php
129
$command = $connection->createCommand('SELECT * FROM post WHERE id=1');
130
$post = $command->queryOne();
131 132 133 134 135
```

When there are multiple values from the same column:

```php
136
$command = $connection->createCommand('SELECT title FROM post');
137 138 139 140 141 142
$titles = $command->queryColumn();
```

When there's a scalar value:

```php
143
$command = $connection->createCommand('SELECT COUNT(*) FROM post');
144 145 146 147 148 149 150 151
$postCount = $command->queryScalar();
```

### UPDATE, INSERT, DELETE etc.

If SQL executed doesn't return any data you can use command's `execute` method:

```php
152
$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
153 154 155
$command->execute();
```

156
Alternatively the following syntax that takes care of proper table and column names quoting is possible:
157 158 159

```php
// INSERT
160
$connection->createCommand()->insert('user', [
161 162
    'name' => 'Sam',
    'age' => 30,
Alexander Makarov committed
163
])->execute();
164 165

// INSERT multiple rows at once
166
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
167 168 169
    ['Tom', 30],
    ['Jane', 20],
    ['Linda', 25],
Alexander Makarov committed
170
])->execute();
171 172

// UPDATE
173
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
174 175

// DELETE
176
$connection->createCommand()->delete('user', 'status = 0')->execute();
177 178
```

179 180 181
Quoting table and column names
------------------------------

182
Most of the time you would use the following syntax for quoting table and column names:
183 184

```php
Alexander Makarov committed
185
$sql = "SELECT COUNT([[$column]]) FROM {{table}}";
186 187 188
$rowCount = $connection->createCommand($sql)->queryScalar();
```

189
In the code above `[[X]]` will be converted to properly quoted column name while `{{Y}}` will be converted to properly
190 191
quoted table name.

192 193 194
For table names there's a special variant `{{%Y}}` that allows you to automatically appending table prefix if it is set:

```php
Alexander Makarov committed
195
$sql = "SELECT COUNT([[$column]]) FROM {{%table}}";
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
$rowCount = $connection->createCommand($sql)->queryScalar();
```

The code above will result in selecting from `tbl_table` if you have table prefix configured like the following in your
config file:

```php
return [
    // ...
    'components' => [
        // ...
        'db' => [
            // ...
            'tablePrefix' => 'tbl_',
        ],
    ],
];
```

215 216
The alternative is to quote table and column names manually using [[yii\db\Connection::quoteTableName()]] and
[[yii\db\Connection::quoteColumnName()]]:
217 218 219 220 221 222 223

```php
$column = $connection->quoteColumnName($column);
$table = $connection->quoteTableName($table);
$sql = "SELECT COUNT($column) FROM $table";
$rowCount = $connection->createCommand($sql)->queryScalar();
```
224 225 226 227 228 229 230

Prepared statements
-------------------

In order to securely pass query parameters you can use prepared statements:

```php
231
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
232 233 234 235 236 237 238
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
```

Another usage is performing a query multiple times while preparing it only once:

```php
239
$command = $connection->createCommand('DELETE FROM post WHERE id=:id');
240 241 242 243 244 245 246 247 248 249 250 251
$command->bindParam(':id', $id);

$id = 1;
$command->execute();

$id = 2;
$command->execute();
```

Transactions
------------

252 253 254 255 256
When running multiple related queries in a sequence you may need to wrap them in a transaction to
ensure you data is consistent. Yii provides a simple interface to work with transactions in simple
cases but also for advanced usage when you need to define isolation levels.

The following code shows a simple pattern that all code that uses transactional queries should follow:
257 258 259 260

```php
$transaction = $connection->beginTransaction();
try {
261
    $connection->createCommand($sql1)->execute();
262
    $connection->createCommand($sql2)->execute();
263 264
    // ... executing other SQL statements ...
    $transaction->commit();
265
} catch(\Exception $e) {
266
    $transaction->rollBack();
267
    throw $e;
268 269 270
}
```

271 272 273 274 275 276 277 278 279 280
The first line starts a new transaction using the [[yii\db\Connection::beginTransaction()|beginTransaction()]]-method of the database connection
object. The transaction itself is represented by a [[yii\db\Transaction]] object stored in `$transaction`.
We wrap the execution of all queries in a try-catch-block to be able to handle errors.
We call [[yii\db\Transaction::commit()|commit()]] on success to commit the transaction and
[[yii\db\Transaction::rollBack()|rollBack()]] in case of an error. This will revert the effect of all queries
that have been executed inside of the transaction.
`throw $e` is used to re-throw the exception in case we can not handle the error ourselfs and deligate it
to some other code or the yii errorhandler.

It is also possible to nest multiple transactions, if needed:
281 282 283 284 285

```php
// outer transaction
$transaction1 = $connection->beginTransaction();
try {
286 287 288 289 290 291 292 293 294 295 296 297
    $connection->createCommand($sql1)->execute();

    // inner transaction
    $transaction2 = $connection->beginTransaction();
    try {
        $connection->createCommand($sql2)->execute();
        $transaction2->commit();
    } catch (Exception $e) {
        $transaction2->rollBack();
    }

    $transaction1->commit();
298
} catch (Exception $e) {
299
    $transaction1->rollBack();
300 301 302
}
```

303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
Note that your DBMS should have support for Savepoints for this to work as expected.
The above code will work for any DBMS but transactional safety is only guaranteed if
the underlying DBMS supports it.

Yii also supports setting [isolation levels] for your transactions.
When beginning a transaction it will run in the default isolation level set by you database system.
You can specifying an isolation level explicitly when starting a transaction:

```php
$transaction = $connection->beginTransaction(\yii\db\Transaction::REPEATABLE_READ);
```

Yii provides four constants for the most common isolation levels:

- [[\yii\db\Transaction::READ_UNCOMMITTED]] - the weakest level, Dirty reads, Non-repeatable reads and Phantoms may occur.
- [[\yii\db\Transaction::READ_COMMITTED]] - avoid Dirty reads.
- [[\yii\db\Transaction::REPEATABLE_READ]] - avoid Dirty reads and Non-repeatable reads.
- [[\yii\db\Transaction::SERIALIZABLE]] - the strongest level, avoids all of the above named problems.

You may use the constants named above but you can also use a string that represents a valid syntax that can be
used in your DBMS following `SET TRANSACTION ISOLATION LEVEL`. For postgres this could be for example
`SERIALIZABLE READ ONLY DEFERRABLE`.

326 327 328 329 330
Note that some DBMS allow setting of the isolation level only for the whole connection so subsequent transactions
may get the same isolation level even if you did not specify any. When using this feature
you may need to set the isolation level for all transactions explicitly to avoid conflicting settings.
At the time of this writing affected DBMS are MSSQL and SQLite.

331
> Note: SQLite only supports two isolation levels, so you can only use `READ UNCOMMITTED` and `SERIALIZABLE`.
332
Usage of other levels will result in an exception to be thrown.
333

334 335 336
> Note: PostgreSQL does not allow settin the isolation level before the transaction starts so you can not
specify the isolation level directly when starting the transaction.
You have to call [[yii\db\Transaction::setIsolationLevel()]] in this case after the transaction has started.
337 338 339

[isolation levels]: http://en.wikipedia.org/wiki/Isolation_%28database_systems%29#Isolation_levels

340

341 342 343 344 345
Working with database schema
----------------------------

### Getting schema information

346
You can get a [[yii\db\Schema]] instance like the following:
347 348 349 350 351 352 353 354 355 356 357

```php
$schema = $connection->getSchema();
```

It contains a set of methods allowing you to retrieve various information about the database:

```php
$tables = $schema->getTableNames();
```

358
For the full reference check [[yii\db\Schema]].
359 360 361

### Modifying schema

362
Aside from basic SQL queries [[yii\db\Command]] contains a set of methods allowing to modify database schema:
363 364 365 366 367 368 369 370 371 372

- createTable, renameTable, dropTable, truncateTable
- addColumn, renameColumn, dropColumn, alterColumn
- addPrimaryKey, dropPrimaryKey
- addForeignKey, dropForeignKey
- createIndex, dropIndex

These can be used as follows:

```php
373
// CREATE TABLE
374
$connection->createCommand()->createTable('post', [
375 376 377
    'id' => 'pk',
    'title' => 'string',
    'text' => 'text',
Alexander Makarov committed
378
]);
379 380
```

381
For the full reference check [[yii\db\Command]].