]> git.nothing2do.fr Git - diary-shell.git/commitdiff
file to handle database added !
authorNorbert Moutarde <norbert.moutarde@nothing2do.eu>
Sat, 29 Jun 2013 11:29:15 +0000 (13:29 +0200)
committerNorbert Moutarde <norbert.moutarde@nothing2do.eu>
Sat, 29 Jun 2013 11:29:15 +0000 (13:29 +0200)
sqldb.cpp [new file with mode: 0644]
sqldb.h [new file with mode: 0644]

diff --git a/sqldb.cpp b/sqldb.cpp
new file mode 100644 (file)
index 0000000..85d28f2
--- /dev/null
+++ b/sqldb.cpp
@@ -0,0 +1,274 @@
+#ifndef sql
+#define sql 1
+#include "sqldb.h"
+#include <sstream>
+#include <vector>
+#include <cstdlib>
+#include <sys/types.h>
+#include <stdlib.h>
+#include <cstring>
+using namespace std;
+
+sqlpg::sqlpg() {
+    string var;
+    //var = "host=postgresql1.alwaysdata.com port=5432 dbname=nothing2do.eu_diary user=nothing2do.eu password=x connect_timeout=10";
+    var = "dbname=bob user=bob password=pass connect_timeout=10";
+    cout << "Chaîne de connection: " + var << endl;
+    //conn =  PQconnectStart(var.c_str());
+    conn =  PQconnectdb(var.c_str());
+}
+
+int sqlpg::status(){
+    string err=toString(PQstatus(conn));
+    switch(PQstatus(conn)) {
+    case CONNECTION_OK:
+        cout << "La connection à la base est Ok" << endl;
+        return 0;
+        break;
+    case CONNECTION_BAD:
+        cout << "La connection à la base est KO : " << PQerrorMessage(conn) << endl;
+        return 1;
+        break;
+    default:
+        cout << "Erreur de connection non répertoriée : (" + err + ") "<< PQerrorMessage(conn) << endl;
+        return -1;
+    }
+}
+template<typename T> string sqlpg::toString( const T & Value ){
+    // utiliser un flux de sortie pour créer la chaîne
+    ostringstream oss;
+    // Ã©crire la valeur dans le flux
+    oss << Value;
+    // renvoyer une string
+    return oss.str();
+}
+int sqlpg::insert(vector<string> text) {
+    string command;
+    string tmp="";
+
+    if (text.size()>2){
+        if ((isdate(text[0]))+(isdate(text[1]))==3){
+            cout<<"date detecte\n";
+            date=text[0];
+            tmp=text[2];
+            for (int a=3;a<text.size(); a++){
+                tmp=tmp+" "+text[a];
+            }
+            command="INSERT INTO raw (date, texte) VALUES ('"+date+" "+text[1]+"', '"+tmp+"')";
+        }
+        else if((text[0]=="-")&&(isdate(text[1])==2)){
+            cout<<"date partielle\n";
+            tmp=text[2];
+            for (int a=3;a<text.size(); a++){
+                tmp=tmp+" "+text[a];
+            }
+            command="INSERT INTO raw (date, texte) VALUES ('"+date+" "+text[1]+"', '"+tmp+"')";
+        }
+        else{
+            tmp=text[0];
+            for (int a=1;a<text.size(); a++){
+                tmp=tmp+" "+text[a];
+            }
+            command="INSERT INTO raw (date, texte) VALUES ('now()', '"+tmp+"')";
+        };
+
+    }
+    else {
+        tmp=text[0];
+        for (int a=1;a<text.size(); a++){
+            tmp=tmp+" "+text[a];
+            };
+            command="INSERT INTO raw (date, texte) VALUES ('now()', '"+tmp+"')";
+        };
+
+    //cout<<command<<endl;
+    /*res=PQexec(conn, command.c_str());
+    testSQL();*/
+    exec(command);
+    return 0;
+}
+
+void sqlpg::deletetuple(string tmp){
+    string command;
+    command="DELETE FROM raw WHERE id ='" + tmp + "'";
+    /*res=PQexec(conn, command.c_str());
+    testSQL();*/
+    exec(command);
+    //cout<<command<<endl;
+}
+void sqlpg::deletedate(string a, string b){
+    string command;
+    command="delete from raw where date between '"+a+"' and '"+b+"';";
+    /*res=PQexec(conn,command.c_str());
+    if (PQresultStatus(res) != PGRES_COMMAND_OK)
+    {
+        cout<<"command failed: "<< PQerrorMessage(conn)<<endl;
+    }*/
+    exec(command);
+    //cout<<command<<endl;
+}
+string now(){//SQL function NOW() exist !
+// current date/time based on current system
+   time_t now = time(0);
+   tm *ltm = localtime(&now);
+   char * date;
+   // print various components of tm structure.
+   sprintf(date,"%d-%d-%d %d:%d:%d", 1900+ltm->tm_year, 1+ltm->tm_mon, ltm->tm_mday, 1+ltm->tm_hour, 1+ltm->tm_min, 1+ltm->tm_sec);
+   string d(date);
+   return d;
+}
+int isdate(string a){
+    if (((a[4])=='-')&&((a[7])=='-')){
+       return 1;
+       }
+    if (((a[2])==':')&&((a[5])==':')){
+       return 2;
+       }
+}
+int sqlpg::hmRecord(){
+    string command;
+    command="select date from raw;";
+    //res=PQexec(conn, command.c_str());
+    exec(command);
+    a=PQntuples(res);
+    return a;
+}
+void sqlpg::var(){
+    cout<<"date="<<date<<endl;
+}
+sqlpg::~sqlpg() {
+    PQclear(res);
+    PQfinish(conn);
+}
+void sqlpg::print(){
+for (int i=0; i<PQntuples(res); i++){
+    int lim=PQnfields(res);
+    for (int j=0; j<lim-1; j++){
+            cout<<PQgetvalue(res, i, j)<<"+";
+        };
+        cout<<PQgetvalue(res, i, lim-1)<<"|";
+    };
+
+cout<<endl;
+}
+void sqlpg::exec(string a){
+    //cout<<"exec("<<a<<")\n";
+    res=PQexec(conn, a.c_str());
+    //cout<<"exec:1/2\n";
+    if (!((PQresultStatus(res) == PGRES_COMMAND_OK)||(PQresultStatus(res) == PGRES_TUPLES_OK)))
+    {
+        cout<<"PQerrorMessage(conn) : "<< PQerrorMessage(conn)<<endl;
+        cout<<"PQresStatus(res)="<<PQresStatus(PQresultStatus(res))<<endl;
+    };
+    //cout<<"exec() finish\n";
+}
+void sqlpg::exec(vector<string> a){
+    cout<<"a.size()=="<<a.size()<<"\n";
+    /*const char *paramValues[1];
+    int         paramLengths[1];
+    int         paramFormats[1];
+    uint32_t    binaryIntVal;
+
+res = PQexecParams(conn,
+    "SELECT * FROM test1 WHERE t = $1",
+    1,       /* one param
+    NULL,    /* let the backend deduce param type
+    paramValues,
+    NULL,    /* don't need param lengths since text
+    NULL,    /* default to all text params
+    0);      /* ask for text results
+
+*/
+    const char *paramValues[1];
+    int         paramLengths[1];
+    int         paramFormats[1];
+    //uint32_t    binaryIntVal;
+paramValues[0]=a[1].c_str();
+    res = PQexecParams(conn,
+                       "SELECT * FROM raw WHERE texte like %$1%",
+                       1,       /* one param */
+                       NULL,    /* let the backend deduce param type */
+                       paramValues,
+                       NULL,    /* don't need param lengths since text */
+                       NULL,    /* default to all text params */
+                       0);      /* ask for text results */
+    cout<<"exec() finish\n";
+}
+inline int sqlpg::testSQL(PGresult* a){
+    if (!((PQresultStatus(a) == PGRES_COMMAND_OK)||(PQresultStatus(a) == PGRES_TUPLES_OK)))
+    {
+        cout<<"PQerrorMessage(conn): "<< PQerrorMessage(conn)<<endl;
+        cout<<"PQresStatus(res)="<<PQresStatus(PQresultStatus(a))<<endl;
+    };
+}
+bool sqlpg::alias(vector<string> a){
+    //cout<<"alias start here\n";
+    string cmd;
+
+    cmd="select command,argc from alias where nom='"+a[0]+"' and argc="+toString(a.size()-1)+";";// I need to select a function with argc too !
+    //cout<<"cmd="<<cmd<<endl;
+    exec(cmd);
+    if (PQntuples(res)<1){
+        //cout<<"alias end pqntuples(res)="<<PQntuples(res)<<endl;
+        return 0;
+    }
+    string cmd2;
+    cmd2=PQgetvalue(res, 0, 0);
+    //cout<<"cmd2="<<cmd2<<endl;
+    int pos=0;
+    int argc=atoi(PQgetvalue(res, 0, 1));
+    //cout<<"argc="<<argc<<endl;
+    char *value[argc];
+    int length[argc];
+    int binary[argc];
+    //cout<<"for argc="<<argc<<"\n";
+    for(int i=0; i<argc; i++){
+        value[i]=a[i+1].c_str();
+        length[i]=a[i+1].size();
+        binary[i]=0;
+        //cout<<"i="<<i<<" value="<<value[i]<<" length="<<length[i]<<"\n";
+    }
+    res=PQexecParams(conn, cmd2.c_str(), argc, NULL, value, length, binary, 0);
+    testSQL(res);
+    print();
+    //cout<<"and end here\n";
+    return 1;
+}
+void sqlpg::compulse(){
+    string cmd="select * from raw where analyzed='0' order by date asc;";
+    exec(cmd);
+    //cout<<"exec1("<<cmd<<")\n";
+    cout<<"PQntuples(res)="<<PQntuples(res)<<endl;
+    int tuples=PQntuples(res);
+    for (int i=0; i<tuples;i++){
+        string buf, txt=PQgetvalue(res, i, PQfnumber(res, "texte"));
+        stringstream ss(txt);
+        while (ss >> buf) {//exec for each words in tuples
+            string a="select time,txt from words where txt='"+buf+"';", command;
+            res2=PQexec(conn, a.c_str());
+            testSQL(res2);
+            int tmp=PQntuples(res2);
+            if(tmp==0){
+                command="insert into words (time, txt) values ('1', '"+buf+"')";
+            }
+            else if(tmp==1){
+                stringstream t;
+                t<<"update words set time="<<atoi(PQgetvalue(res2, 0, 0))+1<<" where txt='"<<buf<<"';";
+                command=t.str();
+            }
+            else{
+                cout<<"erreur de logique (txt est une clé primaire...)\nPQntuple(res)=="<<tmp<<"\n";
+            };
+            testSQL(PQexec(conn, command.c_str()));
+        };
+        stringstream y;
+        y<<"update raw set analyzed='1' where date='"<<(PQgetvalue(res, i, PQfnumber(res, "date")))<<"';";
+        //cout<<"t="<<t<<endl;
+        testSQL(PQexec(conn, y.str().c_str()));
+        //exec(y.str()); it don't works and i don't know why
+    }
+};
+
+
+
+#endif
diff --git a/sqldb.h b/sqldb.h
new file mode 100644 (file)
index 0000000..374a212
--- /dev/null
+++ b/sqldb.h
@@ -0,0 +1,41 @@
+#ifndef SQLDB_H
+#define SQLDB_H
+
+#include <iostream>
+#include <string>
+#include "libpq-fe.h"
+#include <vector>
+#include <cstdio>
+std::string now();
+int isdate(std::string);//return 1 for YYYY-MM-DD and 2 for HH:MM:SS
+
+class sqlpg {
+public:
+    sqlpg ();
+    ~sqlpg();
+    template<typename T> static std::string toString( const T & Value );
+    int status();// return 0 if success, 1 for error, -1
+    int insert(std::vector<std::string>);// format=yyyy-month-day hour:min:sec text
+    std::vector < std::vector <std::string> > list(std::string);// to list the content of table "string"
+    std::vector < std::vector <std::string> > listdate(std::string, std::string=now());// to list the content of table "raw" between 2 date (date and now, by défault)
+    //std::vector<std::vector<int> > size(std::string="");//size of each tuple
+    void deletetuple(std::string);
+    void deletedate(std::string, std::string);// delete tuple between two date
+    void print();// print result of exec(string) call
+    int hmRecord();// How Many records in "raw" table
+    //std::vector<int> search(std::string);//return id of record containing string, useless (SQL deo the same)
+    void var();
+    inline int testSQL(PGresult*);// test if all gone good
+    void exec(std::vector<std::string>);// first string is for SQL command, other are to replace %1,%2, etc...
+    void exec(std::string);
+    bool alias(std::vector<std::string>);
+    void compulse();//populate table words
+private:
+    PGconn *conn;
+    PGresult *res, *res2, *res3;
+    std::vector < std::vector<std::string> > ret;//useless ?
+    std::string b, date;
+    int a;
+};
+
+#endif // SQLDB_H