PharoでGlorp経由でPostgreSQLを利用する方法(日本語対応)

Glorp経由でPostgreSQLのデータベースにデータを登録しようと、ワークスペースで以下のようなコードを実行しましたが、エラーになりました。

login := Login new database: PostgreSQLPlatform new;
         username: 'postgres';
         password: 'postgres';
         connectString: '127.0.0.1_databasename'.

hoge := HogeModel new.
hoge title: '日本語は通る?'.

session := HogeModelDescriptorSystem sessionForLogin: login.
session login.
session save: hoge. "DB登録"
session logout .

スタックトレースをみると、どうやら暗号化のためのMD5クラスのところでこけています。

しかしPharoにはMD5クラス自体が存在しないため、このクラスをSqueakから持ってくることにします。

暗号化パッケージを追加

  1. Squeak 3.10からCryptography-Core, Cryptography-MD5の2つのパッケージをファイルアウトします。
  2. ファイルアウトすると、Squeakのあるフォルダに上記パッケージのファイルが生成されますので、それぞれのファイルをPharoにドラッグ&ドロップします。
  3. ファイル全体をファイルインします。

これで接続自体は成功するようになりました。

しかし、pgAdminでPostgreSQLのテーブルを見ると、日本語が文字化けしています。Glorpには梅澤さんの作成されたGlorpI18Nパッチがありますが、それをMoticelloでLoadしているのですが、文字化けしています。

Unicode対応

MonticelloでGlorpI18Nパッケージを選択し[Browse]ボタンを押すと、このパッチがGlorpのどこに変更しているか、その一覧が出てきます。その一覧のなかを調べていくと、DatabasePlatformクラスの*glorpI18N-overrideカテゴリのcharEncodingメソッドで、エンコーディングを指定していました。

characterEncoding
	"We hope that this will be set appropriately for the connection, but make sure the default is fairly harmless, and will in most cases complain rather than write characters incorrectly"
	characterEncoding isNil ifTrue: [characterEncoding := #utf8].
	^characterEncoding

文字エンコードがUTF8になっているので、ここをUCS2(Unicode)に書き換え、acceptします。どうやら、Squeak 3.10からは内部文字エンコードUnicodeになったようで、Sqeuakの後継であるPharoもその影響を受けているようです。(←これは間違いでした)

characterEncoding
	"We hope that this will be set appropriately for the connection, but make sure the default is fairly harmless, and will in most cases complain rather than write characters incorrectly"
	characterEncoding isNil ifTrue: [characterEncoding := #ucs2].
	^characterEncoding

以上で、PharoでGlorp経由でPostgreSQLを利用することが出来るようになりました。