gnutrition-commits
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[GNUtrition-commits] /srv/bzr/gnutrition/trunk r13: Added check for MySQ


From: Thomas Sinclair
Subject: [GNUtrition-commits] /srv/bzr/gnutrition/trunk r13: Added check for MySQL database and code to import those gnutrition recipes,
Date: Wed, 26 Sep 2012 01:09:15 -0400
User-agent: Bazaar (2.5.0)

------------------------------------------------------------
revno: 13
committer: Thomas Sinclair <address@hidden>
branch nick: trunk
timestamp: Wed 2012-09-26 01:09:15 -0400
message:
  Added check for MySQL database and code to import those gnutrition recipes,
  food plans, etc. into the current SQLite3 db.
  Fixed a few bugs.
added:
  src/mysql.py
modified:
  Makefile.in
  README
  autom4te.cache/output.0
  autom4te.cache/requests
  configure
  configure.in
  src/config.py
  src/database.py
  src/druid.py
  src/druid_ui.py
  src/gnutr_consts.py
  src/person.py
  src/run_app.py
=== modified file 'Makefile.in'
--- a/Makefile.in       2012-05-21 00:15:02 +0000
+++ b/Makefile.in       2012-09-26 05:09:15 +0000
@@ -26,7 +26,7 @@
 
 @SET_MAKE@
 
-SUBDIRS = src data pixmaps doc rpm debian
+SUBDIRS = src data pixmaps rpm debian # doc
 
 files = AUTHORS autogen.sh COPYING gnutrition.desktop py-compile \
        Changelog configure install-sh INSTALL configure.in \
@@ -72,6 +72,7 @@
        rm -f config.cache config.log config.status
        rm -f src/install.py
        rm -f data/.data_prepped
+       rm -f doc/Makefile
 
 deb:
        dpkg-buildpackage -rfakeroot -us -uc

=== modified file 'README'
--- a/README    2012-08-23 01:07:47 +0000
+++ b/README    2012-09-26 05:09:15 +0000
@@ -1,7 +1,7 @@
 
 GENERAL INFORMATION
 
-    This is version 0.32 of GNUTRITION, a recipe and food nutritional
+    This is version 0.32.1 of GNUTRITION, a recipe and food nutritional
     analysis application for GNOME.
 
     GNUtrition can be found on the main GNU FTP server:

=== modified file 'autom4te.cache/output.0'
--- a/autom4te.cache/output.0   2012-07-27 01:47:47 +0000
+++ b/autom4te.cache/output.0   2012-09-26 05:09:15 +0000
@@ -1660,9 +1660,9 @@
 
 
 MAJOR_VERSION=0
-MINOR_VERSION=33
-REVISION=0
-VERSION="0.33.0"
+MINOR_VERSION=32
+REVISION=1
+VERSION="0.32.1"
 
 
 

=== modified file 'autom4te.cache/requests'
--- a/autom4te.cache/requests   2012-05-21 00:15:02 +0000
+++ b/autom4te.cache/requests   2012-09-26 05:09:15 +0000
@@ -14,58 +14,58 @@
                         'configure.in'
                       ],
                       {
+                        '_LT_AC_TAGCONFIG' => 1,
                         'AM_PROG_F77_C_O' => 1,
-                        '_LT_AC_TAGCONFIG' => 1,
+                        'AC_INIT' => 1,
                         'm4_pattern_forbid' => 1,
-                        'AC_INIT' => 1,
+                        '_AM_COND_IF' => 1,
                         'AC_CANONICAL_TARGET' => 1,
-                        '_AM_COND_IF' => 1,
+                        'AC_SUBST' => 1,
                         'AC_CONFIG_LIBOBJ_DIR' => 1,
-                        'AC_SUBST' => 1,
+                        'AC_FC_SRCEXT' => 1,
                         'AC_CANONICAL_HOST' => 1,
-                        'AC_FC_SRCEXT' => 1,
                         'AC_DEFUN' => 1,
                         'AC_PROG_LIBTOOL' => 1,
                         'AM_INIT_AUTOMAKE' => 1,
+                        'AC_CONFIG_SUBDIRS' => 1,
                         'AM_PATH_GUILE' => 1,
-                        'AC_CONFIG_SUBDIRS' => 1,
                         'AM_AUTOMAKE_VERSION' => 1,
                         'LT_CONFIG_LTDL_DIR' => 1,
+                        'AC_REQUIRE_AUX_FILE' => 1,
                         'AC_CONFIG_LINKS' => 1,
-                        'AC_REQUIRE_AUX_FILE' => 1,
+                        'm4_sinclude' => 1,
                         'LT_SUPPORTED_TAG' => 1,
-                        'm4_sinclude' => 1,
                         'AM_MAINTAINER_MODE' => 1,
                         'AC_DEFUN_ONCE' => 1,
                         'AM_NLS' => 1,
                         'AM_GNU_GETTEXT_INTL_SUBDIR' => 1,
+                        '_m4_warn' => 1,
                         'AM_MAKEFILE_INCLUDE' => 1,
-                        '_m4_warn' => 1,
                         'AM_PROG_CXX_C_O' => 1,
+                        '_AM_COND_ENDIF' => 1,
                         '_AM_MAKEFILE_INCLUDE' => 1,
-                        '_AM_COND_ENDIF' => 1,
                         'AM_ENABLE_MULTILIB' => 1,
                         'AM_PROG_MOC' => 1,
                         'AM_SILENT_RULES' => 1,
                         'AC_CONFIG_FILES' => 1,
+                        'LT_INIT' => 1,
                         'include' => 1,
-                        'LT_INIT' => 1,
+                        'AM_GNU_GETTEXT' => 1,
                         'AM_PROG_AR' => 1,
-                        'AM_GNU_GETTEXT' => 1,
                         'AC_LIBSOURCE' => 1,
+                        'AM_PROG_FC_C_O' => 1,
                         'AC_CANONICAL_BUILD' => 1,
-                        'AM_PROG_FC_C_O' => 1,
                         'AC_FC_FREEFORM' => 1,
                         'AH_OUTPUT' => 1,
+                        '_AM_SUBST_NOTMAKE' => 1,
                         'AC_CONFIG_AUX_DIR' => 1,
-                        '_AM_SUBST_NOTMAKE' => 1,
+                        'sinclude' => 1,
+                        'AM_PROG_CC_C_O' => 1,
+                        '_AM_AUTOCONF_VERSION' => 1,
                         'm4_pattern_allow' => 1,
-                        '_AM_AUTOCONF_VERSION' => 1,
-                        'AM_PROG_CC_C_O' => 1,
-                        'sinclude' => 1,
+                        'AC_CANONICAL_SYSTEM' => 1,
+                        'AM_CONDITIONAL' => 1,
                         'AM_XGETTEXT_OPTION' => 1,
-                        'AM_CONDITIONAL' => 1,
-                        'AC_CANONICAL_SYSTEM' => 1,
                         'AC_CONFIG_HEADERS' => 1,
                         'AC_DEFINE_TRACE_LITERAL' => 1,
                         'AM_POT_TOOLS' => 1,

=== modified file 'configure'
--- a/configure 2012-08-23 01:07:47 +0000
+++ b/configure 2012-09-26 05:09:15 +0000
@@ -1661,8 +1661,8 @@
 
 MAJOR_VERSION=0
 MINOR_VERSION=32
-REVISION=0
-VERSION="0.32.0"
+REVISION=1
+VERSION="0.32.1"
 
 
 

=== modified file 'configure.in'
--- a/configure.in      2012-07-27 02:04:16 +0000
+++ b/configure.in      2012-09-26 05:09:15 +0000
@@ -23,9 +23,9 @@
 AC_SUBST(PACKAGE)
 
 MAJOR_VERSION=0
-MINOR_VERSION=33
-REVISION=0
-VERSION="0.33.0"
+MINOR_VERSION=32
+REVISION=1
+VERSION="0.32.1"
 AC_SUBST(MAJOR_VERSION)
 AC_SUBST(MINOR_VERSION)
 AC_SUBST(REVISION)

=== modified file 'src/config.py'
--- a/src/config.py     2012-07-27 01:59:48 +0000
+++ b/src/config.py     2012-09-26 05:09:15 +0000
@@ -39,3 +39,12 @@
     db = shelve.open(fn)
     db[key] = value
     db.close()
+
+def keys():
+    db = shelve.open(fn)
+    for key in db.keys():
+        print key, db[key]
+    db.close()
+
+if __name__ == '__main__':
+    keys()

=== modified file 'src/database.py'
--- a/src/database.py   2012-09-17 00:15:56 +0000
+++ b/src/database.py   2012-09-26 05:09:15 +0000
@@ -185,10 +185,10 @@
             "Seq INTEGER NOT NULL, " +
             # Amount == Unit modifier (for example, 1 in "1 cup").
             "Amount REAL NOT NULL, " +
-                       "Msre_Desc TEXT NOT NULL, " +
+            "Msre_Desc TEXT NOT NULL, " +
             "Gm_wgt REAL NOT NULL, " +
-                       "Num_Data_Pts INTEGER, " +
-                       "Std_Dev REAL, " +
+            "Num_Data_Pts INTEGER, " +
+            "Std_Dev REAL, " +
             "PRIMARY KEY(NDB_No, Seq))",
             ### Insert statement
             "INSERT INTO 'weight' VALUES " +
@@ -260,7 +260,7 @@
             "time TEXT NOT NULL, " +
             "amount REAL NOT NULL, " +
             "Msre_Desc TEXT NOT NULL, " +
-            "Ndb_No INTEGER NOT NULL)", 'food_plan')
+            "NDB_No INTEGER NOT NULL)", 'food_plan')
 
         # create recipe_plan table
         if not 'recipe_plan' in tables:
@@ -306,7 +306,7 @@
             print 'Error :', sqlerr, '\nquery:', sql
             if caller: print 'Caller ', caller
             sys.exit()
-               # Convert to tuple as GNUtrition code expects MySQLdb tuple 
return
+        # Convert to tuple as GNUtrition code expects MySQLdb tuple return
         self.result = tuple(result)
         self.last_query = sql
         self.last_query_params = sql_params
@@ -399,3 +399,149 @@
         else:
             m += 1
         return m
+
+def migrate(mysql):
+    """Retrieve gnutrition table data from MySQL database.
+    Parameters uname and pword are the MySQL username and password used with
+    the older version of GNUtritin."""
+    from gnutr import Dialog
+    lite = Database()
+
+    # Need to check for tables: recipe, ingredient, preparation
+    # person, food_plan, recipe_plan, nutr_goal 
+    tables = ['recipe', 'ingredient', 'preparation','person',
+              'food_plan', 'recipe_plan']
+    mysql.query('SHOW TABLES')
+    old_tables = mysql.get_result()
+    # At some point use of a 'measure' table was discontinued
+    use_msre_no = False
+    found = []
+    for t in old_tables:
+        if t[0] in tables:
+            found.append(t[0])
+        if t[0] == 'measure':
+            use_msre_no = True
+
+    # Quirks:
+    # 0.31 does not save recipe or food_plan (nothing to migrate except 
+    #      person data.
+    # 0.31.1 uses fd_no (for NDB_No) and msre_no to index measure table
+    # 0.32 onward uses NDB_No and Msre_Desc (no measure table)
+
+    # For gnutrition version < 0.32
+    def msre_desc_from_msre_no(msre_no):
+        sql = "SELECT msre_desc FROM measure WHERE msre_no = {0:d}"
+        mysql.query(sql.format(msre_no))
+        return mysql.get_single_result()
+
+    # recipie table
+    if 'recipe' in found:
+        mysql.query("SELECT recipe_no, recipe_name, no_serv, no_ingr, " +
+                    "category_no FROM recipe")
+        result = mysql.get_result()
+        if result and len(result) > 0:
+            print 'found', len(result), 'recipies'
+            print result
+            lite.query("INSERT INTO 'recipe' VALUES (?,?,?,?,?)",
+                           many=True, sql_params=result, caller='migrate')
+    # ingredient table
+    if 'ingredient' in found:
+        sql1 = "SELECT recipe_no, amount, msre_no, fd_no FROM ingredient"
+        sql2 = "SELECT recipe_no, amount, Msre_Desc, NDB_No FROM ingredient"
+        if use_msre_no:
+            mysql.query(sql1)
+        else:
+            mysql.query(sql2)
+        result = mysql.get_result()
+        if result:
+            print 'found', len(result), 'ingredients'
+            print result
+            for i in range(len(result)):
+                recipe_no = result[i][0]
+                amount = result[i][1]
+                if use_msre_no:
+                    Msre_Desc = msre_desc_from_msre_no(result[i][2])
+                else:
+                    Msre_Desc = result[i][2]
+                NDB_No = result[i][3]
+                params = (recipe_no, amount, Msre_Desc, NDB_No)
+                lite.query("INSERT INTO 'ingredient' VALUES (?,?,?,?)",
+                           many=False, sql_params=params, caller='migrate')
+
+    # preparation table
+    if 'preparation' in found:
+        mysql.query("SELECT recipe_no, prep_time, prep_desc FROM preparation")
+        result = mysql.get_result()
+        if result and len(result) > 0:
+            print 'found', len(result), 'entries in preparation table'
+            print result
+            lite.query("INSERT INTO 'preparation' VALUES (?,?,?)",
+                           many=True, sql_params=result, caller='migrate')
+
+    # person table
+    if 'person' in found:
+        mysql.query("SELECT person_no, person_name, user_name FROM person")
+        result = mysql.get_result()
+        if result and len(result) > 0:
+            print 'found', len(result), 'entries in person table'
+            print result
+            lite.query("INSERT INTO 'person' VALUES (?,?,?)",
+                           many=True, sql_params=result, caller='migrate')
+
+    # food_plan table
+    if 'food_plan' in found:
+        sql1 = "SELECT person_no, date, time, amount, msre_no, fd_no FROM 
food_plan"
+        sql2 = "SELECT person_no, date, time, amount, Msre_Desc, NDB_No FROM 
food_plan"
+        if use_msre_no:
+            mysql.query(sql1)
+        else:
+            mysql.query(sql2)
+        result = mysql.get_result()
+        if result and len(result) > 0:
+            print 'found', len(result), 'entries in food_plan table'
+            for i in range(len(result)):
+                person_no = result[i][0]
+                date = result[i][1]
+                time = result[i][2]
+                amount = result[i][3]
+                if use_msre_no:
+                    Msre_Desc = msre_desc_from_msre_no(result[i][4])
+                else:
+                    Msre_Desc = result[i][4]
+                NDB_No = result[i][5]
+                params = (person_no, date, time, amount, Msre_Desc, NDB_No)
+                lite.query("INSERT INTO 'food_plan' VALUES (?,?,?,?,?,?)",
+                           many=False, sql_params=params, caller='migrate')
+    # recipe_plan table
+    if 'recipe_plan' in found:
+        # Need to convert datetime.date and datetime.timedelta MySQL types to
+        # strings before inserting into SQLite table.
+        mysql.query("SELECT person_no, date, time, no_portions, " +
+                    "recipe_no FROM recipe_plan")
+        result = mysql.get_result()
+        print 'found', len(result), 'entries in recipe_plan table'
+        if result and len(result) > 0:
+            for r in range(len(result)):
+                person_no = result[r][0]
+                date = str(result[r][1])
+                time = str(result[r][2])
+                no_portions = result[r][3]
+                recipe_no = result[r][4]
+                params = (person_no, date, time, no_portions, recipe_no)
+                print params
+                lite.query("INSERT INTO 'recipe_plan' VALUES (?,?,?,?,?)",
+                           many=False, sql_params=params, caller='migrate')
+    # nutr_goal table needs to be recalculated
+    return True
+#---------------------------------------------------------------------------
+if __name__ == '__main__':
+    import mysql
+    try:
+       db = mysql.Database('gnutrition', 'gnutrition')
+    except Exception:
+        dialog = Dialog('error',
+                        "Unable to connect to MySQL's GNUtrition database.")
+    else: 
+        sqlite = Database()
+        sqlite.initialize()
+        migrate('gnutrition','gnutrition')

=== modified file 'src/druid.py'
--- a/src/druid.py      2012-07-27 01:59:48 +0000
+++ b/src/druid.py      2012-09-26 05:09:15 +0000
@@ -23,6 +23,7 @@
 import calc_rdi
 import database
 import nutr_goal_dlg
+from gnutr import Dialog
 
 class Druid:
     def __init__(self, app):
@@ -49,161 +50,109 @@
 
         # Database Create
         elif self.ui.page_num == 1:
-            #uname = self.ui.page_list[1].root_user_entry.get_text()
-            #pword = self.ui.page_list[1].root_pass_entry.get_text()
-            #if (not uname) or (not pword):
-            #    return
             try:
-                self.db = database.Database()
-                #self.db = database.Database(uname, pword)
+                self.sqlite = database.Database()
             except Exception, ex:
                 self.ui.set_page(2)
                 return
             
-            self.db.initialize()
-            
+            self.sqlite.initialize()
+
+            # See if this user has GNUtrition data from older version
+            # which used MySQL. That data should be migrated to newer SQLite
+            # storage first.
+            db_uname = config.get_value('Username')
+            db_pword = config.get_value('Password')
+            if (db_uname and db_pword):
+                dialog = Dialog('question',
+                    "Would you like to try to import recipies and other\n" +
+                    "data from MySQL (from older version of gnutrition)?")
+                reply = dialog.run()
+                dialog.destroy()
+                if reply == gtk.RESPONSE_YES:
+                    self.migration = True
+                    import mysql
+                    try:
+                        self.mysql = mysql.Database(db_uname, db_pword) 
+                    except Exception:
+                        # HERE: add dialog notification about failure to
+                        #       connect to MySQL server with stored username
+                        #       and password.
+                        dialog = Dialog('error',
+                            "Unable to connect to MySQL's GNUtrition 
database.")
+                    else:
+                        if self.mysql.initialize():
+                            # This needs MySQL root username and password
+                            #if self.mysql.user_setup(db_uname, db_pword):
+                            database.migrate(self.mysql)
+                        else:
+                            # HERE: add dialog notification about missing
+                            #       gnutr_db database
+                            dialog = Dialog('error',
+                              "MySQL GNUtrition database no longer exists.")
+
             # no error, so skip over page_db_error
-            #self.ui.set_page(3)
-            self.ui.set_page(5)
+            self.ui.set_page(3)
             return
 
-        # User Setup (skipped if using SQLite)
+        # Personal details
         elif self.ui.page_num == 3:
-            #uname = self.ui.page_list[3].user_entry.get_text()
-            #pword = self.ui.page_list[3].pass_entry.get_text()
-            #if (not uname) or (not pword):
-            #    return
-            #success = self.user_setup(uname, pword)
-            #if not success:
-            #    self.ui.set_page(4)
-            #    return
-            #self.db.change_user(uname, pword, 'gnutr_db')
-
+            self.person = person.Person()
             # does the user have an entry in the person table?
-            self.person = person.Person()
-            person_name = self.person.get_name(self.db.user)
-            if person_name:
-                config.set_key_value('Name', person_name)
-                self.person.setup()
-
-                self.ui.set_page(7)
-                return
-            self.ui.set_page(5)
-            return
-
-        # Personal details
-        elif self.ui.page_num == 5:
-######
-            self.person = person.Person()
-            person_name = self.person.get_name(self.db.user)
-            if person_name:
-                config.set_key_value('Name', person_name)
-                self.person.setup()
-
-                self.ui.set_page(7)
-                return
-
-######
-            name = self.ui.page_list[5].name_entry.get_text()
-            age = self.ui.page_list[5].age_entry.get_text()
-            weight_txt = self.ui.page_list[5].weight_entry.get_text()
+            # Note: sqlite.user is basename $HOME 
+            #       gnutrition MySQL setup asks for MySQL username and that
+            #       will be what is in the 'person' table for 'user_name'
+            db_uname = config.get_value('Username')
+            if db_uname:
+                db_name = db_uname
+            else:
+                db_name = self.sqlite.user
+            name = self.person.get_name(db_name)
+            config.set_key_value('Username', db_name)
+            name = self.ui.page_list[3].name_entry.get_text()
+            age = self.ui.page_list[3].age_entry.get_text()
+            weight_txt = self.ui.page_list[3].weight_entry.get_text()
             if (not name) or (not age) or (not weight_txt):
                 return
             weight = float(weight_txt)
 
-            config.set_key_value('Name', name)
+            config.set_key_value('Age', age)
+            config.set_key_value('Weight', weight)
+
+            if config.get_value('Name') != name:
+                config.set_key_value('Name', name)
+
             self.person.add_name(name)
             self.person.setup()
 
-            if self.ui.page_list[5].weight_combo.get_active() == 0:
+            if self.ui.page_list[3].weight_combo.get_active() == 0:
                 # convert from pounds to kilos
                 weight = weight * 0.4536
-            female = self.ui.page_list[5].female_button.get_active()
+            female = self.ui.page_list[3].female_button.get_active()
             if female == 1:
-                pregnant = self.ui.page_list[5].preg_button.get_active()
-                lactating = self.ui.page_list[5].lac_button.get_active()
+                pregnant = self.ui.page_list[3].preg_button.get_active()
+                lactating = self.ui.page_list[3].lac_button.get_active()
             else:
                 pregnant = 0
                 lactating = 0
 
-            list = calc_rdi.compute(age, weight, female, pregnant, lactating)
+            data = calc_rdi.compute(age, weight, female, pregnant, lactating)
             self.nutr_goal_dlg = nutr_goal_dlg.NutrGoalDlg()
-            self.nutr_goal_dlg.save_goal(list)
+            self.nutr_goal_dlg.save_goal(data)
 
-            self.ui.set_page(7)
+            self.ui.set_page(5)
             return
 
         # Finish
-        elif self.ui.page_num == 7:
+        elif self.ui.page_num == 5:
             self.ui.dialog.hide()
             self.app.startup()
            
-    def user_setup(self, uname, pword):
-        # check to see if user name is already in mysql.user and that the
-        # password is correct
-        if self.user_name_exists(uname):
-            if self.password_match(uname, pword):
-                # add the info to the config file.
-                config.set_key_value('Username', uname)
-                config.set_key_value('Password', pword)
-                # check to see if user can access 'gnutr_db'
-                if not self.user_db_access(uname):
-                    # grant privileges to user
-                    self.db.add_user(uname, pword)
-            else:
-                return 0
-        else:
-            self.db.add_user(uname, pword)
-            config.set_key_value('Username', uname)
-            config.set_key_value('Password', pword)
-        return 1
-
-    def user_name_exists(self, uname):
-        self.db.query("USE mysql")
-        self.db.query("SELECT User FROM user WHERE " +
-            "User = '" + uname + "'")
-        name = self.db.get_single_result()
-        if not name:
-            return 0
-        return 1
-
-    def password_match(self, uname, pword):
-        # check to see if the password is correct
-        self.db.query("SELECT Password FROM user WHERE " +
-            "User = '" + str(uname) + "'")
-        result1 = self.db.get_single_result()
-        self.db.query("SELECT PASSWORD('" + str(pword) + "')")
-        result2 = self.db.get_single_result()
-        if result1 == result2:
-            return 1;
-        return 0
-
-    def user_db_access(self, uname):
-        # does the user have access to the gnutr_db?
-        self.db.query("SELECT Db FROM db WHERE " +
-            "User = '" + str(uname) + "'")
-        result = self.db.get_result()
-        for db_name in result:
-            if db_name[0] == 'gnutr_db':
-                return 1
-        return 0
-
     def on_back(self, w, d=None):
         # skip back over page_db_error
-        if self.ui.page_num == 5:
-            self.ui.set_page(1)
-        elif self.ui.page_num == 7:
-            self.ui.set_page(5)
-        else:
-            self.ui.set_page(self.ui.page_num - 1)
-
-    def on_back_original(self, w, d=None):
-        # skip back over page_db_error
         if self.ui.page_num == 3:
             self.ui.set_page(1)
         elif self.ui.page_num == 5:
             self.ui.set_page(3)
-        elif self.ui.page_num == 7:
-            self.ui.set_page(5)
         else:
             self.ui.set_page(self.ui.page_num - 1)

=== modified file 'src/druid_ui.py'
--- a/src/druid_ui.py   2012-07-27 01:59:48 +0000
+++ b/src/druid_ui.py   2012-09-26 05:09:15 +0000
@@ -29,7 +29,7 @@
             label1.set_alignment(0.0, 0.5)
             self.vbox.pack_start(label1, False, False, 5)
 
-            label2 = gtk.Label('You seem to be running GNUtrition for the 
first time.\n\nThe following steps will set up GNUtrition by asking a few 
simple questions.')
+            label2 = gtk.Label('Running this version of GNUtrition for the 
first time...\n')
             label2.set_alignment(0.0, 0.5)
             label2.set_line_wrap(True)
             label2.set_justify(gtk.JUSTIFY_FILL)
@@ -42,41 +42,13 @@
             table1.set_col_spacings(5)
             self.vbox.pack_start(table1, True, True, 0)
 
-            label1 = gtk.Label('Database Creation.') 
+            label1 = gtk.Label("Click 'Next' to create the USDA food 
database.") 
             label1.set_alignment(0.0, 0.5)
             table1.attach(label1, 0, 2, 0, 1, gtk.FILL, 0, 0, 0)
 
-#            label2 = gtk.Label(
-#                'Enter the root username and password for MySQL.') 
-#            label2.set_alignment(0.0, 0.5)
-#            table1.attach(label2, 0, 2, 1, 2, gtk.FILL, 0, 0, 0)
-
-#            label3 = gtk.Label('MySQL root username') 
-#            label3.set_alignment(1.0, 0.5)
-#            table1.attach(label3, 0, 1, 2, 3, gtk.FILL, 0, 0, 0)
-
-#            self.root_user_entry = gtk.Entry()
-#            table1.attach(self.root_user_entry, 1, 2, 2, 3, 
-#                gtk.FILL | gtk.EXPAND, 0, 0, 0)
-
-#            label4 = gtk.Label('MySQL root password') 
-#            label4.set_alignment(1.0, 0.5)
-#            table1.attach(label4, 0, 1, 3, 4, gtk.FILL, 0, 0, 0)
-
-#            self.root_pass_entry = gtk.Entry()
-#            self.root_pass_entry.set_visibility(False);
-#            table1.attach(self.root_pass_entry, 1, 2, 3, 4, 
-#                gtk.FILL | gtk.EXPAND, 0, 0, 0)
-
-            label5 = gtk.Label('When you press the "Next" button GNUtrition 
will check to see if the GNUtrition Database is already installed. If not, 
GNUtrition will install it for you.') 
-            label5.set_alignment(0.0, 0.5)
-            label5.set_line_wrap(True)
-            label5.set_justify(gtk.JUSTIFY_FILL)
-            table1.attach(label5, 0, 2, 4, 5, gtk.FILL, 0, 0, 0)
-
-            label6 = gtk.Label('This may take some time.') 
-            label6.set_alignment(0.0, 0.5)
-            table1.attach(label6, 0, 2, 5, 6, gtk.FILL, 0, 0, 0)
+            label2 = gtk.Label('This will take a little time...')
+            label2.set_alignment(1.0, 0.5)
+            table1.attach(label2, 0, 1, 2, 3, gtk.FILL, 0, 0, 0)
 
         # Error in Database Creation
         elif page_num == 2:
@@ -88,71 +60,9 @@
             label2.set_alignment(0.0, 0.5)
             self.vbox.pack_start(label2, False, False, 5)
 
-            label2 = gtk.Label('Please go back and check that the MySQL root 
username and password are correct.')
-            label2.set_alignment(0.0, 0.5)
-            label2.set_line_wrap(True)
-            self.vbox.pack_start(label2, False, False, 5)
-
         # User Setup
+        # Personal Details
         elif page_num == 3:
-            pass
-            #table1 = gtk.Table(2, 4, False)
-            #table1.set_row_spacings(5)
-            #table1.set_col_spacings(5)
-            #self.vbox.pack_start(table1, True, True, 0)
-
-            #label1 = gtk.Label('User Setup.')
-            #label1.set_alignment(0.0, 0.5)
-            #table1.attach(label1, 0, 2, 0, 1, gtk.FILL, 0, 0, 0)
-
-            #label2 = gtk.Label('In order to access the database you need to 
create a normal MySQL username and password. Specify your choice below. 
GNUtrition will remember them for you.')
-            #label2.set_alignment(0.0, 0.5)
-            #label2.set_line_wrap(True)
-            #label2.set_justify(gtk.JUSTIFY_FILL)
-            #table1.attach(label2, 0, 2, 1, 2, gtk.FILL, 0, 0, 0)
-
-            #label3 = gtk.Label('MySQL username') 
-            #label3.set_alignment(1.0, 0.5)
-            #table1.attach(label3, 0, 1, 2, 3, gtk.FILL, 0, 0, 0)
-
-            #self.user_entry = gtk.Entry()
-            #self.user_entry.set_text(getpass.getuser())
-            #table1.attach(self.user_entry, 1, 2, 2, 3, 
-            #    gtk.FILL | gtk.EXPAND, 0, 0, 0)
-
-            #label4 = gtk.Label('MySQL password') 
-            #label4.set_alignment(1.0, 0.5)
-            #table1.attach(label4, 0, 1, 3, 4, gtk.FILL, 0, 0, 0)
-
-            #self.pass_entry = gtk.Entry()
-            #self.pass_entry.set_visibility(False)
-            #table1.attach(self.pass_entry, 1, 2, 3, 4, 
-            #    gtk.FILL | gtk.EXPAND, 0, 0, 0)
-
-        # Error in User Setup
-        elif page_num == 4:
-            label1 = gtk.Label('Error: User Setup Failed.')
-            label1.set_alignment(0.0, 0.5)
-            self.vbox.pack_start(label1, False, False, 5)
-
-            label2 = gtk.Label('Unable to connect to the database.')
-            label2.set_alignment(0.0, 0.5)
-            self.vbox.pack_start(label2, False, False, 5)
-
-            label3 = gtk.Label('If you have connected to the database before, 
go back to the previous page and check that your password is correct.')
-            label3.set_alignment(0.0, 0.5)
-            label3.set_line_wrap(True)
-            label3.set_justify(gtk.JUSTIFY_FILL)
-            self.vbox.pack_start(label3, False, False, 5)
-
-            label4 = gtk.Label('If you are connecting to the database for the 
very first time, it may be that someone else has already chosen the same user 
name as you. Try going back and chosing another one.')
-            label4.set_alignment(0.0, 0.5)
-            label4.set_line_wrap(True)
-            label4.set_justify(gtk.JUSTIFY_FILL)
-            self.vbox.pack_start(label4, False, False, 5)
-
-        # Personal Details
-        elif page_num == 5:
             table1 = gtk.Table(3, 7, False)
             table1.set_row_spacings(5)
             table1.set_col_spacings(5)
@@ -231,7 +141,7 @@
             self.on_male_button_toggled(None)
 
         # Error in Personal Details
-        elif page_num == 6:
+        elif page_num == 4:
             label1 = gtk.Label('Error: Personal Details Setup Failed.')
             label1.set_alignment(0.0, 0.5)
             self.vbox.pack_start(label1, False, False, 5)
@@ -247,7 +157,7 @@
             self.vbox.pack_start(label2, False, False, 5)
 
         # Finish
-        elif page_num == 7:
+        elif page_num == 5:
             label1 = gtk.Label('GNUtrition has been successfully set up.')
             label1.set_alignment(0.0, 0.5)
             self.vbox.pack_start(label1, False, False, 5)
@@ -313,7 +223,7 @@
         self.connect_signals()
 
         self.page_list = []
-        for num in range(8):
+        for num in range(6):
             page = DruidPage(num)
             self.page_list.append(page)
 
@@ -331,7 +241,7 @@
         self.container.remove(self.page_list[self.page_num].vbox)
         self.back_button.set_sensitive(True)
         self.next_button.set_sensitive(True)
-        if num == 7:
+        if num == 5:
             self.next_button.remove(self.button_hbox2)
             self.set_next_button(1)
         else:
@@ -339,7 +249,7 @@
             self.set_next_button(0)
         if num == 0:
             self.back_button.set_sensitive(False)
-        if num in [ 2, 4, 6]:
+        if num in [2, 4]:
             self.next_button.set_sensitive(False)
         self.container.pack_start(self.page_list[num].vbox, 
             True, True, 0)

=== modified file 'src/gnutr_consts.py'
--- a/src/gnutr_consts.py       2012-05-28 14:46:37 +0000
+++ b/src/gnutr_consts.py       2012-09-26 05:09:15 +0000
@@ -33,6 +33,3 @@
 
 GRAPHICAL = 0
 DIALOG = 1
-
-DB_HOST = "gnutrition.sourceforge.net"
-CGI_PATH = "/submit-recipe.php"

=== added file 'src/mysql.py'
--- a/src/mysql.py      1970-01-01 00:00:00 +0000
+++ b/src/mysql.py      2012-09-26 05:09:15 +0000
@@ -0,0 +1,176 @@
+# GNUtrition - a nutrition and diet analysis program.
+# Copyright (C) 2000-2002 Edgar Denny (address@hidden)
+# Copyright (C) 2010 2012 Free Software Foundation, Inc.
+#
+# This program is free software: you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation, either version 3 of the License, or
+# (at your option) any later version.
+# 
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+import MySQLdb
+import warnings
+
+class Database:
+    _shared_state = {}
+    def __init__(self, uname=None, pword=None):
+        self.__dict__ = self._shared_state
+        if self._shared_state:
+            return
+    # supress warning on "DROP TABLE IF EXISTS" for temp tables
+        warnings.filterwarnings("ignore", "Unknown table.*_temp")
+    # supress 'Data truncated ...' 
+        warnings.filterwarnings("ignore", "Data truncated*")
+
+        self.db = MySQLdb.Connect(user=uname, passwd=pword)
+        self.cursor = self.db.cursor()
+        self.user = uname
+        self.rows = 0
+        self.result = None
+ 
+    def change_user(self, uname, pword, dbase): 
+        try:
+            self.db = MySQLdb.Connect(user=uname, passwd=pword, db=dbase)
+            self.cursor = self.db.cursor()
+            self.user = uname
+        except:
+            return 0
+        return 1
+
+    def initialize(self):
+        self.query('SHOW DATABASES')
+        db_list = self.get_result()
+        for b in db_list:
+            if b[0] == 'gnutr_db':
+                self.query('USE gnutr_db')
+                return True
+        return False
+
+    def query(self, query, caller=None):
+        try:
+            self.cursor.execute(query)
+        except MySQLdb.Error, sqlerr:
+            print 'Error :', sqlerr, '\nquery:', query
+            self.cursor.execute('SHOW ERRORS');
+            import traceback
+            import sys
+            traceback.print_exc()
+            if caller: print 'Caller ', caller
+            sys.exit()
+        self.result = self.cursor.fetchall()
+        self.rows = self.db.affected_rows()
+        self.db.commit()
+#        return self.get_result()
+
+    def get_result(self):
+        result = self.result
+        self.result = None
+        if not result:
+            print 'No result'
+        return result
+
+    def get_row_result(self):
+        result = self.result
+        self.result = None
+        if not result:
+            print 'No result'
+            return None
+        if len(result) == 1:
+            return result[0]
+        print 'Error: not a single row'
+        return None
+
+    def get_single_result(self):
+        result = self.result
+        self.result = None
+        if not result:
+            print 'No result'
+            return None
+        if len(result) == 1:
+            if len(result[0] ) == 1:
+                return result[0][0]
+        print 'Error: not a single value'
+        return None
+
+    def create_table(self, query, tablename):
+        self.query(query)
+        print "table created: ", tablename
+
+    def load_table(self, fn, table):
+        self.query("LOAD DATA LOCAL INFILE '"+ fn + "' " +
+            "INTO TABLE " + table + " FIELDS TERMINATED BY '^'")
+
+    def create_load_table(self, query, filename):
+        import install
+        from os import path
+        self.create_table(query, filename)
+        fn = path.join(install.idir,'data',filename.upper() + '.txt')
+        self.load_table(fn, filename)
+        print "table loaded: ", filename
+
+    def add_user(self, user, password):
+        self.query("GRANT USAGE ON *.* TO " + user +
+            "@localhost IDENTIFIED BY '" + password + "'")
+        self.query("GRANT ALL ON gnutr_db.* TO " + user + 
+            "@localhost IDENTIFIED BY '" + password + "'")
+        self.query("FLUSH PRIVILEGES")
+
+    def delete_db(self):
+        self.query("DROP DATABASE gnutr_db")
+
+    def user_setup(self, uname, pword):
+        # check to see if user name is already in mysql.user and that the
+        # password is correct
+        if self.user_name_exists(uname):
+            if self.password_match(uname, pword):
+                # add the info to the config file.
+                #config.set_key_value('Username', uname)
+                #config.set_key_value('Password', pword)
+                # check to see if user can access 'gnutr_db'
+                if not self.user_db_access(uname):
+                    # grant privileges to user
+                    self.mysql.add_user(uname, pword)
+            else:
+                # HERE: add dialog notifying that ...
+                return 0
+        else:
+            # HERE: add dialog notifying that ...
+            return 0
+        return 1
+
+    def user_name_exists(self, uname):
+        self.mysql.query("USE mysql")
+        self.mysql.query("SELECT User FROM user WHERE " +
+            "User = '" + uname + "'")
+        name = self.mysql.get_single_result()
+        if not name:
+            return 0
+        return 1
+
+    def password_match(self, uname, pword):
+        # check to see if the password is correct
+        self.mysql.query("SELECT Password FROM user WHERE " +
+            "User = '" + str(uname) + "'")
+        result1 = self.mysql.get_single_result()
+        self.db.query("SELECT PASSWORD('" + str(pword) + "')")
+        result2 = self.mysql.get_single_result()
+        if result1 == result2:
+            return 1;
+        return 0
+
+    def user_db_access(self, uname):
+        # does the user have access to the gnutr_db?
+        self.mysql.query("SELECT Db FROM db WHERE " +
+            "User = '" + str(uname) + "'")
+        result = self.mysql.get_result()
+        for db_name in result:
+            if db_name[0] == 'gnutr_db':
+                return 1
+        return 0

=== modified file 'src/person.py'
--- a/src/person.py     2012-09-16 23:02:12 +0000
+++ b/src/person.py     2012-09-26 05:09:15 +0000
@@ -16,6 +16,7 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 
 import database
+import config
 
 class Person:
     _shared_state = {}
@@ -33,7 +34,7 @@
     def add_name(self, person_name):
         user = self.get_user()
         self.db.query("SELECT person_name FROM person")
-        result = self.db.get_single_result()
+        result = self.db.get_result()
 
         if not result:
             # first name to be added to the table
@@ -98,7 +99,8 @@
                         recipe_num))
 
     def get_user(self):
-        return self.db.user
+        #return self.db.user
+        return config.get_value('Username')
 
     def get_person_num(self):
         user_name = self.get_user()

=== modified file 'src/run_app.py'
--- a/src/run_app.py    2012-09-16 23:02:12 +0000
+++ b/src/run_app.py    2012-09-26 05:09:15 +0000
@@ -20,11 +20,12 @@
 
 class RunApp:
     def __init__(self):
-        if not config.get_value('Name'):
+        if not config.get_value('sqlite3'):
             # First run, program default values can be added here
             import druid
             # Set default version check information
             import gnutr_consts
+            config.set_key_value('sqlite3', 'Yes')
             config.set_key_value('check_disabled', gnutr_consts.CHECK_DISABLED)
             config.set_key_value('check_version', gnutr_consts.CHECK_VERSION)
             config.set_key_value('check_interval', gnutr_consts.CHECK_INTERVAL)
@@ -37,22 +38,9 @@
     def startup(self):
         import version
         version.check_version()
-        db_uname = config.get_value('Username')
-        db_pword = config.get_value('Password')
 
         import database 
         self.db = database.Database()
-        #success = self.db.change_user(db_uname, db_pword, 'gnutr_db')
-
-        #if success == 0:
-        #    import gnutr
-        #    import sys
-        #    gnutr.Dialog('error', 
-        #        'Failed to connect to the database.\n\n' +
-        #        'I suggest that you delete the file\n ' +
-        #        '"~/.gnutrition/config" and run "gnutrition" again.')
-        #    gtk.main_quit()
-        #    sys.exit()
 
         import store
         self.store = store.Store()


reply via email to

[Prev in Thread] Current Thread [Next in Thread]