XMLDB 新しいDDL関数の作成 (Dev docs)

提供:MoodleDocs
2023年2月3日 (金) 07:09時点におけるToshihiro KITA (トーク | 投稿記録)による版 (→‎説明された例)
移動先:案内検索

Moodle 2.0 XMLDB ドキュメンテーション > ロードマップ > XMLDB 新しい DDL 関数の作成 ----

(このページは現在翻訳中です)

重要: このページで紹介するすべての機能は、Moodle 2.0 以降 で使用するためのもので、ここではいくつかの新機能をサポートするために DB レイヤ を変更しました。もし、あなたが以前の Moodle バージョンの情報を必要とするならば、2.0 以前 のページをご覧ください。

ジャスティフィケーション

XMLDB の構造 が正しく定義され、それを使ってあらゆる DB モデルを抽象化できるようになったら、今度はその XML 構造から提供される情報に基づいて、必要な DB オブジェクトを作成する関数群を構築することになります。これらの関数はすべてXMLBオブジェクト(XMLDBTable, XMLDBField, XMLDBKey, XMLDBIndex)を使用し、抽象度を保つようにします。

これらの機能によって供給される目的は、以下の通りです:

  • インストール プロセスで、古い *.sql の使用に代わって使用され、必要なすべての DB オブジェクトが作成されます。
  • アップグレード プロセスで、新しい upgrade.php スクリプトで、すべての DB オブジェクトを処理するために使用されます。

XMLDBオブジェクトをDDL関数で使うのか、XMLDBスキーマから完全に独立した新しい関数をたくさん作るのか、当初は完全に決まっていませんでしたが、最終的には、以前に作ったオブジェクトを使うことにしました。主な理由は:

  • テーブルやフィールドなどを表すオブジェクトがある場合、同じ種類のオブジェクトをパラメータとして必要とする新しい関数を作って、それを使わないというのはあまり意味がありません。
  • XMLDB オブジェクトに変更があれば、DDL 関数ですぐに利用できるようになります(新しいカラムタイプが1つ追加される...)。
  • SQL コードの生成はすべて XMLDB クラス自身が担当するので、DDL 関数内のコードは非常にシンプルになります。
  • XMLDB オブジェクトを利用することで、XMLDB エディタ(XMLDB の構造を簡単に編集するツール)を改良し、upgrade.php スクリプトで使用する必要な PHP コードを自動的に生成することができるようになりました。オブジェクト(テーブル/フィールド/インデックス/キー)と実行するアクション(作成/削除/名前変更/変更)を選択するだけで、なんと!アップグレードスクリプトに貼り付けるすべての PHP コードを取得することができます。(近日公開) ;-)

唯一の欠点は、XMLDB オブジェクトの作成と定義のコードをすべて含む必要があるため、アップグレードのコードが少し長くなることです。しかし、その一方で、読みやすいコードになるはずです。

実装

基本コンセプト

全ての機能は:

  • XMLDB オブジェクト (変更されるもの) をパラメータとして受け取ります。
  • DB に対して SQL コマンドを実行する前に、可能な限りのチェックを行います。
  • 成功/エラー時に true/false を返します (XMLDB オブジェクトは、XMLDBObject->getError() 関数で利用できるエラーに関する特別な情報を含みます) 。
  • 有効な場合、デバッグ情報を出力します。

XMLDBオブジェクトの取り扱い

はじめに

DDL 関数自体を呼び出す前に、適切な XMLDB オブジェクトを適切に作成し、関数が作業を行えるようにするために必要な情報をすべて含んでいる必要があります。あらゆる DDL 操作の基本的なコード構造は以下のようにあるべきです:

  1. プログラムによる XMLDB オブジェクトの作成。
  2. DDL 関数の呼び出し。
  3. エラーのチェック

基本例

この手順の簡単な例として、次のような PHP の行があります。これは、主キー、外部キー、インデックスをひとつずつ持つ単純なテーブルを作成するために使用します:

 
$field1 = new xmldb_field('id');
$field1->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, [null, null,] null, null); // [XMLDB_ENUM, null,] Moodle 2.x deprecated  
$field2 = new xmldb_field('name');
$field2->set_attributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, [null, null,] 'default name', 'id'); // [XMLDB_ENUM, null,] Moodle 2.x deprecated 
$field3 = new xmldb_field('course');
$field3->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, [null, null,] null, 'name'); //  [XMLDB_ENUM, null,] Moodle 2.x deprecated 
$field4 = new xmldb_field('type');
$field4->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, [XMLDB_ENUM, array('type1', 'type2', 'type3'),] 'type1', 'course'); //  [XMLDB_ENUM, null,] Moodle 2.x deprecated 
$field5 = new xmldb_field('summary');
$field5->set_attributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, [null, null,] null, 'type'); //  [XMLDB_ENUM, null,] Moodle 2.x deprecated 
$key1 = new xmldb_key('primary');
$key1->set_attributes(XMLDB_KEY_PRIMARY, array('id'), null, null);
$key2 = new xmldb_key('foreignkey1');
$key2->set_attributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id')); 
 
$index1 = new xmldb_index('type');
$index1->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('type'));
 
$table = new xmldb_table('my_first_xmldb_table');
$table->addField($field1);
$table->addField($field2);
$table->addField($field3);
$table->addField($field4);
$table->addField($field5);
 
$table->addKey($key1);
$table->addKey($key2);
 
$table->addIndex($index1);
 
$status = $dbman->create_table($table);

まず最初に、慌てないでください!上記のコードは簡単に、正確に言うと10行に減らすことができますが、少し詳しく説明するために、長いバージョンをここに掲載します。;-) また、XMLDB オブジェクトの使用に関する今後の機能の一つとして、XMLDB エディタがこれらのPHPコードを全て自動生成 してくれることも忘れてはいけません。

説明された例

まず、最初の2行から見ていきましょう:

$field1 = new xmldb_field('id');
$field1->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, [null, null,] null, null); //  [XMLDB_ENUM, null,] Moodle 2.x deprecated

最初の行では、"id" という新しいフィールドを作成しています(これはテーブルのカラムの名前になるので、XMLDBの命名規則コーディングガイドラインに従うことを忘れないようにしてください)。

2行目では、単純な関数呼び出しによって、フィールドのすべての属性を定義しています。パラメータのリストは以下の通りです:

  1. Column Type: これらのうちのいずれか一つ: XMLDB_TYPE_INTEGER, XMLDB_TYPE_NUMBER, XMLDB_TYPE_CHAR, XMLDB_TYPE_TEXT, XMLDB_TYPE_BINARY。XMLDB の内部では他のカラムタイプもサポートしていますが、それはいくつかの特別なテーブルとの互換性のためだけであることに注意してください。Moodle は上記のリストから外れたものを使用するべきではありません。
  2. Column precision: INTEGERS と CHARS には length、NUMBERS には2つのカンマ区切りの数値(全長と小数点以下の桁数)、そして TEXTSとBINARIESはこのうちの1つ: "small", "medium", "big" を指定します。
  3. Unsigned: 数値フィールドが符号なしであるかどうかを指定するために、XMLDB_UNSIGNED 定数を使用します。符号付きの場合は、null を渡します。
  4. Not Null: フィールドが null でないかどうかを指定するために、XMLDB_NOTNULL 定数を使用します。null 可能であれば、null を渡します。
  5. Sequence: フィールドがシーケンス(または自動数値、自動インクリメント、その他呼び方は何でも)であるかどうかを指定するために、XMLDB_SEQUENCE 定数を使用することにします。そうでない場合は、null を渡します。
  6. Enum: フィールドが限られた数の値しか含まないかどうかを指定するために、XMLDB_ENUM 定数を使用します。そうでない場合は、null を渡します。 // Moodle 2.0 は非推奨
  7. Enum values: フィールドが XMLDB_ENUM として定義されている場合、このパラメータは、そのフィールドに可能なすべての値を含む 1 つの配列を持つことになります。そうでない場合は null です。 // Moodle 2.0 は非推奨
  8. Default value: フィールドに定義すべき意味のあるデフォルト値がある場合、このパラメータはそれを含みます。そうでない場合は、null です。
  9. After-field: もし、DB 内の他の正確なカラムの後にフィールドを作成することを強制したい場合、このパラメータでそうすることができます。指定しない場合、追加されたすべてのフィールドは最新のものの後に作成されるので、この例では全く定義できないことに注意してください。未定義の場合は、もう一度 null を使用することにします。

つまり、上記のコードでは、"id" という名前の1つのフィールドを作成しています。このフィールドは10桁の整数で、null ではなく、自動数字になります。次のフィールドを見てみましょう:

$field2 = new xmldb_field('name');
$field2->set_attributes(XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, [null, null,] 'default name', 'id'); //  [XMLDB_ENUM, Enum values,] Moodle 2.x deprecated

ここでは、"name" という名前の新しいフィールドを1つ作成しています。これは、最大長 255cc の1文字で、null ではなく、デフォルト値("default name")を1つ持ち、"id" フィールドの後に作成されます(繰り返しますが、テーブル作成において、この順序は全く役に立たず、テーブルにフィールドを追加した順序が使われることに注意してください)。

次に検証してみましょう:

$field3 = new xmldb_field('course');
$field3->set_attributes(XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, [null, null,] null, 'name'); //  [XMLDB_ENUM, Enum values,] Moodle 2.x deprecated

もう一つの新しいフィールド、名前は "course"、最大長10、符号なし、null でない整数値です (上の行で述べたように、after-field の情報を定義するために 'name' 値は忘れてください)。

もう1つのフィールド:

$field4 = new xmldb_field('type');
$field4->set_attributes(XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, [XMLDB_ENUM, array('type1', 'type2', 'type3'),] 'type1', 'course'); //  [XMLDB_ENUM, Enum values,] Moodle 2.x deprecated

このフィールドは "type" と呼ばれ、char(20) で null ではなく、3つの値 ("type1", "type2", "type3") を持ち、そのデフォルト値は "type1" となる。

そして、この例では最後のフィールドです:

$field5 = new xmldb_field('summary');
$field5->set_attributes(XMLDB_TYPE_TEXT, 'medium', null, null, null, [null, null,] null, 'type');

それは、"summary" というフィールド名で、長さが "medium" の text タイプになります。

また、これらの "null" パラメータをすべて指定することは必須ではなく、右から順に、安全に避けることができることに注意してください。したがって、最後に見たフィールドは、(もう一度、after-field パラメータを無視すれば)可能です。

$field5->set_attributes(XMLDB_TYPE_TEXT, 'medium');

では、キーの作成について解析してみましょう。この例で最初に指定するキーは:

$key1 = new xmldb_key('primary');
$key1->set_atrributes(XMLDB_KEY_PRIMARY, array('id'), null, null);

最初の行で、"primary" という名前のインデックスを作成する。前のコードで指定したフィールド名は DB のフィールド名になるので重要ですが、ここで指定した名前は全く重要ではありません。主に XMLDB のキーとインデックスの命名規則 があるので、作成されるキーとインデックスはその規則に従って自動的に命名されることに注意してください。 Anyway, in the XMLDB files we use to call "primary" to the primary key and to concatenate the name of the fields in the key/index separated by "-" as their official name. But here it isn't important.

The second line completely defines the key. Attributes are:

  1. Key Type: Can be one of these: XMLDB_KEY_PRIMARY, XMLDB_KEY_UNIQUE and XMLDB_KEY_FOREIGN that are the basic constraint types for our relational DB model. It's important to note that all the keys above will have one index created for them automatically so, when you define any Key, you haven't to define any index with the same fields at all. XMLDB will do it for you. More yet, for now, Foreign Keys won't be enforced (just the underlying indexes will be created) because before enabling them a lot of changes need to be performed within Moodle processes. But we want to have all those relations defined since the beginning of XMLDB. It will allow us to move quickly to a pure relational model.
  2. List of fields: An array containing the names of the fields that will be part of the key (and the underlying index).
  3. Reference table: Exclusively for Foreign Keys, the table where the fields defined in the previous parameter are pointing to.
  4. Reference fields: Exclusively for Foreign Keys, the list of fields in the reference table that must match with the list of fields in the own table. Please note that, those "reference fields" must be defined as primary or unique key in the reference table. Relational rules, you know. So avoid pointing to fields not satisfying this condition completely!

With all this info, we know that we are going to create one primary key with the field "id". Remember that XMLDB will set the correct name for that key.

The second index in our example says:

$key2 = new xmldb_key('foreignkey1');
$key2->set_attributes(XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id'));

Here we are creating one more key, of type foreign key, with the field "course" pointing to the "id" field of the "course" table. Once more, the name isn't important at all.

And finally, we arrive to the indexes. Don't forget that all the previously defined keys will generate one underlying index with the fields specified so, in this sections we only have to define some other combinations of fields that are used often by SQL statements. By providing the correct indexes we'll get big speed improvements. But they must be correct. It's absolutely wrong to "index everything" without knowing what is being done. Don't forget it!

In our example we have this lines of code:

$index1 = new xmldb_index('type');
$index1->set_attributes(XMLDB_INDEX_NOTUNIQUE, array('type'));

In the first line we create the new index object. Remember, that the name provided here isn't the name of the index in the RDBMS, XMLDB key and index naming will define it automatically.

In the second line we specify:

  1. Index Type: that can be XMLDB_INDEX_NOTUNIQUE (that is pretty equivalent to null, the default) or XMLDB_INDEX_UNIQUE depending if the list of fields defined in the previous parameter allows duplicate tuples or no.
  2. List of fields: An array containing the names of the fields that will be part of the index.

So, in the example, we are creating one non unique index with the field called "type".

With this we've seen all the individual objects that conforms one table structure. Now we are going all these object to our new table so code says:

$table = new xmldb_table('my_first_xmldb_table');
$table->addField($field1);
$table->addField($field2);
$table->addField($field3);
$table->addField($field4);
$table->addField($field5);

$table->addKey($key1);
$table->addKey($key2);

$table->addIndex($index1);

With this lines we are simply creating one new table, called "my_first_xmldb_table", whose name must follow the XMLDB naming conventions and the coding guidelines. Then all the previously defined fields, keys and indexes are added to the table. Point.

And the final line of our code is:

$status = $dbman->create_table($table);

With this line, we'll create the DB table, with all the fields/keys/indexes specified with all the specs defined in the previous lines, with the correct prefix, proper object naming and particularities for each different RDBMS. This function call will return true/false, depending if the execution of the needed SQL commands has ended Ok or no.

Wow, at last, we end!!

Reduced (and recommended) example

All the lines in the example above have been really good to explain how to create any XMLDBField, XMLDBKey, XMLDBIndex and XMLDBTable structures from PHP code but we must recognise that it's a bit awful in terms of readability and length. So, for the creation of tables, we can use the following code, that is a complete replacement for the previous one:

$table = new xmldb_table('my_first_xmldb_table');
 
$table->add_field('id', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, XMLDB_SEQUENCE, null, null, null);
$table->add_field('name', XMLDB_TYPE_CHAR, '255', null, XMLDB_NOTNULL, null, null, null, 'default name');
$table->add_field('course', XMLDB_TYPE_INTEGER, '10', XMLDB_UNSIGNED, XMLDB_NOTNULL, null, null, null, null);
$table->add_field('type', XMLDB_TYPE_CHAR, '20', null, XMLDB_NOTNULL, null, XMLDB_ENUM, array('type1', 'type2', 'type3'), 'type1');
$table->add_field('summary', XMLDB_TYPE_TEXT, 'medium', null, null, null, null, null, null);
 
$table->add_key('primary', XMLDB_KEY_PRIMARY, array('id'), null, null);
$table->add_key('foreignkey1', XMLDB_KEY_FOREIGN, array('courseid'), 'course', array('id')); 
 
$table->add_index('type', XMLDB_INDEX_NOTUNIQUE, array('type'));
 
$status = $dbman->create_table($table);

Better, isn't it? ;-)

All the documentation in the previous complete example continues being 100% valid here. Just note that, when using this syntax, we have one more field, exactly the first one, that must be used to specify the name of the field/key/index being added. The rest is exactly the same!

Integration with the XMLDB Editor

Now you should know a bit more about how to create tables via PHP under the new XMLDB schema. It was really important to know about it because, in the process, you've seen how to create fields, keys and indexes, plus some extra notions about the whole thing.

Also, the creation of tables is, with difference, the most difficult operation (in terms of PHP generated) that you will find under all the new DDL functions. Other operations like rename, drop, alter will be really easier to use. Trying to help you a bit in the PHP generation, if you use the XMLDB Editor to design and create your DB structures, you will be able to obtain all the code needed to perform different DDL actions automatically.

Just go to the table/field/key/index you are modifying and, after performing the desired changes, press the "PHP Code" link and it will show you one new page with all (practically) the options available. Just select the desired one and the required PHP will appear in seconds

Such code can be directly used by your upgrade scripts (by modifying some minor bits here and there) improving the DB experience and reducing the risk of errors a lot.

Also, it's highly recommended to use such utility to understand better how the PHP code works, like an online tutor. Enjoy it!

関連項目

  • DDL functions: To get access to the updated documentation about the functions available to modify the DB objects.
  • XML structure: To know a bit more about the internal XML structure used to describe all the DB objects using one neutral language.
  • List of functions to create: The list of functions to be created from scratch. Used to follow the progress and its status.