00001 /* 00002 * Copyright (c) 2010 Ferruccio Vitale <unixo@devzero.it> 00003 * All rights reserved. 00004 * 00005 * $Id: Category.cpp 71 2010-07-22 16:04:49Z unixo $ 00006 */ 00007 00008 #include "Category.h" 00009 #include "Database.h" 00010 00011 #define KEY_CAT_CID "cid" 00012 #define KEY_CAT_NAME "name" 00013 #define SQL_CATEGORY_BYID "SELECT cid, name FROM categories WHERE cid = " 00014 #define SQL_CATEGORY_CAT "SELECT cid, name FROM categories ORDER BY name" 00015 00016 00017 Category::Category() : ManagedObject("categories") 00018 { 00019 } 00020 00027 Category *Category::categoryByID(int aCid) 00028 { 00029 Category *cat = NULL; 00030 00031 Database &db = Database::Instance(); 00032 Query q = db.getConnection()->query(); 00033 q << SQL_CATEGORY_BYID << aCid; 00034 StoreQueryResult res = q.store(); 00035 if (!res.empty()) { 00036 cat = new Category(); 00037 cat->setIntForKey(KEY_CAT_CID, aCid); 00038 cat->setValueForKey(KEY_CAT_NAME, (string) res[0][KEY_CAT_NAME]); 00039 00040 return cat; 00041 } 00042 00043 return NULL; 00044 } 00045 00053 Category *Category::factory(string aValue) 00054 { 00055 Category *newCategory = new Category(); 00056 newCategory->setIntForKey(KEY_CAT_CID, 0); 00057 newCategory->setValueForKey(KEY_CAT_NAME, aValue); 00058 00059 return newCategory; 00060 } 00061 00067 string Category::primaryKey() 00068 { 00069 return KEY_CAT_CID; 00070 } 00071 00077 vector<Category *> &Category::catalog() 00078 { 00079 Database& db = Database::Instance(); 00080 vector<Category *> *catalog = NULL; 00081 00082 try { 00083 Connection *conn = db.getConnection(); 00084 Query q = conn->query(SQL_CATEGORY_CAT); 00085 StoreQueryResult res = q.store(); 00086 00087 if (!res.empty()) { 00088 catalog = new vector<Category *>; 00089 catalog->reserve(res.num_rows()); 00090 00091 for (size_t i = 0; i < res.num_rows(); ++i) { 00092 Category *c = new Category(); 00093 c->setValueForKey(KEY_CAT_CID, (string) res[i][KEY_CAT_CID]); 00094 c->setValueForKey(KEY_CAT_NAME, (string) res[i][KEY_CAT_NAME]); 00095 catalog->push_back(c); 00096 } 00097 } 00098 } 00099 catch (std::exception & e) { 00100 //REVIEW 00101 } 00102 00103 return *catalog; 00104 } 00105 00106 ostream& operator<<(ostream& aStream, Category & c) { 00107 return aStream << c.valueForKey(KEY_CAT_CID) << " | " << c.valueForKey(KEY_CAT_NAME); 00108 }