Skip to main content

C++ of the Day #44 - SQLite3 C++ wrapper #2

지난 번에 이어 구현중인 SQLite3 C++ wrapper에 대해 살펴보겠습니다. 먼저 이 wrapper의 이름을 sqlite3++로 결정했습니다. 물론 코드안에서와 같이 특수 문자를 사용할 수 없는 경우에는 sqlite3pp라는 이름을 사용합니다.

지난번 글의 내용에서 변경된 사항들에 대해 먼저 알아보죠.

먼저 몇몇 클래스와 함수들의 이름을 알기 쉽게 바꾸었습니다. 다음이 바뀐 이름들의 목록입니다.


  1. connection --> database

  2. connection::open --> database::connect

  3. connection::close --> database::disconnect

  4. command::step --> command::execute

  5. command::finalize --> command::finish



클래스 상속 관계도 수정이 되었으나 사용자들에게 보이는 변경 사항은 없습니다.

그리고 command::step() 함수의 성공시에 SQLITE_DONE(101)이 출력되던 것을 다른 함수들과의 일관성을 위해 command::execute() 함수는 SQLITE_OK(0)를 리턴하도록 수정하였습니다. 이제 sqlite3++에서 함수의 성공 여부는 리턴값이 0인지를 확인하면 됩니다.

다음으로 SQLite3에서 지원하는 busy_handler, commit_hook, rollback_hook, update_hook, authorizer_handler와 같은 callback 함수들을 등록하는 인터페이스를 database 클래스에 추가하였습니다. 사용하는 방법은 다음과 같이 몇가지가 있습니다. ((boost::function을 사용하여 다양한 타입으로 등록할 수 있도록 구현하였습니다.))

먼저 일반 함수 포인터를 사용하는 방법입니다.


int handle_authorize(int evcode, char const* p1, char const* p2, char const* dbname, char const* tvname) {
cout << "handle_authorize(" << evcode << ")" << endl;
return 0;
}
// ...
db.set_authorize_handler(&handle_authorize);


이런 callback 함수에 user data가 필요한 경우에는 이를 클래스로 만들어 멤버 함수 포인터를 등록할 수도 있습니다. 아래 코드에서는 boost::bind를 사용하여 멤버 함수 포인터를 전달하고 있습니다.


struct handler
{
handler() : cnt_(0) {}

void handle_update(int opcode, char const* dbname, char const* tablename, int64_t rowid) {
cout << "handle_update(" << opcode << ", " << dbname << ", " << tablename << ", " << rowid << ") - " << cnt_ << endl;
++cnt_;
}
int cnt_;
};
// ...
handler h;
db.set_update_handler(bind(&handler::handle_update, &h, _1, _2, _3, _4));


물론 일반 functor를 만들어 사용할 수도 있습니다.


struct rollback_handler
{
void operator()() {
cout << "handle_rollback - " << cnt << endl;
++cnt;
}
int cnt;
};
// ...
db.set_rollback_handler(rollback_handler());


게다가 위의 경우처럼 함수의 내용이 간단한 경우 boost::lambda를 사용할 수도 있죠. :-)


db.set_rollback_handler(cout << constant("handle_rollback\n"));


위의 rollback_handler는 리턴값이 void라 위와 같이 쉽게 사용이 가능하지만 commit_handler와 같이 리턴값이 있는 경우에는 다음과 같이 boost::lambda의 , (comma) operator를 사용하여 리턴값을 지정해 주어야 합니다. 이때는 함수 인자로 인식하지 않도록 괄호를 추가로 사용해야 합니다.


db.set_commit_handler((cout << constant("handle_commit\n"), 0));


이 기능외에도 하나의 database 세션에서 다른 db 파일을 연결해서 쓸 수 있는 attach/detach 기능이나 enable_shared_cache() 기능을 위한 인터페이스도 추가되었습니다.



현재까지 작성된 코드들을 Google Code에 등록해 두었습니다. 다음 링크를 통해 현재 구현중인 코드를 확인할 수 있습니다.

http://sqlite3pp.googlecode.com/svn/trunk/

다음 글에서는 sqlite3++의 마지막 시간으로 SQLite3에서 제공하는 extension에 대한 C++ wrapping에 대해 작성해 보도록 하겠습니다. :-)

Comments

Popular posts from this blog

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...