本家のCookbookを見て、ちょっと試してみたところ、個人的にちょっと扱いづらかったのでいきなりTableクラスとRecordクラスを拡張することから始めてみた。
使いづらかった部分というのは、
// Tableクラスの拡張
Object.extend( Table.prototype, {
_each : function(iterator) {
for(var i = 1; i <= this.count; i++) {
iterator( this.getRow( i ) );
}
},
// カラム名を配列で取得する
colNames : function() {
return this.getColumnInfo().map( function( col ) { return col.name; } );
},
// カラム情報の配列を取得する。orderは列位置、nameはカラム名、typeは型情報
getColumnInfo : function() {
var result = [];
for(var i = 1; i <= this.colCount; i++) {
result.push( {
order : i,
name : this.title( i ),
type : this.type( i - 1 ).toArray().join("")
} );
}
return result;
}
} );
Object.extend( Table.prototype, Enumerable );
// Recordクラスの拡張
Object.extend( Record.prototype, {
// 名前:値形式の単純なオブジェクトを返す
toHash : function() {
var result = {};
for(var i = 0; i < this.count; i++) {
result[ this.name( i ) ] = this.value( i );
}
return result;
}
} );
// オブジェクトをパラメータにとってRecordを作成するファクトリメソッド
Record.fromHash = function(hash) {
var src = $H( hash ).map( function(entry) {
return [ entry.key, "=", entry.value == null ? "NULL" : entry.value ].join("");
} ).join(",");
return new Record( src );
}
このような拡張をした上で、データベースへアクセスしてみる。ここではmdbを使用してみた。
適当なmdbファイルを「test_db」としてODBCデータソース(ユーザDSNまたはシステムDSN)に登録しておいて、以下のようなコードでテーブルの作成、行の挿入、行の取得を行う。
js>var odbc = new ODBC("DSN=test_db")
js>odbc.exec("create table t_test ( id integer primary key, name text )")
true
js>var updater = new Table("odbc://test_db/t_test");
js>updater.add( Record.fromHash( { id : 1, name : "test 1" } ) )
-1
js>updater.add( Record.fromHash( { id : 2, name : "test 2" } ) )
-1
js>var table = odbc.query( "select * from t_test" );
js>table.each( function(record) {
2: writeln( $H( record.toHash() ).inspect() )
3: } )
#<Hash:{'id': '1', 'name': 'test 1'}>
#<Hash:{'id': '2', 'name': 'test 2'}>
js>table.close()
true
js>updater.close()
true
js>odbc.close()
true
js>
まずは、「new ODBC()」でODBCオブジェクトを初期化する。この例ではmdbを使用したためユーザID・パスワードはないが、通常のDBMSの場合は「UID=ユーザID;PWD=パスワード」を追加する必要がある。
次のODBC#execでテスト用のテーブルを作成している。insert/delete/updateの場合もexecメソッドで実行する。
次の変数「updater」は今作成したテーブルの更新に使用するTableオブジェクト。この後に説明するODBC#queryメソッドの戻りもTableオブジェクトだが、それは読み取り専用らしく、更新する場合はこの例のようにURIをパラメータにしてTableをnewする必要がある。
その後はTable#addメソッドで行を新規に追加しているが、追加する行の初期化には、このエントリで拡張したRecrd::fromHashメソッドを使用している。このような拡張をしない場合は、updater.add( new Record( "id=1,name=test 1" ) );のようになる。
次に、ODBC#queryを使用してupdaterとは別にTableを取得している。この「table」は読み取り専用でaddメソッドは失敗する。
セコメントをする