sql_alter

The sql_alter() function is used to send an ALTER type SQL command to the database server to modify the structure of the database.

The function accepts 3 parameters:

  1. $q is the query string (without the term "ALTER") to be executed
  2. $serveur,
  3. $option

Note: This function directly assumes an SQL formatted command, so it is important to respect the SQL standards. It is possible in future versions of SPIP, that the $q parameter will accept a more structured table as input in order to simplify porting to other systems.

The function is used as shown in this example:

sql_alter("TABLE table ADD COLUMN column_name INT");
sql_alter("TABLE table ADD column_name INT"); // COLUMN is an optional keyword for this SQL command
sql_alter("TABLE table CHANGE column_name column_name INT DEFAULT '0'");
sql_alter("TABLE table ADD INDEX column_name (column_name)");
sql_alter("TABLE table DROP INDEX column_name");
sql_alter("TABLE table DROP COLUMN column_name");
sql_alter("TABLE table DROP column_name"); // COLUMN is an optional keyword for this command
sql_alter("TABLE spip_tradlang RENAME spip_tradlangs");
// You may pass several actions, but be careful about other DBMS ports:
sql_alter("TABLE table DROP column_nameA, DROP column_nameB");

The sql_alter() function is particularly used during updates for plugins in the {plugin_name}_upgrade() functions for the various plugins you may have installed.

Example

Add a "composition" column to the spip_articles table (plugin "Composition"):

sql_alter("TABLE spip_articles ADD composition varchar(255) DEFAULT '' NOT NULL");

Add "css" to the "spip_menus" table (plugin "Menus"):

sql_alter("TABLE spip_menus ADD COLUMN css tinytext DEFAULT '' NOT NULL");

The "TradRub" plugin includes in its installation procedure an instruction to add the "id_trad" column to the spip_rubriques table by using the maj_tables() function provided for such a purpose, then adds an index on that same column using sql_alter():

function tradrub_upgrade($nom_meta_base_version, $version_cible){
	$current_version = 0.0;

	if ( (!isset($GLOBALS['meta'][$nom_meta_base_version]) )
		|| (($current_version = $GLOBALS['meta'][$nom_meta_base_version]) != $version_cible))
	{
		include_spip('base/tradrub');
		if ($current_version==0.0){
			include_spip('base/create');
			maj_tables('spip_rubriques');
			// index on the new field
			sql_alter("TABLE spip_rubriques ADD INDEX (id_trad)");
			ecrire_meta($nom_meta_base_version, $current_version=$version_cible, 'non');
		}	
	}
}

Author Mark Baber Published : Updated : 12/03/23

Translations : English, français