[chronojump] Import session with updateDB WIP



commit cc83fb068f569ce823d20de4a65a0c25157237a6
Author: Xavier de Blas <xaviblas gmail com>
Date:   Tue Oct 15 18:08:21 2019 +0200

    Import session with updateDB WIP

 src/chronojump-importer/chronojump_importer.py | 42 +++++++++++-----
 src/chronojump.cs                              |  3 +-
 src/chronojumpImporter.cs                      | 51 ++++++++++++++++++--
 src/forceSensor.cs                             | 43 ++++++++++++++++-
 src/sqlite/forceSensor.cs                      | 66 +++++++++++++++++++++-----
 src/sqlite/main.cs                             |  4 ++
 src/sqlite/runEncoder.cs                       | 14 ++++--
 src/util.cs                                    |  6 ++-
 8 files changed, 193 insertions(+), 36 deletions(-)
---
diff --git a/src/chronojump-importer/chronojump_importer.py b/src/chronojump-importer/chronojump_importer.py
index 53d5f1b8..002a9d15 100755
--- a/src/chronojump-importer/chronojump_importer.py
+++ b/src/chronojump-importer/chronojump_importer.py
@@ -377,7 +377,7 @@ class Database:
 
 
 class ImportSession:
-    def __init__(self, source_path, destination_path, source_base_directory):
+    def __init__(self, source_path, destination_path, source_base_directory, source_temp_directory):
         """ Creates the object to import the session source_session from source_db into destination_db. """
 
         logging.debug("source path:" + source_path)
@@ -386,6 +386,7 @@ class ImportSession:
         self.source_path = source_path
         self.destination_path = destination_path
         self.source_base_directory = source_base_directory
+        self.source_temp_directory = source_temp_directory
 
         self.source_db = Database(source_path, read_only=True)
         self.destination_db = Database(destination_path, read_only=False)
@@ -663,7 +664,7 @@ class ImportSession:
         # but on encoder and forceSensor is linked by ex.uniqueID
 
         if(DEBUGTOFILE):
-            debugFile.write(" start _import_forceSensor ")
+            debugFile.write(" start _import_forceSensor\n")
 
         forceSensor_exercise_from_forceSensor = self.source_db.read(table_name="ForceSensorExercise",
                 where_condition="ForceSensor.uniqueID={}".format(self.source_session),
@@ -693,14 +694,14 @@ class ImportSession:
                                   matches_columns=self.destination_db.column_names("forceSensor", 
skip_columns=["uniqueID", "personID", "sessionID", "exerciseID"]))
 
         if(DEBUGTOFILE):
-            debugFile.write(" end _import_forceSensor ")
+            debugFile.write(" end _import_forceSensor\n")
 
     def _import_runEncoder(self):
         # Imports RunEncoderExercise
         # VERY similar to _import_runEncoder
 
         if(DEBUGTOFILE):
-            debugFile.write(" start _import_runEncoder ")
+            debugFile.write(" start _import_runEncoder\n")
 
         runEncoder_exercise_from_runEncoder = self.source_db.read(table_name="RunEncoderExercise",
                 where_condition="RunEncoder.uniqueID={}".format(self.source_session),
@@ -730,7 +731,7 @@ class ImportSession:
                                   matches_columns=self.destination_db.column_names("runEncoder", 
skip_columns=["uniqueID", "personID", "sessionID", "exerciseID"]))
 
         if(DEBUGTOFILE):
-            debugFile.write(" end _import_runEncoder ")
+            debugFile.write(" end _import_runEncoder\n")
 
 
 
@@ -747,10 +748,16 @@ class ImportSession:
 
     @staticmethod
     def _forceSensor_filename(person_id, original_filename):
-        """ original_filename is like 1-Carmelo-89-2014-12-03_12-48-54.csv. It only replaces the person_id 
(1 in this case)"""
-        filename=original_filename.split("-", 1)
-        filename[0] = str(person_id)
-        return "-".join(filename)
+        """ original_filename is like 19_some person_2019-05-26_15-09-25.csv. It only replaces the person_id 
(1 in this case)"""
+        """ but as we originally do not have database for forceSensor and runEncoder, we just have written 
the name, in this case: add the id before"""
+        pattern = '\A\d+_' #\A for the beginning of the file, then digits and then the _
+        result = re.match(pattern, original_filename)
+        if result:
+            filename = original_filename.split("_", 1)
+            filename[0] = str(person_id)
+            return "_".join(filename)
+        else:
+            return str(person_id) + "_" + original_filename
 
     @staticmethod
     def _forceSensor_url(session_id):
@@ -827,12 +834,12 @@ class ImportSession:
 
     # valid for forceSensor and runEncoder files, theses are the values on tableName
     def _import_forceSensor_or_runEncoder_files(self, table, tableName):
-        if self.source_base_directory is None:
+        if self.source_temp_directory is None:
             # We are skipping to copy the Encoding files. This is used in unit tests.
             return
 
         if(DEBUGTOFILE):
-            debugFile.write(" at import_forceSensor_or_runEncoder_files")
+            debugFile.write(" at import_forceSensor_or_runEncoder_files\n")
             debugFile.write(tableName)
 
         for row in table:
@@ -846,6 +853,9 @@ class ImportSession:
             original_url = self._normalize_path(row.get("url"))
             session_id = row.get("sessionID")
 
+            if(DEBUGTOFILE):
+                debugFile.write("original_filename: " + original_filename.encode('utf-8') + "\n")
+
             # Prepares the new filename and destination_url
             filename = ""
             destionation_url = ""
@@ -860,12 +870,15 @@ class ImportSession:
             row.set("filename", filename)
             row.set("url", destination_url)
 
+            if(DEBUGTOFILE):
+                debugFile.write("filename: " + filename.encode('utf-8') + "\n")
+
             # Copies the files to the new place
             destination_directory = os.path.join(self.destination_path, "..", "..", destination_url)
             destination_directory = os.path.abspath(destination_directory)  # os.makedirs() can't handle 
directories with ".."
 
             destination_filename = os.path.join(destination_directory, filename)
-            source_file = os.path.join(self.source_base_directory, original_url, original_filename)
+            source_file = os.path.join(self.source_temp_directory, original_url, original_filename)
 
             if not os.path.isdir(destination_directory):
                 os.makedirs(destination_directory)
@@ -911,6 +924,9 @@ def process_command_line():
     parser.add_argument("--source_base_directory", type=str, required=False,
                         help="Directory where the encoder/ directory (amongst database/, logs/ and 
multimedia/ can be found\n" +
                              "By default is parent as --source")
+    parser.add_argument("--source_temp_directory", type=str, required=False,
+                        help="Directory where the temp forceSensor and runAnalyzer files are\n" +
+                             "they are at temp folder because name have been changed")
     parser.add_argument("--destination", type=str, required=False,
                         help="chronojump.sqlite that we import to")
     parser.add_argument("--source_session", type=int, required=False,
@@ -943,7 +959,7 @@ def process_command_line():
                 DEBUGTOFILE = True
                 debugFile = open('/tmp/debugFile.txt', 'w')
 
-            importer = ImportSession(args.source, args.destination, source_base_directory)
+            importer = ImportSession(args.source, args.destination, source_base_directory, 
args.source_temp_directory)
 
             if args.destination_session is None:
                 importer.import_as_new_session(args.source_session)
diff --git a/src/chronojump.cs b/src/chronojump.cs
index 78e1c96b..c48841aa 100644
--- a/src/chronojump.cs
+++ b/src/chronojump.cs
@@ -373,8 +373,7 @@ public class ChronoJump
                                messageToShowOnBoot += Catalog.GetString("All DJ jumps have been renamed as 
'DJna' (Drop Jumps with No Arms).") + "\n\n"+ 
                                        Catalog.GetString("If your Drop Jumps were executed using the arms, 
please rename them manually as 'DJa'.") + "\n";
 
-                       SqliteForceSensor.DirToImport = Util.GetForceSensorDir();
-                       SqliteRunEncoder.DirToImport = Util.GetRunEncoderDir();
+                       Sqlite.UpdatingDBFrom = Sqlite.UpdatingDBFromEnum.LOCAL;
 
                        bool softwareIsNew = Sqlite.ConvertToLastChronojumpDBVersion();
                        updatingDB = false;
diff --git a/src/chronojumpImporter.cs b/src/chronojumpImporter.cs
index 9219eb51..1db2d04d 100644
--- a/src/chronojumpImporter.cs
+++ b/src/chronojumpImporter.cs
@@ -132,12 +132,52 @@ class ChronojumpImporter
        // tries to import a newer chronojump version.
        public Result import()
        {
+               //1) create temp dir for forceSensor and runEncoder and copy files there, original files will 
not be used
+               //   no need to be done for encoder files because there we will not to change filename
+
+LogB.Information("import A ");
+               string tempImportDir = Util.GetDatabaseTempImportDir();
+               if(Directory.Exists(tempImportDir))
+               {
+                       try {
+                               var dir = new DirectoryInfo(@tempImportDir);
+                               dir.Delete(true); //recursive delete
+                       } catch {
+                               return new Result (false, "Could not delete directory: " + tempImportDir);
+                       }
+               }
+LogB.Information("import B ");
+               string forceSensorName = "forceSensor";
+               string raceAnalyzerName = "raceAnalyzer";
+LogB.Information("import C ");
+               Directory.CreateDirectory(tempImportDir);
+LogB.Information("import D ");
+               Directory.CreateDirectory(Path.Combine(tempImportDir, forceSensorName, 
sourceSession.ToString()));
+LogB.Information("import E ");
+               Directory.CreateDirectory(Path.Combine(tempImportDir, raceAnalyzerName, 
sourceSession.ToString()));
+LogB.Information("import F ");
+
+               string sourceDir = Path.GetDirectoryName(sourceFile);
+               if(Directory.Exists(Path.Combine(sourceDir, "..", forceSensorName)))
+                       foreach (FileInfo file in new DirectoryInfo(Path.Combine(sourceDir, "..", 
forceSensorName, sourceSession.ToString())).GetFiles())
+                               file.CopyTo(Path.Combine(tempImportDir, forceSensorName, 
sourceSession.ToString(), file.Name));
+
+LogB.Information("import G ");
+               if(Directory.Exists(Path.Combine(sourceDir, "..", raceAnalyzerName)))
+                       foreach (FileInfo file in new DirectoryInfo(Path.Combine(sourceDir, "..", 
raceAnalyzerName, sourceSession.ToString())).GetFiles())
+                               file.CopyTo(Path.Combine(tempImportDir, raceAnalyzerName, 
sourceSession.ToString(), file.Name));
+
+LogB.Information("import H ");
+
+               //2) prepare SQL files
+
                string temporarySourceFile = Path.GetTempFileName ();
                File.Copy (sourceFile, temporarySourceFile, true);
 
                Result sourceDatabaseVersion = getDatabaseVersionFromFile (temporarySourceFile);
                Result destinationDatabaseVersion = getDatabaseVersionFromFile (destinationFile);
 
+LogB.Information("import A ");
                if (! sourceDatabaseVersion.success)
                        return sourceDatabaseVersion;
 
@@ -147,12 +187,14 @@ class ChronojumpImporter
                float destinationDatabaseVersionNum = float.Parse (destinationDatabaseVersion.output);
                float sourceDatabaseVersionNum = float.Parse (sourceDatabaseVersion.output);
 
+               //3 check version of database to be imported
+
                if (destinationDatabaseVersionNum < sourceDatabaseVersionNum) {
                        return new Result (false, Catalog.GetString ("Trying to import a newer database 
version than this Chronojump\n" +
                                "Please, update the running Chronojump."));
                } else if (destinationDatabaseVersionNum > sourceDatabaseVersionNum) {
                        LogB.Debug ("chronojump-importer version before update: ", 
sourceDatabaseVersion.output);
-                       updateDatabase (temporarySourceFile, Path.GetDirectoryName(sourceFile));
+                       updateDatabase (temporarySourceFile);
                        string versionAfterUpdate = getDatabaseVersionFromFile (temporarySourceFile).output;
                        LogB.Debug ("chronojump-importer version after update: ", versionAfterUpdate);
                }
@@ -166,6 +208,8 @@ class ChronojumpImporter
                // encoder files
                parameters.Add ("--source_base_directory");
                parameters.Add (Path.Combine(Path.GetDirectoryName(sourceFile), "..")); 
+               parameters.Add ("--source_temp_directory");
+               parameters.Add (Util.GetDatabaseTempImportDir());
                parameters.Add ("--destination");
                parameters.Add (destinationFile);
                parameters.Add ("--source_session");
@@ -188,7 +232,7 @@ class ChronojumpImporter
                return result;
        }
 
-       private static void updateDatabase(string databaseFile, string sourceDir)
+       private static void updateDatabase(string databaseFile)
        {
                StaticClassState classOriginalState = new StaticClassState (typeof (Sqlite));
 
@@ -200,8 +244,7 @@ class ChronojumpImporter
                Sqlite.setSqlFilePath (databaseFile);
                Sqlite.Connect ();
 
-               SqliteForceSensor.DirToImport = Path.Combine(sourceDir, "..", "forceSensor");
-               SqliteRunEncoder.DirToImport = Path.Combine(sourceDir, "..", "raceAnalyzer");
+               Sqlite.UpdatingDBFrom = Sqlite.UpdatingDBFromEnum.IMPORTED_SESSION;
 
                Sqlite.ConvertToLastChronojumpDBVersion ();
 
diff --git a/src/forceSensor.cs b/src/forceSensor.cs
index 8e0e200f..f5ea56df 100644
--- a/src/forceSensor.cs
+++ b/src/forceSensor.cs
@@ -102,6 +102,8 @@ public class ForceSensor
                if(uniqueID != -1)
                        uniqueIDStr = uniqueID.ToString();
 
+               LogB.Information("toSQLInsert filename: " + filename);
+
                return
                        "(" + uniqueIDStr + ", " + personID + ", " + sessionID + ", " + exerciseID + ", \"" + 
captureOption.ToString() + "\", " +
                        angle + ", \"" + laterality + "\", \"" + filename + "\", \"" + url + "\", \"" + 
dateTime + "\", \"" +
@@ -320,6 +322,9 @@ public class ForceSensorExercise
                        Util.BoolToInt(elastic).ToString();
        }
 
+       /*
+        * is there any need of this?
+        *
        public string ToSQLInsertString_DB_1_68()
        {
                string uniqueIDStr = "NULL";
@@ -331,6 +336,7 @@ public class ForceSensorExercise
                        resistance + "\", " + angleDefault + ", \"" + description + "\", " +
                        Util.BoolToInt(tareBeforeCapture).ToString();
        }
+       */
 
        public bool Changed(ForceSensorExercise newEx)
        {
@@ -1402,10 +1408,12 @@ public class ForceSensorLoadTryToAssignPersonAndMore
        public Person GetPerson()
        {
                string personName = getNameAndMore();
+               LogB.Information("getPerson: " + personName);
                if(personName == "")
                        return new Person(-1);
 
                Person p = SqlitePerson.SelectByName(dbconOpened, personName);
+               LogB.Information("person: " + p.ToString());
                if(SqlitePersonSession.PersonSelectExistsInSession(dbconOpened, p.UniqueID, currentSessionID))
                        return p;
 
@@ -1414,6 +1422,25 @@ public class ForceSensorLoadTryToAssignPersonAndMore
 
        private string getNameAndMore()
        {
+               /*
+                *      there was a period were exercise param exists but can be captured without defining it,
+                *      it was represented as:
+                *        personName__laterality_date_hour
+                *        personName__laterality_comment_date_hour
+                *        ...
+                *      so fix this __ to:
+                *        personName_none_laterality_date_hour
+                *        personName_none_laterality_comment_date_hour
+                */
+
+               LogB.Information("filename: " + filename);
+               bool exerciseMissing = false;
+               if(filename.IndexOf("__") != -1)
+               {
+                       filename = filename.Replace("__", "_none_");
+                       exerciseMissing = true; //this will return "" as exercise
+               }
+
                string [] strFull = filename.Split(new char[] {'_'});
 
                /*
@@ -1424,13 +1451,25 @@ public class ForceSensorLoadTryToAssignPersonAndMore
                 *      personName_exercisename_laterality_comment_date_hour
                 *      note comment can have more _ so it can be
                 *      personName_exercisename_laterality_mycomment_with_some_underscores_date_hour
+                *
+                * Since there was database (2019 Sept 6), the filename is:
+                *      currentPerson.UniqueID + "_" + currentPerson.Name + "_" + 
UtilDate.ToFile(forceSensorTimeStartCapture);
+                *      but this method is not called since that date, because there's no need to call: 
import_from_1_68_to_1_69()
                 */
+
                if(strFull.Length == 3)
-                       return strFull[0];
+               {
+                       /*
+                       Match match = Regex.Match(file.Name, @"\A(\d+_)");
+                       if(match.Groups.Count == 2)
+                       */
+
+                       return strFull[0]; //personName_date_hour
+               }
                else if(strFull.Length >= 5)
                {
                        //strFull[1] is the exercise, but check that it existst on database
-                       if(Sqlite.Exists(dbconOpened, Constants.ForceSensorExerciseTable, strFull[1]))
+                       if(! exerciseMissing && Sqlite.Exists(dbconOpened, 
Constants.ForceSensorExerciseTable, strFull[1]))
                                Exercise = strFull[1];
 
                        if(
diff --git a/src/sqlite/forceSensor.cs b/src/sqlite/forceSensor.cs
index 5ac7a03b..6591f699 100644
--- a/src/sqlite/forceSensor.cs
+++ b/src/sqlite/forceSensor.cs
@@ -64,6 +64,7 @@ class SqliteForceSensor : Sqlite
        {
                openIfNeeded(dbconOpened);
 
+               LogB.Information("goint to insert: " + insertString);
                dbcmd.CommandText = "INSERT INTO " + table +
                                " (uniqueID, personID, sessionID, exerciseID, captureOption, angle, 
laterality, filename, url, dateTime, comments, videoURL)" +
                                " VALUES " + insertString;
@@ -260,15 +261,16 @@ class SqliteForceSensor : Sqlite
                return array;
        }
 
-       public static string DirToImport;
-
        protected internal static void import_from_1_68_to_1_69() //database is opened
        {
                LogB.PrintAllThreads = true; //TODO: remove this
                LogB.Information("at import_from_1_68_to_1_69()");
 
-               string forceSensorDir = DirToImport;
+               string forceSensorDir = Util.GetForceSensorDir();
+               if(Sqlite.UpdatingDBFrom == Sqlite.UpdatingDBFromEnum.IMPORTED_SESSION)
+                       forceSensorDir = Path.Combine(Util.GetDatabaseTempImportDir(), "forceSensor");
 
+               int unknownPersonID = Sqlite.ExistsAndGetUniqueID(true, Constants.PersonTable, 
Catalog.GetString("Unknown"));
                int unknownExerciseID = Sqlite.ExistsAndGetUniqueID(true, Constants.ForceSensorExerciseTable, 
Catalog.GetString("Unknown"));
 
                DirectoryInfo [] sessions = new DirectoryInfo(forceSensorDir).GetDirectories();
@@ -282,8 +284,26 @@ class SqliteForceSensor : Sqlite
                                        new ForceSensorLoadTryToAssignPersonAndMore(true, 
fileWithoutExtension, Convert.ToInt32(session.Name));
 
                                Person p = fslt.GetPerson();
+                               //if person is not foundz
                                if(p.UniqueID == -1)
-                                       continue;
+                               {
+                                       if(unknownPersonID == -1)
+                                       {
+//TODO: atencio pq aixo no s'esta insertant al final, s'inserta pero no sabem de moment on
+//i suposo que l'exercici tampoc
+                                               LogB.Information("going to insert person Unknown");
+                                               Person pUnknown = new Person (Catalog.GetString("Unknown"), 
"M", DateTime.Now,
+                                                               Constants.RaceUndefinedID,
+                                                               Constants.CountryUndefinedID,
+                                                               "", "", //future1: rfid
+                                                               Constants.ServerUndefinedID, true); 
//dbconOpened
+                                               unknownPersonID = pUnknown.UniqueID;
+
+                                               //el crea pero no queda guardat a la bd
+                                       }
+                                       p.UniqueID = unknownPersonID;
+                                       p.Name = Catalog.GetString("Unknown");
+                               }
 
                                if(! Util.IsNumber(session.Name, false))
                                        continue;
@@ -302,11 +322,23 @@ class SqliteForceSensor : Sqlite
                                        {
                                                ForceSensorExercise fse = new ForceSensorExercise (-1, 
Catalog.GetString("Unknown"), 0, "", 0, "", false, false, false);
                                                //note we are on 1_68 so we need this import method
-                                               unknownExerciseID = 
SqliteForceSensorExercise.InsertAtDB_1_68(true, fse);
+                                               //unknownExerciseID = 
SqliteForceSensorExercise.InsertAtDB_1_68(true, fse);
+                                               unknownExerciseID = SqliteForceSensorExercise.Insert(true, 
fse);
                                        }
 
                                        exerciseID = unknownExerciseID;
                                        exerciseName = Catalog.GetString("Unknown");
+
+                                       //put the old path on comment
+                                       fslt.Comment = file.Name;
+                               }
+
+                               if(fslt.Exercise != "")
+                               {
+                                       ForceSensorExercise fse = new ForceSensorExercise (-1, fslt.Exercise, 
0, "", 0, "", false, false, false);
+                                       //note we are on 1_68 so we need this import method
+                                       //unknownExerciseID = SqliteForceSensorExercise.InsertAtDB_1_68(true, 
fse);
+                                       unknownExerciseID = SqliteForceSensorExercise.Insert(true, fse);
                                }
 
                                //laterality (in English)
@@ -319,20 +351,28 @@ class SqliteForceSensor : Sqlite
                                        lat = Constants.ForceSensorLateralityBoth;
 
                                string parsedDate = UtilDate.ToFile(DateTime.MinValue);
+                               LogB.Information("KKKKKK " + file.Name);
                                Match match = Regex.Match(file.Name, @"(\d+-\d+-\d+_\d+-\d+-\d+)");
                                if(match.Groups.Count == 2)
                                        parsedDate = match.Value;
 
                                //filename will be this
                                string myFilename = p.UniqueID + "_" + p.Name + "_" + parsedDate + ".csv";
-                               //try to move the file
+                               //try to rename the file
                                try{
-                                       File.Move(file.FullName, 
Util.GetForceSensorSessionDir(Convert.ToInt32(session.Name)) + Path.DirectorySeparatorChar + myFilename);
+                                       //File.Move(file.FullName, 
Util.GetForceSensorSessionDir(Convert.ToInt32(session.Name)) + Path.DirectorySeparatorChar + myFilename);
+                                       //file.MoveTo(myFilename);
+                                       LogB.Information("copy from file.FullName: " + file.FullName);
+                                       LogB.Information("copy to: " + file.FullName.Replace(file.Name, 
myFilename));
+                                       File.Move(file.FullName, file.FullName.Replace(file.Name, 
myFilename));
                                } catch {
                                        //if cannot, then use old filename
-                                       myFilename = file.FullName;
+                                       //myFilename = file.FullName;
+                                       LogB.Information("catched at move, using the old filename: " + 
file.Name);
+                                       myFilename = file.Name;
                                }
 
+                               LogB.Information("going to insert forceSensor");
                                ForceSensor forceSensor = new ForceSensor(-1, p.UniqueID, 
Convert.ToInt32(session.Name), exerciseID,
                                                ForceSensor.CaptureOptions.NORMAL,
                                                ForceSensor.AngleUndefined, lat,
@@ -366,13 +406,13 @@ class SqliteForceSensorExercise : Sqlite
                        "CREATE TABLE " + table + " ( " +
                        "uniqueID INTEGER PRIMARY KEY, " +
                        "name TEXT, " +
-                       "percentBodyWeight INT, " +
+                       "percentBodyWeight INT NOT NULL, " +
                        "resistance TEXT, " +                           //unused
                        "angleDefault INT, " +
                        "description TEXT, " +
                        "tareBeforeCapture INT, " +
-                       "forceResultant INT, " +
-                       "elastic INT)";
+                       "forceResultant INT NOT NULL, " +
+                       "elastic INT NOT NULL)";
                LogB.SQL(dbcmd.CommandText.ToString());
                dbcmd.ExecuteNonQuery();
        }
@@ -401,6 +441,9 @@ class SqliteForceSensorExercise : Sqlite
                return myLast;
        }
 
+       /*
+        * is there any need of this?
+        *
        public static int InsertAtDB_1_68 (bool dbconOpened, ForceSensorExercise ex)
        {
                if(! dbconOpened)
@@ -422,6 +465,7 @@ class SqliteForceSensorExercise : Sqlite
 
                return myLast;
        }
+       */
 
        public static void Update (bool dbconOpened, ForceSensorExercise ex)
        {
diff --git a/src/sqlite/main.cs b/src/sqlite/main.cs
index 65da2e2e..abad8252 100644
--- a/src/sqlite/main.cs
+++ b/src/sqlite/main.cs
@@ -98,6 +98,10 @@ class Sqlite
        //create blank database
        static bool creatingBlankDatabase = false;
 
+       //use LOCAL on chronojump start if db changed
+       //use IMPORTED_SESSION when importing a session
+       public enum UpdatingDBFromEnum { LOCAL, IMPORTED_SESSION }
+       public static UpdatingDBFromEnum UpdatingDBFrom;
        
        public enum Orders_by { DEFAULT, ID_DESC }
 
diff --git a/src/sqlite/runEncoder.cs b/src/sqlite/runEncoder.cs
index e2098af9..a9eb46cd 100644
--- a/src/sqlite/runEncoder.cs
+++ b/src/sqlite/runEncoder.cs
@@ -257,15 +257,23 @@ class SqliteRunEncoder : Sqlite
                return array;
        }
 
-       public static string DirToImport;
-
        protected internal static void import_from_1_70_to_1_71() //database is opened
        {
                LogB.PrintAllThreads = true; //TODO: remove this
                LogB.Information("at import_from_1_70_to_1_71()");
 
+               string raceAnalyzerDir = Util.GetRunEncoderDir();
+               if(Sqlite.UpdatingDBFrom == Sqlite.UpdatingDBFromEnum.IMPORTED_SESSION)
+                       raceAnalyzerDir = Path.Combine(Util.GetDatabaseTempImportDir(), "raceAnalyzer");
+
+               if(! Directory.Exists(raceAnalyzerDir))
+               {
+                       LogB.Information("nothing to import");
+                       LogB.PrintAllThreads = false; //TODO: remove this
+                       return;
+               }
+
                bool importedSomething = false;
-               string raceAnalyzerDir = DirToImport;
                DirectoryInfo [] sessions = new DirectoryInfo(raceAnalyzerDir).GetDirectories();
                foreach (DirectoryInfo session in sessions) //session.Name will be the UniqueID
                {
diff --git a/src/util.cs b/src/util.cs
index 9261601b..22e0b0b3 100644
--- a/src/util.cs
+++ b/src/util.cs
@@ -916,7 +916,11 @@ public class Util
        public static string GetDatabaseTempDir() {
                return Path.Combine(Path.GetTempPath(), "Chronojump");
        }
-       
+
+       public static string GetDatabaseTempImportDir() {
+               return Path.Combine(Path.GetTempPath(), "ChronojumpImportDir");
+       }
+
        /********** end of database paths ************/
 
        /*      


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