egroupware/phpgwapi/inc/adodb/docs-datadict.htm
2004-03-15 22:17:52 +00:00

551 lines
23 KiB
HTML

<html>
<head>
<title>ADODB Data Dictionary Manual</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<style type="text/css">
body, td {
/*font-family: Arial, Helvetica, sans-serif;*/
font-size: 11pt;
}
pre {
font-size: 9pt;
}
.toplink {
font-size: 8pt;
}
</style>
</head>
<body bgcolor="#FFFFFF">
<h2>ADOdb Data Dictionary Library for PHP</h2>
<p>V4.20 22 Feb 2004 (c) 2000-2004 John Lim (<a href="mailto:jlim#natsoft.com.my">jlim#natsoft.com.my</a>).<br> AXMLS (c) 2004 ars Cognita, Inc</p>
<p><font size="1">This software is dual licensed using BSD-Style and LGPL. This means you can use it in compiled proprietary and commercial products.</font></p>
<p>Useful ADOdb links: <a href=http://php.weblogs.com/adodb?dd=1>Download</a> &nbsp; <a href=http://php.weblogs.com/adodb_manual?dd=1>Other Docs</a></p>
<p>This documentation describes a PHP class library to automate the creation of tables,
indexes and foreign key constraints portably for multiple databases. Richard Tango-Lowy and Dan Cech
have been kind enough to contribute <a href=#xmlschema>AXMLS</a>, an XML schema system for defining databases.</p>
<p>Currently the following databases are supported:</p>
<p>
<b>Well-tested:</b> PostgreSQL, MySQL, Oracle, MSSQL.<br />
<b>Beta-quality:</b> DB2, Informix, Sybase, Interbase, Firebird.<br />
<b>Alpha-quality:</b> MS Access (does not support DEFAULT values) and generic ODBC.
</p>
<h3>Example Usage</h3>
<pre>
include_once('adodb.inc.php');
<font color="#006600"># First create a normal connection</font>
$db->NewADOConnection('mysql');
$db->Connect(...);
<font color="#006600"># Then create a data dictionary object, using this connection</font>
$dict = <strong>NewDataDictionary</strong>($db);
<font color="#006600"># We have a portable declarative data dictionary format in ADOdb, similar to SQL.
# Field types use 1 character codes, and fields are separated by commas.
# The following example creates three fields: "col1", "col2" and "col3":</font>
$flds = "
<font color="#663300"><strong> col1 C(32) NOTNULL DEFAULT 'abc',
col2 I DEFAULT 0,
col3 N(12.2)</strong></font>
";
<font color="#006600"># We demonstrate creating tables and indexes</font>
$sqlarray = $dict-><strong>CreateTableSQL</strong>($tabname, $flds, $taboptarray);
$dict-><strong>ExecuteSQLArray</strong>($sqlarray);<br>
$idxflds = 'co11, col2';
$sqlarray = $dict-><strong>CreateIndexSQL</strong>($idxname, $tabname, $idxflds);
$dict-><strong>ExecuteSQLArray</strong>($sqlarray);
</pre>
<h3>Functions</h3>
<h4>function CreateDatabase($dbname, $optionsarray=false)</h4>
<p>Create a database with the name $dbname;</p>
<h4>function CreateTableSQL($tabname, $fldarray, $taboptarray=false)</h4>
<pre>
RETURNS: an array of strings, the sql to be executed, or false
$tabname: name of table
$fldarray: string (or array) containing field info
$taboptarray: array containing table options
</pre>
<p>The new format of $fldarray uses a free text format, where each field is comma-delimited.
The first token for each field is the field name, followed by the type and optional
field size. Then optional keywords in $otheroptions:</p>
<pre> "$fieldname $type $colsize $otheroptions"</pre>
<p>The older (and still supported) format of $fldarray is a 2-dimensional array, where each row in the 1st dimension represents one field. Each row has this format:</p>
<pre> array($fieldname, $type, [,$colsize] [,$otheroptions]*)</pre>
<p>The first 2 fields must be the field name and the field type. The field type can be a portable type codes or the actual type for that database.</p>
<p>Legal portable type codes include:</p>
<pre>
C: varchar
X: Largest varchar size
XL: For Oracle, returns CLOB, otherwise same as 'X' above
C2: Multibyte varchar
X2: Multibyte varchar (largest size)
B: BLOB (binary large object)
D: Date (some databases do not support this, and we return a datetime type)
T: Datetime or Timestamp
L: Integer field suitable for storing booleans (0 or 1)
I: Integer (mapped to I4)
I1: 1-byte integer
I2: 2-byte integer
I4: 4-byte integer
I8: 8-byte integer
F: Floating point number
N: Numeric or decimal number
</pre>
<p>The $colsize field represents the size of the field. If a decimal number is used, then it is assumed that the number following the dot is the precision, so 6.2 means a number of size 6 digits and 2 decimal places. It is recommended that the default for number types be represented as a string to avoid any rounding errors.</p>
<p>The $otheroptions include the following keywords (case-insensitive):</p>
<pre>
AUTO For autoincrement number. Emulated with triggers if not available.
Sets NOTNULL also.
AUTOINCREMENT Same as auto.
KEY Primary key field. Sets NOTNULL also. Compound keys are supported.
PRIMARY Same as KEY.
DEF Synonym for DEFAULT for lazy typists.
DEFAULT The default value. Character strings are auto-quoted unless
the string begins and ends with spaces, eg ' SYSDATE '.
NOTNULL If field is not null.
DEFDATE Set default value to call function to get today's date.
DEFTIMESTAMP Set default to call function to get today's datetime.
NOQUOTE Prevents autoquoting of default string values.
CONSTRAINTS Additional constraints defined at the end of the field
definition.
</pre>
<p>The Data Dictonary accepts two formats, the older array specification:</p>
<pre>
$flds = array(
array('COLNAME', 'DECIMAL', '8.4', 'DEFAULT' => 0, 'NOTNULL'),
array('id', 'I' , 'AUTO'),
array('`MY DATE`', 'D' , 'DEFDATE'),
array('NAME', 'C' , '32', 'CONSTRAINTS' => 'FOREIGN KEY REFERENCES reftable')
);
</pre>
<p>Or the simpler declarative format:</p>
<pre>
$flds = "<font color="#660000"><strong>
COLNAME DECIMAL(8.4) DEFAULT 0 NOTNULL,
id I AUTO,
`MY DATE` D DEFDATE,
NAME C(32) CONSTRAINTS 'FOREIGN KEY REFERENCES reftable'</strong></font>
";
</pre>
<p>Note that if you have special characters in the field name (e.g. My Date), you should enclose it in back-quotes. Normally field names are not case-sensitive, but if you enclose it in back-quotes, some databases treat the names as case-sensitive, and some don't. So be careful.</p>
<p>The $taboptarray is the 3rd parameter of the CreateTableSQL function. This contains table specific settings. Legal keywords include:</p>
<ul>
<li><b>REPLACE</b><br />
Indicates that the previous table definition should be removed (dropped)together with ALL data. See first example below.
</li>
<li><b>DROP</b><br />
Drop table. Useful for removing unused tables.
</li>
<li><b>CONSTRAINTS</b><br />
Define this as the key, with the constraint as the value. See the postgresql example below.
Additional constraints defined for the whole table. You will probably need to prefix this with a comma.
</li>
</ul>
<p>Database specific table options can be defined also using the name of the database type as the array key. In the following example, <em>create the table as ISAM with MySQL, and store the table in the &quot;users&quot; tablespace if using Oracle</em>. And because we specified REPLACE, drop the table first.</p>
<pre> $taboptarray = array('mysql' => 'TYPE=ISAM', 'oci8' => 'tablespace users', 'REPLACE');</pre>
<p>You can also define foreignkey constraints. The following is syntax for postgresql:
<pre> $taboptarray = array('constraints' => ', FOREIGN KEY (col1) REFERENCES reftable (refcol)');</pre>
<h4>function DropTableSQL($tabname)</h4>
<p>Returns the SQL to drop the specified table.</p>
<h4>function ChangeTableSQL($tabname, $flds)</h4>
<p>Checks to see if table exists, if table does not exist, behaves like CreateTableSQL.
If table exists, generates appropriate ALTER TABLE MODIFY COLUMN commands if
field already exists, or ALTER TABLE ADD $column if field does not exist.</p>
<p>The class must be connected to the database for ChangeTableSQL to detect the
existence of the table. Idea and code contributed by Florian Buzin.</p>
<h4>function CreateIndexSQL($idxname, $tabname, $flds, $idxoptarray=false)</h4>
<pre>
RETURNS: an array of strings, the sql to be executed, or false
$idxname: name of index
$tabname: name of table
$flds: list of fields as a comma delimited string or an array of strings
$idxoptarray: array of index creation options
</pre>
<p>$idxoptarray is similar to $taboptarray in that index specific information can be embedded in the array. Other options include:</p>
<pre>
CLUSTERED Create clustered index (only mssql)
BITMAP Create bitmap index (only oci8)
UNIQUE Make unique index
FULLTEXT Make fulltext index (only mysql)
HASH Create hash index (only postgres)
DROP Drop legacy index
</pre>
<h4>function DropIndexSQL ($idxname, $tabname = NULL)</h4>
<p>Returns the SQL to drop the specified index.</p>
<h4>function AddColumnSQL($tabname, $flds)</h4>
<p>Add one or more columns. Not guaranteed to work under all situations.</p>
<h4>function AlterColumnSQL($tabname, $flds)</h4>
<p>Warning, not all databases support this feature.</p>
<h4>function DropColumnSQL($tabname, $flds)</h4>
<p>Drop 1 or more columns.</p>
<h4>function SetSchema($schema)</h4>
<p>Set the schema.</p>
<h4>function &amp;MetaTables()</h4>
<h4>function &amp;MetaColumns($tab, $upper=true, $schema=false)</h4>
<h4>function &amp;MetaPrimaryKeys($tab,$owner=false,$intkey=false)</h4>
<h4>function &amp;MetaIndexes($table, $primary = false, $owner = false)</h4>
<p>These functions are wrappers for the corresponding functions in the connection object. However, the table names will be autoquoted by the TableName function (see below) before being passed to the connection object.</p>
<h4>function NameQuote($name = NULL)</h4>
<p>If the provided name is quoted with backquotes (`) or contains special characters, returns the name quoted with the appropriate quote character, otherwise the name is returned unchanged.</p>
<h4>function TableName($name)</h4>
<p>The same as NameQuote, but will prepend the current schema if specified</p>
<h4>function MetaType($t,$len=-1,$fieldobj=false)</h4>
<h4>function ActualType($meta)</h4>
<p>Convert between database-independent 'Meta' and database-specific 'Actual' type codes.</p>
<h4>function ExecuteSQLArray($sqlarray, $contOnError = true)</h4>
<pre>
RETURNS: 0 if failed, 1 if executed all but with errors, 2 if executed successfully
$sqlarray: an array of strings with sql code (no semicolon at the end of string)
$contOnError: if true, then continue executing even if error occurs
</pre>
<p>Executes an array of SQL strings returned by CreateTableSQL or CreateIndexSQL.</p>
<hr />
<a name=xmlschema></a>
<h2>ADOdb XML Schema (AXMLS)</h2>
<p>This is a class contributed by Richard Tango-Lowy and Dan Cech that allows the user to quickly
and easily build a database using the excellent ADODB database library and a simple XML formatted file.
You can <a href=http://sourceforge.net/projects/adodb-xmlschema/>download the latest version of AXMLS here</a>.</p>
<h3>Quick Start</h3>
<p>First, create an XML database schema. Let's call it "schema.xml:"</p>
<pre>
&lt;?xml version="1.0"?&gt;
&lt;schema version=&quot;0.2&quot;&gt;
&lt;table name="mytable"&gt;
&lt;field name="row1" type="I"&gt;
&lt;descr&gt;An integer row that's a primary key and autoincrements&lt;/descr&gt;
&lt;KEY/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;/field&gt;
&lt;field name="row2" type="C" size="16"&gt;
&lt;descr&gt;A 16 character varchar row that can't be null&lt;/descr&gt;
&lt;NOTNULL/&gt;
&lt;/field&gt;
&lt;index name=&quot;myindex&quot;&gt;
&lt;col&gt;row1&lt;/col&gt;
&lt;col&gt;row2&lt;/col&gt;
&lt;/index&gt;
&lt;/table&gt;
&lt;sql&gt;
&lt;descr&gt;SQL to be executed only on specific platforms&lt;/descr&gt;
&lt;query platform="postgres|postgres7"&gt;
insert into mytable ( row1, row2 ) values ( 12, 'stuff' )
&lt;/query&gt;
&lt;query platform="mysql"&gt;
insert into mytable ( row1, row2 ) values ( 12, 'different stuff' )
&lt;/query&gt;
&lt;/sql&gt;
&lt;/schema&gt;
</pre>
<p>Create a new database using the appropriate tool for your platform.<br />
Executing the following PHP code will create the a <i>mytable</i> and <i>myindex</i>
in the database and insert one row into <i>mytable</i> if the platform is postgres or mysql.</p>
<pre>
include_once('/path/to/adodb.inc.php');
include_once('/path/to/adodb-xmlschema.inc.php');
<font color="#006600">// To build the schema, start by creating a normal ADOdb connection:</font>
$db->NewADOConnection( 'mysql' );
$db->Connect( ... );
<font color="#006600">// Create the schema object and build the query array.</font>
$schema = new <b>adoSchema</b>( $db );
<font color="#006600">// Optionally, set a prefix for newly-created tables. In this example
// the prefix "myprefix_" will result in a table named "myprefix_tablename".</font>
$schema-><b>SetPrefix</b>( 'myprefix_' );
<font color="#006600">// Build the SQL array</font>
$schema-><b>ParseSchema</b>( 'schema.xml' );
<font color="#006600">// Execute the SQL on the database</font>
$result = $schema-><b>ExecuteSchema</b>();
<font color="#006600">// Finally, clean up after the XML parser
// (PHP won't do this for you!)</font>
$schema-><b>Destroy</b>();
</pre>
<h3>Using AXMLS in Your
Application</h3>
<p>
There are two steps involved in using
AXMLS in your application: first,
you must create a schema, or XML representation of your
database, and second, you must create the PHP code that will
parse and execute the schema.</p>
<p>Let's begin with a schema that describes a typical, if simplistic
user management table for an application.</p>
<pre class="listing"><pre>
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;schema version=&quot;0.2&quot;&gt;
&lt;table name=&quot;users&quot;&gt;
&lt;desc&gt;A typical users table for our application.&lt;/desc&gt;
&lt;field name=&quot;userId&quot; type=&quot;I&quot;&gt;
&lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;
&lt;KEY/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;/field&gt;
&lt;field name=&quot;userName&quot; type=&quot;C&quot; size=&quot;16&quot;&gt;&lt;NOTNULL/&gt;&lt;/field&gt;
&lt;index name=&quot;userName&quot;&gt;
&lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;
&lt;col&gt;userName&lt;/col&gt;
&lt;UNIQUE/&gt;
&lt;/index&gt;
&lt;/table&gt;
&lt;sql&gt;
&lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;
&lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;
&lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;
&lt;/sql&gt;
&lt;/schema&gt;
</pre></pre>
<p>Let's take a detailed look at this schema.</p>
<p>The opening &lt;?xml version=&quot;1.0&quot;?&gt; tag is
required by XML. The &lt;schema&gt; tag
tells the parser that the enclosed markup defines an XML
schema. The version=&quot;0.2&quot; attribute sets
<em>the version of the AXMLS DTD used by the XML
schema.</em> <p>All versions of AXMLS prior
to version 1.0 have a schema version of &quot;0.1&quot;. The current
schema version is &quot;0.2&quot;.</p></p>
<pre class="listing"><pre>
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;schema version=&quot;0.2&quot;&gt;
...
&lt;/schema&gt;
</pre></pre>
<p>Next we define one or more tables. A table consists of a
fields (and other objects) enclosed by
&lt;table&gt; tags. The
name=&quot;&quot; attribute specifies the name of
the table that will be created in the database.</p>
<pre class="listing"><pre>
&lt;table name=&quot;users&quot;&gt;
&lt;desc&gt;A typical users table for our application.&lt;/desc&gt;
&lt;field name=&quot;userId&quot; type=&quot;I&quot;&gt;
&lt;descr&gt;A unique ID assigned to each user.&lt;/descr&gt;
&lt;KEY/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;/field&gt;
&lt;field name=&quot;userName&quot; type=&quot;C&quot; size=&quot;16&quot;&gt;&lt;NOTNULL/&gt;&lt;/field&gt;
&lt;/table&gt;
</pre></pre>
<p>This table is called &quot;users&quot; and has a description and
two fields. The description is optional, and is currently
only for your own information; it is not applied to the
database.</p>
<p>The first &lt;field&gt; tag will create
a field named &quot;userId&quot; of type &quot;I&quot;, or integer. (See the
ADOdb Data Dictionary
documentation for a list of valid types.) This
&lt;field&gt; tag encloses two special
field options: &lt;KEY/&gt;, which
specifies this field as a primary key, and
&lt;AUTOINCREMENT/&gt;, which specifies
that the database engine should automatically fill this
field with the next available value when a new row is
inserted.</p>
<p>The second &lt;field&gt; tag will create
a field named &quot;userName&quot; of type &quot;C&quot;, or character, and of
length 16 characters. The &lt;NOTNULL/&gt;
option specifies that this field does not allow
NULLs.</p>
<p>There are two ways to add indexes to a table. The
simplest is to mark a field with the
&lt;KEY/&gt; option as described above; a
primary key is a unique index. The second and more powerful
method uses the &lt;index&gt; tags.</p>
<pre class="listing"><pre>
&lt;table name=&quot;users&quot;&gt;
...
&lt;index name=&quot;userName&quot;&gt;
&lt;descr&gt;Put a unique index on the user name&lt;/descr&gt;
&lt;col&gt;userName&lt;/col&gt;
&lt;UNIQUE/&gt;
&lt;/index&gt;
&lt;/table&gt;
</pre></pre>
<p>The &lt;index&gt; tag specifies that an
index should be created on the enclosing table. The
name=&quot;&quot; attribute provides the name of the
index that will be created in the database. The
description, as above, is for your information only. The
&lt;col&gt; tags list each column that
will be included in the index. Finally, the
&lt;UNIQUE/&gt; tag specifies that this
will be created as a unique index.</p>
<p>Finally, AXMLS allows you to include arbitrary SQL that
will be applied to the database when the schema is
executed.</p>
<pre class="listing"><pre>
&lt;sql&gt;
&lt;descr&gt;Insert some data into the users table.&lt;/descr&gt;
&lt;query&gt;insert into users (userName) values ( 'admin' )&lt;/query&gt;
&lt;query&gt;insert into users (userName) values ( 'Joe' )&lt;/query&gt;
&lt;/sql&gt;
</pre></pre>
<p>The &lt;sql&gt; tag encloses any number
of SQL queries that you define for your own use.</p>
<p>Now that we've defined an XML schema, you need to know how to
apply it to your database. Here's a simple PHP script that shows
how to load the schema.</p>
<p><pre class="listing"><pre>
&lt;?PHP
/* You must tell the script where to find the ADOdb and
* the AXMLS libraries.
*/
require( &quot;path_to_adodb/adodb.inc.php&quot;);
require( &quot;path_to_adodb/adodb-xmlschema.inc.php&quot; );
/* Configuration information. Define the schema filename,
* RDBMS platform (see the ADODB documentation for valid
* platform names), and database connection information here.
*/
$schemaFile = 'example.xml';
$platform = 'mysql';
$dbHost = 'localhost';
$dbName = 'database';
$dbUser = 'username';
$dbPassword = 'password';
/* Start by creating a normal ADODB connection.
*/
$db = ADONewConnection( $platform );
$db-&gt;Connect( $dbHost, $dbUser, $dbPassword, $dbName );
/* Use the database connection to create a new adoSchema object.
*/
$schema = new adoSchema( $db );
/* Call ParseSchema() to build SQL from the XML schema file.
* Then call ExecuteSchema() to apply the resulting SQL to
* the database.
*/
$sql = $schema-&gt;ParseSchema( $schemaFile );
$result = $schema-&gt;ExecuteSchema();
?&gt;
</pre></pre></p>
<p>Let's look at each part of the example in turn. After you
manually create the database, there are three steps required to
load (or upgrade) your schema.</p>
<p>First, create a normal ADOdb connection. The variables
and values here should be those required to connect to your
database.</p>
<pre class="listing"><pre>
$db = ADONewConnection( 'mysql' );
$db-&gt;Connect( 'host', 'user', 'password', 'database' );
</pre></pre>
<p>Second, create the adoSchema object that load and
manipulate your schema. You must pass an ADOdb database
connection object in order to create the adoSchema
object.</p>
<pre class="listing"><pre>
$schema = new adoSchema( $db );
</pre></pre>
<p>Third, call ParseSchema() to parse the
schema and then ExecuteSchema() to apply
it to the database. You must pass
ParseSchema() the path and filename of
your schema file.</p>
<pre class="listing"><pre>
$schema-&gt;ParseSchema( $schemaFile );
$schema-&gt;ExecuteSchema();
</pre></pre>
<p>Execute the above code and then log into your database. If you've
done all this right, you should see your tables, indexes, and
SQL.</p>
<p>You can find the source files for this tutorial in the
examples directory as
tutorial_shema.xml and
tutorial.php. See the class documentation for
a more detailed description of the adoSchema methods, including
methods and schema elements that are not described in this
tutorial.</p>
<H3>XML Schema Format:</H3>
<P>(See <a href="xmlschema.dtd">xmlschema.dtd</a> for the full specification)</P>
<PRE>
&lt;?xml version="1.0"?&gt;
&lt;schema version=&quot;0.2&quot;&gt;
&lt;table name="tablename" platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;field name="fieldname" type="datadict_type" size="size"&gt;
&lt;KEY/&gt;
&lt;NOTNULL/&gt;
&lt;AUTOINCREMENT/&gt;
&lt;DEFAULT value="value"/&gt;
&lt;/field&gt;
<i> ... more fields</i>
&lt;index name="indexname" platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;col&gt;fieldname&lt;/col&gt;
<i> ... more columns</i>
&lt;/index&gt;
<i> ... more indexes</i>
&lt;/table&gt;
<i> ... more tables</i>
&lt;sql platform="platform1|platform2|..."&gt;
&lt;descr&gt;Optional description&lt;/descr&gt;
&lt;query platform="platform1|platform2|..."&gt;SQL query&lt;/query&gt;
<i> ... more queries</i>
&lt;/sql&gt;
<i> ... more SQL</i>
&lt;/schema&gt;
</pre>
<h3>Upgrading</h3>
If your schema version is older, than XSLT is used to transform the schema to the newest version.
This means that if you are using an older XML schema format, you need to have the XSLT extension installed.
If you do not want to require your users to have the XSLT extension installed, make sure you
modify your XML schema to conform to the latest version.
<hr />
<address>If you have any questions or comments, please email them to Richard at richtl#arscognita.com.
</address>
</body>
</html>