2009年9月1日火曜日

Monoで他のDBも使ってみたよ!+(db4o、NHibernate編)3

このエントリーをはてなブックマークに追加

動作確認

基本的なDB操作(登録、更新、削除)を確認するために、次のコード(C#)を使用します。db4o DBはEmbeded Serverモードでオープンします。

 作業する上でのディレクトリ構造は、下表の通りとします。

ディレクトリファイル
~/src/cs/db4oExampleIProductRepository.cs
~/src/cs/db4oExample/Testclient.cs, client.exe.config
~/src/cs/db4oExample/TestDataProductRepository.cs, TestDataHelper.cs
IProductRepositoryインターフェース、ProductRepository、TestDataHelperクラス

[IProductRepository.cs]
using System;

namespace db4oExample
{
  public interface IProductRepository : IDisposable
  {
    void Add(Product product);
    void Update(Product product);
    void Remove(Product product);
    void GetAll();
  }
}

[ProductRepository.cs]
using System;
using System.Collections.Generic;
using System.Linq;
using Db4objects.Db4o;
using Db4objects.Db4o.Linq;

using db4oExample;

namespace db4oExample.TestData
{
  public class ProductRepository : IProductRepository
  {
    private static IList<Product> _cache;

    public void Add(Product product)
    {
      using (IObjectContainer client = TestDataHelper.OpenClient())
      {
        Product r1 = _getByIdFromCache(product.Id);
        if (r1 != null)
        {
          Console.WriteLine("Add:既にデータあり #1");
          return;
        }

        Product r2 = _getById(client, product.Id);
        if (r2 != null)
        {
          Console.WriteLine("Add:既にデータあり #2");
          return;
        }

        try
        {
          client.Store(product);
          client.Commit();
        }
        catch(Exception ex)
        {
          Console.WriteLine("例外: {0}", ex.Message);
          client.Rollback();
        }
      }
    }

    public void Update(Product product)
    {
      using (IObjectContainer client = TestDataHelper.OpenClient())
      {
        Product r1 = _getByIdFromCache(product.Id);
        if (r1 == null)
        {
          Console.WriteLine("Update:該当データなし #1");
          return;
        }      

        Product r2 = _getByProduct(client, r1);
        if (r2 == null)
        {
          Console.WriteLine("Update:該当データなし #2");
          return;
        }

        r2.Name        = product.Name;
        r2.Price       = product.Price;
        r2.Description = product.Description;

        try
        {
          client.Store(r2);
          client.Commit();
        }
        catch(Exception ex)
        {
          Console.WriteLine("例外: {0}", ex.Message);
          client.Rollback();
        }
      }
    }

    public void Remove(Product product)
    {
      using (IObjectContainer client = TestDataHelper.OpenClient())
      {
        Product r1 = _getByIdFromCache(product.Id);
        if (r1 == null)
        {
          Console.WriteLine("Remove:該当データなし #1");
          return;
        }

        Product r2 = _getByProduct(client, r1);
        if (r2 == null)
        {
          Console.WriteLine("Remove:該当データなし #2");
          return;
        }

        try
        {
          client.Delete(r2);
          client.Commit();
        }
        catch(Exception ex)
        {
          Console.WriteLine("例外: {0}", ex.Message);
          client.Rollback();
        }
      }
    }

    public void GetAll()
    {
      using (IObjectContainer client = TestDataHelper.OpenClient())
      {
        _cache = (from Product p in client
          orderby p.Id
          select p).ToList();

        foreach (Product p in _cache)
        {
          Console.WriteLine(p);
        }
      }
    }

    public void Dispose()
    {
      TestDataHelper.CloseServer();
    }

    private Product _getById(IObjectContainer client, int id)
    {
      return (from Product p in client
        where p.Id == id
        select p).SingleOrDefault();
    }

    private Product _getByIdFromCache(int id)
    {
      return (from Product p in _cache
        where p.Id == id
        select p).SingleOrDefault();
    }

    private Product _getByProduct(IObjectContainer client, Product product)
    {
      return (from Product p in client
        where p.Id == product.Id &&
          p.Name == product.Name &&
          p.Price == product.Price &&
          p.Description == product.Description
        select p).SingleOrDefault();
    }
  }
}

[TestDataHelper.cs]
using System;
using System.Configuration;
using Db4objects.Db4o;

namespace db4oExample.TestData
{
  public class TestDataHelper
  {
    private static IObjectServer _server;

    private static IObjectServer Server
    {
      get
      {
        if (_server == null)
        {
          string dbfile = ConfigurationManager.AppSettings["dbfile"];
          _server = Db4oFactory.OpenServer(dbfile, 0);
        }
        return _server;
      }
    }

    public static IObjectContainer OpenClient()
    {
      return Server.OpenClient();
    }

    public static void CloseServer()
    {
      if (Server != null)
      {
        Server.Close();
      }
    }
  }
}
ライブラリとしてビルドします。

[ビルド実行例]
$ cd ~/src/cs/db4oExample
$ gmcs -t:library -r:System.Configuration.dll,Db4objects.Db4o.dll,Db4objects.Db4o.Linq.dll -out:./Test/db4oExample.dll Product.cs IProductRepository.cs -recurse:./TestData/*.cs
動作確認用プログラム
ProductRepositoryインスタンスを使用したDB操作を行います。

[client.cs]
using System;

using db4oExample;
using db4oExample.TestData;

namespace db4oExample.Test
{
  public class Client
  {
    public static void Main(string[] args)
    {
      using (IProductRepository products = new ProductRepository())
      {
        products.GetAll();

        string s = "";
        while(s != "5")
        {
          Console.WriteLine();
          Console.Write("1:ADD\n2:UPDATE\n3:REMOVE\n4:RELOAD\n5:EXIT\n?> ");
          s = Console.ReadLine();
          switch(s)
          {
            case "1": AddProduct(products);    goto case "4"; // 追加
            case "2": UpdateProduct(products); goto case "4"; // 更新
            case "3": RemoveProduct(products); goto case "4"; // 削除
            case "4": products.GetAll();       goto default; // 再読込
            case "5": goto default; // 終了
            default : break;
          }
        }
      }
    }

    private static void AddProduct(IProductRepository products)
    {
      try
      {
        products.Add(CreateProduct());
      }
      catch(Exception ex)
      {
        Console.WriteLine("例外: {0}", ex.Message);
      }
    }

    private static void UpdateProduct(IProductRepository products)
    {
      try
      {
        products.Update(CreateProduct());
      }
      catch(Exception ex)
      {
        Console.WriteLine("例外: {0}", ex.Message);
      }
    }

    private static void RemoveProduct(IProductRepository products)
    {
      Console.Write("ID(int)?> ");
      string id = Console.ReadLine();

      try
      {
        Product product = new Product();
        product.Id = Int32.Parse(id);
        products.Remove(product);
      }
      catch(Exception ex)
      {
        Console.WriteLine("例外: {0}", ex.Message);
      }
    }

    private static Product CreateProduct()
    {
      Console.Write("ID(int)?> ");
      string id = Console.ReadLine();
      Console.Write("NAME(string)?> ");
      string name = Console.ReadLine();
      Console.Write("PRICE(num)?> ");
      string price = Console.ReadLine();
      Console.Write("DESCRIPTION(string)?> ");
      string description = Console.ReadLine();

      Product product = new Product();
      product.Id   = Int32.Parse(id);
      product.Name = name;

      if (price != "")
      {
        product.Price = Decimal.Parse(price);
      }

      product.Description = description;

      return product;
    }
  }
}
/*
* ビルド:
*
*   gmcs -r:db4oExample.dll client.cs
*
* 実行:
*
*   mono client.exe
*
*/

[client.exe.config]
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="dbfile" value="/home/sta/data/db4o/TestData.db4o" />
  </appSettings>
</configuration>

[実行例]
$ cd ~/src/cs/db4oExample/Test
$ mono client.exe
ID:0 NAME:db4o PRICE: DESCRIPTION:db4o 7.4
ID:1 NAME:Clamp PRICE:12.48 DESCRIPTION:Workbench clamp
ID:50 NAME:Flat Head Screwdriver PRICE:3.17 DESCRIPTION:Flat head
ID:75 NAME:Tire Bar PRICE: DESCRIPTION:Tool for changing tires.
ID:3000 NAME:3mm Bracket PRICE:0.52 DESCRIPTION:

1:ADD
2:UPDATE
3:REMOVE
4:RELOAD
5:EXIT
?> 1
ID(int)?> 2
NAME(string)?> test2
PRICE(num)?> 2.2
DESCRIPTION(string)?> for test2
ID:0 NAME:db4o PRICE: DESCRIPTION:db4o 7.4
ID:1 NAME:Clamp PRICE:12.48 DESCRIPTION:Workbench clamp
ID:2 NAME:test2 PRICE:2.2 DESCRIPTION:for test2
ID:50 NAME:Flat Head Screwdriver PRICE:3.17 DESCRIPTION:Flat head
ID:75 NAME:Tire Bar PRICE: DESCRIPTION:Tool for changing tires.
ID:3000 NAME:3mm Bracket PRICE:0.52 DESCRIPTION:

1:ADD
2:UPDATE
3:REMOVE
4:RELOAD
5:EXIT
?> 2
ID(int)?> 2
NAME(string)?> Test2
PRICE(num)?> 2.22
DESCRIPTION(string)?> テスト2
ID:0 NAME:db4o PRICE: DESCRIPTION:db4o 7.4
ID:1 NAME:Clamp PRICE:12.48 DESCRIPTION:Workbench clamp
ID:2 NAME:Test2 PRICE:2.22 DESCRIPTION:テスト2
ID:50 NAME:Flat Head Screwdriver PRICE:3.17 DESCRIPTION:Flat head
ID:75 NAME:Tire Bar PRICE: DESCRIPTION:Tool for changing tires.
ID:3000 NAME:3mm Bracket PRICE:0.52 DESCRIPTION:

1:ADD
2:UPDATE
3:REMOVE
4:RELOAD
5:EXIT
?> 3
ID(int)?> 2
ID:0 NAME:db4o PRICE: DESCRIPTION:db4o 7.4
ID:1 NAME:Clamp PRICE:12.48 DESCRIPTION:Workbench clamp
ID:50 NAME:Flat Head Screwdriver PRICE:3.17 DESCRIPTION:Flat head
ID:75 NAME:Tire Bar PRICE: DESCRIPTION:Tool for changing tires.
ID:3000 NAME:3mm Bracket PRICE:0.52 DESCRIPTION:

1:ADD
2:UPDATE
3:REMOVE
4:RELOAD
5:EXIT
?> 5

 Monoで他のDBも使ってみたよ!+(db4o、NHibernate編)4 へ続く。

0 件のコメント:

コメントを投稿