Академический Документы
Профессиональный Документы
Культура Документы
Last updated on
3 October 2016
Some commonly misused keywords: TIMESTAMP, TYPE, TYPES, MODULE, DATA, DATE, TIME, ...
See also [bug] SQL Reserved Words.
Example:
<?php
db_query("INSERT INTO {filters} (format, module, delta, weight) VALUES (%d, 'php', 0,
0)", $format);
?>
NOTE: as of Drupal 6.x, table definitions and constraints (e.g. primary keys, unique keys, indexes)
should be always handled by the Schema API, which solves cross-database compatibility concerns
automatically.
Naming
Use singular nouns for table names since they describe the entity the table represents. Drupal 6.x
mixed singular/plural usage and this convention changed for Drupal 7.x.
It is a good practice to prefix table names with the module name to prevent possible namespace
conflicts.
Name every constraint (primary, foreign, unique keys) yourself. Otherwise, you'll see funny-looking
system-generated names in error messages. This happened with the moderation_roles table which
initially defined a key without explicit name as KEY (mid). This got mysqldump'ed as KEY mid
(mid) which resulted in a syntax error as mid() is a mysql function (see [bug] mysql --ansi cannot
import install database).
Index names should begin with the name of the table they depend on, eg. INDEX users_sid_idx.
NOTE: as of Drupal 6.x, table definitions and constraints should be always handled by the Schema
API.
MySQL
Enable ANSI and Strict Mode
References
Joe Celko - SQL for Smarties: Advanced SQL Programming
RDBMS Naming conventions
Indentation
Drupal does not have a standard method for indentation or formating of longer SQL queries on multiple
lines. Some competing strategies include:
if (!(db_query(
"
INSERT INTO {mlsp_media_file_type}
SET extension = '%s',
attributes = '%s'
",
$file_type_entry['extension'],
$selected_attributes
))) {
$errors = TRUE;
}
or
$sql = "SELECT t.*, j1.col1, j2.col2"
. " FROM {table} AS t"
. " LEFT JOIN {join1} AS j1 ON j1.id = t.jid"
. " LEFT JOIN {join2} AS j2 ON j2.id = t.jjid"
. " WHERE t.col LIKE '%s'"
. " ORDER BY %s"
;
$result = db_query($sql, 'findme', 't.weight');
$sql = <<