Commit 876973a8 authored by hansbrix's avatar hansbrix

html->wiki conversion script

parent c4ca5964
......@@ -2,12 +2,14 @@
Doctrine_Db_Profiler is an eventlistener for Doctrine_Db. It provides flexible query profiling. Besides the sql strings
the query profiles include elapsed time to run the queries. This allows inspection of the queries that have been performed without the
need for adding extra debugging code to model classes.
<br \><br \>
Doctrine_Db_Profiler can be enabled by adding it as an eventlistener for Doctrine_Db.
<br \><br \>
<?php
renderCode("<?php
?>");
?>
<code type="php">
?></code>
[<b>Note</b>: The term 'Transaction' doesnt refer to database transactions here but to the general meaning of this term]<br />
[<b>Note</b>: This component is in <b>Alpha State</b>]<br />
<br />
[**Note**: The term 'Transaction' doesnt refer to database transactions here but to the general meaning of this term]
[**Note**: This component is in **Alpha State**]
Locking is a mechanism to control concurrency. The two most well known locking strategies
are optimistic and pessimistic locking. The following is a short description of these
two strategies from which only pessimistic locking is currently supported by Doctrine.<br />
<br />
<b>Optimistic Locking:</b><br />
two strategies from which only pessimistic locking is currently supported by Doctrine.
**Optimistic Locking:**
The state/version of the object(s) is noted when the transaction begins.
When the transaction finishes the noted state/version of the participating objects is compared
to the current state/version. When the states/versions differ the objects have been modified
by another transaction and the current transaction should fail.
This approach is called 'optimistic' because it is assumed that it is unlikely that several users
will participate in transactions on the same objects at the same time.<br />
<br />
<b>Pessimistic Locking:</b><br />
will participate in transactions on the same objects at the same time.
**Pessimistic Locking:**
The objects that need to participate in the transaction are locked at the moment
the user starts the transaction. No other user can start a transaction that operates on these objects
while the locks are active. This ensures that the user who starts the transaction can be sure that
noone else modifies the same objects until he has finished his work.<br />
<br />
noone else modifies the same objects until he has finished his work.
Doctrine's pessimistic offline locking capabilities can be used to control concurrency during actions or procedures
that take several HTTP request and response cycles and/or a lot of time to complete.
Roman Borschel - romanb at #doctrine (freenode)<br />
Roman Borschel - romanb at #doctrine (freenode)
Don't hesitate to contact me if you have questions, ideas, ect.
......@@ -3,16 +3,22 @@ You can think of this validation as a gateway that needs to be passed right befo
persistent data store. The definition of these business rules takes place at the record level, that means
in your active record model classes (classes derived from Doctrine_Record).
The first thing you need to do to be able to use this kind of validation is to enable it globally.
This is done through the Doctrine_Manager (see the code below).<br />
<br />
Once you enabled validation, you'll get a bunch of validations automatically:<br />
<br />
This is done through the Doctrine_Manager (see the code below).
Once you enabled validation, you'll get a bunch of validations automatically:
- Data type validations: All values assigned to columns are checked for the right type. That means
if you specified a column of your record as type 'integer', Doctrine will validate that
any values assigned to that column are of this type. This kind of type validation tries to
be as smart as possible since PHP is a loosely typed language. For example 2 as well as "7"
are both valid integers whilst "3f" is not. Type validations occur on every column (since every
column definition needs a type).<br /><br />
column definition needs a type).
- Length validation: As the name implies, all values assigned to columns are validated to make
sure that the value does not exceed the maximum length.
......
The type and length validations are handy but most of the time they're not enough. Therefore
Doctrine provides some mechanisms that can be used to validate your data in more detail.<br />
<br />
Doctrine provides some mechanisms that can be used to validate your data in more detail.
Validators: Validators are an easy way to specify further validations. Doctrine has a lot of predefined
validators that are frequently needed such as email, country, ip, range and regexp validators. You
find a full list of available validators at the bottom of this page. You can specify which validators
apply to which column through the 4th argument of the hasColumn() method.
If that is still not enough and you need some specialized validation that is not yet available as
a predefined validator you have three options:<br />
<br />
- You can write the validator on your own.<br />
- You can propose your need for a new validator to a Doctrine developer.<br />
- You can use validation hooks.<br />
<br />
a predefined validator you have three options:
- You can write the validator on your own.
- You can propose your need for a new validator to a Doctrine developer.
- You can use validation hooks.
The first two options are advisable if it is likely that the validation is of general use
and is potentially applicable in many situations. In that case it is a good idea to implement
a new validator. However if the validation is special it is better to use hooks provided by Doctrine:<br />
<br />
- validate() (Executed every time the record gets validated)<br />
- validateOnInsert() (Executed when the record is new and gets validated)<br />
- validateOnUpdate() (Executed when the record is not new and gets validated)<br />
<br />
a new validator. However if the validation is special it is better to use hooks provided by Doctrine:
- validate() (Executed every time the record gets validated)
- validateOnInsert() (Executed when the record is new and gets validated)
- validateOnUpdate() (Executed when the record is not new and gets validated)
If you need a special validation in your active record
you can simply override one of these methods in your active record class (a descendant of Doctrine_Record).
Within thess methods you can use all the power of PHP to validate your fields. When a field
doesnt pass your validation you can then add errors to the record's error stack.
The following code snippet shows an example of how to define validators together with custom
validation:<br />
validation:
<code type="php">
class User extends Doctrine_Record {
......
Now that you know how to specify your business rules in your models, it is time to look at how to
deal with these rules in the rest of your application.<br />
<br />
Implicit validation:<br />
deal with these rules in the rest of your application.
Implicit validation:
Whenever a record is going to be saved to the persistent data store (i.e. through calling $record->save())
the full validation procedure is executed. If errors occur during that process an exception of the type
Doctrine_Validator_Exception will be thrown. You can catch that exception and analyze the errors by
......@@ -10,15 +13,20 @@ an ordinary array with references to all records that did not pass validation. Y
further explore the errors of each record by analyzing the error stack of each record.
The error stack of a record can be obtained with the instance method Doctrine_Record::getErrorStack().
Each error stack is an instance of the class Doctrine_Validator_ErrorStack. The error stack
provides an easy to use interface to inspect the errors.<br />
<br />
Explicit validation:<br />
provides an easy to use interface to inspect the errors.
Explicit validation:
You can explicitly trigger the validation for any record at any time. For this purpose Doctrine_Record
provides the instance method Doctrine_Record::isValid(). This method returns a boolean value indicating
the result of the validation. If the method returns FALSE, you can inspect the error stack in the same
way as seen above except that no exception is thrown, so you simply obtain
the error stack of the record that didnt pass validation through Doctrine_Record::getErrorStack().<br />
<br />
the error stack of the record that didnt pass validation through Doctrine_Record::getErrorStack().
The following code snippet shows an example of handling implicit validation which caused a Doctrine_Validator_Exception.
<code type="php">
......
There are couple of availible Cache attributes on Doctrine:
<ul>
<li \>Doctrine::ATTR_CACHE_SIZE
<ul>
<li \> Defines which cache container Doctrine uses
<li \> Possible values: Doctrine::CACHE_* (for example Doctrine::CACHE_FILE)
</ul>
<li \>Doctrine::ATTR_CACHE_DIR
<ul>
<li \> cache directory where .cache files are saved
<li \> the default cache dir is %ROOT%/cachedir, where
* Doctrine::ATTR_CACHE_SIZE
* Defines which cache container Doctrine uses
* Possible values: Doctrine::CACHE_* (for example Doctrine::CACHE_FILE)
* Doctrine::ATTR_CACHE_DIR
* cache directory where .cache files are saved
* the default cache dir is %ROOT%/cachedir, where
%ROOT% is automatically converted to doctrine root dir
</ul>
<li \>Doctrine::ATTR_CACHE_SLAM
<ul>
<li \> On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature
</ul>
<li \>Doctrine::ATTR_CACHE_SIZE
<ul>
<li \> Cache size attribute
</ul>
<li \>Doctrine::ATTR_CACHE_TTL
<ul>
<li \> How often the cache is cleaned
</ul>
</ul>
* Doctrine::ATTR_CACHE_SLAM
* On very busy servers whenever you start the server or modify files you can create a race of many processes all trying to cache the same file at the same time. This option sets the percentage of processes that will skip trying to cache an uncached file. Or think of it as the probability of a single process to skip caching. For example, setting apc.slam_defense to 75 would mean that there is a 75% chance that the process will not cache an uncached file. So, the higher the setting the greater the defense against cache slams. Setting this to 0 disables this feature
* Doctrine::ATTR_CACHE_SIZE
* Cache size attribute
* Doctrine::ATTR_CACHE_TTL
* How often the cache is cleaned
Doctrine has very comprehensive and fast caching solution.
Its cache is <b>always up-to-date</b>.
Its cache is **always up-to-date**.
In order to achieve this doctrine does the following things:
<br /><br />
<table border=1 class='dashed' cellpadding=0 cellspacing=0>
<tr><td>
1. Every Doctrine_Table has its own cache directory. The default is cache/componentname/. All the cache files are saved into that directory.
|| 1. Every Doctrine_Table has its own cache directory. The default is cache/componentname/. All the cache files are saved into that directory.
The format of each cache file is [primarykey].cache.
<br /><br />
2. When retrieving records from the database doctrine always tries to hit the cache first.
<br /><br />
3. If a record (Doctrine_Record) is retrieved from database or inserted into database it will be saved into cache.
<br /><br />
4. When a Data Access Object is deleted or updated it will be deleted from the cache
</td></tr>
</table>
<br /><br />
4. When a Data Access Object is deleted or updated it will be deleted from the cache ||
Now one might wonder that this kind of solution won't work since eventually the cache will be a copy of database!
So doctrine does the following things to ensure the cache won't get too big:
<br /><br />
<table border=1 class='dashed' cellpadding=0 cellspacing=0>
<tr><td>
1. Every time a cache file is accessed the id of that record will be added into the $fetched property of Doctrine_Cache
<br /><br />
|| 1. Every time a cache file is accessed the id of that record will be added into the $fetched property of Doctrine_Cache
2. At the end of each script the Doctrine_Cache destructor will write all these primary keys at the end of a stats.cache file
<br /><br />
3. Doctrine does propabalistic cache cleaning. The default interval is 200 page loads (= 200 constructed Doctrine_Managers). Basically this means
that the average number of page loads between cache cleans is 200.
<br /><br />
4. On every cache clean stats.cache files are being read and the least accessed cache files
(cache files that have the smallest id occurance in the stats file) are then deleted.
For example if the cache size is set to 200 and the number of files in cache is 300, then 100 least accessed files are being deleted.
Doctrine also clears every stats.cache file.
Doctrine also clears every stats.cache file. ||
</td></tr>
</table>
<br /><br />
So for every 199 fast page loads there is one page load which suffers a little overhead from the cache cleaning operation.
Doctrine_Cache offers many options for performance fine-tuning:
<ul>
<li \> savePropability <br \>
* savePropability
Option that defines the propability of which
a query is getting cached.
<br \><br \>
<li \> cleanPropability <br \>
* cleanPropability
Option that defines the propability the actual cleaning will occur
when calling Doctrine_Cache::clean();
<br \><br \>
<li \> statsPropability
* statsPropability
<ul \>
<?php ?>
Doctrine_Cache offers an intuitive and easy-to-use query caching solution. It provides the following things:
<ul>
<li \> Multiple cache backends to choose from (including Memcached, APC and Sqlite)
<br \><br \>
<li \> Manual tuning and/or self-optimization. Doctrine_Cache knows how to optimize itself, yet it leaves user
* Multiple cache backends to choose from (including Memcached, APC and Sqlite)
* Manual tuning and/or self-optimization. Doctrine_Cache knows how to optimize itself, yet it leaves user
full freedom of whether or not he/she wants to take advantage of this feature.
<br \><br \>
<li \> Advanced options for fine-tuning. Doctrine_Cache has many options for fine-tuning performance.
<br \><br \>
<li \> Cache hooks itself directly into Doctrine_Db eventlistener system allowing it to be easily added on-demand.
</ul>
<br \><br \>
* Advanced options for fine-tuning. Doctrine_Cache has many options for fine-tuning performance.
* Cache hooks itself directly into Doctrine_Db eventlistener system allowing it to be easily added on-demand.
Doctrine_Cache hooks into Doctrine_Db eventlistener system allowing pluggable caching.
It evaluates queries and puts SELECT statements in cache. The caching is based on propabalistics. For example
if savePropability = 0.1 there is a 10% chance that a query gets cached.
<br \><br \>
Now eventually the cache would grow very big, hence Doctrine uses propabalistic cache cleaning.
When calling Doctrine_Cache::clean() with cleanPropability = 0.25 there is a 25% chance of the clean operation being invoked.
What the cleaning does is that it first reads all the queries in the stats file and sorts them by the number of times occurred.
Then if the size is set to 100 it means the cleaning operation will leave 100 most issued queries in cache and delete all other cache entries.
<br \><br \>
<br \><br \>
Initializing a new cache instance:
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$dbh = new Doctrine_Db('mysql:host=localhost;dbname=test', \$user, \$pass);
\$cache = new Doctrine_Cache('memcache');
......@@ -38,8 +53,11 @@ renderCode("<?php
// register it as a Doctrine_Db listener
\$dbh->addListener(\$cache);
?>");
?>
<br \><br \>
?></code>
Now you know how to set up the query cache. In the next chapter you'll learn how to tweak the cache in order to get maximum performance.
<br \><br \>
<ul>
<li \>Negative numbers are not permitted as indices.
</ul>
<ul>
<li \>An indexed array may be started with any non-negative number, however this is discouraged and it is recommended that all arrays have a base index of 0.
</ul>
<ul>
<li \>When declaring indexed arrays with the array construct, a trailing space must be added after each comma delimiter to improve readability.
</ul>
<ul>
<li \>It is also permitted to declare multiline indexed arrays using the "array" construct. In this case, each successive line must be padded with spaces.
</ul>
<ul>
<li \>When declaring associative arrays with the array construct, it is encouraged to break the statement into multiple lines. In this case, each successive line must be padded with whitespace such that both the keys and the values are aligned:
</ul>
* Negative numbers are not permitted as indices.
* An indexed array may be started with any non-negative number, however this is discouraged and it is recommended that all arrays have a base index of 0.
* When declaring indexed arrays with the array construct, a trailing space must be added after each comma delimiter to improve readability.
* It is also permitted to declare multiline indexed arrays using the "array" construct. In this case, each successive line must be padded with spaces.
* When declaring associative arrays with the array construct, it is encouraged to break the statement into multiple lines. In this case, each successive line must be padded with whitespace such that both the keys and the values are aligned:
<code type="php">
$sampleArray = array('Doctrine', 'ORM', 1, 2, 3);
......
<ul>
<li \>Classes must be named by following the naming conventions.
</ul>
<ul>
<li \>The brace is always written right after the class name (or interface declaration).
</ul>
<ul>
<li \>Every class must have a documentation block that conforms to the PHPDocumentor standard.
</ul>
<ul>
<li \>Any code within a class must be indented four spaces.
</ul>
<ul>
<li \>Only one class is permitted per PHP file.
</ul>
<ul>
<li \>Placing additional code in a class file is NOT permitted.
</ul>
* Classes must be named by following the naming conventions.
* The brace is always written right after the class name (or interface declaration).
* Every class must have a documentation block that conforms to the PHPDocumentor standard.
* Any code within a class must be indented four spaces.
* Only one class is permitted per PHP file.
* Placing additional code in a class file is NOT permitted.
This is an example of an acceptable class declaration:
......
<?php ?>
<ul>
<li \>Control statements based on the if and elseif constructs must have a single space before the opening parenthesis of the conditional, and a single space after the closing parenthesis.
</ul>
<ul>
<li \>Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses are encouraged to improve logical grouping of larger conditionals.
</ul>
<ul>
<li \>The opening brace is written on the same line as the conditional statement. The closing brace is always written on its own line. Any content within the braces must be indented four spaces.
</ul>
<?php
renderCode("<?php
* Control statements based on the if and elseif constructs must have a single space before the opening parenthesis of the conditional, and a single space after the closing parenthesis.
* Within the conditional statements between the parentheses, operators must be separated by spaces for readability. Inner parentheses are encouraged to improve logical grouping of larger conditionals.
* The opening brace is written on the same line as the conditional statement. The closing brace is always written on its own line. Any content within the braces must be indented four spaces.
<code type="php">
if (\$foo != 2) {
\$foo = 2;
}");
?>
<ul>
<li \>For "if" statements that include "elseif" or "else", the formatting must be as in these examples:
</ul>
<?php
renderCode("<?php
}</code>
* For "if" statements that include "elseif" or "else", the formatting must be as in these examples:
<code type="php">
if (\$foo != 1) {
\$foo = 1;
} else {
......@@ -30,14 +27,12 @@ if (\$foo != 2) {
\$foo = 3;
} else {
\$foo = 11;
}");
?>
<ul>
<li \>PHP allows for these statements to be written without braces in some circumstances, the following format for if statements is also allowed:
</ul>
<?php
renderCode("<?php
}</code>
* PHP allows for these statements to be written without braces in some circumstances, the following format for if statements is also allowed:
<code type="php">
if (\$foo != 1)
\$foo = 1;
else
......@@ -49,16 +44,14 @@ elseif (\$foo == 1)
\$foo = 3;
else
\$foo = 11;
");
?>
<ul>
<li \>Control statements written with the "switch" construct must have a single space before the opening parenthesis of the conditional statement, and also a single space after the closing parenthesis.
</ul>
<ul>
<li \>All content within the "switch" statement must be indented four spaces. Content under each "case" statement must be indented an additional four spaces but the breaks must be at the same indentation level as the "case" statements.
</ul>
<?php
renderCode("<?php
</code>
* Control statements written with the "switch" construct must have a single space before the opening parenthesis of the conditional statement, and also a single space after the closing parenthesis.
* All content within the "switch" statement must be indented four spaces. Content under each "case" statement must be indented an additional four spaces but the breaks must be at the same indentation level as the "case" statements.
<code type="php">
switch (\$case) {
case 1:
case 2:
......@@ -68,9 +61,8 @@ switch (\$case) {
default:
break;
}
?>");
?>
<ul>
<li \>The construct default may never be omitted from a switch statement.
</ul>
?></code>
* The construct default may never be omitted from a switch statement.
Documentation Format
<ul>
<li \>All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: http://phpdoc.org/
</ul>
* All documentation blocks ("docblocks") must be compatible with the phpDocumentor format. Describing the phpDocumentor format is beyond the scope of this document. For more information, visit: http://phpdoc.org/
Methods:
<ul>
<li \>Every method, must have a docblock that contains at a minimum:
</ul>
<ul>
<li \>A description of the function
</ul>
* Every method, must have a docblock that contains at a minimum:
* A description of the function
* All of the arguments
* All of the possible return values
* It is not necessary to use the "@access" tag because the access level is already known from the "public", "private", or "protected" construct used to declare the function.
<ul>
<li \>All of the arguments
</ul>
<ul>
<li \>All of the possible return values
</ul>
* If a function/method may throw an exception, use @throws:
<ul>
<li \>It is not necessary to use the "@access" tag because the access level is already known from the "public", "private", or "protected" construct used to declare the function.
</ul>
<ul>
<li \>If a function/method may throw an exception, use @throws:
</ul>
* @throws exceptionclass [description]
<ul>
<li \>@throws exceptionclass [description]
</ul>
<ul>
<li \>When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always used to demarcate the string:
</ul>
<ul>
<li \>When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or "double quotes". This is especially encouraged for SQL statements:
</ul>
<ul>
<li \>Variable substitution is permitted using the following form:
</ul>
<ul>
<li \>Strings may be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
</ul>
<ul>
<li \>When concatenating strings with the "." operator, it is permitted to break the statement into multiple lines to improve readability. In these cases, each successive line should be padded with whitespace such that the "."; operator is aligned under the "=" operator:
</ul>
* When a string is literal (contains no variable substitutions), the apostrophe or "single quote" must always used to demarcate the string:
* When a literal string itself contains apostrophes, it is permitted to demarcate the string with quotation marks or "double quotes". This is especially encouraged for SQL statements:
* Variable substitution is permitted using the following form:
* Strings may be concatenated using the "." operator. A space must always be added before and after the "." operator to improve readability:
* When concatenating strings with the "." operator, it is permitted to break the statement into multiple lines to improve readability. In these cases, each successive line should be padded with whitespace such that the "."; operator is aligned under the "=" operator:
<code type="php">
......
<ul>
<li \>The Doctrine ORM Framework uses the same class naming convention as PEAR and Zend framework, where the names of the classes directly
* The Doctrine ORM Framework uses the same class naming convention as PEAR and Zend framework, where the names of the classes directly
map to the directories in which they are stored. The root level directory of the Doctrine Framework is the "Doctrine/" directory,
under which all classes are stored hierarchially.
</ul>
<ul>
<li \>Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged.
* Class names may only contain alphanumeric characters. Numbers are permitted in class names but are discouraged.
Underscores are only permitted in place of the path separator, eg. the filename "Doctrine/Table/Exception.php" must map to the class name "Doctrine_Table_Exception".
</ul>
<ul>
<li \>If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters
* If a class name is comprised of more than one word, the first letter of each new word must be capitalized. Successive capitalized letters
are not allowed, e.g. a class "XML_Reader" is not allowed while "Xml_Reader" is acceptable.
</ul>
Following rules must apply to all constants used within Doctrine framework:
<ul><li \> Constants may contain both alphanumeric characters and the underscore.</ul>
* Constants may contain both alphanumeric characters and the underscore.
<ul><li \> Constants must always have all letters capitalized.</ul>
* Constants must always have all letters capitalized.
* For readablity reasons, words in constant names must be separated by underscore characters. For example, ATTR_EXC_LOGGING is permitted but ATTR_EXCLOGGING is not.
* Constants must be defined as class members by using the "const" construct. Defining constants in the global scope with "define" is NOT permitted.
<ul><li \> For readablity reasons, words in constant names must be separated by underscore characters. For example, ATTR_EXC_LOGGING is permitted but ATTR_EXCLOGGING is not.
</ul>
<ul><li \> Constants must be defined as class members by using the "const" construct. Defining constants in the global scope with "define" is NOT permitted.
</ul>
<code type="php">
class Doctrine_SomeClass {
......
<ul>
<li \>For all other files, only alphanumeric characters, underscores, and the dash character ("-") are permitted. Spaces are prohibited.
</ul>
<ul>
<li \>Any file that contains any PHP code must end with the extension ".php". These examples show the acceptable filenames for containing the class names from the examples in the section above:
<br \> <br \>
Doctrine/Db.php <br \>
<br \>
Doctrine/Connection/Transaction.php <br \>
</ul>
<ul>
<li \>File names must follow the mapping to class names described above.
</ul>
* For all other files, only alphanumeric characters, underscores, and the dash character ("-") are permitted. Spaces are prohibited.
* Any file that contains any PHP code must end with the extension ".php". These examples show the acceptable filenames for containing the class names from the examples in the section above:
Doctrine/Db.php
Doctrine/Connection/Transaction.php
* File names must follow the mapping to class names described above.
<ul>
<li>Function names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in function names but are discouraged.
</ul>
<ul>
<li>Function names must always start with a lowercase letter. When a function name consists of more than one word, the first letter of each new word must be capitalized. This is commonly called the "studlyCaps" or "camelCaps" method.
</ul>
<ul>
<li>Verbosity is encouraged. Function names should be as verbose as is practical to enhance the understandability of code.
</ul>
<ul>
<li>For object-oriented programming, accessors for objects should always be prefixed with either "get" or "set". This applies to all classes except for Doctrine_Record which has some accessor methods prefixed with 'obtain' and 'assign'. The reason
for this is that since all user defined ActiveRecords inherit Doctrine_Record, it should populate the get / set namespace as little as possible.
</ul>
<ul>
<li>Functions in the global scope ("floating functions") are NOT permmitted. All static functions should be wrapped in a static class.
</ul>
<ul>
<li \>Interface classes must follow the same conventions as other classes (see above), however must end with the word "Interface"
* Interface classes must follow the same conventions as other classes (see above), however must end with the word "Interface"
(unless the interface is approved not to contain it such as Doctrine_Overloadable). Some examples:
<br \><br \>
Doctrine_Db_EventListener_Interface <br \>
<br \>
Doctrine_EventListener_Interface <br \>
</ul>
Doctrine_Db_EventListener_Interface
Doctrine_EventListener_Interface
All variables must satisfy the following conditions:
<ul>
<li \>Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged.
</ul>
<ul>
<li \>Variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
</ul>
* Variable names may only contain alphanumeric characters. Underscores are not permitted. Numbers are permitted in variable names but are discouraged.
<ul>
<li \>Verbosity is encouraged. Variables should always be as verbose as practical. Terse variable names such as "$i" and "$n" are discouraged for anything other than the smallest loop contexts. If a loop contains more than 20 lines of code, the variables for the indices need to have more descriptive names.
</ul>
<ul>
<li \>Within the framework certain generic object variables should always use the following names:
<ul>
<li \> Doctrine_Connection -> <i>$conn</i>
<li \> Doctrine_Collection -> <i>$coll</i>
<li \> Doctrine_Manager -> <i>$manager</i>
<li \> Doctrine_Query -> <i>$query</i>
<li \> Doctrine_Db -> <i>$db</i>
* Variable names must always start with a lowercase letter and follow the "camelCaps" capitalization convention.
* Verbosity is encouraged. Variables should always be as verbose as practical. Terse variable names such as "$i" and "$n" are discouraged for anything other than the smallest loop contexts. If a loop contains more than 20 lines of code, the variables for the indices need to have more descriptive names.
* Within the framework certain generic object variables should always use the following names:
* Doctrine_Connection -> //$conn//
* Doctrine_Collection -> //$coll//
* Doctrine_Manager -> //$manager//
* Doctrine_Query -> //$query//
* Doctrine_Db -> //$db//
</ul>
There are cases when more descriptive names are more appropriate (for example when multiple objects of the same class are used in same context),
in that case it is allowed to use different names than the ones mentioned.
</ul>
For files that contain only PHP code, the closing tag ("?>") is never permitted. It is not required by PHP. Not including it prevents trailing whitespace from being accidentally injected into the output.
<br \><br \>
IMPORTANT: Inclusion of arbitrary binary data as permitted by __HALT_COMPILER() is prohibited from any Doctrine framework PHP file or files derived from them. Use of this feature is only permitted for special installation scripts.
<ul>
<li \>Line termination is the standard way for Unix text files. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.
</ul>
<ul>
<li \>Do not use carriage returns (CR) like Macintosh computers (0x0D).
</ul>
<ul>
<li \>Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).
</ul>
* Line termination is the standard way for Unix text files. Lines must end only with a linefeed (LF). Linefeeds are represented as ordinal 10, or hexadecimal 0x0A.
* Do not use carriage returns (CR) like Macintosh computers (0x0D).
* Do not use the carriage return/linefeed combination (CRLF) as Windows computers (0x0D, 0x0A).
<b>CLASSES</b><br \><br \>
<ul>
<li \>
**CLASSES**
*
All test classes should be referring to a class or specific testing aspect of some class.
<br \><br \>
For example <i>Doctrine_Record_TestCase</i> is a valid name since its referring to class named
<i>Doctrine_Record</i>.
<br \><br \>
<i>Doctrine_Record_State_TestCase</i> is also a valid name since its referring to testing the state aspect
For example //Doctrine_Record_TestCase// is a valid name since its referring to class named
//Doctrine_Record//.
//Doctrine_Record_State_TestCase// is also a valid name since its referring to testing the state aspect
of the Doctrine_Record class.
<br \><br \>
However something like <i>Doctrine_PrimaryKey_TestCase</i> is not valid since its way too generic.
<br \><br \>
<li \> Every class should have atleast one TestCase equivalent
<li \> All testcase classes should inherit Doctrine_UnitTestCase
</ul>
<br \><br \>
<b>METHODS</b><br \><br \>
<ul>
<li \>All methods should support agile documentation; if some method failed it should be evident from the name of the test method what went wrong.
Also the test method names should give information of the system they test.<br \><br \>
For example <i>Doctrine_Export_Pgsql_TestCase::testCreateTableSupportsAutoincPks()</i> is a valid test method name. Just by looking at it we know
However something like //Doctrine_PrimaryKey_TestCase// is not valid since its way too generic.
* Every class should have atleast one TestCase equivalent
* All testcase classes should inherit Doctrine_UnitTestCase
**METHODS**
* All methods should support agile documentation; if some method failed it should be evident from the name of the test method what went wrong.
Also the test method names should give information of the system they test.
For example //Doctrine_Export_Pgsql_TestCase::testCreateTableSupportsAutoincPks()// is a valid test method name. Just by looking at it we know
what it is testing. Also we can run agile documentation tool to get little up-to-date system information.
<br \><br \>
NOTE: Commonly used testing method naming convention TestCase::test[methodName] is *NOT* allowed in Doctrine. So in this case
<b class='title'>Doctrine_Export_Pgsql_TestCase::testCreateTable()</b> would not be allowed!
<br \><br \>
<li \>Test method names can often be long. However the content within the methods should rarely be more than dozen lines long. If you need several assert-calls
<b class='title'>Doctrine_Export_Pgsql_TestCase::testCreateTable()** would not be allowed!
* Test method names can often be long. However the content within the methods should rarely be more than dozen lines long. If you need several assert-calls
divide the method into smaller methods.
</ul>
<b>ASSERTIONS</b><br \><br \>
<ul>
<li \>There should never be assertions within any loops and rarely within functions.
**ASSERTIONS**
* There should never be assertions within any loops and rarely within functions.
......@@ -3,19 +3,21 @@ If the same attribute is set on both lower level and upper level, the uppermost
if user first sets default fetchmode in global level to Doctrine::FETCH_BATCH and then sets 'example' table fetchmode to Doctrine::FETCH_LAZY,
the lazy fetching strategy will be used whenever the records of 'example' table are being fetched.
<br \><br \>
<li> Global level
<ul>
The attributes set in global level will affect every connection and every table in each connection.
</ul>
<li> Connection level
<ul>
The attributes set in connection level will take effect on each table in that connection.
</ul>
<li> Table level
<ul>
The attributes set in table level will take effect only on that table.
</ul>
<code type="php">
// setting a global level attribute
......
......@@ -4,48 +4,56 @@ You can quote the db identifiers (table and field names) with quoteIdentifier().
Some of the internal Doctrine methods generate queries. Enabling the "quote_identifier" attribute of Doctrine you can tell Doctrine to quote the identifiers in these generated queries. For all user supplied queries this option is irrelevant.
Portability is broken by using the following characters inside delimited identifiers:
<br \> <br \>
<ul>
<li \>backtick (`) -- due to MySQL
<li \>double quote (") -- due to Oracle
<li \>brackets ([ or ]) -- due to Access
</ul>
* backtick (`) -- due to MySQL
* double quote (") -- due to Oracle
* brackets ([ or ]) -- due to Access
Delimited identifiers are known to generally work correctly under the following drivers:
<br \>
<ul>
<li \>Mssql
<li \>Mysql
<li \>Oracle
<li \>Pgsql
* Mssql
* Mysql
<li \>Sqlite
* Oracle
* Pgsql
* Sqlite
* Firebird
<li \>Firebird
</ul>
When using the quoteIdentifiers option, all of the field identifiers will be automatically quoted in the resulting SQL statements:
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$conn->setAttribute('quote_identifiers', true);
?>");
?>
<br \><br \>
?></code>
will result in a SQL statement that all the field names are quoted with the backtick '`' operator (in MySQL).
<br \>
<div class='sql'>SELECT * FROM `sometable` WHERE `id` = '123'</div>
<br \>
as opposed to:
<br \>
<div class='sql'>SELECT * FROM sometable WHERE id='123'</div>
......@@ -4,26 +4,46 @@ Each database management system (DBMS) has it's own behaviors. For example, some
You control which portability modes are enabled by using the portability configuration option. Configuration options are set via factory() and setOption().
The portability modes are bitwised, so they can be combined using | and removed using ^. See the examples section below on how to do this.
<br \><br \>
Portability Mode Constants
<br \><br \>
<i>Doctrine::PORTABILITY_ALL (default)</i>
<br \><br \>
//Doctrine::PORTABILITY_ALL (default)//
turn on all portability features. this is the default setting.
<br \><br \>
<i>Doctrine::PORTABILITY_DELETE_COUNT</i>
<br \><br \>
//Doctrine::PORTABILITY_DELETE_COUNT//
Force reporting the number of rows deleted. Some DBMS's don't count the number of rows deleted when performing simple DELETE FROM tablename queries. This mode tricks such DBMS's into telling the count by adding WHERE 1=1 to the end of DELETE queries.
<br \><br \>
<i>Doctrine::PORTABILITY_EMPTY_TO_NULL</i>
<br \><br \>
//Doctrine::PORTABILITY_EMPTY_TO_NULL//
Convert empty strings values to null in data in and output. Needed because Oracle considers empty strings to be null, while most other DBMS's know the difference between empty and null.
<br \><br \>
<i>Doctrine::PORTABILITY_ERRORS</i>
<br \><br \>
//Doctrine::PORTABILITY_ERRORS//
Makes certain error messages in certain drivers compatible with those from other DBMS's
<br \><br \>
Table 33-1. Error Code Re-mappings
......@@ -31,49 +51,73 @@ Driver Description Old Constant New Constant
mysql, mysqli unique and primary key constraints Doctrine::ERROR_ALREADY_EXISTS Doctrine::ERROR_CONSTRAINT
mysql, mysqli not-null constraints Doctrine::ERROR_CONSTRAINT Doctrine::ERROR_CONSTRAINT_NOT_NULL
<br \><br \>
<i>Doctrine::PORTABILITY_FIX_ASSOC_FIELD_NAMES</i>
<br \><br \>
//Doctrine::PORTABILITY_FIX_ASSOC_FIELD_NAMES//
This removes any qualifiers from keys in associative fetches. some RDBMS , like for example SQLite, will be default use the fully qualified name for a column in assoc fetches if it is qualified in a query.
<br \><br \>
<i>Doctrine::PORTABILITY_FIX_CASE</i>
<br \><br \>
//Doctrine::PORTABILITY_FIX_CASE//
Convert names of tables and fields to lower or upper case in all methods. The case depends on the 'field_case' option that may be set to either CASE_LOWER (default) or CASE_UPPER
<br \><br \>
<i>Doctrine::PORTABILITY_NONE</i>
<br \><br \>
//Doctrine::PORTABILITY_NONE//
Turn off all portability features
<br \><br \>
<i>Doctrine::PORTABILITY_NUMROWS</i>
<br \><br \>
//Doctrine::PORTABILITY_NUMROWS//
Enable hack that makes numRows() work in Oracle
<br \><br \>
<i>Doctrine::PORTABILITY_RTRIM</i>
<br \><br \>
//Doctrine::PORTABILITY_RTRIM//
Right trim the data output for all data fetches. This does not applied in drivers for RDBMS that automatically right trim values of fixed length character values, even if they do not right trim value of variable length character values.
<br \><br \>
Using setAttribute() to enable portability for lowercasing and trimming
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$conn->setAttribute('portability',
Doctrine::PORTABILITY_FIX_CASE | Doctrine::PORTABILITY_RTRIM);
?>");
?>
?></code>
<br \><br \>
Using setAttribute() to enable all portability options except trimming
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$conn->setAttribute('portability',
Doctrine::PORTABILITY_ALL ^ Doctrine::PORTABILITY_RTRIM);
?>");
?>
?></code>
<?php ?>
Doctrine allows you to bind connections to components (= your ActiveRecord classes). This means everytime a component issues a query
or data is being fetched from the table the component is pointing at Doctrine will use the bound connection.
<br \> <br \>
<?php
renderCode("<?php
<code type="php">
\$conn = \$manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
\$conn2 = \$manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
......@@ -19,6 +20,5 @@ renderCode("<?php
// Doctrine uses 'connection 2' for fetching here
\$groups = \$q->from('Group g')->where('g.id IN (1,2,3)')->execute();
?>");
?>
?></code>
<?php ?>
Lazy-connecting to database is handled via Doctrine_Db wrapper. When using Doctrine_Db instead of PDO / Doctrine_Adapter, lazy-connecting
to database is being performed (that means Doctrine will only connect to database when needed). <br \><br \>This feature can be very useful
to database is being performed (that means Doctrine will only connect to database when needed).
This feature can be very useful
when using for example page caching, hence not actually needing a database connection on every request. Remember connecting to database is an expensive operation.
<br \> <br \>
<?php
renderCode("<?php
<code type="php">
// we may use PDO / PEAR like DSN
// here we use PEAR like DSN
\$dbh = new Doctrine_Db('mysql://username:password@localhost/test');
......@@ -17,6 +20,5 @@ renderCode("<?php
// connects database and performs a query
\$conn->query('FROM User u');
?>");
?>
?></code>
......@@ -2,9 +2,10 @@
From the start Doctrine has been designed to work with multiple connections. Unless separately specified Doctrine always uses the current connection
for executing the queries. The following example uses openConnection() second argument as an optional
connection alias.
<br \><br \>
<?php
renderCode("<?php
<code type="php">
// Doctrine_Manager controls all the connections
\$manager = Doctrine_Manager::getInstance();
......@@ -13,14 +14,16 @@ renderCode("<?php
\$conn = \$manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
?>
");
?>
<br \><br \>
</code>
For convenience Doctrine_Manager provides static method connection() which opens new connection when arguments are given to it and returns the current
connection when no arguments have been speficied.
<br \><br \>
<?php
renderCode("<?php
<code type="php">
// open first connection
\$conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');
......@@ -29,44 +32,49 @@ renderCode("<?php
// \$conn2 == \$conn
?>
");
?>
</code>
<br \><br \>
The current connection is the lastly opened connection.
<br \><br \>
<?php
renderCode("<?php
<code type="php">
// open second connection
\$conn2 = \$manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');
\$manager->getCurrentConnection(); // \$conn2
?>");
?>
<br \><br \>
?></code>
You can change the current connection by calling setCurrentConnection().
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$manager->setCurrentConnection('connection 1');
\$manager->getCurrentConnection(); // \$conn
?>
");
?>
<br \><br \>
</code>
You can iterate over the opened connection by simple passing the manager object to foreach clause. This is possible since Doctrine_Manager implements
special IteratorAggregate interface.
<br \><br \>
<?php
renderCode("<?php
<code type="php">
// iterating through connections
foreach(\$manager as \$conn) {
}
?>");
?>
?></code>
<?php ?>
Opening a new database connection in Doctrine is very easy. If you wish to use PDO (www.php.net/PDO) you can just initalize a new PDO object:
<br \> <br \>
<?php
renderCode("<?php
<code type="php">
\$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
\$user = 'dbuser';
\$password = 'dbpass';
......@@ -12,13 +13,15 @@ try {
} catch (PDOException \$e) {
echo 'Connection failed: ' . \$e->getMessage();
}
?>");
?>
<br \><br \>
?></code>
If your database extension isn't supported by PDO you can use special Doctrine_Adapter class (if availible). The following example uses db2 adapter:
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$dsn = 'db2:dbname=testdb;host=127.0.0.1';
\$user = 'dbuser';
\$password = 'dbpass';
......@@ -28,14 +31,15 @@ try {
} catch (PDOException \$e) {
echo 'Connection failed: ' . \$e->getMessage();
}
?>");
?>
<br \><br \>
?></code>
The next step is opening a new Doctrine_Connection.
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$conn = Doctrine_Manager::connection(\$dbh);
?>");
?>
?></code>
<?php ?>
Doctrine_Export drivers provide an easy database portable way of altering existing database tables.
<br \><br \>
NOTE: if you only want to get the generated sql (and not execute it) use Doctrine_Export::alterTableSql()
<br \><br \>
<?php
renderCode("<?php
<code type="php">
\$dbh = new PDO('dsn','username','pw');
\$conn = Doctrine_Manager::getInstance()
->openConnection(\$dbh);
......@@ -16,41 +19,39 @@ renderCode("<?php
// On mysql this method returns:
// ALTER TABLE mytable ADD COLUMN name VARCHAR(255)
?>");
?>
<br \><br \>
?></code>
Doctrine_Export::alterTable() takes two parameters:
<br \><br \>
string <i>$name</i>
<dd>name of the table that is intended to be changed. <br \>
array <i>$changes</i>
: string //$name// : name of the table that is intended to be changed.
<dd>associative array that contains the details of each type of change that is intended to be performed.
: array //$changes// : associative array that contains the details of each type of change that is intended to be performed.
The types of changes that are currently supported are defined as follows:
<ul>
<li \><i>name</i>
* //name//
New name for the table.
<li \><i>add</i>
* //add//
Associative array with the names of fields to be added as indexes of the array. The value of each entry of the array should be set to another associative array with the properties of the fields to be added. The properties of the fields should be the same as defined by the Doctrine parser.
<li \><i>remove</i>
* //remove//
Associative array with the names of fields to be removed as indexes of the array. Currently the values assigned to each entry are ignored. An empty array should be used for future compatibility.
<li \><i>rename</i>
* //rename//
Associative array with the names of fields to be renamed as indexes of the array. The value of each entry of the array should be set to another associative array with the entry named name with the new field name and the entry named Declaration that is expected to contain the portion of the field declaration already in DBMS specific SQL code as it is used in the CREATE TABLE statement.
<li \><i>change</i>
* //change//
Associative array with the names of the fields to be changed as indexes of the array. Keep in mind that if it is intended to change either the name of a field and any other properties, the change array entries should have the new names of the fields as array indexes.
</ul>
The value of each entry of the array should be set to another associative array with the properties of the fields to that are meant to be changed as array entries. These entries should be assigned to the new values of the respective properties. The properties of the fields should be the same as defined by the Doctrine parser.
......
Syntax:
<div class='sql'>
<pre>
<code>
operand comparison_operator ANY (subquery)
operand comparison_operator SOME (subquery)
operand comparison_operator ALL (subquery)
</pre>
</div>
</code>
An ALL conditional expression returns true if the comparison operation is true for all values
in the result of the subquery or the result of the subquery is empty. An ALL conditional expression
is false if the result of the comparison is false for at least one row, and is unknown if neither true nor
false.
<br \><br \>
<div class='sql'>
<pre>
<code>
FROM C WHERE C.col1 < ALL (FROM C2(col1))
</pre>
</div>
</code>
An ANY conditional expression returns true if the comparison operation is true for some
value in the result of the subquery. An ANY conditional expression is false if the result of the subquery
is empty or if the comparison operation is false for every value in the result of the subquery, and is
unknown if neither true nor false.
<div class='sql'>
<pre>
<code>
FROM C WHERE C.col1 > ANY (FROM C2(col1))
</pre>
</div>
</code>
The keyword SOME is an alias for ANY.
<div class='sql'>
<pre>
<code>
FROM C WHERE C.col1 > SOME (FROM C2(col1))
</pre>
</div>
<br \>
</code>
The comparison operators that can be used with ALL or ANY conditional expressions are =, <, <=, >, >=, <>. The
result of the subquery must be same type with the conditional expression.
<br \><br \>
NOT IN is an alias for <> ALL. Thus, these two statements are equal:
<br \><br \>
<div class='sql'>
<pre>
<code>
FROM C WHERE C.col1 <> ALL (FROM C2(col1));
FROM C WHERE C.col1 NOT IN (FROM C2(col1));
</pre>
</div>
</code>
Syntax:
<div class='sql'>
<pre>
<i>operand</i> [NOT ]EXISTS (<i>subquery</i>)
</pre>
</div>
The EXISTS operator returns TRUE if the subquery returns one or more rows and FALSE otherwise. <br \>
<br \>
The NOT EXISTS operator returns TRUE if the subquery returns 0 rows and FALSE otherwise.<br \>
<br \>
<code>
//operand// [NOT ]EXISTS (//subquery//)
</code>
The EXISTS operator returns TRUE if the subquery returns one or more rows and FALSE otherwise.
The NOT EXISTS operator returns TRUE if the subquery returns 0 rows and FALSE otherwise.
Finding all articles which have readers:
<div class='sql'>
<pre>
<code>
FROM Article
WHERE EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</pre>
</div>
</code>
Finding all articles which don't have readers:
<div class='sql'>
<pre>
<code>
FROM Article
WHERE NOT EXISTS (FROM ReaderLog(id)
WHERE ReaderLog.article_id = Article.id)
</pre>
</div>
</code>
Syntax:
<div class='sql'>
<pre>
<i>operand</i> IN (<i>subquery</i>|<i>value list</i>)
</pre>
</div>
An IN conditional expression returns true if the <i>operand</i> is found from result of the <i>subquery</i>
or if its in the specificied comma separated <i>value list</i>, hence the IN expression is always false if the result of the subquery
<code>
//operand// IN (//subquery//|//value list//)
</code>
An IN conditional expression returns true if the //operand// is found from result of the //subquery//
or if its in the specificied comma separated //value list//, hence the IN expression is always false if the result of the subquery
is empty.
When <i>value list</i> is being used there must be at least one element in that list.
When //value list// is being used there must be at least one element in that list.
<div class='sql'>
<pre>
<code>
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
FROM User WHERE User.id IN (1,3,4,5)
</pre>
</div>
</code>
The keyword IN is an alias for = ANY. Thus, these two statements are equal:
<div class='sql'>
<pre>
<code>
FROM C1 WHERE C1.col1 = ANY (FROM C2(col1));
FROM C1 WHERE C1.col1 IN (FROM C2(col1));
</pre>
</div>
</code>
Syntax:<br \>
Syntax:
string_expression [NOT] LIKE pattern_value [ESCAPE escape_character]
<br \>
<br \>
The string_expression must have a string value. The pattern_value is a string literal or a string-valued
input parameter in which an underscore (_) stands for any single character, a percent (%) character
stands for any sequence of characters (including the empty sequence), and all other characters stand for
themselves. The optional escape_character is a single-character string literal or a character-valued
input parameter (i.e., char or Character) and is used to escape the special meaning of the underscore
and percent characters in pattern_value.
<br \><br \>
Examples:
<br \>
<ul>
<li \>address.phone LIKE 12%3 is true for '123' '12993' and false for '1234'
<li \>asentence.word LIKE l_se is true for lose and false for 'loose'
<li \>aword.underscored LIKE \_% ESCAPE '\' is true for '_foo' and false for 'bar'
<li \>address.phone NOT LIKE ‘12%3’ is false for '123' and '12993' and true for '1234'
</ul>
<br \>
* address.phone LIKE 12%3 is true for '123' '12993' and false for '1234'
* asentence.word LIKE l_se is true for lose and false for 'loose'
* aword.underscored LIKE \_% ESCAPE '\' is true for '_foo' and false for 'bar'
* address.phone NOT LIKE ‘12%3’ is false for '123' and '12993' and true for '1234'
If the value of the string_expression or pattern_value is NULL or unknown, the value of the LIKE
expression is unknown. If the escape_characteris specified and is NULL, the value of the LIKE expression
is unknown.
......
<b>Strings</b><br \>
**Strings**
A string literal is enclosed in single quotesfor example: 'literal'. A string literal that includes a single
quote is represented by two single quotesfor example: 'literal''s'.
<div class='sql'>
<pre>
<code>
FROM User WHERE User.name = 'Vincent'
</pre>
</div>
</code>
**Integers**
<b>Integers</b><br \>
Integer literals support the use of PHP integer literal syntax.
<div class='sql'>
<pre>
<code>
FROM User WHERE User.id = 4
</pre>
</div>
</code>
**Floats**
<b>Floats</b><br \>
Float literals support the use of PHP float literal syntax.
<div class='sql'>
<pre>
<code>
FROM Account WHERE Account.amount = 432.123
</pre>
</div>
</code>
**Booleans**
<br \>
<b>Booleans</b><br \>
The boolean literals are true and false.
<div class='sql'>
<pre>
<code>
FROM User WHERE User.admin = true
FROM Session WHERE Session.is_authed = false
</pre>
</div>
</code>
**Enums**
<br \>
<b>Enums</b><br \>
The enumerated values work in the same way as string literals.
<div class='sql'>
<pre>
<code>
FROM User WHERE User.type = 'admin'
</pre>
</div>
</code>
<br \>
Predefined reserved literals are case insensitive, although its a good standard to write them in uppercase.
The operators are listed below in order of decreasing precedence.
<ul>
<li \> Navigation operator (.)
<li \> Arithmetic operators: <br \>
+, - unary <br \>
*, / multiplication and division <br \>
+, - addition and subtraction <br \>
<li \> Comparison operators : =, >, >=, <, <=, <> (not equal), [NOT] LIKE, <br \>
[NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY <br \>
<li \> Logical operators:<br \>
NOT <br \>
AND <br \>
OR <br \>
</ul>
* Navigation operator (.)
* Arithmetic operators:
+, - unary
*, / multiplication and division
+, - addition and subtraction
* Comparison operators : =, >, >=, <, <=, <> (not equal), [NOT] LIKE,
[NOT] IN, IS [NOT] NULL, IS [NOT] EMPTY
* Logical operators:
NOT
AND
OR
A subquery can contain any of the keywords or clauses that an ordinary SELECT query can contain.
<br \><br \>
Some advantages of the subqueries:
<ul>
<li \>They allow queries that are structured so that it is possible to isolate each part of a statement.
<li \>They provide alternative ways to perform operations that would otherwise require complex joins and unions.
* They allow queries that are structured so that it is possible to isolate each part of a statement.
* They provide alternative ways to perform operations that would otherwise require complex joins and unions.
* They are, in many people's opinion, readable. Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”
<li \>They are, in many people's opinion, readable. Indeed, it was the innovation of subqueries that gave people the original idea of calling the early SQL “Structured Query Language.”
</ul>
<code type="php">
// finding all users which don't belong to any group 1
......
<div class='sql'>
<pre>
DELETE FROM <i>component_name</i>
[WHERE <i>where_condition</i>]
<code>
DELETE FROM //component_name//
[WHERE //where_condition//]
[ORDER BY ...]
[LIMIT <i>record_count</i>]
</pre>
</div>
<ul>
<li \>The DELETE statement deletes records from <i>component_name</i> and returns the number of records deleted.
[LIMIT //record_count//]
</code>
* The DELETE statement deletes records from //component_name// and returns the number of records deleted.
<li \>The optional WHERE clause specifies the conditions that identify which records to delete.
* The optional WHERE clause specifies the conditions that identify which records to delete.
Without WHERE clause, all records are deleted.
<li \>If the ORDER BY clause is specified, the records are deleted in the order that is specified.
* If the ORDER BY clause is specified, the records are deleted in the order that is specified.
* The LIMIT clause places a limit on the number of rows that can be deleted.
The statement will stop as soon as it has deleted //record_count// records.
<li \>The LIMIT clause places a limit on the number of rows that can be deleted.
The statement will stop as soon as it has deleted <i>record_count</i> records.
</ul>
<code type="php">
$q = 'DELETE FROM Account WHERE id > ?';
......
Syntax: <br \>
Syntax:
<div class='sql'>
<pre>
FROM <i>component_reference</i> [[LEFT | INNER] JOIN <i>component_reference</i>] ...
</pre>
</div>
<code>
FROM //component_reference// [[LEFT | INNER] JOIN //component_reference//] ...
</code>
The FROM clause indicates the component or components from which to retrieve records.
If you name more than one component, you are performing a join.
For each table specified, you can optionally specify an alias.
<br \><br \>
<li \> The default join type is <i>LEFT JOIN</i>. This join can be indicated by the use of either 'LEFT JOIN' clause or simply ',', hence the following queries are equal:
<div class='sql'>
<pre>
* The default join type is //LEFT JOIN//. This join can be indicated by the use of either 'LEFT JOIN' clause or simply ',', hence the following queries are equal:
<code>
SELECT u.*, p.* FROM User u LEFT JOIN u.Phonenumber
SELECT u.*, p.* FROM User u, u.Phonenumber p
</pre>
</div>
</code>
<li \><i>INNER JOIN</i> produces an intersection between two specified components (that is, each and every record in the first component is joined to each and every record in the second component).
So basically <i>INNER JOIN</i> can be used when you want to efficiently fetch for example all users which have one or more phonenumbers.
<div class='sql'>
<pre>
* //INNER JOIN// produces an intersection between two specified components (that is, each and every record in the first component is joined to each and every record in the second component).
So basically //INNER JOIN// can be used when you want to efficiently fetch for example all users which have one or more phonenumbers.
<code>
SELECT u.*, p.* FROM User u INNER JOIN u.Phonenumber p
</pre>
</div>
</code>
<?php ?>
<ul>
<li \>The <i>CONCAT</i> function returns a string that is a concatenation of its arguments. In the example above we
* The //CONCAT// function returns a string that is a concatenation of its arguments. In the example above we
map the concatenation of users firstname and lastname to a value called name
<br \><br \><?php
renderCode("<?php
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('CONCAT(u.firstname, u.lastname) name')->from('User u')->execute();
......@@ -13,15 +14,17 @@ foreach(\$users as \$user) {
// its a mapped function value
print \$user->name;
}
?>");
?>
?></code>
<br \><br \>
<li \>The second and third arguments of the <i>SUBSTRING</i> function denote the starting position and length of
* The second and third arguments of the //SUBSTRING// function denote the starting position and length of
the substring to be returned. These arguments are integers. The first position of a string is denoted by 1.
The <i>SUBSTRING</i> function returns a string.
<br \><br \><?php
renderCode("<?php
The //SUBSTRING// function returns a string.
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"SUBSTRING(u.name, 0, 1) = 'z'\")->execute();
......@@ -29,16 +32,18 @@ renderCode("<?php
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?>
<br \><br \>
?></code>
<li \>The <i>TRIM</i> function trims the specified character from a string. If the character to be trimmed is not
* The //TRIM// function trims the specified character from a string. If the character to be trimmed is not
specified, it is assumed to be space (or blank). The optional trim_character is a single-character string
literal or a character-valued input parameter (i.e., char or Character)[30]. If a trim specification is
not provided, BOTH is assumed. The <i>TRIM</i> function returns the trimmed string.
<br \><br \><?php
renderCode("<?php
not provided, BOTH is assumed. The //TRIM// function returns the trimmed string.
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"TRIM(u.name) = 'Someone'\")->execute();
......@@ -46,13 +51,15 @@ renderCode("<?php
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?> <br \><br \>
<li \>The <i>LOWER</i> and <i>UPPER</i> functions convert a string to lower and upper case, respectively. They return a
string. <br \><br \>
?></code>
* The //LOWER// and //UPPER// functions convert a string to lower and upper case, respectively. They return a
string.
<?php
renderCode("<?php
<code type="php">
\$q = new Doctrine_Query();
\$users = \$q->select('u.name')->from('User u')->where(\"LOWER(u.name) = 'someone'\")->execute();
......@@ -60,18 +67,21 @@ renderCode("<?php
foreach(\$users as \$user) {
print \$user->name;
}
?>");
?> <br \><br \>
<li \>
The <i>LOCATE</i> function returns the position of a given string within a string, starting the search at a specified
?></code>
*
The //LOCATE// function returns the position of a given string within a string, starting the search at a specified
position. It returns the first position at which the string was found as an integer. The first argument
is the string to be located; the second argument is the string to be searched; the optional third argument
is an integer that represents the string position at which the search is started (by default, the beginning of
the string to be searched). The first position in a string is denoted by 1. If the string is not found, 0 is
returned.
<br \><br \>
<li \>The <i>LENGTH</i> function returns the length of the string in characters as an integer.
</ul>
* The //LENGTH// function returns the length of the string in characters as an integer.
<ul>
<li> GROUP BY and HAVING clauses can be used for dealing with aggregate functions
<br \>
<li> Following aggregate functions are availible on DQL: COUNT, MAX, MIN, AVG, SUM
<br \>
Selecting alphabetically first user by name.
<div class='sql'>
<pre>
<code>
SELECT MIN(u.name) FROM User u
</pre>
</div>
</code>
Selecting the sum of all Account amounts.
<div class='sql'>
<pre>
<code>
SELECT SUM(a.amount) FROM Account a
</pre>
</div>
</code>
<br \>
<li> Using an aggregate function in a statement containing no GROUP BY clause, results in grouping on all rows. In the example above
we fetch all users and the number of phonenumbers they have.
<div class='sql'>
<pre>
<code>
SELECT u.*, COUNT(p.id) FROM User u, u.Phonenumber p GROUP BY u.id
</pre>
</div>
</code>
<br \>
<li> The HAVING clause can be used for narrowing the results using aggregate values. In the following example we fetch
all users which have atleast 2 phonenumbers
<div class='sql'>
<pre>
<code>
SELECT u.* FROM User u, u.Phonenumber p HAVING COUNT(p.id) >= 2
</pre>
</div>
</code>
</ul>
<code type="php">
......
Doctrine Query Language(DQL) is an Object Query Language created for helping users in complex object retrieval.
You should always consider using DQL(or raw SQL) when retrieving relational data efficiently (eg. when fetching users and their phonenumbers).
<br \><br \>
When compared to using raw SQL, DQL has several benefits: <br \>
<ul>
<li \>From the start it has been designed to retrieve records(objects) not result set rows
</ul>
<ul>
<li \>DQL understands relations so you don't have to type manually sql joins and join conditions
</ul>
<ul>
<li \>DQL is portable on different databases
</ul>
<ul>
<li \>DQL has some very complex built-in algorithms like (the record limit algorithm) which can help
When compared to using raw SQL, DQL has several benefits:
* From the start it has been designed to retrieve records(objects) not result set rows
* DQL understands relations so you don't have to type manually sql joins and join conditions
* DQL is portable on different databases
* DQL has some very complex built-in algorithms like (the record limit algorithm) which can help
developer to efficiently retrieve objects
</ul>
<ul>
<li \>It supports some functions that can save time when dealing with one-to-many, many-to-many relational data with conditional fetching.
</ul>
* It supports some functions that can save time when dealing with one-to-many, many-to-many relational data with conditional fetching.
If the power of DQL isn't enough, you should consider using the rawSql API for object population.
......@@ -29,9 +32,11 @@ If the power of DQL isn't enough, you should consider using the rawSql API for o
$users = $conn->getTable('User')->findAll();
foreach($users as $user) {
print $user->name."<br \>";
print $user->name."
";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."<br \>";
print $phonenumber."
";
}
}
......@@ -41,9 +46,11 @@ foreach($users as $user) {
$users = $conn->query("FROM User.Phonenumber");
foreach($users as $user) {
print $user->name."<br \>";
print $user->name."
";
foreach($user->Phonenumber as $phonenumber) {
print $phonenumber."<br \>";
print $phonenumber."
";
}
}
......
DQL LIMIT clause is portable on all supported databases. Special attention have been paid to following facts:
<br \><br \>
<li \> Only Mysql, Pgsql and Sqlite implement LIMIT / OFFSET clauses natively
<br \><br \>
<li \> In Oracle / Mssql / Firebird LIMIT / OFFSET clauses need to be emulated in driver specific way
<br \><br \>
<li \> The limit-subquery-algorithm needs to execute to subquery separately in mysql, since mysql doesn't yet support
LIMIT clause in subqueries<br \><br \>
<li \> Pgsql needs the order by fields to be preserved in SELECT clause, hence LS-algorithm needs to take this into consideration
when pgsql driver is used<br \><br \>
<li \> Oracle only allows < 30 object identifiers (= table/column names/aliases), hence the limit subquery must use as short aliases as possible
* Only Mysql, Pgsql and Sqlite implement LIMIT / OFFSET clauses natively
* In Oracle / Mssql / Firebird LIMIT / OFFSET clauses need to be emulated in driver specific way
* The limit-subquery-algorithm needs to execute to subquery separately in mysql, since mysql doesn't yet support
LIMIT clause in subqueries
* Pgsql needs the order by fields to be preserved in SELECT clause, hence LS-algorithm needs to take this into consideration
when pgsql driver is used
* Oracle only allows < 30 object identifiers (= table/column names/aliases), hence the limit subquery must use as short aliases as possible
and it must avoid alias collisions with the main query.
The limit-subquery-algorithm is an algorithm that DQL parser uses internally when one-to-many / many-to-many relational
data is being fetched simultaneously. This kind of special algorithm is needed for the LIMIT clause to limit the number
of records instead of sql result set rows.
<br \><br \>
In the following example we have users and phonenumbers with their relation being one-to-many. Now lets say we want fetch the first 20 users
and all their related phonenumbers.
<br \><br \>
Now one might consider that adding a simple driver specific LIMIT 20 at the end of query would return the correct results.
Thats wrong, since we you might get anything between 1-20 users as the first user might have 20 phonenumbers and then record set would consist of 20 rows.
<br \><br \>
DQL overcomes this problem with subqueries and with complex but efficient subquery analysis. In the next example we are going to fetch first 20 users and all their phonenumbers with single efficient query.
Notice how the DQL parser is smart enough to use column aggregation inheritance even in the subquery and how its smart enough to use different aliases
for the tables in the subquery to avoid alias collisions.
<br \><br \>
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<div class='sql'>
<pre>
<code>
SELECT
e.id AS e__id,
e.name AS e__name,
......@@ -33,23 +40,25 @@ WHERE e.id IN (
SELECT DISTINCT e2.id
FROM entity e2
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</pre>
</div>
</code>
<br \><br \>
In the next example we are going to fetch first 20 users and all their phonenumbers and only
those users that actually have phonenumbers with single efficient query, hence we use an INNER JOIN.
Notice how the DQL parser is smart enough to use the INNER JOIN in the subquery.
<br \><br \>
DQL QUERY:
<div class='sql'><pre>
SELECT u.id, u.name, p.* FROM User u LEFT JOIN u.Phonenumber p LIMIT 20
</pre></div>
SQL QUERY:
<div class='sql'>
<pre>
<code>
SELECT
e.id AS e__id,
e.name AS e__name,
......@@ -63,7 +72,6 @@ SELECT DISTINCT e2.id
FROM entity e2
INNER JOIN phonenumber p2 ON e2.id = p2.entity_id
WHERE (e2.type = 0) LIMIT 20) AND (e.type = 0)
</pre>
</div>
</code>
Record collections can be sorted efficiently at the database level using the ORDER BY clause.
Syntax:
<div class='sql'>
<pre>
<code>
[ORDER BY {ComponentAlias.columnName}
[ASC | DESC], ...]
</pre>
</div>
</code>
Examples:
<br \>
<div class='sql'>
<pre>
<code>
FROM User.Phonenumber
ORDER BY User.name, Phonenumber.phonenumber
FROM User u, u.Email e
ORDER BY e.address, u.id
</pre>
</div>
</code>
In order to sort in reverse order you can add the DESC (descending) keyword to the name of the column in the ORDER BY clause that you are sorting by. The default is ascending order; this can be specified explicitly using the ASC keyword.
<br \>
<div class='sql'>
<pre>
<code>
FROM User u, u.Email e
ORDER BY e.address DESC, u.id ASC;
</pre>
</div>
</code>
<li>
<p>NOT, !
</p>
<p>
NOT, !
Logical NOT. Evaluates to 1 if the
operand is 0, to 0 if
the operand is non-zero, and NOT NULL
returns NULL.
</p>
<b class='title'>DQL condition :</b> NOT 10<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> NOT 0<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :</b> NOT NULL<br \>
-&gt; NULL<br \>
<b class='title'>DQL condition :</b> ! (1+1)<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> ! 1+1<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :** NOT 10
-&gt; 0
<b class='title'>DQL condition :** NOT 0
-&gt; 1
<b class='title'>DQL condition :** NOT NULL
-&gt; NULL
<b class='title'>DQL condition :** ! (1+1)
-&gt; 0
<b class='title'>DQL condition :** ! 1+1
-&gt; 1
</pre>
<p>
The last example produces 1 because the
expression evaluates the same way as
(!1)+1.
</p>
</li>
<li>
<p><a name="function_and"></a>
<a name="function_and"></a>
<a class="indexterm" name="id2965271"></a>
<a class="indexterm" name="id2965283"></a>
AND
</p>
<p>
Logical AND. Evaluates to 1 if all
operands are non-zero and not NULL, to
0 if one or more operands are
0, otherwise NULL is
returned.
</p>
<b class='title'>DQL condition :</b> 1 AND 1<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :</b> 1 AND 0<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> 1 AND NULL<br \>
-&gt; NULL<br \>
<b class='title'>DQL condition :</b> 0 AND NULL<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> NULL AND 0<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :** 1 AND 1
-&gt; 1
<b class='title'>DQL condition :** 1 AND 0
-&gt; 0
<b class='title'>DQL condition :** 1 AND NULL
-&gt; NULL
<b class='title'>DQL condition :** 0 AND NULL
-&gt; 0
<b class='title'>DQL condition :** NULL AND 0
-&gt; 0
</pre>
</li>
<li>
OR
</p>
<p>
Logical OR. When both operands are
non-NULL, the result is
1 if any operand is non-zero, and
......@@ -67,45 +99,69 @@
NULL otherwise. If both operands are
NULL, the result is
NULL.
</p>
<b class='title'>DQL condition :</b> 1 OR 1<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :</b> 1 OR 0<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :</b> 0 OR 0<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> 0 OR NULL<br \>
-&gt; NULL<br \>
<b class='title'>DQL condition :</b> 1 OR NULL<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :** 1 OR 1
-&gt; 1
<b class='title'>DQL condition :** 1 OR 0
-&gt; 1
<b class='title'>DQL condition :** 0 OR 0
-&gt; 0
<b class='title'>DQL condition :** 0 OR NULL
-&gt; NULL
<b class='title'>DQL condition :** 1 OR NULL
-&gt; 1
</pre>
</li>
<li>
<p><a name="function_xor"></a>
<a name="function_xor"></a>
<a class="indexterm" name="id2965520"></a>
XOR
</p>
<p>
Logical XOR. Returns NULL if either
operand is NULL. For
non-NULL operands, evaluates to
1 if an odd number of operands is
non-zero, otherwise 0 is returned.
</p>
<b class='title'>DQL condition :</b> 1 XOR 1<br \>
-&gt; 0<br \>
<b class='title'>DQL condition :</b> 1 XOR 0<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :</b> 1 XOR NULL<br \>
-&gt; NULL<br \>
<b class='title'>DQL condition :</b> 1 XOR 1 XOR 1<br \>
-&gt; 1<br \>
<b class='title'>DQL condition :** 1 XOR 1
-&gt; 0
<b class='title'>DQL condition :** 1 XOR 0
-&gt; 1
<b class='title'>DQL condition :** 1 XOR NULL
-&gt; NULL
<b class='title'>DQL condition :** 1 XOR 1 XOR 1
-&gt; 1
</pre>
<p>
a XOR b is mathematically equal to
(a AND (NOT b)) OR ((NOT a) and b).
</p>
</li>
</ul>
SELECT statement syntax:
<div class='sql'>
<pre>
<code>
SELECT
[ALL | DISTINCT]
<i>select_expr</i>, ...
[FROM <i>components</i>
[WHERE <i>where_condition</i>]
[GROUP BY <i>groupby_expr</i>
//select_expr//, ...
[FROM //components//
[WHERE //where_condition//]
[GROUP BY //groupby_expr//
[ASC | DESC], ... ]
[HAVING <i>where_condition</i>]
[ORDER BY <i>orderby_expr</i>
[HAVING //where_condition//]
[ORDER BY //orderby_expr//
[ASC | DESC], ...]
[LIMIT <i>row_count</i> OFFSET <i>offset</i>}]
</pre>
</div>
<br \>
[LIMIT //row_count// OFFSET //offset//}]
</code>
The SELECT statement is used for the retrieval of data from one or more components.
<ul>
<li \>Each <i>select_expr</i> indicates a column or an aggregate function value that you want to retrieve. There must be at least one <i>select_expr</i> in every SELECT statement.
<div class='sql'>
<pre>
* Each //select_expr// indicates a column or an aggregate function value that you want to retrieve. There must be at least one //select_expr// in every SELECT statement.
<code>
SELECT a.name, a.amount FROM Account a
</pre>
</div>
</code>
<li \>An asterisk can be used for selecting all columns from given component. Even when using an asterisk the executed sql queries never actually use it
* An asterisk can be used for selecting all columns from given component. Even when using an asterisk the executed sql queries never actually use it
(Doctrine converts asterisk to appropriate column names, hence leading to better performance on some databases).
<div class='sql'>
<pre>
<code>
SELECT a.* FROM Account a
</pre>
</div>
<li \>FROM clause <i>components</i> indicates the component or components from which to retrieve records.
<div class='sql'>
<pre>
</code>
* FROM clause //components// indicates the component or components from which to retrieve records.
<code>
SELECT a.* FROM Account a
SELECT u.*, p.*, g.* FROM User u LEFT JOIN u.Phonenumber p LEFT JOIN u.Group g
</pre>
</div>
<li \>The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected. <i>where_condition</i> is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause.
<div class='sql'>
<pre>
</code>
* The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected. //where_condition// is an expression that evaluates to true for each row to be selected. The statement selects all rows if there is no WHERE clause.
<code>
SELECT a.* FROM Account a WHERE a.amount > 2000
</pre>
</div>
<li \>In the WHERE clause, you can use any of the functions and operators that DQL supports, except for aggregate (summary) functions
</code>
* In the WHERE clause, you can use any of the functions and operators that DQL supports, except for aggregate (summary) functions
<li \>The HAVING clause can be used for narrowing the results with aggregate functions
<div class='sql'>
<pre>
* The HAVING clause can be used for narrowing the results with aggregate functions
<code>
SELECT u.* FROM User u LEFT JOIN u.Phonenumber p HAVING COUNT(p.id) > 3
</pre>
</div>
<li \>The ORDER BY clause can be used for sorting the results
<div class='sql'>
<pre>
</code>
* The ORDER BY clause can be used for sorting the results
<code>
SELECT u.* FROM User u ORDER BY u.name
</pre>
</div>
<li \>The LIMIT and OFFSET clauses can be used for efficiently limiting the number of records to a given <i>row_count</i>
<div class='sql'>
<pre>
</code>
* The LIMIT and OFFSET clauses can be used for efficiently limiting the number of records to a given //row_count//
<code>
SELECT u.* FROM User u LIMIT 20
</pre>
</div>
</ul>
</code>
UPDATE statement syntax:
<div class='sql'>
<pre>
UPDATE <i>component_name</i>
SET <i>col_name1</i>=<i>expr1</i> [, <i>col_name2</i>=<i>expr2</i> ...]
[WHERE <i>where_condition</i>]
<code>
UPDATE //component_name//
SET //col_name1//=//expr1// [, //col_name2//=//expr2// ...]
[WHERE //where_condition//]
[ORDER BY ...]
[LIMIT <i>record_count</i>]
</pre>
</div>
<ul>
<li \>The UPDATE statement updates columns of existing records in <i>component_name</i> with new values and returns the number of affected records.
[LIMIT //record_count//]
</code>
* The UPDATE statement updates columns of existing records in //component_name// with new values and returns the number of affected records.
<li \>The SET clause indicates which columns to modify and the values they should be given.
* The SET clause indicates which columns to modify and the values they should be given.
<li \>The optional WHERE clause specifies the conditions that identify which records to update.
* The optional WHERE clause specifies the conditions that identify which records to update.
Without WHERE clause, all records are updated.
<li \>The optional ORDER BY clause specifies the order in which the records are being updated.
* The optional ORDER BY clause specifies the order in which the records are being updated.
* The LIMIT clause places a limit on the number of records that can be updated. You can use LIMIT row_count to restrict the scope of the UPDATE.
A LIMIT clause is a **rows-matched restriction** not a rows-changed restriction.
The statement stops as soon as it has found //record_count// rows that satisfy the WHERE clause, whether or not they actually were changed.
<li \>The LIMIT clause places a limit on the number of records that can be updated. You can use LIMIT row_count to restrict the scope of the UPDATE.
A LIMIT clause is a <b>rows-matched restriction</b> not a rows-changed restriction.
The statement stops as soon as it has found <i>record_count</i> rows that satisfy the WHERE clause, whether or not they actually were changed.
</ul>
<code type="php">
$q = 'UPDATE Account SET amount = amount + 200 WHERE id > 200';
......
Syntax:
<div class='sql'>
<pre>
WHERE <i>where_condition</i>
</pre>
</div>
<ul>
<li \> The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected.
<br \><br \>
<li \> <i>where_condition</i> is an expression that evaluates to true for each row to be selected.
<br \><br \>
<li \> The statement selects all rows if there is no WHERE clause.
<br \><br \>
<li \> When narrowing results with aggregate function values HAVING clause should be used instead of WHERE clause
<br \><br \>
</ul>
<code>
WHERE //where_condition//
</code>
* The WHERE clause, if given, indicates the condition or conditions that the records must satisfy to be selected.
* //where_condition// is an expression that evaluates to true for each row to be selected.
* The statement selects all rows if there is no WHERE clause.
* When narrowing results with aggregate function values HAVING clause should be used instead of WHERE clause
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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