ConDict

Check-in [eb602c3be7]
Login

Check-in [eb602c3be7]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:done delete-function (by ID and pattern
Timelines: family | ancestors | descendants | both | testing
Files: files | file ages | folders
SHA1: eb602c3be73aa215dbfe755f643773291259928c
User & Date: zorro 2012-09-09 08:14:27.724
Context
2012-09-09
16:44
add prepare-function before modify data in DB check-in: 8797b391ef user: zorro tags: testing
08:16
get main function from testing branch check-in: 04bdda6ca6 user: zorro tags: trunk
08:14
done delete-function (by ID and pattern check-in: eb602c3be7 user: zorro tags: testing
2012-09-08
21:13
fixed bug for edit-multiusers check-in: a9de4f4419 user: zorro tags: testing
Changes
Unified Diff Ignore Whitespace Patch
Changes to condt.py.
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
        '.list': {'desc': 'list users words', 'command': None},
        '.en': {'desc': 'dictionary mode English to Russian', 'command': None},
        '.ru': {'desc': 'dictionary mode Russian to English', 'command': None},
        '.add': {'desc': 'add new words', 'command': None},
        '.connect': {'desc': 'test connection', 'command': None},
        '.export': {'desc': 'export user dictionary to CSV file', 'command': None},
        '.edit': {'desc': 'edit words', 'command': None},
        # '.del': {'desc': 'delete words', 'command': None},
        '.exit': {'desc': 'quit from program', 'command': None},
        }
    def __init__(self, name, dbfile):
        super().__init__(name, dbfile)       
        self.__pcounter = 3
        self.init_command()
        self.user_id = self.get_user()







|







36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
        '.list': {'desc': 'list users words', 'command': None},
        '.en': {'desc': 'dictionary mode English to Russian', 'command': None},
        '.ru': {'desc': 'dictionary mode Russian to English', 'command': None},
        '.add': {'desc': 'add new words', 'command': None},
        '.connect': {'desc': 'test connection', 'command': None},
        '.export': {'desc': 'export user dictionary to CSV file', 'command': None},
        '.edit': {'desc': 'edit words', 'command': None},
        '.delete': {'desc': 'delete words', 'command': None},
        '.exit': {'desc': 'quit from program', 'command': None},
        }
    def __init__(self, name, dbfile):
        super().__init__(name, dbfile)       
        self.__pcounter = 3
        self.init_command()
        self.user_id = self.get_user()
71
72
73
74
75
76
77

78
79
80
81
82
83
84
        self.COMMANDS['.list']['command'] = self.command_list
        self.COMMANDS['.en']['command'] = self.command_en
        self.COMMANDS['.ru']['command'] = self.command_ru
        self.COMMANDS['.add']['command'] = self.command_add
        self.COMMANDS['.connect']['command'] = self.command_connect
        self.COMMANDS['.export']['command'] = self.command_export
        self.COMMANDS['.edit']['command'] = self.command_edit


    def hash_pass(self, password):
        result = bytes(password.strip() + SALT, 'utf-8')
        result = bytes(hashlib.md5(result).hexdigest(), 'utf-8')
        return hashlib.sha1(result).hexdigest()

    def check_name(self, cur):







>







71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
        self.COMMANDS['.list']['command'] = self.command_list
        self.COMMANDS['.en']['command'] = self.command_en
        self.COMMANDS['.ru']['command'] = self.command_ru
        self.COMMANDS['.add']['command'] = self.command_add
        self.COMMANDS['.connect']['command'] = self.command_connect
        self.COMMANDS['.export']['command'] = self.command_export
        self.COMMANDS['.edit']['command'] = self.command_edit
        self.COMMANDS['.delete']['command'] = self.command_delete

    def hash_pass(self, password):
        result = bytes(password.strip() + SALT, 'utf-8')
        result = bytes(hashlib.md5(result).hexdigest(), 'utf-8')
        return hashlib.sha1(result).hexdigest()

    def check_name(self, cur):
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350


351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375

376
377
378
379


































380




381
382

383
384
385
386
387
388
389











            print("Export finished successfully to file: {0}".format(export_name))
        return 'export'

    def command_edit(self, translate_id):
        """Edit translate words form DB, search by ID"""
        # search id
        cur = self.connect.cursor()
        # in term data always - add, may be delete
        # in translate data - edit
        try:
            translate_id = int(translate_id)
            sql_str = "SELECT `term`.`en`, `translate`.`rus`, `term`.`token` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) WHERE `translate`.`id`=(?) AND `user_id`=(?)"
            cur.execute(sql_str, (translate_id, self.user_id))
            result = cur.fetchone()
            if not result: raise IncorrectDbData()


            # enter en-ru
            en = input('En [' + result[0] + ']:')
            if not en: en = result[0]
            ru = input('Ru [' + result[1] + ']:')
            if not ru: ru = result[1]
            # new token
            need_del = False
            token = hashlib.md5(bytes(en, 'utf-8')).hexdigest()
            if token != result[2]:
                cur.execute("INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))", (token, en))
                need_del = True
            # translate
            cur.execute("UPDATE `translate` SET `rus`=(?), `term`=(?) WHERE `term`=(?) AND `user_id`=(?)", (ru, token, result[2], self.user_id))
            # delete in term if it needed
            if need_del:
                cur.execute("SELECT `id` FROM `translate` WHERE `term`=(?) LIMIT 1", (result[2],))
                if not cur.fetchone(): cur.execute("DELETE FROM `term` WHERE `token`=(?)", (result[2],))
        except IncorrectDbData as e:
            print('Record not found for current user.')
        except (ValueError, sqlite3.DatabaseError) as er:
            if DEBUG: print(er)
            print("Error, use '.edit ID' (ID is numerical)")
        else:
            self.connect.commit()
            cur.close()

        return 'edit'

    def command_delete(self, id_or_pattern):
        """Delete translate words form DB, search by ID or pattern (several rows)"""


































        pass





    def command_connect(self, arg=None):

        result = get_test_connection()
        if result:
            print("Ok connection")
        else:
            print("Error connection")
        self.online = result
        return 'connect'


















<
<


<
|
|
|
>
>













|





|





>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>


>







>
>
>
>
>
>
>
>
>
>
>
337
338
339
340
341
342
343


344
345

346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
            print("Export finished successfully to file: {0}".format(export_name))
        return 'export'

    def command_edit(self, translate_id):
        """Edit translate words form DB, search by ID"""
        # search id
        cur = self.connect.cursor()


        try:
            translate_id = int(translate_id)

            result = self.check_user_translate(cur, translate_id)
            if not result: 
                raise IncorrectDbData()
            else:
                result = result[0]
            # enter en-ru
            en = input('En [' + result[0] + ']:')
            if not en: en = result[0]
            ru = input('Ru [' + result[1] + ']:')
            if not ru: ru = result[1]
            # new token
            need_del = False
            token = hashlib.md5(bytes(en, 'utf-8')).hexdigest()
            if token != result[2]:
                cur.execute("INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))", (token, en))
                need_del = True
            # translate
            cur.execute("UPDATE `translate` SET `rus`=(?), `term`=(?) WHERE `term`=(?) AND `user_id`=(?)", (ru, token, result[2], self.user_id))
            # delete recodrs in term if it needed
            if need_del:
                cur.execute("SELECT `id` FROM `translate` WHERE `term`=(?) LIMIT 1", (result[2],))
                if not cur.fetchone(): cur.execute("DELETE FROM `term` WHERE `token`=(?)", (result[2],))
        except IncorrectDbData as e:
            print('Record not found for current user.')
        except (TypeError, ValueError, sqlite3.DatabaseError) as er:
            if DEBUG: print(er)
            print("Error, use '.edit ID' (ID is numerical)")
        else:
            self.connect.commit()
            cur.close()
            print('Successfully update')
        return 'edit'

    def command_delete(self, id_or_pattern):
        """Delete translate words form DB, search by ID or pattern (several rows)"""
        cur = self.connect.cursor()
        try:
            try:
                pattern = int(id_or_pattern) 
                by_pattern = False
            except ValueError as e:
                pattern = id_or_pattern
                by_pattern = True
            result = self.check_user_translate(cur, pattern, by_pattern)
            if not result: raise IncorrectDbData()
            print('Records for delete:')
            id_for_del = []
            for row in result:
                # id, token
                id_for_del.append((row[3], row[2]))
                print("ID={0}:\t'{1}'".format(row[3], row[0]))
            correction = input("It is right [N/y]?")
            if correction not in ('Y', 'y'):
                return 'delete'
            # delete for correction information
            for rec in id_for_del:
                # delete translate
                cur.execute("DELETE FROM `translate` WHERE `id`=(?)", (rec[0],))
                # delete progress
                cur.execute("DELETE FROM `progress` WHERE `translate_id`=(?)", (rec[0],))
                # del from term if it needed
                cur.execute("SELECT `term` FROM `translate` WHERE `term`=(?) LIMIT 1", (rec[1],))
                if not cur.fetchone():
                    cur.execute("DELETE FROM `term` WHERE `token`=(?)", (rec[1],))
        except IncorrectDbData as e:
            print('Record not found for current user.')
        except (sqlite3.DatabaseError, TypeError) as er:
            if DEBUG: print(er)
            print("Error, use '.delete [ID or pattern]' (ID is numerical)")
        else:
            self.connect.commit()
            cur.close()
            print('Successfully update')
        return 'delete'

    def command_connect(self, arg=None):
        """test connection, set user status"""
        result = get_test_connection()
        if result:
            print("Ok connection")
        else:
            print("Error connection")
        self.online = result
        return 'connect'

    def check_user_translate(self, cur, for_search, by_pattern=False):
        sql_str = "SELECT `term`.`en`, `translate`.`rus`, `term`.`token`, `translate`.`id` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) "
        if by_pattern:
            pattern = for_search + '%' 
            sql_str += "WHERE `term`.`en` LIKE (?) AND `user_id`=(?) ORDER BY `translate`.`id`"
        else:
            pattern = for_search
            sql_str += "WHERE `translate`.`id`=(?) AND `user_id`=(?) ORDER BY `translate`.`id`"
        cur.execute(sql_str, (pattern, self.user_id))
        return cur.fetchall()
Changes to db.sqlite.

cannot compute difference between binary files