2010年12月10日

BDBの使い方 基本編

DBって何?


データベースです。

プログラムで使うデータを保存するためのものですね。
データベースと言われて、真っ先に出てくるのはSQL。
主流なのはPostgreSQLとMySQLで、高機能なのがPostgresSQLで、シンプルな代わりに軽いのがMySQLというような住み分けになっています。

最近ではNoSQLなんて動きもあって、そもそもSQL自体が大げさなのでもっとシンプルなKVSとかが注目を集めています。

なんて話をしておきながら、今回の記事はSQLもKVSも扱いません。BDBです。
部類的にはKVSだったりするんでしょうか。まぁいい。

歴史的経緯


正式名称はBerkeley Database。
カルフォルニア大学のバークレー校で開発されたものらしいですが、開発者がSleepycat Softwareという会社を設立してそちらで開発。
その後はOracleに買収されて今に至る と紆余曲折しているようです。
オープンソースのもあるので利用はできるようです。

使い方


プログラムからは関数を呼び出して使います。
当然DBの操作を行うコードを書かねばなりません。

C言語での使い方の流れはこんな感じ。
  1. ヘッダファイルをinclude
  2. dbopenでデータベースファイルを開く
  3. put/getでデータベース内のデータを扱う
  4. syncで操作した内容をファイルに反映させる
  5. dbcloseでファイルを閉じる


ヘッダファイル
#include <sys/types.h>
#include <db.h>
#include <fcntl.h>
#include <limits.h>


dbopen
DB * dbopen(const char *file, int flags, int mode, DBTYPE type, const void *openinfo);

fileはファイルの名前を渡します。
flagsとmodeについてはopen()で指定するものと同様です。

DBTYPEは、DB内部でのデータ構造です。
DB_BTREE、DB_HASH、DB_RECONOのいずれかを指定します。
openinfoは、データを処理するためのアクセスメソッドを指定するみたいですが、NULLにすればデフォルトのものが適用されるそうです。

DB構造体
typedef struct {
 DBTYPE type;
 int (*close)(const DB *db);
 int (*del)(const DB *db, const DBT *key, u_int flags);
 int (*fd)(const DB *db);
 int (*get)(const DB *db, DBT *key, DBT *data, u_int flags);
 int (*put)(const DB *db, DBT *key, const DBT *data, u_int flags);
 int (*sync)(const DB *db, u_int flags);
 int (*seq)(const DB *db, DBT *key, DBT *data, u_int flags);
} DB;


dbopen()の返り値がこれなので
db = dbopen(なんたらかんたら)みたいに実行してから
db->get(なんたらかんたら)のようにして、各種操作を行います。

DBT構造体
typedef struct {
 void *data;
 size_t size;
} DBT;


実際に扱うデータは、このDBT構造体で扱います。
dataへのポインタと、データサイズだけというとってもシンプルな構造。
key用とdata用に2つ作る必要があります。

サンプルコード

//dbtest.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <db.h>
#include <fcntl.h>
#include <limits.h>

int main(int argc, char** argv)
{
  const char* file;
  int flags;
  int mode;
  DBTYPE type;
  const void* openinfo = NULL;
  DB* db;
  DBT* key;
  DBT* value;
  DBT* get;
  int opt;
  char keybuf[512];
  char valuebuf[2048];
  char getbuf[2048];

  key = malloc(sizeof(DBT));
  value = malloc(sizeof(DBT));
  get = malloc(sizeof(DBT));
  key->data = keybuf;
  value->data = valuebuf;
  get->data = getbuf;

  while((opt = getopt(argc, argv, "k:v:")) != -1) {
    switch(opt) {
      case 'k':
        strcpy(key->data, optarg);
        printf("key is %s\n", (char *)key->data);
        break;
      case 'v':
        strcpy(value->data, optarg);
        printf("value is %s\n", (char *)value->data);
        break;
    }
  }

  key->size = strlen(key->data);
  value->size = (strlen(value->data)+1);
  printf("value size is %d\n", (int)value->size);

  file = "hash.db";
  flags = O_CREAT;
  flags |= O_RDWR;
  mode = S_IRWXU;
  type = DB_HASH;

  db = dbopen(file, flags, mode, type, openinfo);
  db->put(db, key, value, 0);
  db->sync(db, 0);
  db->get(db, key, get, 0);
  printf("got value is %s\n", (char *)get->data);
  printf("got value size is %d\n", (int)get->size);
  db->close(db);
  return 0;
}


引数で指定したkey/valueをdbに書きこんで、そのまま読み出すプログラム。
以下のように実行します。


# ./dbtest -k key -v value
key is key
value is value
value size is 6
got value is value
got value size is 6


value->size = (strlen(value->data)+1);で、+1しているのがポイントです。
strlenだと、ヌル文字をカウントしないので、+1しないと以下のような結果になってしまいます。

# ./dbtest -k key -v value
key is key
value is value
value size is 5
got value is valuekey
got value's size is 5

valueの後にkeyというデータもくっついています。
DB_TYPEにDB_HASHを使った場合は起きますが、DB_BTREEでは起きませんでした。
おそらくデータを保存する際の書式で、DB_BTREEではヌル文字で区切っているけど、DB_HASHではデータにヌル文字が含まれている前提なのではないでしょうか。
なのでgetした際に、ヌル文字が登場するまで読んでいて他のデータが混ざっているのかなぁと。

postmapで確認
同じプログラムからkey/valueを取得しても、ちゃんと動いているか分かりにくいので、postmapでも確認してみましょう。
postmapとはpostfixに付属のツールで、DBファイルのデータを扱えます。
※DBの確認方法としてはあんまり一般的ではないと思われます。

# postmap -q key hash
value


余談
postmapを最初に見つけたときに
postfixをposixに空目していて、何の疑いもなく
DBの確認に使っていましたとさ\(^o^)/

nanodayo at 00:51コメント(22) 
プログラミング | データベース

コメント一覧

1. Posted by Hogan Sito Ufficiale   2014年08月23日 17:15
Scarpe Hogan Cozy permettono tootsies della nostra azienda a raggiungere il miglior yoga e massaggi. Il mercato attuale l'impostazione relativa scarpe Hogan sono indubbiamente particolare ed ancora più profondo. L'accordo esatto o promozione o produzione di Hogan rebel hanno effettivamente altre raccomandazioni. Hogan è ben noto in tutto il mondo con il prodotto di prim'ordine e inoltre facendo. Infine, la durata capisce il trionfo molto coinvolto con Hogan. Il più lungo termine sarà il kick off point. Prendono tutto il sapore della storia sulla causa relativa alla persistente ripristinare il picco per questo desiderio subire dal telaio a lungo termine del conto delle esigenze delle donne e la dieta donne attraenti così sane. La maggior parte delle scarpe sono formulati adatto però, non monotona, che si sta per ottenere regolarmente bellezza intorno a scarpe Hogan Interactive. Temperature estreme essere possibile evidenti scarpe di pelle sintetica in vendita in legno, scuro in aggiunta al bluastro o forse il famoso Hogan Interactive in camoscio marrone scuro a titolo di illuminazione gradazioni rare e grigio.
Hogan Sito Ufficiale http://www.associazionitraumi.it/wp-rss3.php
2. Posted by www.summitalmonds.com/?pid=29355   2014年09月10日 11:45
je les verrais bien avec un paréo, ou une robe d'été légère dans les mêmes tons rosés.
3. Posted by North Face On Sale   2014年10月10日 08:29
とある道化の悪戯記録:BDBの使い方 基本編
North Face On Sale http://www.lovelyfilms.co.uk/
4. Posted by Britney   2016年12月04日 04:30
I was just looking at your とある道化の悪戯記録:BDBの使い方 基本編 site and see that your site has the potential to become very popular. I just want to tell you, In case you don't already know... There is a website service which already has more than 16 million users, and the majority of the users are interested in websites like yours. By getting your site on this service you have a chance to get your site more visitors than you can imagine. It is free to sign up and you can read more about it here: http://azte.ch/as - Now, let me ask you... Do you need your site to be successful to maintain your business? Do you need targeted visitors who are interested in the services and products you offer? Are looking for exposure, to increase sales, and to quickly develop awareness for your site? If your answer is YES, you can achieve these things only if you get your site on the service I am describing. This traffic network advertises you to thousands, while also giving you a chance to test the service before paying anything at all. All the popular websites are using this service to boost their readership and ad revenue! Why aren’t you? And what is better than traffic? It’s recurring traffic! That's how running a successful website works... Here's to your success! Read more here: http://www.esdlink.de/67
5. Posted by Evelyn Serrell   2016年12月09日 03:10
This is a message to the website creator. I discovered your とある道化の悪戯記録:BDBの使い方 基本編 page by searching on Google but it was hard to find as you were not on the first page of search results. I know you could have more visitors to your site. I have found a company which offers to dramatically increase your rankings and traffic to your site: http://dtl.la/tmJ9x I managed to get close to 500 visitors/day using their service, you could also get a lot more targeted visitors from search engines than you have now. Their services brought significantly more traffic to my website. I hope this helps!
6. Posted by Jennifer   2016年12月09日 20:26
I decided to leave a message here on your とある道化の悪戯記録:BDBの使い方 基本編 page instead of calling you. Do you need more likes for your Facebook Fan Page? The more people that LIKE your website and fanpage on Facebook, the more credibility you will have with new visitors. It works the same for Twitter, Instagram and Youtube. When people visit your page and see that you have a lot of followers, they now want to follow you too. They too want to know what all the hype is and why all those people are following you. Get some free likes, followers, and views just for trying this service I found: http://greybeard95a.com/37v
7. Posted by Livia Schacter   2016年12月14日 23:16
I was just looking at your とある道化の悪戯記録:BDBの使い方 基本編 site and see that your website has the potential to become very popular. I just want to tell you, In case you didn't already know... There is a website service which already has more than 16 million users, and the majority of the users are looking for websites like yours. By getting your website on this network you have a chance to get your site more visitors than you can imagine. It is free to sign up and you can read more about it here: http://mod24.pl/8 - Now, let me ask you... Do you need your website to be successful to maintain your way of life? Do you need targeted visitors who are interested in the services and products you offer? Are looking for exposure, to increase sales, and to quickly develop awareness for your site? If your answer is YES, you can achieve these things only if you get your site on the network I am talking about. This traffic network advertises you to thousands, while also giving you a chance to test the service before paying anything. All the popular blogs are using this service to boost their traffic and ad revenue! Why aren’t you? And what is better than traffic? It’s recurring traffic! That's how running a successful site works... Here's to your success! Find out more here: http://mod24.pl/8
8. Posted by Jennifer   2016年12月16日 11:32
I decided to leave a message here on your とある道化の悪戯記録:BDBの使い方 基本編 page instead of calling you. Do you need more likes for your Facebook Fan Page? The more people that LIKE your website and fanpage on Facebook, the more credibility you will have with new visitors. It works the same for Twitter, Instagram and Youtube. When people visit your page and see that you have a lot of followers, they now want to follow you too. They too want to know what all the hype is and why all those people are following you. Get some free likes, followers, and views just for trying this service I found: http://tapeciarnia.waw.pl/1xcx2
9. Posted by Jennifer   2016年12月22日 20:47
I decided to leave a message here on your とある道化の悪戯記録:BDBの使い方 基本編 page instead of calling you. Do you need more likes for your Facebook Fan Page? The more people that LIKE your website and fanpage on Facebook, the more credibility you will have with new visitors. It works the same for Twitter, Instagram and Youtube. When people visit your page and see that you have a lot of followers, they now want to follow you too. They too want to know what all the hype is and why all those people are following you. Get some free likes, followers, and views just for trying this service I found: http://r.advantech.com/oq
10. Posted by Livia Schacter   2017年01月01日 15:08
Hi my name is Livia Schacter and I just wanted to send you a quick message here instead of calling you. I came to your とある道化の悪戯記録:BDBの使い方 基本編 website and noticed you could have a lot more visitors. I have found that the key to running a popular website is making sure the visitors you are getting are interested in your subject matter. There is a company that you can get keyword targeted traffic from and they let you try their service for free for 7 days. I managed to get over 300 targeted visitors to day to my website. https://lil.ink/4q
11. Posted by Jennifer   2017年01月23日 23:46
I decided to leave a message here on your とある道化の悪戯記録:BDBの使い方 基本編 page instead of calling you. Do you need more likes for your Facebook Fan Page? The more people that LIKE your website and fanpage on Facebook, the more credibility you will have with new visitors. It works the same for Twitter, Instagram and Youtube. When people visit your page and see that you have a lot of followers, they now want to follow you too. They too want to know what all the hype is and why all those people are following you. Get some free likes, followers, and views just for trying this service I found: http://brt.st/5pFF
12. Posted by Elisa Brown   2017年05月07日 02:11
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://priscilarodrigues.com.br/url/v
13. Posted by Chelsea Wallace   2017年05月12日 09:20
This is a message to the とある道化の悪戯記録:BDBの使い方 基本編 admin. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your site: http://tdil.co/3p - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://acortarurl.es/97
14. Posted by Chelsea Wallace   2017年05月16日 23:33
This is a comment to the とある道化の悪戯記録:BDBの使い方 基本編 admin. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your website: http://trucri.me/u5za1 - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://www.arvut.org/1/eCV
15. Posted by Virginia Williams   2017年11月29日 12:06
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://0nulu.com/sdq Unsubscribe here: http://0nulu.com/nbz
16. Posted by Nicole Mawrey   2018年11月08日 13:39
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE website traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: https://38x.de/92sj7 Unsubscribe here: https://twe.lv/gg
17. Posted by Kelley Brown   2018年12月19日 03:53
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://sp7.site/7 Unsubscribe here: http://sp7.site/8
18. Posted by Kelley Brown   2018年12月26日 04:49
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://likes.avanimisra.com/4p4l Unsubscribe here: http://sp7.site/8
19. Posted by Kelley Brown   2018年12月31日 21:58
I discovered your とある道化の悪戯記録:BDBの使い方 基本編 page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: http://likes.avanimisra.com/4p4l Unsubscribe here: http://sp7.site/8
20. Posted by Rebecca Newton   2019年02月02日 09:15
This is a comment to the とある道化の悪戯記録:BDBの使い方 基本編 admin. Your website is missing out on at least 300 visitors per day. Our traffic system will dramatically increase your traffic to your website: http://tgi.link/5ozd - We offer 500 free targeted visitors during our free trial period and we offer up to 30,000 targeted visitors per month. Hope this helps :) Unsubscribe here: http://y.rxhnet.de/5kfw
21. Posted by Rebecca Newton   2019年02月08日 11:20
I came across your とある道化の悪戯記録:BDBの使い方 基本編 website and wanted to let you know that we have decided to open our POWERFUL and PRIVATE web traffic system to the public for a limited time! You can sign up for our targeted traffic network with a free trial as we make this offer available again. If you need targeted traffic that is interested in your subject matter or products start your free trial today: http://y.rxhnet.de/2w6y Unsubscribe here: http://y.rxhnet.de/5kfw
22. Posted by Joann   2019年05月22日 04:22
I discovered your とある道化の悪戯記録:BDBの使い方 基本編 page and noticed you could have a lot more traffic. I have found that the key to running a website is making sure the visitors you are getting are interested in your subject matter. We can send you targeted traffic and we let you try it for free. Get over 1,000 targeted visitors per day to your website. Start your free trial: https://oxx.jp/2a Unsubscribe here: https://oxx.jp/2b

コメントする

名前
 
  絵文字