Commit ecf019e3 by Alexander Makarov

Merge branch 'master'

parents 8cd24773 82bdcdcb
......@@ -11,7 +11,7 @@ class m130524_201442_init extends \yii\db\Migration
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('tbl_user', [
$this->createTable($this->db->tablePrefix . 'user', [
'id' => Schema::TYPE_PK,
'username' => Schema::TYPE_STRING . ' NOT NULL',
'auth_key' => Schema::TYPE_STRING . '(32) NOT NULL',
......@@ -28,6 +28,6 @@ class m130524_201442_init extends \yii\db\Migration
public function down()
{
$this->dropTable('tbl_user');
$this->dropTable($this->db->tablePrefix . 'user');
}
}
......@@ -66,7 +66,7 @@ class PasswordResetRequestFormTest extends DbTestCase
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
'dataFile' => '@frontend/tests/unit/fixtures/data/user.php'
],
];
}
......
......@@ -29,7 +29,7 @@ class ResetPasswordFormTest extends DbTestCase
return [
'user' => [
'class' => UserFixture::className(),
'dataFile' => '@frontend/tests/unit/fixtures/data/tbl_user.php'
'dataFile' => '@frontend/tests/unit/fixtures/data/user.php'
],
];
}
......
......@@ -9,8 +9,8 @@ class UserTest extends TestCase
protected function setUp()
{
parent::setUp();
// uncomment the following to load fixtures for table tbl_user
//$this->loadFixtures(['tbl_user']);
// uncomment the following to load fixtures for user table
//$this->loadFixtures(['user']);
}
// TODO add test methods here
......
......@@ -75,6 +75,14 @@ a class like `yii\web\Request` can be autoloaded by Yii. If you use a third part
such as Zend Framework, you may define a path alias `@Zend` which refers to its installation
directory and Yii will be able to autoload any class in this library.
The following aliases are predefined by the core framework:
- `@yii` - framework directory.
- `@app` - base path of currently running application.
- `@runtime` - runtime directory.
- `@vendor` - Composer vendor directory.
- `@webroot` - web root directory of currently running web application.
- `@web` - base URL of currently running web application.
Autoloading
-----------
......
......@@ -80,7 +80,7 @@ class m101129_185401_create_news_table extends \yii\db\Migration
{
public function up()
{
$this->createTable('tbl_news', [
$this->createTable('news', [
'id' => 'pk',
'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT,
......@@ -89,7 +89,7 @@ class m101129_185401_create_news_table extends \yii\db\Migration
public function down()
{
$this->dropTable('tbl_news');
$this->dropTable('news');
}
}
......@@ -124,13 +124,13 @@ class m101129_185401_create_news_table extends \yii\db\Migration
{
public function safeUp()
{
$this->createTable('tbl_news', [
$this->createTable('news', [
'id' => 'pk',
'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT,
]);
$this->createTable('tbl_user', [
$this->createTable('user', [
'id' => 'pk',
'login' => Schema::TYPE_STRING . ' NOT NULL',
'password' => Schema::TYPE_STRING . ' NOT NULL',
......@@ -139,8 +139,8 @@ class m101129_185401_create_news_table extends \yii\db\Migration
public function safeDown()
{
$this->dropTable('tbl_news');
$this->dropTable('tbl_user');
$this->dropTable('news');
$this->dropTable('user');
}
}
......@@ -169,8 +169,8 @@ the migrations, it will run the `up()` method in every new migration class, one
after another, in the order of the timestamp value in the class name.
After applying a migration, the migration tool will keep a record in a database
table named `tbl_migration`. This allows the tool to identify which migrations
have been applied and which are not. If the `tbl_migration` table does not exist,
table named `migration`. This allows the tool to identify which migrations
have been applied and which are not. If the `migration` table does not exist,
the tool will automatically create it in the database specified by the `db`
application component.
......@@ -284,7 +284,7 @@ line:
sub-directory under the application base path.
* `migrationTable`: string, specifies the name of the database table for storing
migration history information. It defaults to `tbl_migration`. The table
migration history information. It defaults to `migration`. The table
structure is `version varchar(255) primary key, apply_time integer`.
* `connectionID`: string, specifies the ID of the database application component.
......
......@@ -31,7 +31,7 @@ And the following example shows how to use ActiveDataProvider without ActiveReco
```php
$query = new Query();
$provider = new ActiveDataProvider([
'query' => $query->from('tbl_post'),
'query' => $query->from('post'),
'pagination' => [
'pageSize' => 20,
],
......@@ -64,7 +64,7 @@ ArrayDataProvider may be used in the following way:
```php
$query = new Query();
$provider = new ArrayDataProvider([
'allModels' => $query->from('tbl_post')->all(),
'allModels' => $query->from('post')->all(),
'sort' => [
'attributes' => ['id', 'username', 'email'],
],
......@@ -94,11 +94,11 @@ and pagination behaviors.
```php
$count = Yii::$app->db->createCommand('
SELECT COUNT(*) FROM tbl_user WHERE status=:status
SELECT COUNT(*) FROM user WHERE status=:status
', [':status' => 1])->queryScalar();
$dataProvider = new SqlDataProvider([
'sql' => 'SELECT * FROM tbl_user WHERE status=:status',
'sql' => 'SELECT * FROM user WHERE status=:status',
'params' => [':status' => 1],
'totalCount' => $count,
'sort' => [
......
......@@ -103,28 +103,28 @@ Once you have a connection instance you can execute SQL queries using [[yii\db\C
When query returns a set of rows:
```php
$command = $connection->createCommand('SELECT * FROM tbl_post');
$command = $connection->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
```
When only a single row is returned:
```php
$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=1');
$command = $connection->createCommand('SELECT * FROM post WHERE id=1');
$post = $command->queryOne();
```
When there are multiple values from the same column:
```php
$command = $connection->createCommand('SELECT title FROM tbl_post');
$command = $connection->createCommand('SELECT title FROM post');
$titles = $command->queryColumn();
```
When there's a scalar value:
```php
$command = $connection->createCommand('SELECT COUNT(*) FROM tbl_post');
$command = $connection->createCommand('SELECT COUNT(*) FROM post');
$postCount = $command->queryScalar();
```
......@@ -133,7 +133,7 @@ $postCount = $command->queryScalar();
If SQL executed doesn't return any data you can use command's `execute` method:
```php
$command = $connection->createCommand('UPDATE tbl_post SET status=1 WHERE id=1');
$command = $connection->createCommand('UPDATE post SET status=1 WHERE id=1');
$command->execute();
```
......@@ -141,23 +141,23 @@ Alternatively the following syntax that takes care of proper table and column na
```php
// INSERT
$connection->createCommand()->insert('tbl_user', [
$connection->createCommand()->insert('user', [
'name' => 'Sam',
'age' => 30,
])->execute();
// INSERT multiple rows at once
$connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
$connection->createCommand()->batchInsert('user', ['name', 'age'], [
['Tom', 30],
['Jane', 20],
['Linda', 25],
])->execute();
// UPDATE
$connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute();
$connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
// DELETE
$connection->createCommand()->delete('tbl_user', 'status = 0')->execute();
$connection->createCommand()->delete('user', 'status = 0')->execute();
```
Quoting table and column names
......@@ -189,7 +189,7 @@ Prepared statements
In order to securely pass query parameters you can use prepared statements:
```php
$command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id');
$command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
$command->bindValue(':id', $_GET['id']);
$post = $command->query();
```
......@@ -197,7 +197,7 @@ $post = $command->query();
Another usage is performing a query multiple times while preparing it only once:
```php
$command = $connection->createCommand('DELETE FROM tbl_post WHERE id=:id');
$command = $connection->createCommand('DELETE FROM post WHERE id=:id');
$command->bindParam(':id', $id);
$id = 1;
......@@ -281,7 +281,7 @@ These can be used as follows:
```php
// CREATE TABLE
$connection->createCommand()->createTable('tbl_post', [
$connection->createCommand()->createTable('post', [
'id' => 'pk',
'title' => 'string',
'text' => 'text',
......
......@@ -10,7 +10,7 @@ use Yii;
try {
10/0;
} catch (ErrorException) {
} catch (ErrorException $e) {
Yii::warning("Tried dividing by zero.");
}
......@@ -19,38 +19,39 @@ try {
As demonstrated above you may handle errors using `try`-`catch`.
Second, even fatal errors in Yii are rendered in a nice way. This means that in debugging mode, you can trace the causes
of fatal errors in order to more quickly identify the cause of the problem.
Rendering errors in a dedicated controller action
-------------------------------------------------
The default Yii error page is great when developing a site, and is acceptable for production sites if `YII_DEBUG`
is turned off in your bootstrap index.php file. But you may want to customize the default error page to make it
is turned off in your bootstrap `index.php` file. But you may want to customize the default error page to make it
more suitable for your project.
The easiest way to create a custom error page it is to use a dedicated controller action for error rendering. First,
you'll need to configure the `errorHandler` component in the application's configuration:
```php
return [
// ...
'components' => [
// ...
'components' => [
// ...
'errorHandler' => [
'errorAction' => 'site/error',
'errorHandler' => [
'errorAction' => 'site/error',
],
]
```
With that configuration in place, whenever an error occurs, Yii will execute the "error" action of the "Site" controller.
With that configuration in place, whenever an error occurs, Yii will execute the `error`-action of the `site`-controller.
That action should look for an exception and, if present, render the proper view file, passing along the exception:
```php
public function actionError()
{
if (\Yii::$app->exception !== null) {
return $this->render('error', ['exception' => \Yii::$app->exception]);
$exception = \Yii::$app->errorHandler->exception;
if ($exception !== null) {
return $this->render('error', ['exception' => $exception]);
}
}
```
......@@ -58,14 +59,13 @@ public function actionError()
Next, you would create the `views/site/error.php` file, which would make use of the exception. The exception object has
the following properties:
- `statusCode`: the HTTP status code (e.g. 403, 500). Available for HTTP exceptions only.
- `statusCode`: the HTTP status code (e.g. 403, 500). Available for [[yii\web\HttpException|HTTP exceptions]] only.
- `code`: the code of the exception.
- `type`: the error type (e.g. HttpException, PHP Error).
- `message`: the error message.
- `file`: the name of the PHP script file where the error occurs.
- `line`: the line number of the code where the error occurs.
- `trace`: the call stack of the error.
- `source`: the context source code where the error occurs.
Rendering errors without a dedicated controller action
------------------------------------------------------
......@@ -91,4 +91,4 @@ automatically be used. The view will be passed three variables:
- `$message`: the error message
- `$exception`: the exception being handled
The `$exception` object will have the same properties outlined above.
The `$exception` object will have the same properties as outlined above.
......@@ -11,7 +11,7 @@ A typical usage of the query builder looks like the following:
```php
$rows = (new \yii\db\Query())
->select('id, name')
->from('tbl_user')
->from('user')
->limit(10)
->all();
......@@ -19,7 +19,7 @@ $rows = (new \yii\db\Query())
$query = (new \yii\db\Query())
->select('id, name')
->from('tbl_user')
->from('user')
->limit(10);
// Create a command. You can get the actual SQL using $command->sql
......@@ -62,7 +62,7 @@ In order to form a basic `SELECT` query, you need to specify what columns to sel
```php
$query->select('id, name')
->from('tbl_user');
->from('user');
```
Select options can be specified as a comma-separated string, as in the above, or as an array.
......@@ -70,7 +70,7 @@ The array syntax is especially useful when forming the selection dynamically:
```php
$query->select(['id', 'name'])
->from('tbl_user');
->from('user');
```
> Info: You should always use the array format if your `SELECT` clause contains SQL expressions.
......@@ -78,14 +78,14 @@ $query->select(['id', 'name'])
> If you list it together with other columns in a string, the expression may be split into several parts
> by commas, which is not what you want to see.
When specifying columns, you may include the table prefixes or column aliases, e.g., `tbl_user.id`, `tbl_user.id AS user_id`.
When specifying columns, you may include the table prefixes or column aliases, e.g., `user.id`, `user.id AS user_id`.
If you are using array to specify the columns, you may also use the array keys to specify the column aliases,
e.g., `['user_id' => 'tbl_user.id', 'user_name' => 'tbl_user.name']`.
e.g., `['user_id' => 'user.id', 'user_name' => 'user.name']`.
To select distinct rows, you may call `distinct()`, like the following:
```php
$query->select('user_id')->distinct()->from('tbl_post');
$query->select('user_id')->distinct()->from('post');
```
### `FROM`
......@@ -93,30 +93,30 @@ $query->select('user_id')->distinct()->from('tbl_post');
To specify which table(s) to select data from, call `from()`:
```php
$query->select('*')->from('tbl_user');
$query->select('*')->from('user');
```
You may specify multiple tables using a comma-separated string or an array.
Table names can contain schema prefixes (e.g. `'public.tbl_user'`) and/or table aliases (e.g. `'tbl_user u'`).
Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
The method will automatically quote the table names unless it contains some parenthesis
(which means the table is given as a sub-query or DB expression). For example,
```php
$query->select('u.*, p.*')->from(['tbl_user u', 'tbl_post p']);
$query->select('u.*, p.*')->from(['user u', 'post p']);
```
When the tables are specified as an array, you may also use the array keys as the table aliases
(if a table does not need alias, do not use a string key). For example,
```php
$query->select('u.*, p.*')->from(['u' => 'tbl_user u', 'p' => 'tbl_post']);
$query->select('u.*, p.*')->from(['u' => 'user u', 'p' => 'post']);
```
You may specify a sub-query using a `Query` object. In this case, the corresponding array key will be used
as the alias for the sub-query.
```php
$subQuery = (new Query())->select('id')->from('tbl_user')->where('status=1');
$subQuery = (new Query())->select('id')->from('user')->where('status=1');
$query->select('*')->from(['u' => $subQuery]);
```
......@@ -293,9 +293,9 @@ The `JOIN` clauses are generated in the Query Builder by using the applicable jo
This left join selects data from two related tables in one query:
```php
$query->select(['tbl_user.name AS author', 'tbl_post.title as title'])
->from('tbl_user')
->leftJoin('tbl_post', 'tbl_post.user_id = tbl_user.id');
$query->select(['user.name AS author', 'post.title as title'])
->from('user')
->leftJoin('post', 'post.user_id = user.id');
```
In the code, the `leftJoin()` method's first parameter
......@@ -304,7 +304,7 @@ specifies the table to join to. The second parameter defines the join condition.
If your database application supports other join types, you can use those via the generic `join` method:
```php
$query->join('FULL OUTER JOIN', 'tbl_post', 'tbl_post.user_id = tbl_user.id');
$query->join('FULL OUTER JOIN', 'post', 'post.user_id = user.id');
```
The first argument is the join type to perform. The second is the table to join to, and the third is the condition.
......@@ -325,10 +325,10 @@ In Yii in order to build it you can first form two query objects and then use `u
```php
$query = new Query();
$query->select("id, 'post' as type, name")->from('tbl_post')->limit(10);
$query->select("id, 'post' as type, name")->from('post')->limit(10);
$anotherQuery = new Query();
$anotherQuery->select('id, 'user' as type, name')->from('tbl_user')->limit(10);
$anotherQuery->select('id, 'user' as type, name')->from('user')->limit(10);
$query->union($anotherQuery);
```
......@@ -348,7 +348,7 @@ Batch query can be used like the following:
use yii\db\Query;
$query = (new Query())
->from('tbl_user')
->from('user')
->orderBy('id');
foreach ($query->batch() as $users) {
......@@ -377,7 +377,7 @@ will still keep the proper index. For example,
use yii\db\Query;
$query = (new Query())
->from('tbl_user')
->from('user')
->indexBy('username');
foreach ($query->batch() as $users) {
......
......@@ -44,7 +44,7 @@ class UserFixture extends ActiveFixture
The fixture data for an `ActiveFixture` fixture is usually provided in a file located at `FixturePath/data/TableName.php`,
where `FixturePath` stands for the directory containing the fixture class file, and `TableName`
is the name of the table associated with the fixture. In the example above, the file should be
`@app/tests/fixtures/data/tbl_user.php`. The data file should return an array of data rows
`@app/tests/fixtures/data/user.php`. The data file should return an array of data rows
to be inserted into the user table. For example,
```php
......
......@@ -396,7 +396,7 @@ and [[yii\db\QueryBuilder|QueryBuilder]] to generate SQL statements from query o
```php
$query = new \yii\db\Query();
$query->select('id, name')
->from('tbl_user')
->from('user')
->limit(10);
$command = $query->createCommand();
......
......@@ -52,7 +52,7 @@ use yii\helpers\FileHelper;
*
* - `$fixture` - current fixture array.
* - `$faker` - faker generator instance
* - `$index` - current fixture index. For example if user need to generate 3 fixtures for tbl_user, it will be 0..2
* - `$index` - current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2
*
* After you set all needed fields in callback, you need to return $fixture array back from the callback.
*
......
......@@ -62,7 +62,7 @@ If you use callback as a attribute value, then it will be called as shown with t
* ```$fixture``` - current fixture array.
* ```$faker``` - faker generator instance
* ```$index``` - current fixture index. For example if user need to generate 3 fixtures for tbl_user, it will be 0..2.
* ```$index``` - current fixture index. For example if user need to generate 3 fixtures for user table, it will be 0..2.
After you set all needed fields in callback, you need to return $fixture array back from the callback.
......
......@@ -93,8 +93,8 @@ class Generator extends \yii\gii\Generator
return array_merge(parent::hints(), [
'ns' => 'This is the namespace of the ActiveRecord class to be generated, e.g., <code>app\models</code>',
'db' => 'This is the ID of the DB application component.',
'tableName' => 'This is the name of the DB table that the new ActiveRecord class is associated with, e.g. <code>tbl_post</code>.
The table name may consist of the DB schema part if needed, e.g. <code>public.tbl_post</code>.
'tableName' => 'This is the name of the DB table that the new ActiveRecord class is associated with, e.g. <code>post</code>.
The table name may consist of the DB schema part if needed, e.g. <code>public.post</code>.
The table name may end with asterisk to match multiple table names, e.g. <code>tbl_*</code>
will match tables who name starts with <code>tbl_</code>. In this case, multiple ActiveRecord classes
will be generated, one for each matching table name; and the class names will be generated from
......
......@@ -8,6 +8,7 @@
namespace yii\mongodb;
use Yii;
use yii\base\ErrorHandler;
use yii\base\InvalidConfigException;
use yii\di\Instance;
......@@ -49,6 +50,7 @@ class Session extends \yii\web\Session
*/
public $sessionCollection = 'session';
/**
* Initializes the Session component.
* This method will initialize the [[db]] property to make sure it refers to a valid MongoDB connection.
......@@ -148,10 +150,11 @@ class Session extends \yii\web\Session
['upsert' => true]
);
} catch (\Exception $e) {
if (YII_DEBUG) {
echo $e->getMessage();
}
// it is too late to log an error message here
$exception = ErrorHandler::convertExceptionToString($e);
// its too late to use Yii logging here
error_log($exception);
echo $exception;
return false;
}
......
......@@ -135,7 +135,7 @@ class Command extends \yii\db\Command
* For example,
*
* ~~~
* $connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute();
* $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
* ~~~
*
* The method will properly escape the column names and bind the values to be updated.
......
......@@ -182,6 +182,7 @@ Yii Framework 2 Change Log
- Enh: Added `yii\web\UrlRuleInterface` and `yii\web\CompositeUrlRule` (qiangxue)
- Enh: Added `yii\web\Request::getAuthUser()` and `getAuthPassword()` (qiangxue)
- Enh: Added summaryOptions and emptyTextOptions to BaseListView (johonunu)
- Enh: Implemented Oracle column comment reading from another schema (gureedo, samdark)
- Chg #47: Changed Markdown library to cebe/markdown and adjusted Markdown helper API (cebe)
- Chg #735: Added back `ActiveField::hiddenInput()` (qiangxue)
- Chg #1186: Changed `Sort` to use comma to separate multiple sort fields and use negative sign to indicate descending sort (qiangxue)
......@@ -218,6 +219,9 @@ Yii Framework 2 Change Log
- Chg #2281: Renamed `ActiveRecord::create()` to `populateRecord()` and changed signature. This method will not call instantiate() anymore (cebe)
- Chg #2405: The CSS class of `MaskedInput` now defaults to `form-control` (qiangxue)
- Chg #2426: Changed URL creation method signatures to be consistent (samdark)
- Chg #2516: Moved error handling from application to ErrorHandler class and fixed problems with HTTP Exception response code (cebe)
- `Yii::$app->exception` has now moved to `Yii::$app->errorHandler->exception`
- `yii\base\ErrorHandler` was split into `yii\web\ErrorHandler` and `yii\console\ErrorHandler`
- Chg #2544: Changed `DetailView`'s `name:format:label` to `attribute:format:label` to match `GridView` (samdark)
- Chg #2603: `yii\base\ErrorException` now extends `\ErrorException` (samdark)
- Chg #2629: `Module::controllerPath` is now read only, and all controller classes must be namespaced under `Module::controllerNamespace`. (qiangxue)
......@@ -228,6 +232,7 @@ Yii Framework 2 Change Log
- Removed `yii\web\Controller::getCanonicalUrl`, use `yii\helpers\Url::canonical` instead.
- Chg #2691: Null parameters will not be included in the generated URLs by `UrlManager` (gonimar, qiangxue)
- Chg #2734: `FileCache::keyPrefix` defaults to empty string now (qiangxue)
- Chg #2911: Removed `tbl_` default for table prefix (samdark)
_ Chg #2912: Relative view files will be looked for under the directory containing the view currently being rendered (qiangxue)
- Chg: Renamed `yii\jui\Widget::clientEventsMap` to `clientEventMap` (qiangxue)
- Chg: Renamed `ActiveRecord::getPopulatedRelations()` to `getRelatedRecords()` (qiangxue)
......
......@@ -116,9 +116,9 @@ yii = (function ($) {
}
var $form = $e.closest('form');
var newForm = !$form.length || $e.prop('href') != '';
var action = $e.prop('href');
var newForm = !$form.length || action;
if (newForm) {
var action = $e.prop('href');
if (!action || !action.match(/(^\/|:\/\/)/)) {
action = window.location.href;
}
......@@ -129,10 +129,13 @@ yii = (function ($) {
}
if (!method.match(/(get|post)/i)) {
$form.append('<input name="_method" value="' + method + '" type="hidden">');
method = 'POST';
}
var csrfParam = pub.getCsrfParam();
if (csrfParam) {
$form.append('<input name="' + csrfParam + '" value="' + pub.getCsrfToken() + '" type="hidden">');
if (!method.match(/(get|head|options)/i)) {
var csrfParam = pub.getCsrfParam();
if (csrfParam) {
$form.append('<input name="' + csrfParam + '" value="' + pub.getCsrfToken() + '" type="hidden">');
}
}
$form.hide().appendTo('body');
}
......@@ -143,8 +146,13 @@ yii = (function ($) {
activeFormData.submitObject = $e;
}
var oldMethod = $form.prop('method');
$form.prop('method', method);
$form.trigger('submit');
$form.prop('method', oldMethod);
if (newForm) {
$form.remove();
}
......
......@@ -126,13 +126,6 @@ abstract class Application extends Module
*/
public $layout = 'main';
/**
* @var integer the size of the reserved memory. A portion of memory is pre-allocated so that
* when an out-of-memory issue occurs, the error handler is able to handle the error with
* the help of this reserved memory. If you set this value to be 0, no memory will be reserved.
* Defaults to 256KB.
*/
public $memoryReserveSize = 262144;
/**
* @var string the requested route
*/
public $requestedRoute;
......@@ -168,20 +161,11 @@ abstract class Application extends Module
*/
public $bootstrap = [];
/**
* @var \Exception the exception that is being handled currently. When this is not null,
* it means the application is handling some exception and extra care should be taken.
*/
public $exception;
/**
* @var integer the current application state during a request handling life cycle.
* This property is managed by the application. Do not modify this property.
*/
public $state;
/**
* @var string Used to reserve memory for fatal error handler.
*/
private $_memoryReserve;
/**
* Constructor.
......@@ -195,8 +179,8 @@ abstract class Application extends Module
$this->state = self::STATE_BEGIN;
$this->registerErrorHandler($config);
$this->preInit($config);
$this->registerErrorHandlers();
Component::__construct($config);
}
......@@ -212,13 +196,13 @@ abstract class Application extends Module
public function preInit(&$config)
{
if (!isset($config['id'])) {
throw new InvalidConfigException('The "id" configuration is required.');
throw new InvalidConfigException('The "id" configuration for the Application is required.');
}
if (isset($config['basePath'])) {
$this->setBasePath($config['basePath']);
unset($config['basePath']);
} else {
throw new InvalidConfigException('The "basePath" configuration is required.');
throw new InvalidConfigException('The "basePath" configuration for the Application is required.');
}
if (isset($config['vendorPath'])) {
......@@ -301,18 +285,18 @@ abstract class Application extends Module
}
/**
* Registers error handlers.
* Registers the errorHandler component as a PHP error handler.
*/
public function registerErrorHandlers()
protected function registerErrorHandler(&$config)
{
if (YII_ENABLE_ERROR_HANDLER) {
ini_set('display_errors', 0);
set_exception_handler([$this, 'handleException']);
set_error_handler([$this, 'handleError']);
if ($this->memoryReserveSize > 0) {
$this->_memoryReserve = str_repeat('x', $this->memoryReserveSize);
if (!isset($config['components']['errorHandler']['class'])) {
echo "Error: no errorHandler component is configured.\n";
exit(1);
}
register_shutdown_function([$this, 'handleFatalError']);
$this->set('errorHandler', $config['components']['errorHandler']);
unset($config['components']['errorHandler']);
$this->getErrorHandler()->register();
}
}
......@@ -480,7 +464,7 @@ abstract class Application extends Module
/**
* Returns the error handler component.
* @return ErrorHandler the error handler application component.
* @return \yii\web\ErrorHandler|\yii\console\ErrorHandler the error handler application component.
*/
public function getErrorHandler()
{
......@@ -586,7 +570,6 @@ abstract class Application extends Module
{
return [
'log' => ['class' => 'yii\log\Dispatcher'],
'errorHandler' => ['class' => 'yii\base\ErrorHandler'],
'view' => ['class' => 'yii\web\View'],
'formatter' => ['class' => 'yii\base\Formatter'],
'i18n' => ['class' => 'yii\i18n\I18N'],
......@@ -623,160 +606,4 @@ abstract class Application extends Module
exit($status);
}
}
/**
* Handles uncaught PHP exceptions.
*
* This method is implemented as a PHP exception handler.
*
* @param \Exception $exception the exception that is not caught
*/
public function handleException($exception)
{
if ($exception instanceof ExitException) {
return;
}
$this->exception = $exception;
// disable error capturing to avoid recursive errors while handling exceptions
restore_error_handler();
restore_exception_handler();
try {
$this->logException($exception);
if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($exception);
} else {
echo $this->renderException($exception);
if (PHP_SAPI === 'cli' && !YII_ENV_TEST) {
exit(1);
}
}
} catch (\Exception $e) {
// exception could be thrown in ErrorHandler::handle()
$msg = (string) $e;
$msg .= "\nPrevious exception:\n";
$msg .= (string) $exception;
if (YII_DEBUG) {
if (PHP_SAPI === 'cli') {
echo $msg . "\n";
} else {
echo '<pre>' . htmlspecialchars($msg, ENT_QUOTES, $this->charset) . '</pre>';
}
}
$msg .= "\n\$_SERVER = " . var_export($_SERVER, true);
error_log($msg);
exit(1);
}
}
/**
* Handles PHP execution errors such as warnings, notices.
*
* This method is used as a PHP error handler. It will simply raise an `ErrorException`.
*
* @param integer $code the level of the error raised
* @param string $message the error message
* @param string $file the filename that the error was raised in
* @param integer $line the line number the error was raised at
*
* @throws ErrorException
*/
public function handleError($code, $message, $file, $line)
{
if (error_reporting() & $code) {
// load ErrorException manually here because autoloading them will not work
// when error occurs while autoloading a class
if (!class_exists('\\yii\\base\\Exception', false)) {
require_once(__DIR__ . '/Exception.php');
}
if (!class_exists('\\yii\\base\\ErrorException', false)) {
require_once(__DIR__ . '/ErrorException.php');
}
$exception = new ErrorException($message, $code, $code, $file, $line);
// in case error appeared in __toString method we can't throw any exception
$trace = debug_backtrace(false);
array_shift($trace);
foreach ($trace as $frame) {
if ($frame['function'] == '__toString') {
$this->handleException($exception);
exit(1);
}
}
throw $exception;
}
}
/**
* Handles fatal PHP errors
*/
public function handleFatalError()
{
unset($this->_memoryReserve);
// load ErrorException manually here because autoloading them will not work
// when error occurs while autoloading a class
if (!class_exists('\\yii\\base\\Exception', false)) {
require_once(__DIR__ . '/Exception.php');
}
if (!class_exists('\\yii\\base\\ErrorException', false)) {
require_once(__DIR__ . '/ErrorException.php');
}
$error = error_get_last();
if (ErrorException::isFatalError($error)) {
$exception = new ErrorException($error['message'], $error['type'], $error['type'], $error['file'], $error['line']);
$this->exception = $exception;
// use error_log because it's too late to use Yii log
error_log($exception);
if (($handler = $this->getErrorHandler()) !== null) {
$handler->handle($exception);
} else {
echo $this->renderException($exception);
}
exit(1);
}
}
/**
* Renders an exception without using rich format.
* @param \Exception $exception the exception to be rendered.
* @return string the rendering result
*/
public function renderException($exception)
{
if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$message = $exception->getName() . ': ' . $exception->getMessage();
if (Yii::$app->controller instanceof \yii\console\Controller) {
$message = Yii::$app->controller->ansiFormat($message, Console::FG_RED);
}
} else {
$message = YII_DEBUG ? (string) $exception : 'Error: ' . $exception->getMessage();
}
if (PHP_SAPI === 'cli') {
return $message . "\n";
} else {
return '<pre>' . htmlspecialchars($message, ENT_QUOTES, $this->charset) . '</pre>';
}
}
/**
* Logs the given exception
* @param \Exception $exception the exception to be logged
*/
protected function logException($exception)
{
$category = get_class($exception);
if ($exception instanceof HttpException) {
$category = 'yii\\web\\HttpException:' . $exception->statusCode;
} elseif ($exception instanceof \ErrorException) {
$category .= ':' . $exception->getSeverity();
}
Yii::error((string) $exception, $category);
}
}
......@@ -29,10 +29,7 @@ class ErrorException extends \ErrorException
*/
public function __construct($message = '', $code = 0, $severity = 1, $filename = __FILE__, $lineno = __LINE__, \Exception $previous = null)
{
parent::__construct($message, $code, $previous);
$this->severity = $severity;
$this->file = $filename;
$this->line = $lineno;
parent::__construct($message, $code, $severity, $filename, $lineno, $previous);
if (function_exists('xdebug_get_function_stack')) {
$trace = array_slice(array_reverse(xdebug_get_function_stack()), 3, -1);
......
......@@ -473,7 +473,8 @@ class Formatter extends Component
/**
* Formats the value as the time interval between a date and now in human readable form.
* @param integer|string|DateTime|DateInterval $value the value to be formatted. The following
*
* @param integer|string|DateTime|\DateInterval $value the value to be formatted. The following
* types of value are supported:
*
* - an integer representing a UNIX timestamp
......@@ -481,6 +482,7 @@ class Formatter extends Component
* - a PHP DateTime object
* - a PHP DateInterval object (a positive time interval will refer to the past, a negative one to the future)
*
* @param integer|string|DateTime|\DateInterval $referenceTime if specified the value is used instead of now
* @return string the formatted result
*/
public function asRelativeTime($value, $referenceTime = null)
......
......@@ -16,7 +16,7 @@ use yii\di\Instance;
/**
* DbCache implements a cache application component by storing cached data in a database.
*
* By default, DbCache stores session data in a DB table named 'tbl_cache'. This table
* By default, DbCache stores session data in a DB table named 'cache'. This table
* must be pre-created. The table name can be changed by setting [[cacheTable]].
*
* Please refer to [[Cache]] for common cache operations that are supported by DbCache.
......@@ -47,7 +47,7 @@ class DbCache extends Cache
* The table should be pre-created as follows:
*
* ~~~
* CREATE TABLE tbl_cache (
* CREATE TABLE cache (
* id char(128) NOT NULL PRIMARY KEY,
* expire int(11),
* data BLOB
......
......@@ -188,9 +188,20 @@ class Application extends \yii\base\Application
*/
public function coreComponents()
{
return array_merge([
return array_merge(parent::coreComponents(), [
'request' => ['class' => 'yii\console\Request'],
'response' => ['class' => 'yii\console\Response'],
], parent::coreComponents());
]);
}
/**
* Registers the errorHandler component as a PHP error handler.
*/
protected function registerErrorHandler(&$config)
{
if (!isset($config['components']['errorHandler']['class'])) {
$config['components']['errorHandler']['class'] = 'yii\\console\\ErrorHandler';
}
parent::registerErrorHandler($config);
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\console;
use Yii;
use yii\base\ErrorException;
use yii\base\UserException;
use yii\helpers\Console;
/**
* ErrorHandler handles uncaught PHP errors and exceptions.
*
* ErrorHandler is configured as an application component in [[\yii\base\Application]] by default.
* You can access that instance via `Yii::$app->errorHandler`.
*
* @author Carsten Brandt <mail@cebe.cc>
* @since 2.0
*/
class ErrorHandler extends \yii\base\ErrorHandler
{
/**
* Renders an exception using ansi format for console output.
* @param \Exception $exception the exception to be rendered.
*/
protected function renderException($exception)
{
if ($exception instanceof Exception && ($exception instanceof UserException || !YII_DEBUG)) {
$message = $this->formatMessage($exception->getName() . ': ') . $exception->getMessage();
} elseif (YII_DEBUG) {
if ($exception instanceof Exception) {
$message = $this->formatMessage("Exception ({$exception->getName()})");
} elseif ($exception instanceof ErrorException) {
$message = $this->formatMessage($exception->getName());
} else {
$message = $this->formatMessage('Exception');
}
$message .= $this->formatMessage(" '" . get_class($exception) . "'", [Console::BOLD, Console::FG_BLUE])
. " with message " . $this->formatMessage("'{$exception->getMessage()}'", [Console::BOLD]) //. "\n"
. "\n\nin " . dirname($exception->getFile()) . DIRECTORY_SEPARATOR . $this->formatMessage(basename($exception->getFile()), [Console::BOLD])
. ':' . $this->formatMessage($exception->getLine(), [Console::BOLD, Console::FG_YELLOW]) . "\n\n"
. $this->formatMessage("Stack trace:\n", [Console::BOLD]) . $exception->getTraceAsString();
} else {
$message = $this->formatMessage('Error: ') . $exception->getMessage();
}
if (PHP_SAPI === 'cli') {
Console::stderr($message . "\n");
} else {
echo $message . "\n";
}
}
/**
* Colorizes a message for console output.
* @param string $message the message to colorize.
* @param array $format the message format.
* @return string the colorized message.
* @see Console::ansiFormat() for details on how to specify the message format.
*/
protected function formatMessage($message, $format = [Console::FG_RED, Console::BOLD])
{
$stream = (PHP_SAPI === 'cli') ? STDERR : STDOUT;
// try controller first to allow check for --color switch
if (Yii::$app->controller instanceof \yii\console\Controller && Yii::$app->controller->isColorEnabled($stream)
|| Yii::$app instanceof \yii\console\Application && Console::streamSupportsAnsiColors($stream)) {
$message = Console::ansiFormat($message, $format);
}
return $message;
}
}
\ No newline at end of file
......@@ -33,7 +33,7 @@ use yii\helpers\FileHelper;
* create it as follows:
*
* ~~~
* CREATE TABLE tbl_migration (
* CREATE TABLE migration (
* version varchar(180) PRIMARY KEY,
* apply_time integer
* )
......
......@@ -39,7 +39,7 @@ use yii\di\Instance;
* ~~~
* $query = new Query;
* $provider = new ActiveDataProvider([
* 'query' => $query->from('tbl_post'),
* 'query' => $query->from('post'),
* 'pagination' => [
* 'pageSize' => 20,
* ],
......
......@@ -30,7 +30,7 @@ use yii\helpers\ArrayHelper;
* ~~~
* $query = new Query;
* $provider = new ArrayDataProvider([
* 'allModels' => $query->from('tbl_post')->all(),
* 'allModels' => $query->from('post')->all(),
* 'sort' => [
* 'attributes' => ['id', 'username', 'email'],
* ],
......
......@@ -26,11 +26,11 @@ use yii\di\Instance;
*
* ~~~
* $count = Yii::$app->db->createCommand('
* SELECT COUNT(*) FROM tbl_user WHERE status=:status
* SELECT COUNT(*) FROM user WHERE status=:status
* ', [':status' => 1])->queryScalar();
*
* $dataProvider = new SqlDataProvider([
* 'sql' => 'SELECT * FROM tbl_user WHERE status=:status',
* 'sql' => 'SELECT * FROM user WHERE status=:status',
* 'params' => [':status' => 1],
* 'totalCount' => $count,
* 'sort' => [
......
......@@ -357,7 +357,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
* // find all orders, eager loading "books", and sort the orders and books by the book names.
* Order::find()->joinWith([
* 'books' => function ($query) {
* $query->orderBy('tbl_item.name');
* $query->orderBy('item.name');
* }
* ])->all();
* ```
......@@ -628,7 +628,7 @@ class ActiveQuery extends Query implements ActiveQueryInterface
* public function getItems()
* {
* return $this->hasMany(Item::className(), ['id' => 'item_id'])
* ->viaTable('tbl_order_item', ['order_id' => 'id']);
* ->viaTable('order_item', ['order_id' => 'id']);
* }
* ```
*
......
......@@ -21,8 +21,8 @@ use yii\helpers\StringHelper;
* row in a database table. The object's attributes are mapped to the columns of the corresponding table.
* Referencing an Active Record attribute is equivalent to accessing the corresponding table column for that record.
*
* As an example, say that the `Customer` ActiveRecord class is associated with the `tbl_customer` table.
* This would mean that the class's `name` attribute is automatically mapped to the `name` column in `tbl_customer`.
* As an example, say that the `Customer` ActiveRecord class is associated with the `customer` table.
* This would mean that the class's `name` attribute is automatically mapped to the `name` column in `customer` table.
* Thanks to Active Record, assuming the variable `$customer` is an object of type `Customer`, to get the value of
* the `name` column for the table row, you can use the expression `$customer->name`.
* In this example, Active Record is providing an object-oriented interface for accessing data stored in the database.
......@@ -38,7 +38,7 @@ use yii\helpers\StringHelper;
* {
* public static function tableName()
* {
* return 'tbl_customer';
* return 'customer';
* }
* }
* ```
......@@ -58,12 +58,12 @@ use yii\helpers\StringHelper;
* ```php
* $user = new User();
* $user->name = 'Qiang';
* $user->save(); // a new row is inserted into tbl_user
* $user->save(); // a new row is inserted into user table
*
* // the following will retrieve the user 'CeBe' from the database
* $user = User::find()->where(['name' => 'CeBe'])->one();
*
* // this will get related records from table tbl_orders when relation is defined
* // this will get related records from orders table when relation is defined
* $orders = $user->orders;
* ```
*
......@@ -131,7 +131,7 @@ class ActiveRecord extends BaseActiveRecord
* Below is an example:
*
* ~~~
* $customers = Customer::findBySql('SELECT * FROM tbl_customer')->all();
* $customers = Customer::findBySql('SELECT * FROM customer')->all();
* ~~~
*
* @param string $sql the SQL statement to be executed
......
......@@ -17,7 +17,7 @@ use yii\base\Object;
* you can iterate it to obtain a batch of data in each iteration. For example,
*
* ```php
* $query = (new Query)->from('tbl_user');
* $query = (new Query)->from('user');
* foreach ($query->batch() as $i => $users) {
* // $users represents the rows in the $i-th batch
* }
......
......@@ -23,7 +23,7 @@ use yii\caching\Cache;
* For example,
*
* ~~~
* $users = $connection->createCommand('SELECT * FROM tbl_user')->queryAll();
* $users = $connection->createCommand('SELECT * FROM user')->queryAll();
* ~~~
*
* Command supports SQL statement preparation and parameter binding.
......@@ -36,7 +36,7 @@ use yii\caching\Cache;
* [[update()]], etc. For example,
*
* ~~~
* $connection->createCommand()->insert('tbl_user', [
* $connection->createCommand()->insert('user', [
* 'name' => 'Sam',
* 'age' => 30,
* ])->execute();
......@@ -438,7 +438,7 @@ class Command extends \yii\base\Component
* For example,
*
* ~~~
* $connection->createCommand()->insert('tbl_user', [
* $connection->createCommand()->insert('user', [
* 'name' => 'Sam',
* 'age' => 30,
* ])->execute();
......@@ -465,7 +465,7 @@ class Command extends \yii\base\Component
* For example,
*
* ~~~
* $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
* $connection->createCommand()->batchInsert('user', ['name', 'age'], [
* ['Tom', 30],
* ['Jane', 20],
* ['Linda', 25],
......@@ -491,7 +491,7 @@ class Command extends \yii\base\Component
* For example,
*
* ~~~
* $connection->createCommand()->update('tbl_user', ['status' => 1], 'age > 30')->execute();
* $connection->createCommand()->update('user', ['status' => 1], 'age > 30')->execute();
* ~~~
*
* The method will properly escape the column names and bind the values to be updated.
......@@ -517,7 +517,7 @@ class Command extends \yii\base\Component
* For example,
*
* ~~~
* $connection->createCommand()->delete('tbl_user', 'status = 0')->execute();
* $connection->createCommand()->delete('user', 'status = 0')->execute();
* ~~~
*
* The method will properly escape the table and column names.
......
......@@ -39,9 +39,9 @@ use yii\caching\Cache;
* After the DB connection is established, one can execute SQL statements like the following:
*
* ~~~
* $command = $connection->createCommand('SELECT * FROM tbl_post');
* $command = $connection->createCommand('SELECT * FROM post');
* $posts = $command->queryAll();
* $command = $connection->createCommand('UPDATE tbl_post SET status=1');
* $command = $connection->createCommand('UPDATE post SET status=1');
* $command->execute();
* ~~~
*
......@@ -50,7 +50,7 @@ use yii\caching\Cache;
* to prevent SQL injection attacks. The following is an example:
*
* ~~~
* $command = $connection->createCommand('SELECT * FROM tbl_post WHERE id=:id');
* $command = $connection->createCommand('SELECT * FROM post WHERE id=:id');
* $command->bindValue(':id', $_GET['id']);
* $post = $command->query();
* ~~~
......@@ -221,7 +221,7 @@ class Connection extends Component
* as `{{%TableName}}`, then the percentage character `%` will be replaced with this
* property value. For example, `{{%post}}` becomes `{{tbl_post}}`.
*/
public $tablePrefix = 'tbl_';
public $tablePrefix = '';
/**
* @var array mapping between PDO driver names and [[Schema]] classes.
* The keys of the array are PDO driver names while the values the corresponding
......
......@@ -17,7 +17,7 @@ use yii\base\InvalidCallException;
* iterating through the reader. For example,
*
* ~~~
* $command = $connection->createCommand('SELECT * FROM tbl_post');
* $command = $connection->createCommand('SELECT * FROM post');
* $reader = $command->query();
*
* while ($row = $reader->read()) {
......
......@@ -25,7 +25,7 @@ use yii\base\Component;
* $query = new Query;
* // compose the query
* $query->select('id, name')
* ->from('tbl_user')
* ->from('user')
* ->limit(10);
* // build and execute the query
* $rows = $query->all();
......@@ -60,7 +60,7 @@ class Query extends Component implements QueryInterface
*/
public $distinct;
/**
* @var array the table(s) to be selected from. For example, `['tbl_user', 'tbl_post']`.
* @var array the table(s) to be selected from. For example, `['user', 'post']`.
* This is used to construct the FROM clause in a SQL statement.
* @see from()
*/
......@@ -82,8 +82,8 @@ class Query extends Component implements QueryInterface
*
* ~~~
* [
* ['INNER JOIN', 'tbl_user', 'tbl_user.id = author_id'],
* ['LEFT JOIN', 'tbl_team', 'tbl_team.id = team_id'],
* ['INNER JOIN', 'user', 'user.id = author_id'],
* ['LEFT JOIN', 'team', 'team.id = team_id'],
* ]
* ~~~
*/
......@@ -143,9 +143,9 @@ class Query extends Component implements QueryInterface
* For example,
*
* ```php
* $query = (new Query)->from('tbl_user');
* $query = (new Query)->from('user');
* foreach ($query->batch() as $rows) {
* // $rows is an array of 10 or fewer rows from tbl_user
* // $rows is an array of 10 or fewer rows from user table
* }
* ```
*
......@@ -171,7 +171,7 @@ class Query extends Component implements QueryInterface
* only one row of data is returned. For example,
*
* ```php
* $query = (new Query)->from('tbl_user');
* $query = (new Query)->from('user');
* foreach ($query->each() as $row) {
* }
* ```
......@@ -383,7 +383,7 @@ class Query extends Component implements QueryInterface
* Sets the SELECT part of the query.
* @param string|array $columns the columns to be selected.
* Columns can be specified in either a string (e.g. "id, name") or an array (e.g. ['id', 'name']).
* Columns can contain table prefixes (e.g. "tbl_user.id") and/or column aliases (e.g. "tbl_user.id AS user_id").
* Columns can be prefixed with table names (e.g. "user.id") and/or contain column aliases (e.g. "user.id AS user_id").
* The method will automatically quote the column names unless a column contains some parenthesis
* (which means the column contains a DB expression).
*
......@@ -422,9 +422,9 @@ class Query extends Component implements QueryInterface
/**
* Sets the FROM part of the query.
* @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'tbl_user'`)
* or an array (e.g. `['tbl_user', 'tbl_profile']`) specifying one or several table names.
* Table names can contain schema prefixes (e.g. `'public.tbl_user'`) and/or table aliases (e.g. `'tbl_user u'`).
* @param string|array $tables the table(s) to be selected from. This can be either a string (e.g. `'user'`)
* or an array (e.g. `['user', 'profile']`) specifying one or several table names.
* Table names can contain schema prefixes (e.g. `'public.user'`) and/or table aliases (e.g. `'user u'`).
* The method will automatically quote the table names unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression).
*
......@@ -643,7 +643,7 @@ class Query extends Component implements QueryInterface
* @param string|array $table the table to be joined.
*
* Use string to represent the name of the table to be joined.
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* Table name can contain schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
* The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression).
*
......@@ -668,7 +668,7 @@ class Query extends Component implements QueryInterface
* @param string|array $table the table to be joined.
*
* Use string to represent the name of the table to be joined.
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* Table name can contain schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
* The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression).
*
......@@ -693,7 +693,7 @@ class Query extends Component implements QueryInterface
* @param string|array $table the table to be joined.
*
* Use string to represent the name of the table to be joined.
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* Table name can contain schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
* The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression).
*
......@@ -718,7 +718,7 @@ class Query extends Component implements QueryInterface
* @param string|array $table the table to be joined.
*
* Use string to represent the name of the table to be joined.
* Table name can contain schema prefix (e.g. 'public.tbl_user') and/or table alias (e.g. 'tbl_user u').
* Table name can contain schema prefix (e.g. 'public.user') and/or table alias (e.g. 'user u').
* The method will automatically quote the table name unless it contains some parenthesis
* (which means the table is given as a sub-query or DB expression).
*
......
......@@ -94,7 +94,7 @@ class QueryBuilder extends \yii\base\Object
* For example,
*
* ~~~
* $sql = $queryBuilder->insert('tbl_user', [
* $sql = $queryBuilder->insert('user', [
* 'name' => 'Sam',
* 'age' => 30,
* ], $params);
......@@ -141,7 +141,7 @@ class QueryBuilder extends \yii\base\Object
* For example,
*
* ~~~
* $sql = $queryBuilder->batchInsert('tbl_user', ['name', 'age'], [
* $sql = $queryBuilder->batchInsert('user', ['name', 'age'], [
* ['Tom', 30],
* ['Jane', 20],
* ['Linda', 25],
......@@ -196,7 +196,7 @@ class QueryBuilder extends \yii\base\Object
*
* ~~~
* $params = [];
* $sql = $queryBuilder->update('tbl_user', ['status' => 1], 'age > 30', $params);
* $sql = $queryBuilder->update('user', ['status' => 1], 'age > 30', $params);
* ~~~
*
* The method will properly escape the table and column names.
......@@ -242,7 +242,7 @@ class QueryBuilder extends \yii\base\Object
* For example,
*
* ~~~
* $sql = $queryBuilder->delete('tbl_user', 'status = 0');
* $sql = $queryBuilder->delete('user', 'status = 0');
* ~~~
*
* The method will properly escape the table and column names.
......@@ -276,7 +276,7 @@ class QueryBuilder extends \yii\base\Object
* For example,
*
* ~~~
* $sql = $queryBuilder->createTable('tbl_user', [
* $sql = $queryBuilder->createTable('user', [
* 'id' => 'pk',
* 'name' => 'string',
* 'age' => 'integer',
......
......@@ -132,7 +132,7 @@ SELECT a.column_name, a.data_type ||
com.comments as column_comment
FROM ALL_TAB_COLUMNS A
inner join ALL_OBJECTS B ON b.owner = a.owner and ltrim(B.OBJECT_NAME) = ltrim(A.TABLE_NAME)
LEFT JOIN user_col_comments com ON (A.table_name = com.table_name AND A.column_name = com.column_name)
LEFT JOIN all_col_comments com ON (A.owner = com.owner AND A.table_name = com.table_name AND A.column_name = com.column_name)
WHERE
a.owner = '{$schemaName}'
and (b.object_type = 'TABLE' or b.object_type = 'VIEW')
......
......@@ -46,7 +46,7 @@ class QueryBuilder extends \yii\db\QueryBuilder
* For example,
*
* ~~~
* $connection->createCommand()->batchInsert('tbl_user', ['name', 'age'], [
* $connection->createCommand()->batchInsert('user', ['name', 'age'], [
* ['Tom', 30],
* ['Jane', 20],
* ['Linda', 25],
......
......@@ -301,6 +301,13 @@ class Container extends Component
unset($this->_definitions[$class], $this->_singletons[$class]);
}
/**
* Normalizes the class definition.
* @param string $class class name
* @param string|array|callable $definition the class definition
* @return array the normalized class definition
* @throws InvalidConfigException if the definition is invalid.
*/
protected function normalizeDefinition($class, $definition)
{
if (empty($definition)) {
......@@ -311,7 +318,11 @@ class Container extends Component
return $definition;
} elseif (is_array($definition)) {
if (!isset($definition['class'])) {
$definition['class'] = $class;
if (strpos($class, '\\') !== false) {
$definition['class'] = $class;
} else {
throw new InvalidConfigException("A class definition requires a \"class\" member.");
}
}
return $definition;
} else {
......
......@@ -22,23 +22,23 @@ use yii\db\Query;
* The database must contain the following two tables:
*
* ~~~
* CREATE TABLE tbl_source_message (
* CREATE TABLE source_message (
* id INTEGER PRIMARY KEY AUTO_INCREMENT,
* category VARCHAR(32),
* message TEXT
* );
*
* CREATE TABLE tbl_message (
* CREATE TABLE message (
* id INTEGER,
* language VARCHAR(16),
* translation TEXT,
* PRIMARY KEY (id, language),
* CONSTRAINT fk_message_source_message FOREIGN KEY (id)
* REFERENCES tbl_source_message (id) ON DELETE CASCADE ON UPDATE RESTRICT
* REFERENCES source_message (id) ON DELETE CASCADE ON UPDATE RESTRICT
* );
* ~~~
*
* The `tbl_source_message` table stores the messages to be translated, and the `tbl_message` table stores
* The `source_message` table stores the messages to be translated, and the `message` table stores
* the translated messages. The name of these two tables can be customized by setting [[sourceMessageTable]]
* and [[messageTable]], respectively.
*
......
......@@ -15,7 +15,7 @@ use yii\di\Instance;
/**
* DbTarget stores log messages in a database table.
*
* By default, DbTarget stores the log messages in a DB table named 'tbl_log'. This table
* By default, DbTarget stores the log messages in a DB table named 'log'. This table
* must be pre-created. The table name can be changed by setting [[logTable]].
*
* @author Qiang Xue <qiang.xue@gmail.com>
......@@ -34,7 +34,7 @@ class DbTarget extends Target
* The table should be pre-created as follows:
*
* ~~~
* CREATE TABLE tbl_log (
* CREATE TABLE log (
* id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
* level INTEGER,
* category VARCHAR(255),
......
......@@ -7,6 +7,7 @@
namespace yii\mail;
use yii\base\ErrorHandler;
use yii\base\Object;
use Yii;
......@@ -58,7 +59,7 @@ abstract class BaseMessage extends Object implements MessageInterface
try {
return $this->toString();
} catch (\Exception $e) {
trigger_error($e->getMessage() . "\n\n" . $e->getTraceAsString());
ErrorHandler::convertExceptionToError($e);
return '';
}
}
......
......@@ -39,15 +39,15 @@ class DbManager extends Manager
*/
public $db = 'db';
/**
* @var string the name of the table storing authorization items. Defaults to 'tbl_auth_item'.
* @var string the name of the table storing authorization items. Defaults to 'auth_item'.
*/
public $itemTable = '{{%auth_item}}';
/**
* @var string the name of the table storing authorization item hierarchy. Defaults to 'tbl_auth_item_child'.
* @var string the name of the table storing authorization item hierarchy. Defaults to 'auth_item_child'.
*/
public $itemChildTable = '{{%auth_item_child}}';
/**
* @var string the name of the table storing authorization item assignments. Defaults to 'tbl_auth_assignment'.
* @var string the name of the table storing authorization item assignments. Defaults to 'auth_assignment'.
*/
public $assignmentTable = '{{%auth_assignment}}';
......
......@@ -9,11 +9,11 @@
* @since 2.0
*/
drop table if exists [tbl_auth_assignment];
drop table if exists [tbl_auth_item_child];
drop table if exists [tbl_auth_item];
drop table if exists [auth_assignment];
drop table if exists [auth_item_child];
drop table if exists [auth_item];
create table [tbl_auth_item]
create table [auth_item]
(
[name] varchar(64) not null,
[type] integer not null,
......@@ -24,21 +24,21 @@ create table [tbl_auth_item]
key [type] ([type])
);
create table [tbl_auth_item_child]
create table [auth_item_child]
(
[parent] varchar(64) not null,
[child] varchar(64) not null,
primary key ([parent],[child]),
foreign key ([parent]) references [tbl_auth_item] ([name]) on delete cascade on update cascade,
foreign key ([child]) references [tbl_auth_item] ([name]) on delete cascade on update cascade
foreign key ([parent]) references [auth_item] ([name]) on delete cascade on update cascade,
foreign key ([child]) references [auth_item] ([name]) on delete cascade on update cascade
);
create table [tbl_auth_assignment]
create table [auth_assignment]
(
[item_name] varchar(64) not null,
[user_id] varchar(64) not null,
[biz_rule] text,
[data] text,
primary key ([item_name],[user_id]),
foreign key ([item_name]) references [tbl_auth_item] ([name]) on delete cascade on update cascade
foreign key ([item_name]) references [auth_item] ([name]) on delete cascade on update cascade
);
......@@ -9,11 +9,11 @@
* @since 2.0
*/
drop table if exists `tbl_auth_assignment`;
drop table if exists `tbl_auth_item_child`;
drop table if exists `tbl_auth_item`;
drop table if exists `auth_assignment`;
drop table if exists `auth_item_child`;
drop table if exists `auth_item`;
create table `tbl_auth_item`
create table `auth_item`
(
`name` varchar(64) not null,
`type` integer not null,
......@@ -24,21 +24,21 @@ create table `tbl_auth_item`
key `type` (`type`)
) engine InnoDB;
create table `tbl_auth_item_child`
create table `auth_item_child`
(
`parent` varchar(64) not null,
`child` varchar(64) not null,
primary key (`parent`,`child`),
foreign key (`parent`) references `tbl_auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
foreign key (`parent`) references `auth_item` (`name`) on delete cascade on update cascade,
foreign key (`child`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
create table `tbl_auth_assignment`
create table `auth_assignment`
(
`item_name` varchar(64) not null,
`user_id` varchar(64) not null,
`biz_rule` text,
`data` text,
primary key (`item_name`,`user_id`),
foreign key (`item_name`) references `tbl_auth_item` (`name`) on delete cascade on update cascade
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
) engine InnoDB;
......@@ -9,11 +9,11 @@
* @since 2.0
*/
drop table if exists "tbl_auth_assignment";
drop table if exists "tbl_auth_item_child";
drop table if exists "tbl_auth_item";
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
create table "tbl_auth_item"
create table "auth_item"
(
"name" varchar(64) not null,
"type" integer not null,
......@@ -24,21 +24,21 @@ create table "tbl_auth_item"
key "type" ("type")
);
create table "tbl_auth_item_child"
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "tbl_auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "tbl_auth_item" ("name") on delete cascade on update cascade
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "tbl_auth_assignment"
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"biz_rule" text,
"data" text,
primary key ("item_name","user_id"),
foreign key ("item_name") references "tbl_auth_item" ("name") on delete cascade on update cascade
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
......@@ -9,11 +9,11 @@
* @since 2.0
*/
drop table if exists "tbl_auth_assignment";
drop table if exists "tbl_auth_item_child";
drop table if exists "tbl_auth_item";
drop table if exists "auth_assignment";
drop table if exists "auth_item_child";
drop table if exists "auth_item";
create table "tbl_auth_item"
create table "auth_item"
(
"name" varchar(64) not null,
"type" integer not null,
......@@ -23,23 +23,23 @@ create table "tbl_auth_item"
primary key ("name")
);
create index tbl_auth_item_type_idx on "tbl_auth_item" ("type");
create index auth_item_type_idx on "auth_item" ("type");
create table "tbl_auth_item_child"
create table "auth_item_child"
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references "tbl_auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "tbl_auth_item" ("name") on delete cascade on update cascade
foreign key ("parent") references "auth_item" ("name") on delete cascade on update cascade,
foreign key ("child") references "auth_item" ("name") on delete cascade on update cascade
);
create table "tbl_auth_assignment"
create table "auth_assignment"
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"biz_rule" text,
"data" text,
primary key ("item_name","user_id"),
foreign key ("item_name") references "tbl_auth_item" ("name") on delete cascade on update cascade
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
);
......@@ -9,11 +9,11 @@
* @since 2.0
*/
drop table if exists 'tbl_auth_assignment';
drop table if exists 'tbl_auth_item_child';
drop table if exists 'tbl_auth_item';
drop table if exists 'auth_assignment';
drop table if exists 'auth_item_child';
drop table if exists 'auth_item';
create table 'tbl_auth_item'
create table 'auth_item'
(
"name" varchar(64) not null,
"type" integer not null,
......@@ -24,21 +24,21 @@ create table 'tbl_auth_item'
key "type" ("type")
);
create table 'tbl_auth_item_child'
create table 'auth_item_child'
(
"parent" varchar(64) not null,
"child" varchar(64) not null,
primary key ("parent","child"),
foreign key ("parent") references 'tbl_auth_item' ("name") on delete cascade on update cascade,
foreign key ("child") references 'tbl_auth_item' ("name") on delete cascade on update cascade
foreign key ("parent") references 'auth_item' ("name") on delete cascade on update cascade,
foreign key ("child") references 'auth_item' ("name") on delete cascade on update cascade
);
create table 'tbl_auth_assignment'
create table 'auth_assignment'
(
"item_name" varchar(64) not null,
"user_id" varchar(64) not null,
"biz_rule" text,
"data" text,
primary key ("item_name","user_id"),
foreign key ("item_name") references 'tbl_auth_item' ("name") on delete cascade on update cascade
foreign key ("item_name") references 'auth_item' ("name") on delete cascade on update cascade
);
......@@ -146,11 +146,22 @@ class Application extends \yii\base\Application
*/
public function coreComponents()
{
return array_merge([
return array_merge(parent::coreComponents(), [
'request' => ['class' => 'yii\web\Request'],
'response' => ['class' => 'yii\web\Response'],
'session' => ['class' => 'yii\web\Session'],
'user' => ['class' => 'yii\web\User'],
], parent::coreComponents());
]);
}
/**
* Registers the errorHandler component as a PHP error handler.
*/
protected function registerErrorHandler(&$config)
{
if (!isset($config['components']['errorHandler']['class'])) {
$config['components']['errorHandler']['class'] = 'yii\\web\\ErrorHandler';
}
parent::registerErrorHandler($config);
}
}
......@@ -105,10 +105,9 @@ class Controller extends \yii\base\Controller
public function beforeAction($action)
{
if (parent::beforeAction($action)) {
if ($this->enableCsrfValidation && Yii::$app->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
if ($this->enableCsrfValidation && Yii::$app->errorHandler->exception === null && !Yii::$app->getRequest()->validateCsrfToken()) {
throw new BadRequestHttpException(Yii::t('yii', 'Unable to verify your data submission.'));
}
return true;
} else {
return false;
......
......@@ -16,7 +16,7 @@ use yii\di\Instance;
/**
* DbSession extends [[Session]] by using database as session data storage.
*
* By default, DbSession stores session data in a DB table named 'tbl_session'. This table
* By default, DbSession stores session data in a DB table named 'session'. This table
* must be pre-created. The table name can be changed by setting [[sessionTable]].
*
* The following example shows how you can configure the application to use DbSession:
......@@ -48,7 +48,7 @@ class DbSession extends Session
* The table should be pre-created as follows:
*
* ~~~
* CREATE TABLE tbl_session
* CREATE TABLE session
* (
* id CHAR(40) NOT NULL PRIMARY KEY,
* expire INTEGER,
......@@ -182,10 +182,11 @@ class DbSession extends Session
->execute();
}
} catch (\Exception $e) {
if (YII_DEBUG) {
echo $e->getMessage();
}
// it is too late to log an error message here
$exception = ErrorHandler::convertExceptionToString($e);
// its too late to use Yii logging here
error_log($exception);
echo $exception;
return false;
}
......
......@@ -68,7 +68,7 @@ class ErrorAction extends Action
public function run()
{
if (($exception = Yii::$app->exception) === null) {
if (($exception = Yii::$app->errorHandler->exception) === null) {
return '';
}
......
......@@ -84,10 +84,10 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
public $handler;
/**
* @var array parameter-value pairs to override default session cookie parameters that are used for session_set_cookie_params() function
* Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httpOnly'
* Array may have the following possible keys: 'lifetime', 'path', 'domain', 'secure', 'httponly'
* @see http://www.php.net/manual/en/function.session-set-cookie-params.php
*/
private $_cookieParams = ['httpOnly' => true];
private $_cookieParams = ['httponly' => true];
/**
* Initializes the application component.
......@@ -301,20 +301,14 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
*/
public function getCookieParams()
{
$params = session_get_cookie_params();
if (isset($params['httponly'])) {
$params['httpOnly'] = $params['httponly'];
unset($params['httponly']);
}
return array_merge($params, $this->_cookieParams);
return array_merge(session_get_cookie_params(), array_change_key_case($this->_cookieParams));
}
/**
* Sets the session cookie parameters.
* The cookie parameters passed to this method will be merged with the result
* of `session_get_cookie_params()`.
* @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httpOnly`.
* @param array $value cookie parameters, valid keys include: `lifetime`, `path`, `domain`, `secure` and `httponly`.
* @throws InvalidParamException if the parameters are incomplete.
* @see http://us2.php.net/manual/en/function.session-set-cookie-params.php
*/
......@@ -333,10 +327,10 @@ class Session extends Component implements \IteratorAggregate, \ArrayAccess, \Co
{
$data = $this->getCookieParams();
extract($data);
if (isset($lifetime, $path, $domain, $secure, $httpOnly)) {
session_set_cookie_params($lifetime, $path, $domain, $secure, $httpOnly);
if (isset($lifetime, $path, $domain, $secure, $httponly)) {
session_set_cookie_params($lifetime, $path, $domain, $secure, $httponly);
} else {
throw new InvalidParamException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httpOnly.');
throw new InvalidParamException('Please make sure cookieParams contains these elements: lifetime, path, domain, secure and httponly.');
}
}
......
......@@ -8,6 +8,7 @@ namespace yii\widgets;
use Yii;
use yii\base\Component;
use yii\base\ErrorHandler;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\base\Model;
......@@ -140,8 +141,7 @@ class ActiveField extends Component
try {
return $this->render();
} catch (\Exception $e) {
trigger_error($e->getMessage() . "\n\n" . $e->getTraceAsString());
ErrorHandler::convertExceptionToError($e);
return '';
}
}
......
......@@ -17,7 +17,7 @@ class Category extends ActiveRecord
{
public static function tableName()
{
return 'tbl_category';
return 'category';
}
public function getItems()
......
......@@ -25,7 +25,7 @@ class Customer extends ActiveRecord
public static function tableName()
{
return 'tbl_customer';
return 'customer';
}
public function getProfile()
......@@ -49,9 +49,9 @@ class Customer extends ActiveRecord
/** @var ActiveQuery $rel */
$rel = $this->hasMany(Item::className(), ['id' => 'item_id']);
return $rel->viaTable('tbl_order_item', ['order_id' => 'id'], function ($q) {
return $rel->viaTable('order_item', ['order_id' => 'id'], function ($q) {
/** @var ActiveQuery $q */
$q->viaTable('tbl_order', ['customer_id' => 'id']);
$q->viaTable('order', ['customer_id' => 'id']);
})->orderBy('id');
}
......
......@@ -13,7 +13,7 @@ class Item extends ActiveRecord
{
public static function tableName()
{
return 'tbl_item';
return 'item';
}
public function getCategory()
......
......@@ -15,6 +15,6 @@ class NullValues extends ActiveRecord
{
public static function tableName()
{
return 'tbl_null_values';
return 'null_values';
}
}
......@@ -14,7 +14,7 @@ class Order extends ActiveRecord
{
public static function tableName()
{
return 'tbl_order';
return 'order';
}
public function getCustomer()
......@@ -59,7 +59,7 @@ class Order extends ActiveRecord
public function getBooks()
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->viaTable('tbl_order_item', ['order_id' => 'id'])
->viaTable('order_item', ['order_id' => 'id'])
->where(['category_id' => 1]);
}
......@@ -67,7 +67,7 @@ class Order extends ActiveRecord
{
return $this->hasMany(Item::className(), ['id' => 'item_id'])
->onCondition(['category_id' => 1])
->viaTable('tbl_order_item', ['order_id' => 'id']);
->viaTable('order_item', ['order_id' => 'id']);
}
public function beforeSave($insert)
......
......@@ -14,7 +14,7 @@ class OrderItem extends ActiveRecord
{
public static function tableName()
{
return 'tbl_order_item';
return 'order_item';
}
public function getOrder()
......
......@@ -16,6 +16,6 @@ class Profile extends ActiveRecord
{
public static function tableName()
{
return 'tbl_profile';
return 'profile';
}
}
......@@ -3,7 +3,7 @@
namespace yiiunit\data\ar;
/**
* Model representing tbl_type table
* Model representing type table
*
* @property int $int_col
* @property int $int_col2 DEFAULT 1
......@@ -25,7 +25,7 @@ class Type extends ActiveRecord
*/
public static function tableName()
{
return 'tbl_type';
return 'type';
}
}
\ No newline at end of file
......@@ -59,7 +59,7 @@ class Order extends ActiveRecord
// public function getBooks()
// {
// return $this->hasMany('Item', ['id' => 'item_id'])
// ->viaTable('tbl_order_item', ['order_id' => 'id'])
// ->viaTable('order_item', ['order_id' => 'id'])
// ->where(['category_id' => 1]);
// }
......
......@@ -3,31 +3,31 @@
* The database setup in config.php is required to perform then relevant tests:
*/
DROP TABLE IF EXISTS tbl_composite_fk;
DROP TABLE IF EXISTS tbl_order_item;
DROP TABLE IF EXISTS tbl_item;
DROP TABLE IF EXISTS tbl_order;
DROP TABLE IF EXISTS tbl_category;
DROP TABLE IF EXISTS tbl_customer;
DROP TABLE IF EXISTS tbl_profile;
DROP TABLE IF EXISTS tbl_null_values;
DROP TABLE IF EXISTS tbl_type;
DROP TABLE IF EXISTS tbl_constraints;
CREATE TABLE `tbl_constraints`
DROP TABLE IF EXISTS `composite_fk`;
DROP TABLE IF EXISTS `order_item`;
DROP TABLE IF EXISTS `item`;
DROP TABLE IF EXISTS `order`;
DROP TABLE IF EXISTS `category`;
DROP TABLE IF EXISTS `customer`;
DROP TABLE IF EXISTS `profile`;
DROP TABLE IF EXISTS `null_values`;
DROP TABLE IF EXISTS `type`;
DROP TABLE IF EXISTS `constraints`;
CREATE TABLE `constraints`
(
`id` integer not null,
`field1` varchar(255)
);
CREATE TABLE `tbl_profile` (
CREATE TABLE `profile` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`description` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tbl_customer` (
CREATE TABLE `customer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(128) NOT NULL,
`name` varchar(128),
......@@ -37,40 +37,40 @@ CREATE TABLE `tbl_customer` (
PRIMARY KEY (`id`)
);
CREATE TABLE `tbl_category` (
CREATE TABLE `category` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE `tbl_item` (
CREATE TABLE `item` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_item_category_id` FOREIGN KEY (`category_id`) REFERENCES `tbl_category` (`id`) ON DELETE CASCADE
CONSTRAINT `FK_item_category_id` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ON DELETE CASCADE
);
CREATE TABLE `tbl_order` (
CREATE TABLE `order` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`customer_id` int(11) NOT NULL,
`created_at` int(11) NOT NULL,
`total` decimal(10,0) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_order_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `tbl_customer` (`id`) ON DELETE CASCADE
CONSTRAINT `FK_order_customer_id` FOREIGN KEY (`customer_id`) REFERENCES `customer` (`id`) ON DELETE CASCADE
);
CREATE TABLE `tbl_order_item` (
CREATE TABLE `order_item` (
`order_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
`subtotal` decimal(10,0) NOT NULL,
PRIMARY KEY (`order_id`,`item_id`),
CONSTRAINT `FK_order_item_order_id` FOREIGN KEY (`order_id`) REFERENCES `tbl_order` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_order_item_item_id` FOREIGN KEY (`item_id`) REFERENCES `tbl_item` (`id`) ON DELETE CASCADE
CONSTRAINT `FK_order_item_order_id` FOREIGN KEY (`order_id`) REFERENCES `order` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_order_item_item_id` FOREIGN KEY (`item_id`) REFERENCES `item` (`id`) ON DELETE CASCADE
);
CREATE TABLE tbl_null_values (
CREATE TABLE null_values (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`var1` INT NULL,
`var2` INT NULL,
......@@ -80,7 +80,7 @@ CREATE TABLE tbl_null_values (
);
CREATE TABLE `tbl_type` (
CREATE TABLE `type` (
`int_col` int(11) NOT NULL,
`int_col2` int(11) DEFAULT '1',
`char_col` char(100) NOT NULL,
......@@ -96,37 +96,37 @@ CREATE TABLE `tbl_type` (
`bool_col2` tinyint DEFAULT '1'
);
CREATE TABLE `tbl_composite_fk` (
CREATE TABLE `composite_fk` (
`id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `tbl_order_item` (`order_id`,`item_id`) ON DELETE CASCADE
CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `order_item` (`order_id`,`item_id`) ON DELETE CASCADE
);
INSERT INTO tbl_profile (description) VALUES ('profile customer 1');
INSERT INTO tbl_profile (description) VALUES ('profile customer 3');
INSERT INTO `profile` (description) VALUES ('profile customer 1');
INSERT INTO `profile` (description) VALUES ('profile customer 3');
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO tbl_customer (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO `customer` (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO `customer` (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO `customer` (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO tbl_category (name) VALUES ('Books');
INSERT INTO tbl_category (name) VALUES ('Movies');
INSERT INTO `category` (name) VALUES ('Books');
INSERT INTO `category` (name) VALUES ('Movies');
INSERT INTO tbl_item (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Cars', 2);
INSERT INTO `item` (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO `item` (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO `item` (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO `item` (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO `item` (name, category_id) VALUES ('Cars', 2);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO `order` (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO `order` (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO `order` (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO `order_item` (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
IF OBJECT_ID('[dbo].[tbl_order_item]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_order_item];
IF OBJECT_ID('[dbo].[tbl_item]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_item];
IF OBJECT_ID('[dbo].[tbl_order]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_order];
IF OBJECT_ID('[dbo].[tbl_category]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_category];
IF OBJECT_ID('[dbo].[tbl_customer]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_customer];
IF OBJECT_ID('[dbo].[tbl_profile]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_profile];
IF OBJECT_ID('[dbo].[tbl_type]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_type];
IF OBJECT_ID('[dbo].[tbl_null_values]', 'U') IS NOT NULL DROP TABLE [dbo].[tbl_null_values];
IF OBJECT_ID('[dbo].[order_item]', 'U') IS NOT NULL DROP TABLE [dbo].[order_item];
IF OBJECT_ID('[dbo].[item]', 'U') IS NOT NULL DROP TABLE [dbo].[item];
IF OBJECT_ID('[dbo].[order]', 'U') IS NOT NULL DROP TABLE [dbo].[order];
IF OBJECT_ID('[dbo].[category]', 'U') IS NOT NULL DROP TABLE [dbo].[category];
IF OBJECT_ID('[dbo].[customer]', 'U') IS NOT NULL DROP TABLE [dbo].[customer];
IF OBJECT_ID('[dbo].[profile]', 'U') IS NOT NULL DROP TABLE [dbo].[profile];
IF OBJECT_ID('[dbo].[type]', 'U') IS NOT NULL DROP TABLE [dbo].[type];
IF OBJECT_ID('[dbo].[null_values]', 'U') IS NOT NULL DROP TABLE [dbo].[null_values];
CREATE TABLE [dbo].[tbl_profile] (
CREATE TABLE [dbo].[profile] (
[id] [int] IDENTITY(1,1) NOT NULL,
[description] [varchar](128) NOT NULL,
CONSTRAINT [PK_customer] PRIMARY KEY CLUSTERED (
......@@ -15,7 +15,7 @@ CREATE TABLE [dbo].[tbl_profile] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_customer] (
CREATE TABLE [dbo].[customer] (
[id] [int] IDENTITY(1,1) NOT NULL,
[email] [varchar](128) NOT NULL,
[name] [varchar](128),
......@@ -27,7 +27,7 @@ CREATE TABLE [dbo].[tbl_customer] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_category] (
CREATE TABLE [dbo].[category] (
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](128) NOT NULL,
CONSTRAINT [PK_category] PRIMARY KEY CLUSTERED (
......@@ -35,7 +35,7 @@ CREATE TABLE [dbo].[tbl_category] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_item] (
CREATE TABLE [dbo].[item] (
[id] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](128) NOT NULL,
[category_id] [int] NOT NULL,
......@@ -44,7 +44,7 @@ CREATE TABLE [dbo].[tbl_item] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_order] (
CREATE TABLE [dbo].[order] (
[id] [int] IDENTITY(1,1) NOT NULL,
[customer_id] [int] NOT NULL,
[created_at] [int] NOT NULL,
......@@ -54,7 +54,7 @@ CREATE TABLE [dbo].[tbl_order] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_order_item] (
CREATE TABLE [dbo].[order_item] (
[order_id] [int] NOT NULL,
[item_id] [int] NOT NULL,
[quantity] [int] NOT NULL,
......@@ -65,7 +65,7 @@ CREATE TABLE [dbo].[tbl_order_item] (
) ON [PRIMARY]
);
CREATE TABLE [dbo].[tbl_null_values] (
CREATE TABLE [dbo].[null_values] (
id [int] UNSIGNED NOT NULL,
var1 [int] UNSIGNED NULL,
var2 [int] NULL,
......@@ -74,7 +74,7 @@ CREATE TABLE [dbo].[tbl_null_values] (
PRIMARY KEY (id)
);
CREATE TABLE [dbo].[tbl_type] (
CREATE TABLE [dbo].[type] (
[int_col] [int] NOT NULL,
[int_col2] [int] DEFAULT '1',
[char_col] [char](100) NOT NULL,
......@@ -89,29 +89,29 @@ CREATE TABLE [dbo].[tbl_type] (
[bool_col2] [tinyint] DEFAULT '1'
);
INSERT INTO [dbo].[tbl_profile] ([description]) VALUES ('profile customer 1');
INSERT INTO [dbo].[tbl_profile] ([description]) VALUES ('profile customer 3');
INSERT INTO [dbo].[profile] ([description]) VALUES ('profile customer 1');
INSERT INTO [dbo].[profile] ([description]) VALUES ('profile customer 3');
INSERT INTO [dbo].[tbl_customer] ([email], [name], [address], [status], [profile_id]) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO [dbo].[tbl_customer] ([email], [name], [address], [status]) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO [dbo].[tbl_customer] ([email], [name], [address], [status], [profile_id]) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO [dbo].[customer] ([email], [name], [address], [status], [profile_id]) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO [dbo].[customer] ([email], [name], [address], [status]) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO [dbo].[customer] ([email], [name], [address], [status], [profile_id]) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO [dbo].[tbl_category] ([name]) VALUES ('Books');
INSERT INTO [dbo].[tbl_category] ([name]) VALUES ('Movies');
INSERT INTO [dbo].[category] ([name]) VALUES ('Books');
INSERT INTO [dbo].[category] ([name]) VALUES ('Movies');
INSERT INTO [dbo].[tbl_item] ([name], [category_id]) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO [dbo].[tbl_item] ([name], [category_id]) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO [dbo].[tbl_item] ([name], [category_id]) VALUES ('Ice Age', 2);
INSERT INTO [dbo].[tbl_item] ([name], [category_id]) VALUES ('Toy Story', 2);
INSERT INTO [dbo].[tbl_item] ([name], [category_id]) VALUES ('Cars', 2);
INSERT INTO [dbo].[item] ([name], [category_id]) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO [dbo].[item] ([name], [category_id]) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO [dbo].[item] ([name], [category_id]) VALUES ('Ice Age', 2);
INSERT INTO [dbo].[item] ([name], [category_id]) VALUES ('Toy Story', 2);
INSERT INTO [dbo].[item] ([name], [category_id]) VALUES ('Cars', 2);
INSERT INTO [dbo].[tbl_order] ([customer_id], [created_at], [total]) VALUES (1, 1325282384, 110.0);
INSERT INTO [dbo].[tbl_order] ([customer_id], [created_at], [total]) VALUES (2, 1325334482, 33.0);
INSERT INTO [dbo].[tbl_order] ([customer_id], [created_at], [total]) VALUES (2, 1325502201, 40.0);
INSERT INTO [dbo].[order] ([customer_id], [created_at], [total]) VALUES (1, 1325282384, 110.0);
INSERT INTO [dbo].[order] ([customer_id], [created_at], [total]) VALUES (2, 1325334482, 33.0);
INSERT INTO [dbo].[order] ([customer_id], [created_at], [total]) VALUES (2, 1325502201, 40.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (1, 1, 1, 30.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (1, 2, 2, 40.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 4, 1, 10.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 5, 1, 15.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 3, 1, 8.0);
INSERT INTO [dbo].[tbl_order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (3, 2, 1, 40.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (1, 1, 1, 30.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (1, 2, 2, 40.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 4, 1, 10.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 5, 1, 15.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (2, 3, 1, 8.0);
INSERT INTO [dbo].[order_item] ([order_id], [item_id], [quantity], [subtotal]) VALUES (3, 2, 1, 40.0);
......@@ -4,28 +4,28 @@
* and create an account 'postgres/postgres' which owns this test database.
*/
DROP TABLE IF EXISTS tbl_order_item CASCADE;
DROP TABLE IF EXISTS tbl_item CASCADE;
DROP TABLE IF EXISTS tbl_order CASCADE;
DROP TABLE IF EXISTS tbl_category CASCADE;
DROP TABLE IF EXISTS tbl_customer CASCADE;
DROP TABLE IF EXISTS tbl_profile CASCADE;
DROP TABLE IF EXISTS tbl_type CASCADE;
DROP TABLE IF EXISTS tbl_null_values CASCADE;
DROP TABLE IF EXISTS tbl_constraints CASCADE;
CREATE TABLE tbl_constraints
DROP TABLE IF EXISTS "order_item" CASCADE;
DROP TABLE IF EXISTS "item" CASCADE;
DROP TABLE IF EXISTS "order" CASCADE;
DROP TABLE IF EXISTS "category" CASCADE;
DROP TABLE IF EXISTS "customer" CASCADE;
DROP TABLE IF EXISTS "profile" CASCADE;
DROP TABLE IF EXISTS "type" CASCADE;
DROP TABLE IF EXISTS "null_values" CASCADE;
DROP TABLE IF EXISTS "constraints" CASCADE;
CREATE TABLE "constraints"
(
id integer not null,
field1 varchar(255)
);
CREATE TABLE tbl_profile (
CREATE TABLE "profile" (
id serial not null primary key,
description varchar(128) NOT NULL
);
CREATE TABLE tbl_customer (
CREATE TABLE "customer" (
id serial not null primary key,
email varchar(128) NOT NULL,
name varchar(128),
......@@ -34,35 +34,35 @@ CREATE TABLE tbl_customer (
profile_id integer
);
comment on column public.tbl_customer.email is 'someone@example.com';
comment on column public.customer.email is 'someone@example.com';
CREATE TABLE tbl_category (
CREATE TABLE "category" (
id serial not null primary key,
name varchar(128) NOT NULL
);
CREATE TABLE tbl_item (
CREATE TABLE "item" (
id serial not null primary key,
name varchar(128) NOT NULL,
category_id integer NOT NULL references tbl_category(id) on UPDATE CASCADE on DELETE CASCADE
category_id integer NOT NULL references "category"(id) on UPDATE CASCADE on DELETE CASCADE
);
CREATE TABLE tbl_order (
CREATE TABLE "order" (
id serial not null primary key,
customer_id integer NOT NULL references tbl_customer(id) on UPDATE CASCADE on DELETE CASCADE,
customer_id integer NOT NULL references "customer"(id) on UPDATE CASCADE on DELETE CASCADE,
created_at integer NOT NULL,
total decimal(10,0) NOT NULL
);
CREATE TABLE tbl_order_item (
order_id integer NOT NULL references tbl_order(id) on UPDATE CASCADE on DELETE CASCADE,
item_id integer NOT NULL references tbl_item(id) on UPDATE CASCADE on DELETE CASCADE,
CREATE TABLE "order_item" (
order_id integer NOT NULL references "order"(id) on UPDATE CASCADE on DELETE CASCADE,
item_id integer NOT NULL references "item"(id) on UPDATE CASCADE on DELETE CASCADE,
quantity integer NOT NULL,
subtotal decimal(10,0) NOT NULL,
PRIMARY KEY (order_id,item_id)
);
CREATE TABLE tbl_null_values (
CREATE TABLE "null_values" (
id INT NOT NULL,
var1 INT NULL,
var2 INT NULL,
......@@ -71,7 +71,7 @@ CREATE TABLE tbl_null_values (
PRIMARY KEY (id)
);
CREATE TABLE tbl_type (
CREATE TABLE "type" (
int_col integer NOT NULL,
int_col2 integer DEFAULT '1',
char_col char(100) NOT NULL,
......@@ -86,58 +86,58 @@ CREATE TABLE tbl_type (
bool_col2 smallint DEFAULT '1'
);
INSERT INTO tbl_profile (description) VALUES ('profile customer 1');
INSERT INTO tbl_profile (description) VALUES ('profile customer 3');
INSERT INTO "profile" (description) VALUES ('profile customer 1');
INSERT INTO "profile" (description) VALUES ('profile customer 3');
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO tbl_customer (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO "customer" (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO "customer" (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO "customer" (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO tbl_category (name) VALUES ('Books');
INSERT INTO tbl_category (name) VALUES ('Movies');
INSERT INTO "category" (name) VALUES ('Books');
INSERT INTO "category" (name) VALUES ('Movies');
INSERT INTO tbl_item (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Cars', 2);
INSERT INTO "item" (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO "item" (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO "item" (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO "item" (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO "item" (name, category_id) VALUES ('Cars', 2);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
/**
* (Postgres-)Database Schema for validator tests
*/
DROP TABLE IF EXISTS tbl_validator_main CASCADE;
DROP TABLE IF EXISTS tbl_validator_ref CASCADE;
DROP TABLE IF EXISTS "validator_main" CASCADE;
DROP TABLE IF EXISTS "validator_ref" CASCADE;
CREATE TABLE tbl_validator_main (
CREATE TABLE "validator_main" (
id integer not null primary key,
field1 VARCHAR(255)
);
CREATE TABLE tbl_validator_ref (
CREATE TABLE "validator_ref" (
id integer not null primary key,
a_field VARCHAR(255),
ref integer
);
INSERT INTO tbl_validator_main (id, field1) VALUES (1, 'just a string1');
INSERT INTO tbl_validator_main (id, field1) VALUES (2, 'just a string2');
INSERT INTO tbl_validator_main (id, field1) VALUES (3, 'just a string3');
INSERT INTO tbl_validator_main (id, field1) VALUES (4, 'just a string4');
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (6, 'ref_to_5', 5);
INSERT INTO "validator_main" (id, field1) VALUES (1, 'just a string1');
INSERT INTO "validator_main" (id, field1) VALUES (2, 'just a string2');
INSERT INTO "validator_main" (id, field1) VALUES (3, 'just a string3');
INSERT INTO "validator_main" (id, field1) VALUES (4, 'just a string4');
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (6, 'ref_to_5', 5);
......@@ -3,23 +3,23 @@
* The database setup in config.php is required to perform then relevant tests:
*/
DROP TABLE IF EXISTS tbl_composite_fk;
DROP TABLE IF EXISTS tbl_order_item;
DROP TABLE IF EXISTS tbl_item;
DROP TABLE IF EXISTS tbl_order;
DROP TABLE IF EXISTS tbl_category;
DROP TABLE IF EXISTS tbl_customer;
DROP TABLE IF EXISTS tbl_profile;
DROP TABLE IF EXISTS tbl_type;
DROP TABLE IF EXISTS tbl_null_values;
CREATE TABLE tbl_profile (
DROP TABLE IF EXISTS "composite_fk";
DROP TABLE IF EXISTS "order_item";
DROP TABLE IF EXISTS "item";
DROP TABLE IF EXISTS "order";
DROP TABLE IF EXISTS "category";
DROP TABLE IF EXISTS "customer";
DROP TABLE IF EXISTS "profile";
DROP TABLE IF EXISTS "type";
DROP TABLE IF EXISTS "null_values";
CREATE TABLE "profile" (
id INTEGER NOT NULL,
description varchar(128) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tbl_customer (
CREATE TABLE "customer" (
id INTEGER NOT NULL,
email varchar(128) NOT NULL,
name varchar(128),
......@@ -29,20 +29,20 @@ CREATE TABLE tbl_customer (
PRIMARY KEY (id)
);
CREATE TABLE tbl_category (
CREATE TABLE "category" (
id INTEGER NOT NULL,
name varchar(128) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tbl_item (
CREATE TABLE "item" (
id INTEGER NOT NULL,
name varchar(128) NOT NULL,
category_id INTEGER NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE tbl_order (
CREATE TABLE "order" (
id INTEGER NOT NULL,
customer_id INTEGER NOT NULL,
created_at INTEGER NOT NULL,
......@@ -50,7 +50,7 @@ CREATE TABLE tbl_order (
PRIMARY KEY (id)
);
CREATE TABLE tbl_order_item (
CREATE TABLE "order_item" (
order_id INTEGER NOT NULL,
item_id INTEGER NOT NULL,
quantity INTEGER NOT NULL,
......@@ -58,15 +58,15 @@ CREATE TABLE tbl_order_item (
PRIMARY KEY (order_id, item_id)
);
CREATE TABLE `tbl_composite_fk` (
`id` int(11) NOT NULL,
`order_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `FK_composite_fk_order_item` FOREIGN KEY (`order_id`,`item_id`) REFERENCES `tbl_order_item` (`order_id`,`item_id`) ON DELETE CASCADE
CREATE TABLE "composite_fk" (
id int(11) NOT NULL,
order_id int(11) NOT NULL,
item_id int(11) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT FK_composite_fk_order_item FOREIGN KEY (order_id, item_id) REFERENCES "order_item" (order_id, item_id) ON DELETE CASCADE
);
CREATE TABLE tbl_null_values (
CREATE TABLE "null_values" (
id INTEGER UNSIGNED PRIMARY KEY NOT NULL,
var1 INTEGER UNSIGNED,
var2 INTEGER,
......@@ -74,7 +74,7 @@ CREATE TABLE tbl_null_values (
stringcol VARCHAR(32) DEFAULT NULL
);
CREATE TABLE tbl_type (
CREATE TABLE "type" (
int_col INTEGER NOT NULL,
int_col2 INTEGER DEFAULT '1',
char_col char(100) NOT NULL,
......@@ -89,58 +89,58 @@ CREATE TABLE tbl_type (
bool_col2 tinyint(1) DEFAULT '1'
);
INSERT INTO tbl_profile (description) VALUES ('profile customer 1');
INSERT INTO tbl_profile (description) VALUES ('profile customer 3');
INSERT INTO "profile" (description) VALUES ('profile customer 1');
INSERT INTO "profile" (description) VALUES ('profile customer 3');
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO tbl_customer (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO tbl_customer (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO "customer" (email, name, address, status, profile_id) VALUES ('user1@example.com', 'user1', 'address1', 1, 1);
INSERT INTO "customer" (email, name, address, status) VALUES ('user2@example.com', 'user2', 'address2', 1);
INSERT INTO "customer" (email, name, address, status, profile_id) VALUES ('user3@example.com', 'user3', 'address3', 2, 2);
INSERT INTO tbl_category (name) VALUES ('Books');
INSERT INTO tbl_category (name) VALUES ('Movies');
INSERT INTO "category" (name) VALUES ('Books');
INSERT INTO "category" (name) VALUES ('Movies');
INSERT INTO tbl_item (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO tbl_item (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO tbl_item (name, category_id) VALUES ('Cars', 2);
INSERT INTO "item" (name, category_id) VALUES ('Agile Web Application Development with Yii1.1 and PHP5', 1);
INSERT INTO "item" (name, category_id) VALUES ('Yii 1.1 Application Development Cookbook', 1);
INSERT INTO "item" (name, category_id) VALUES ('Ice Age', 2);
INSERT INTO "item" (name, category_id) VALUES ('Toy Story', 2);
INSERT INTO "item" (name, category_id) VALUES ('Cars', 2);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO tbl_order (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (1, 1325282384, 110.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (2, 1325334482, 33.0);
INSERT INTO "order" (customer_id, created_at, total) VALUES (2, 1325502201, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO tbl_order_item (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (1, 1, 1, 30.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (1, 2, 2, 40.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 4, 1, 10.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 5, 1, 15.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (2, 3, 1, 8.0);
INSERT INTO "order_item" (order_id, item_id, quantity, subtotal) VALUES (3, 2, 1, 40.0);
/**
* (SqLite-)Database Schema for validator tests
*/
DROP TABLE IF EXISTS tbl_validator_main;
DROP TABLE IF EXISTS tbl_validator_ref;
DROP TABLE IF EXISTS "validator_main";
DROP TABLE IF EXISTS "validator_ref";
CREATE TABLE tbl_validator_main (
CREATE TABLE "validator_main" (
id INTEGER PRIMARY KEY ,
field1 VARCHAR(255)
);
CREATE TABLE tbl_validator_ref (
CREATE TABLE "validator_ref" (
id INTEGER PRIMARY KEY ,
a_field VARCHAR(255),
ref INT(11)
);
INSERT INTO tbl_validator_main (id, field1) VALUES (1, 'just a string1');
INSERT INTO tbl_validator_main (id, field1) VALUES (2, 'just a string2');
INSERT INTO tbl_validator_main (id, field1) VALUES (3, 'just a string3');
INSERT INTO tbl_validator_main (id, field1) VALUES (4, 'just a string4');
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO tbl_validator_ref (id, a_field, ref) VALUES (6, 'ref_to_5', 5);
INSERT INTO "validator_main" (id, field1) VALUES (1, 'just a string1');
INSERT INTO "validator_main" (id, field1) VALUES (2, 'just a string2');
INSERT INTO "validator_main" (id, field1) VALUES (3, 'just a string3');
INSERT INTO "validator_main" (id, field1) VALUES (4, 'just a string4');
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (1, 'ref_to_2', 2);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (2, 'ref_to_2', 2);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (3, 'ref_to_3', 3);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (4, 'ref_to_4', 4);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (5, 'ref_to_4', 4);
INSERT INTO "validator_ref" (id, a_field, ref) VALUES (6, 'ref_to_5', 5);
......@@ -10,7 +10,7 @@ class ValidatorTestMainModel extends ActiveRecord
public static function tableName()
{
return 'tbl_validator_main';
return 'validator_main';
}
public function getReferences()
......
......@@ -12,7 +12,7 @@ class ValidatorTestRefModel extends ActiveRecord
public static function tableName()
{
return 'tbl_validator_ref';
return 'validator_ref';
}
public function getMain()
......
......@@ -102,8 +102,8 @@ class ActiveRecordTest extends ElasticSearchTestCase
$customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2], false);
$customer->save(false);
// INSERT INTO tbl_category (name) VALUES ('Books');
// INSERT INTO tbl_category (name) VALUES ('Movies');
// INSERT INTO category (name) VALUES ('Books');
// INSERT INTO category (name) VALUES ('Movies');
$item = new Item();
$item->id = 1;
......
......@@ -71,8 +71,8 @@ class ActiveRecordTest extends RedisTestCase
$customer->setAttributes(['email' => 'user3@example.com', 'name' => 'user3', 'address' => 'address3', 'status' => 2, 'profile_id' => 2], false);
$customer->save(false);
// INSERT INTO tbl_category (name) VALUES ('Books');
// INSERT INTO tbl_category (name) VALUES ('Movies');
// INSERT INTO category (name) VALUES ('Books');
// INSERT INTO category (name) VALUES ('Movies');
$item = new Item();
$item->setAttributes(['name' => 'Agile Web Application Development with Yii1.1 and PHP5', 'category_id' => 1], false);
......
......@@ -28,8 +28,8 @@ class QueryTest extends SphinxTestCase
public function testFrom()
{
$query = new Query;
$query->from('tbl_user');
$this->assertEquals(['tbl_user'], $query->from);
$query->from('user');
$this->assertEquals(['user'], $query->from);
}
public function testMatch()
......
......@@ -269,19 +269,6 @@ class FormatterTest extends TestCase
$dateThen = new DateTime('2014-02-28');
$this->assertSame('a month ago', $this->formatter->asRelativeTime($dateThen, $dateNow));
// Relative to current time tests (can't test with seconds though due to the tests computation time)
$this->assertSame('4 minutes ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_244_seconds])));
$this->assertSame('a minute ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_minute])));
$this->assertSame('33 minutes ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_33_minutes])));
$this->assertSame('an hour ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_hour])));
$this->assertSame('6 hours ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_6_hours])));
$this->assertSame('a day ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_day])));
$this->assertSame('2 months ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_89_days])));
$this->assertSame('a month ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_month])));
$this->assertSame('5 months ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_5_months])));
$this->assertSame('a year ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_year])));
$this->assertSame('12 years ago', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_12_years])));
// Invert all the DateIntervals
$interval_1_second->invert = true;
$interval_244_seconds->invert = true;
......@@ -334,21 +321,5 @@ class FormatterTest extends TestCase
$dateThen = new DateTime('2014-03-31');
$this->assertSame('in a month', $this->formatter->asRelativeTime($this->buildDateSubIntervals('2014-03-03', [$interval_1_month]), $dateNow));
$this->assertSame('in 28 days', $this->formatter->asRelativeTime($dateThen, $dateNow));
// Relative to current time tests (can't test with seconds though due to the tests computation time)
// We add 5 seconds to compensate for tests computation time
$interval_5_seconds = new DateInterval('PT5S');
$interval_5_seconds->invert = true;
$this->assertSame('in 4 minutes', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_244_seconds, $interval_5_seconds])));
$this->assertSame('in a minute', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_minute, $interval_5_seconds])));
$this->assertSame('in 33 minutes', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_33_minutes, $interval_5_seconds])));
$this->assertSame('in an hour', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_hour, $interval_5_seconds])));
$this->assertSame('in 6 hours', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_6_hours, $interval_5_seconds])));
$this->assertSame('in a day', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_day, $interval_5_seconds])));
$this->assertSame('in 2 months', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_89_days, $interval_5_seconds])));
$this->assertSame('in a month', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_month, $interval_5_seconds])));
$this->assertSame('in 5 months', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_5_months, $interval_5_seconds])));
$this->assertSame('in a year', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_1_year, $interval_5_seconds])));
$this->assertSame('in 12 years', $this->formatter->asRelativeTime($this->buildDateSubIntervals('now', [$interval_12_years, $interval_5_seconds])));
}
}
......@@ -23,7 +23,7 @@ class DbCacheTest extends CacheTestCase
parent::setUp();
$this->getConnection()->createCommand("
CREATE TABLE IF NOT EXISTS tbl_cache (
CREATE TABLE IF NOT EXISTS cache (
id char(128) NOT NULL,
expire int(11) DEFAULT NULL,
data LONGBLOB,
......
......@@ -126,7 +126,7 @@ class ActiveDataProviderTest extends DatabaseTestCase
$query = new Query;
$provider = new ActiveDataProvider([
'db' => $this->getConnection(),
'query' => $query->from('tbl_order')->orderBy('id'),
'query' => $query->from('order')->orderBy('id'),
]);
$orders = $provider->getModels();
$this->assertEquals(3, count($orders));
......@@ -136,7 +136,7 @@ class ActiveDataProviderTest extends DatabaseTestCase
$query = new Query;
$provider = new ActiveDataProvider([
'db' => $this->getConnection(),
'query' => $query->from('tbl_order'),
'query' => $query->from('order'),
'pagination' => [
'pageSize' => 2,
]
......@@ -150,7 +150,7 @@ class ActiveDataProviderTest extends DatabaseTestCase
$query = new Query;
$provider = new ActiveDataProvider([
'db' => $this->getConnection(),
'query' => $query->from('tbl_order')->orderBy('id'),
'query' => $query->from('order')->orderBy('id'),
]);
$this->assertEquals(3, count($provider->getModels()));
......@@ -165,7 +165,7 @@ class ActiveDataProviderTest extends DatabaseTestCase
$query = new Query;
$provider = new ActiveDataProvider([
'db' => $this->getConnection(),
'query' => $query->from('tbl_order')->orderBy('id'),
'query' => $query->from('order')->orderBy('id'),
]);
$pagination = $provider->getPagination();
$this->assertEquals(0, $pagination->getPageCount());
......
......@@ -104,16 +104,16 @@ class ActiveRecordTest extends DatabaseTestCase
public function testFindBySql()
{
// find one
$customer = Customer::findBySql('SELECT * FROM tbl_customer ORDER BY id DESC')->one();
$customer = Customer::findBySql('SELECT * FROM customer ORDER BY id DESC')->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals('user3', $customer->name);
// find all
$customers = Customer::findBySql('SELECT * FROM tbl_customer')->all();
$customers = Customer::findBySql('SELECT * FROM customer')->all();
$this->assertEquals(3, count($customers));
// find with parameter binding
$customer = Customer::findBySql('SELECT * FROM tbl_customer WHERE id=:id', [':id' => 2])->one();
$customer = Customer::findBySql('SELECT * FROM customer WHERE id=:id', [':id' => 2])->one();
$this->assertTrue($customer instanceof Customer);
$this->assertEquals('user2', $customer->name);
}
......@@ -269,7 +269,7 @@ class ActiveRecordTest extends DatabaseTestCase
public function testJoinWith()
{
// left join and eager loading
$orders = Order::find()->joinWith('customer')->orderBy('tbl_customer.id DESC, tbl_order.id')->all();
$orders = Order::find()->joinWith('customer')->orderBy('customer.id DESC, order.id')->all();
$this->assertEquals(3, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertEquals(3, $orders[1]->id);
......@@ -281,9 +281,9 @@ class ActiveRecordTest extends DatabaseTestCase
// inner join filtering and eager loading
$orders = Order::find()->innerJoinWith([
'customer' => function ($query) {
$query->where('tbl_customer.id=2');
$query->where('customer.id=2');
},
])->orderBy('tbl_order.id')->all();
])->orderBy('order.id')->all();
$this->assertEquals(2, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertEquals(3, $orders[1]->id);
......@@ -293,9 +293,9 @@ class ActiveRecordTest extends DatabaseTestCase
// inner join filtering, eager loading, conditions on both primary and relation
$orders = Order::find()->innerJoinWith([
'customer' => function ($query) {
$query->where(['tbl_customer.id' => 2]);
$query->where(['customer.id' => 2]);
},
])->where(['tbl_order.id' => [1, 2]])->orderBy('tbl_order.id')->all();
])->where(['order.id' => [1, 2]])->orderBy('order.id')->all();
$this->assertEquals(1, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertTrue($orders[0]->isRelationPopulated('customer'));
......@@ -303,9 +303,9 @@ class ActiveRecordTest extends DatabaseTestCase
// inner join filtering without eager loading
$orders = Order::find()->innerJoinWith([
'customer' => function ($query) {
$query->where('tbl_customer.id=2');
$query->where('customer.id=2');
},
], false)->orderBy('tbl_order.id')->all();
], false)->orderBy('order.id')->all();
$this->assertEquals(2, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertEquals(3, $orders[1]->id);
......@@ -315,15 +315,15 @@ class ActiveRecordTest extends DatabaseTestCase
// inner join filtering without eager loading, conditions on both primary and relation
$orders = Order::find()->innerJoinWith([
'customer' => function ($query) {
$query->where(['tbl_customer.id' => 2]);
$query->where(['customer.id' => 2]);
},
], false)->where(['tbl_order.id' => [1, 2]])->orderBy('tbl_order.id')->all();
], false)->where(['order.id' => [1, 2]])->orderBy('order.id')->all();
$this->assertEquals(1, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertFalse($orders[0]->isRelationPopulated('customer'));
// join with via-relation
$orders = Order::find()->innerJoinWith('books')->orderBy('tbl_order.id')->all();
$orders = Order::find()->innerJoinWith('books')->orderBy('order.id')->all();
$this->assertEquals(2, count($orders));
$this->assertEquals(1, $orders[0]->id);
$this->assertEquals(3, $orders[1]->id);
......@@ -335,12 +335,12 @@ class ActiveRecordTest extends DatabaseTestCase
// join with sub-relation
$orders = Order::find()->innerJoinWith([
'items' => function ($q) {
$q->orderBy('tbl_item.id');
$q->orderBy('item.id');
},
'items.category' => function ($q) {
$q->where('tbl_category.id = 2');
$q->where('category.id = 2');
},
])->orderBy('tbl_order.id')->all();
])->orderBy('order.id')->all();
$this->assertEquals(1, count($orders));
$this->assertTrue($orders[0]->isRelationPopulated('items'));
$this->assertEquals(2, $orders[0]->id);
......@@ -351,9 +351,9 @@ class ActiveRecordTest extends DatabaseTestCase
// join with table alias
$orders = Order::find()->joinWith([
'customer' => function ($q) {
$q->from('tbl_customer c');
$q->from('customer c');
}
])->orderBy('c.id DESC, tbl_order.id')->all();
])->orderBy('c.id DESC, order.id')->all();
$this->assertEquals(3, count($orders));
$this->assertEquals(2, $orders[0]->id);
$this->assertEquals(3, $orders[1]->id);
......@@ -363,7 +363,7 @@ class ActiveRecordTest extends DatabaseTestCase
$this->assertTrue($orders[2]->isRelationPopulated('customer'));
// join with ON condition
$orders = Order::find()->joinWith('books2')->orderBy('tbl_order.id')->all();
$orders = Order::find()->joinWith('books2')->orderBy('order.id')->all();
$this->assertEquals(3, count($orders));
$this->assertEquals(1, $orders[0]->id);
$this->assertEquals(2, $orders[1]->id);
......@@ -411,22 +411,22 @@ class ActiveRecordTest extends DatabaseTestCase
$this->assertEquals(1, $customer->id);
$order = Order::find()->joinWith([
'items' => function ($q) {
$q->from(['items' => 'tbl_item'])
$q->from(['items' => 'item'])
->orderBy('items.id');
},
])->orderBy('tbl_order.id')->one();
])->orderBy('order.id')->one();
}
public function testJoinWithAndScope()
{
// hasOne inner join
$customers = Customer::find()->active()->innerJoinWith('profile')->orderBy('tbl_customer.id')->all();
$customers = Customer::find()->active()->innerJoinWith('profile')->orderBy('customer.id')->all();
$this->assertEquals(1, count($customers));
$this->assertEquals(1, $customers[0]->id);
$this->assertTrue($customers[0]->isRelationPopulated('profile'));
// hasOne outer join
$customers = Customer::find()->active()->joinWith('profile')->orderBy('tbl_customer.id')->all();
$customers = Customer::find()->active()->joinWith('profile')->orderBy('customer.id')->all();
$this->assertEquals(2, count($customers));
$this->assertEquals(1, $customers[0]->id);
$this->assertEquals(2, $customers[1]->id);
......@@ -438,9 +438,9 @@ class ActiveRecordTest extends DatabaseTestCase
// hasMany
$customers = Customer::find()->active()->joinWith([
'orders' => function ($q) {
$q->orderBy('tbl_order.id');
$q->orderBy('order.id');
}
])->orderBy('tbl_customer.id DESC, tbl_order.id')->all();
])->orderBy('customer.id DESC, order.id')->all();
$this->assertEquals(2, count($customers));
$this->assertEquals(2, $customers[0]->id);
$this->assertEquals(1, $customers[1]->id);
......
......@@ -31,7 +31,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// initialize property test
$query = new Query();
$query->from('tbl_customer')->orderBy('id');
$query->from('customer')->orderBy('id');
$result = $query->batch(2, $db);
$this->assertTrue($result instanceof BatchQueryResult);
$this->assertEquals(2, $result->batchSize);
......@@ -39,7 +39,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// normal query
$query = new Query();
$query->from('tbl_customer')->orderBy('id');
$query->from('customer')->orderBy('id');
$allRows = [];
$batch = $query->batch(2, $db);
foreach ($batch as $rows) {
......@@ -60,7 +60,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// empty query
$query = new Query();
$query->from('tbl_customer')->where(['id' => 100]);
$query->from('customer')->where(['id' => 100]);
$allRows = [];
$batch = $query->batch(2, $db);
foreach ($batch as $rows) {
......@@ -70,7 +70,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// query with index
$query = new Query();
$query->from('tbl_customer')->indexBy('name');
$query->from('customer')->indexBy('name');
$allRows = [];
foreach ($query->batch(2, $db) as $rows) {
$allRows = array_merge($allRows, $rows);
......@@ -82,7 +82,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// each
$query = new Query();
$query->from('tbl_customer')->orderBy('id');
$query->from('customer')->orderBy('id');
$allRows = [];
foreach ($query->each(100, $db) as $rows) {
$allRows[] = $rows;
......@@ -94,7 +94,7 @@ class BatchQueryResultTest extends DatabaseTestCase
// each with key
$query = new Query();
$query->from('tbl_customer')->orderBy('id')->indexBy('name');
$query->from('customer')->orderBy('id')->indexBy('name');
$allRows = [];
foreach ($query->each(100, $db) as $key => $row) {
$allRows[$key] = $row;
......
......@@ -19,7 +19,7 @@ class CommandTest extends DatabaseTestCase
$this->assertEquals(null, $command->sql);
// string
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$command = $db->createCommand($sql);
$this->assertEquals($sql, $command->sql);
}
......@@ -28,11 +28,11 @@ class CommandTest extends DatabaseTestCase
{
$db = $this->getConnection(false);
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$command = $db->createCommand($sql);
$this->assertEquals($sql, $command->sql);
$sql2 = 'SELECT * FROM tbl_order';
$sql2 = 'SELECT * FROM order';
$command->sql = $sql2;
$this->assertEquals($sql2, $command->sql);
}
......@@ -41,16 +41,16 @@ class CommandTest extends DatabaseTestCase
{
$db = $this->getConnection(false);
$sql = 'SELECT [[id]], [[t.name]] FROM {{tbl_customer}} t';
$sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t';
$command = $db->createCommand($sql);
$this->assertEquals("SELECT `id`, `t`.`name` FROM `tbl_customer` t", $command->sql);
$this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql);
}
public function testPrepareCancel()
{
$db = $this->getConnection(false);
$command = $db->createCommand('SELECT * FROM tbl_customer');
$command = $db->createCommand('SELECT * FROM customer');
$this->assertEquals(null, $command->pdoStatement);
$command->prepare();
$this->assertNotEquals(null, $command->pdoStatement);
......@@ -62,11 +62,11 @@ class CommandTest extends DatabaseTestCase
{
$db = $this->getConnection();
$sql = 'INSERT INTO tbl_customer(email, name , address) VALUES (\'user4@example.com\', \'user4\', \'address4\')';
$sql = 'INSERT INTO customer(email, name , address) VALUES (\'user4@example.com\', \'user4\', \'address4\')';
$command = $db->createCommand($sql);
$this->assertEquals(1, $command->execute());
$sql = 'SELECT COUNT(*) FROM tbl_customer WHERE name =\'user4\'';
$sql = 'SELECT COUNT(*) FROM customer WHERE name =\'user4\'';
$command = $db->createCommand($sql);
$this->assertEquals(1, $command->queryScalar());
......@@ -80,55 +80,55 @@ class CommandTest extends DatabaseTestCase
$db = $this->getConnection();
// query
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$reader = $db->createCommand($sql)->query();
$this->assertTrue($reader instanceof DataReader);
// queryAll
$rows = $db->createCommand('SELECT * FROM tbl_customer')->queryAll();
$rows = $db->createCommand('SELECT * FROM customer')->queryAll();
$this->assertEquals(3, count($rows));
$row = $rows[2];
$this->assertEquals(3, $row['id']);
$this->assertEquals('user3', $row['name']);
$rows = $db->createCommand('SELECT * FROM tbl_customer WHERE id=10')->queryAll();
$rows = $db->createCommand('SELECT * FROM customer WHERE id=10')->queryAll();
$this->assertEquals([], $rows);
// queryOne
$sql = 'SELECT * FROM tbl_customer ORDER BY id';
$sql = 'SELECT * FROM customer ORDER BY id';
$row = $db->createCommand($sql)->queryOne();
$this->assertEquals(1, $row['id']);
$this->assertEquals('user1', $row['name']);
$sql = 'SELECT * FROM tbl_customer ORDER BY id';
$sql = 'SELECT * FROM customer ORDER BY id';
$command = $db->createCommand($sql);
$command->prepare();
$row = $command->queryOne();
$this->assertEquals(1, $row['id']);
$this->assertEquals('user1', $row['name']);
$sql = 'SELECT * FROM tbl_customer WHERE id=10';
$sql = 'SELECT * FROM customer WHERE id=10';
$command = $db->createCommand($sql);
$this->assertFalse($command->queryOne());
// queryColumn
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$column = $db->createCommand($sql)->queryColumn();
$this->assertEquals(range(1, 3), $column);
$command = $db->createCommand('SELECT id FROM tbl_customer WHERE id=10');
$command = $db->createCommand('SELECT id FROM customer WHERE id=10');
$this->assertEquals([], $command->queryColumn());
// queryScalar
$sql = 'SELECT * FROM tbl_customer ORDER BY id';
$sql = 'SELECT * FROM customer ORDER BY id';
$this->assertEquals($db->createCommand($sql)->queryScalar(), 1);
$sql = 'SELECT id FROM tbl_customer ORDER BY id';
$sql = 'SELECT id FROM customer ORDER BY id';
$command = $db->createCommand($sql);
$command->prepare();
$this->assertEquals(1, $command->queryScalar());
$command = $db->createCommand('SELECT id FROM tbl_customer WHERE id=10');
$command = $db->createCommand('SELECT id FROM customer WHERE id=10');
$this->assertFalse($command->queryScalar());
$command = $db->createCommand('bad SQL');
......@@ -141,7 +141,7 @@ class CommandTest extends DatabaseTestCase
$db = $this->getConnection();
// bindParam
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, :name, :address)';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, :name, :address)';
$command = $db->createCommand($sql);
$email = 'user4@example.com';
$name = 'user4';
......@@ -151,12 +151,12 @@ class CommandTest extends DatabaseTestCase
$command->bindParam(':address', $address);
$command->execute();
$sql = 'SELECT name FROM tbl_customer WHERE email=:email';
$sql = 'SELECT name FROM customer WHERE email=:email';
$command = $db->createCommand($sql);
$command->bindParam(':email', $email);
$this->assertEquals($name, $command->queryScalar());
$sql = 'INSERT INTO tbl_type (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, :blob_col, :numeric_col, :bool_col)';
$sql = 'INSERT INTO type (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, :blob_col, :numeric_col, :bool_col)';
$command = $db->createCommand($sql);
$intCol = 123;
$charCol = 'abc';
......@@ -172,7 +172,7 @@ class CommandTest extends DatabaseTestCase
$command->bindParam(':bool_col', $boolCol);
$this->assertEquals(1, $command->execute());
$sql = 'SELECT * FROM tbl_type';
$sql = 'SELECT * FROM type';
$row = $db->createCommand($sql)->queryOne();
$this->assertEquals($intCol, $row['int_col']);
$this->assertEquals($charCol, $row['char_col']);
......@@ -181,12 +181,12 @@ class CommandTest extends DatabaseTestCase
$this->assertEquals($numericCol, $row['numeric_col']);
// bindValue
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$command = $db->createCommand($sql);
$command->bindValue(':email', 'user5@example.com');
$command->execute();
$sql = 'SELECT email FROM tbl_customer WHERE name=:name';
$sql = 'SELECT email FROM customer WHERE name=:name';
$command = $db->createCommand($sql);
$command->bindValue(':name', 'user5');
$this->assertEquals('user5@example.com', $command->queryScalar());
......@@ -197,20 +197,20 @@ class CommandTest extends DatabaseTestCase
$db = $this->getConnection();
// default: FETCH_ASSOC
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$command = $db->createCommand($sql);
$result = $command->queryOne();
$this->assertTrue(is_array($result) && isset($result['id']));
// FETCH_OBJ, customized via fetchMode property
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$command = $db->createCommand($sql);
$command->fetchMode = \PDO::FETCH_OBJ;
$result = $command->queryOne();
$this->assertTrue(is_object($result));
// FETCH_NUM, customized in query method
$sql = 'SELECT * FROM tbl_customer';
$sql = 'SELECT * FROM customer';
$command = $db->createCommand($sql);
$result = $command->queryOne([], \PDO::FETCH_NUM);
$this->assertTrue(is_array($result) && isset($result[0]));
......@@ -219,7 +219,7 @@ class CommandTest extends DatabaseTestCase
public function testBatchInsert()
{
$command = $this->getConnection()->createCommand();
$command->batchInsert('tbl_customer',
$command->batchInsert('customer',
['email', 'name', 'address'], [
['t1@example.com', 't1', 't1 address'],
['t2@example.com', null, false],
......
......@@ -115,7 +115,7 @@ class QueryBuilderTest extends DatabaseTestCase
public function testAddDropPrimaryKey()
{
$tableName = 'tbl_constraints';
$tableName = 'constraints';
$pkeyName = $tableName . "_pkey";
// ADD
......
......@@ -29,8 +29,8 @@ class QueryTest extends DatabaseTestCase
public function testFrom()
{
$query = new Query;
$query->from('tbl_user');
$this->assertEquals(['tbl_user'], $query->from);
$query->from('user');
$this->assertEquals(['user'], $query->from);
}
public function testWhere()
......@@ -185,10 +185,10 @@ class QueryTest extends DatabaseTestCase
{
$db = $this->getConnection();
$result = (new Query)->from('tbl_customer')->where(['status' => 2])->one($db);
$result = (new Query)->from('customer')->where(['status' => 2])->one($db);
$this->assertEquals('user3', $result['name']);
$result = (new Query)->from('tbl_customer')->where(['status' => 3])->one($db);
$result = (new Query)->from('customer')->where(['status' => 3])->one($db);
$this->assertFalse($result);
}
}
......@@ -17,12 +17,12 @@ class SchemaTest extends DatabaseTestCase
$schema = $this->getConnection()->schema;
$tables = $schema->getTableNames();
$this->assertTrue(in_array('tbl_customer', $tables));
$this->assertTrue(in_array('tbl_category', $tables));
$this->assertTrue(in_array('tbl_item', $tables));
$this->assertTrue(in_array('tbl_order', $tables));
$this->assertTrue(in_array('tbl_order_item', $tables));
$this->assertTrue(in_array('tbl_type', $tables));
$this->assertTrue(in_array('customer', $tables));
$this->assertTrue(in_array('category', $tables));
$this->assertTrue(in_array('item', $tables));
$this->assertTrue(in_array('order', $tables));
$this->assertTrue(in_array('order_item', $tables));
$this->assertTrue(in_array('type', $tables));
}
public function testGetTableSchemas()
......@@ -49,8 +49,8 @@ class SchemaTest extends DatabaseTestCase
$schema->db->enableSchemaCache = true;
$schema->db->schemaCache = new FileCache();
$noCacheTable = $schema->getTableSchema('tbl_type', true);
$cachedTable = $schema->getTableSchema('tbl_type', true);
$noCacheTable = $schema->getTableSchema('type', true);
$cachedTable = $schema->getTableSchema('type', true);
$this->assertEquals($noCacheTable, $cachedTable);
}
......@@ -59,11 +59,11 @@ class SchemaTest extends DatabaseTestCase
/** @var Schema $schema */
$schema = $this->getConnection()->schema;
$table = $schema->getTableSchema('tbl_composite_fk');
$table = $schema->getTableSchema('composite_fk');
$this->assertCount(1, $table->foreignKeys);
$this->assertTrue(isset($table->foreignKeys[0]));
$this->assertEquals('tbl_order_item', $table->foreignKeys[0][0]);
$this->assertEquals('order_item', $table->foreignKeys[0][0]);
$this->assertEquals('order_id', $table->foreignKeys[0]['order_id']);
$this->assertEquals('item_id', $table->foreignKeys[0]['item_id']);
}
......
......@@ -16,7 +16,7 @@ class CubridCommandTest extends CommandTest
$db = $this->getConnection();
// bindParam
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, :name, :address)';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, :name, :address)';
$command = $db->createCommand($sql);
$email = 'user4@example.com';
$name = 'user4';
......@@ -26,12 +26,12 @@ class CubridCommandTest extends CommandTest
$command->bindParam(':address', $address);
$command->execute();
$sql = 'SELECT name FROM tbl_customer WHERE email=:email';
$sql = 'SELECT name FROM customer WHERE email=:email';
$command = $db->createCommand($sql);
$command->bindParam(':email', $email);
$this->assertEquals($name, $command->queryScalar());
$sql = "INSERT INTO tbl_type (int_col, char_col, char_col2, enum_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, '', :char_col, :enum_col, :float_col, CHAR_TO_BLOB(:blob_col), :numeric_col, :bool_col)";
$sql = "INSERT INTO type (int_col, char_col, char_col2, enum_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, '', :char_col, :enum_col, :float_col, CHAR_TO_BLOB(:blob_col), :numeric_col, :bool_col)";
$command = $db->createCommand($sql);
$intCol = 123;
$charCol = 'abc';
......@@ -49,7 +49,7 @@ class CubridCommandTest extends CommandTest
$command->bindParam(':bool_col', $boolCol);
$this->assertEquals(1, $command->execute());
$sql = 'SELECT * FROM tbl_type';
$sql = 'SELECT * FROM type';
$row = $db->createCommand($sql)->queryOne();
$this->assertEquals($intCol, $row['int_col']);
$this->assertEquals($enumCol, $row['enum_col']);
......@@ -60,12 +60,12 @@ class CubridCommandTest extends CommandTest
$this->assertEquals($boolCol, $row['bool_col']);
// bindValue
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$command = $db->createCommand($sql);
$command->bindValue(':email', 'user5@example.com');
$command->execute();
$sql = 'SELECT email FROM tbl_customer WHERE name=:name';
$sql = 'SELECT email FROM customer WHERE name=:name';
$command = $db->createCommand($sql);
$command->bindValue(':name', 'user5');
$this->assertEquals('user5@example.com', $command->queryScalar());
......@@ -75,8 +75,8 @@ class CubridCommandTest extends CommandTest
{
$db = $this->getConnection(false);
$sql = 'SELECT [[id]], [[t.name]] FROM {{tbl_customer}} t';
$sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t';
$command = $db->createCommand($sql);
$this->assertEquals('SELECT "id", "t"."name" FROM "tbl_customer" t', $command->sql);
$this->assertEquals('SELECT "id", "t"."name" FROM "customer" t', $command->sql);
}
}
......@@ -16,9 +16,9 @@ class MssqlCommandTest extends CommandTest
{
$db = $this->getConnection(false);
$sql = 'SELECT [[id]], [[t.name]] FROM {{tbl_customer}} t';
$sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t';
$command = $db->createCommand($sql);
$this->assertEquals("SELECT [id], [t].[name] FROM [tbl_customer] t", $command->sql);
$this->assertEquals("SELECT [id], [t].[name] FROM [customer] t", $command->sql);
}
public function testPrepareCancel()
......@@ -31,7 +31,7 @@ class MssqlCommandTest extends CommandTest
$db = $this->getConnection();
// bindParam
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, :name, :address)';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, :name, :address)';
$command = $db->createCommand($sql);
$email = 'user4@example.com';
$name = 'user4';
......@@ -41,12 +41,12 @@ class MssqlCommandTest extends CommandTest
$command->bindParam(':address', $address);
$command->execute();
$sql = 'SELECT name FROM tbl_customer WHERE email=:email';
$sql = 'SELECT name FROM customer WHERE email=:email';
$command = $db->createCommand($sql);
$command->bindParam(':email', $email);
$this->assertEquals($name, $command->queryScalar());
$sql = 'INSERT INTO tbl_type (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, CONVERT([varbinary], :blob_col), :numeric_col, :bool_col)';
$sql = 'INSERT INTO type (int_col, char_col, float_col, blob_col, numeric_col, bool_col) VALUES (:int_col, :char_col, :float_col, CONVERT([varbinary], :blob_col), :numeric_col, :bool_col)';
$command = $db->createCommand($sql);
$intCol = 123;
$charCol = 'abc';
......@@ -62,7 +62,7 @@ class MssqlCommandTest extends CommandTest
$command->bindParam(':bool_col', $boolCol);
$this->assertEquals(1, $command->execute());
$sql = 'SELECT int_col, char_col, float_col, CONVERT([nvarchar], blob_col) AS blob_col, numeric_col FROM tbl_type';
$sql = 'SELECT int_col, char_col, float_col, CONVERT([nvarchar], blob_col) AS blob_col, numeric_col FROM type';
$row = $db->createCommand($sql)->queryOne();
$this->assertEquals($intCol, $row['int_col']);
$this->assertEquals($charCol, trim($row['char_col']));
......@@ -71,12 +71,12 @@ class MssqlCommandTest extends CommandTest
$this->assertEquals($numericCol, $row['numeric_col']);
// bindValue
$sql = 'INSERT INTO tbl_customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$sql = 'INSERT INTO customer(email, name, address) VALUES (:email, \'user5\', \'address5\')';
$command = $db->createCommand($sql);
$command->bindValue(':email', 'user5@example.com');
$command->execute();
$sql = 'SELECT email FROM tbl_customer WHERE name=:name';
$sql = 'SELECT email FROM customer WHERE name=:name';
$command = $db->createCommand($sql);
$command->bindValue(':name', 'user5');
$this->assertEquals('user5@example.com', $command->queryScalar());
......
......@@ -15,8 +15,8 @@ class SqliteCommandTest extends CommandTest
{
$db = $this->getConnection(false);
$sql = 'SELECT [[id]], [[t.name]] FROM {{tbl_customer}} t';
$sql = 'SELECT [[id]], [[t.name]] FROM {{customer}} t';
$command = $db->createCommand($sql);
$this->assertEquals("SELECT `id`, `t`.`name` FROM `tbl_customer` t", $command->sql);
$this->assertEquals("SELECT `id`, `t`.`name` FROM `customer` t", $command->sql);
}
}
......@@ -84,7 +84,7 @@ class SqliteQueryBuilderTest extends QueryBuilderTest
public function testBatchInsert()
{
$sql = $this->getQueryBuilder()->batchInsert('{{tbl_customer}} t', ['t.id', 't.name'], [[1, 'a'], [2, 'b']]);
$this->assertEquals("INSERT INTO {{tbl_customer}} t (`t`.`id`, `t`.`name`) SELECT 1, 'a' UNION SELECT 2, 'b'", $sql);
$sql = $this->getQueryBuilder()->batchInsert('{{customer}} t', ['t.id', 't.name'], [[1, 'a'], [2, 'b']]);
$this->assertEquals("INSERT INTO {{customer}} t (`t`.`id`, `t`.`name`) SELECT 1, 'a' UNION SELECT 2, 'b'", $sql);
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment