Source

trac-ticketlinks / trac / ticket / model.py

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 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
 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
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
# -*- coding: utf-8 -*-
#
# Copyright (C) 2003-2009 Edgewall Software
# Copyright (C) 2003-2006 Jonas Borgström <jonas@edgewall.com>
# Copyright (C) 2005 Christopher Lenz <cmlenz@gmx.de>
# Copyright (C) 2006 Christian Boos <cboos@neuf.fr>
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://trac.edgewall.org/wiki/TracLicense.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://trac.edgewall.org/log/.
#
# Author: Jonas Borgström <jonas@edgewall.com>
#         Christopher Lenz <cmlenz@gmx.de>

import itertools
import operator
import re
from datetime import date, datetime

from trac.attachment import Attachment
from trac.core import TracError
from trac.resource import Resource, ResourceNotFound
from trac.ticket.api import TicketSystem
from trac.util import embedded_numbers, partition
from trac.util.text import empty
from trac.util.datefmt import from_utimestamp, to_utimestamp, utc, utcmax
from trac.util.translation import _

__all__ = ['Ticket', 'Type', 'Status', 'Resolution', 'Priority', 'Severity',
           'Component', 'Milestone', 'Version', 'group_milestones']


class Ticket(object):

    # Fields that must not be modified directly by the user
    protected_fields = ('resolution', 'status', 'time', 'changetime')

    @staticmethod
    def id_is_valid(num):
        return 0 < int(num) <= 1L << 31

    # 0.11 compatibility
    time_created = property(lambda self: self.values.get('time'))
    time_changed = property(lambda self: self.values.get('changetime'))
    
    def __init__(self, env, tkt_id=None, db=None, version=None):
        self.env = env
        if tkt_id is not None:
            tkt_id = int(tkt_id)
        self.resource = Resource('ticket', tkt_id, version)
        self.fields = TicketSystem(self.env).get_ticket_fields()
        self.time_fields = [f['name'] for f in self.fields
                            if f['type'] == 'time']
        self.values = {}
        if tkt_id is not None:
            self._fetch_ticket(tkt_id, db)
        else:
            self._init_defaults(db)
            self.id = None
        self._old = {}

    def _get_db(self, db):
        return db or self.env.get_read_db()

    exists = property(fget=lambda self: self.id is not None)

    def _init_defaults(self, db=None):
        for field in self.fields:
            default = None
            if field['name'] in self.protected_fields:
                # Ignore for new - only change through workflow
                pass
            elif not field.get('custom'):
                default = self.env.config.get('ticket',
                                              'default_' + field['name'])
            else:
                default = field.get('value')
                options = field.get('options')
                if default and options and default not in options:
                    try:
                        default = options[int(default)]
                    except (ValueError, IndexError):
                        self.env.log.warning('Invalid default value "%s" '
                                             'for custom field "%s"'
                                             % (default, field['name']))
            if default:
                self.values.setdefault(field['name'], default)

    def _fetch_ticket(self, tkt_id, db=None):
        row = None
        if self.id_is_valid(tkt_id):
            db = self._get_db(db)

            # Fetch the standard ticket fields
            std_fields = [f['name'] for f in self.fields 
			              if not (f.get('custom') or f.get('link'))]
            cursor = db.cursor()
            cursor.execute("SELECT %s FROM ticket WHERE id=%%s"
                           % ','.join(std_fields), (tkt_id,))
            row = cursor.fetchone()
        if not row:
            raise ResourceNotFound(_('Ticket %(id)s does not exist.', 
                                     id=tkt_id), _('Invalid ticket number'))

        self.id = tkt_id
        for i, field in enumerate(std_fields):
            value = row[i]
            if field in self.time_fields:
                self.values[field] = from_utimestamp(value)
            elif value is None:
                self.values[field] = empty
            else:
                self.values[field] = value

        # Fetch custom fields if available
        custom_fields = [f['name'] for f in self.fields if f.get('custom')]
        cursor.execute("SELECT name,value FROM ticket_custom WHERE ticket=%s",
                       (tkt_id,))
        for name, value in cursor:
            if name in custom_fields:
                if value is None:
                    self.values[name] = empty
                else:
                    self.values[name] = value
                
        # Fetch links 
        link_fields = [f['name'] for f in self.fields if f.get('link')]
        cursor.execute("""SELECT type, destination 
                       FROM ticket_links
                       WHERE source=%%s and type IN (%s)
                       ORDER BY type, destination
                       """ 
                       % ','.join(['%s'] * len(link_fields)), 
                       [tkt_id] + link_fields)
        grouped_recs = itertools.groupby(cursor, operator.itemgetter(0))
        link_values = dict((end, ', '.join(['#%s' % r[1] for r in recs]))
                           for end, recs in grouped_recs)
        for end in link_fields:
            self.values[end] = link_values.get(end, '')
            

    def __getitem__(self, name):
        return self.values.get(name)

    def __setitem__(self, name, value):
        """Log ticket modifications so the table ticket_change can be updated
        """
        if name in self.values and self.values[name] == value:
            return
        if name not in self._old: # Changed field
            self._old[name] = self.values.get(name)
        elif self._old[name] == value: # Change of field reverted
            del self._old[name]
        if value:
            if isinstance(value, list):
                raise TracError(_("Multi-values fields not supported yet"))
            field = [field for field in self.fields if field['name'] == name]
            if field and field[0].get('type') != 'textarea':
                value = value.strip()
        self.values[name] = value

    def get_value_or_default(self, name):
        """Return the value of a field or the default value if it is undefined
        """
        try:
            value = self.values[name]
            if value is not empty:
                return value
            field = [field for field in self.fields if field['name'] == name]
            if field:
                return field[0].get('value', '')
        except KeyError:
            pass
        
    def populate(self, values):
        """Populate the ticket with 'suitable' values from a dictionary"""
        field_names = [f['name'] for f in self.fields]
        for name in [name for name in values.keys() if name in field_names]:
            self[name] = values.get(name, '')

        # We have to do an extra trick to catch unchecked checkboxes
        for name in [name for name in values.keys() if name[9:] in field_names
                     and name.startswith('checkbox_')]:
            if name[9:] not in values:
                self[name[9:]] = '0'

    def populate_from(self, tkt_id, link_field_name=None, 
                            copy_field_names=None):
        """Populate the ticket with 'suitable' values from another ticket.
        """
        ticket_sys = TicketSystem(self.env)
        field_names = [f['name'] for f in self.fields]
        
        if not link_field_name and copy_field_names is None:
            copy_field_names = ticket_sys.default_copy_fields
            
        elif (link_field_name in ticket_sys.link_ends_map 
              and copy_field_names is None):
            link_field = [f for f in self.fields 
                            if f['name'] == link_field_name][0]
            copy_field_names = link_field['copy_fields']
            
            # Record in this ticket (self) the ticket id from which we have 
            # populated the values, against the other end of the link.
            # Doing so will cause this our ticket (self.id) to be recorded in 
            # link_field_name on the other ticket, if link_field_name is
            # bi-directional ticket link
            other_end = ticket_sys.other_end(link_field_name)
            self[other_end] = str('#%s' % tkt_id)
            
        try:
            tkt_id = int(tkt_id)
        except ValueError:
            return
        # TODO What if tkt_id isn't valid? Currently shows as a TracError
        other_ticket = Ticket(self.env, tkt_id)
        
        for name in [name for name in copy_field_names if name in field_names]:
             self[name] = other_ticket[name]
            
    def insert(self, when=None, db=None):
        """Add ticket to database.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert not self.exists, 'Cannot insert an existing ticket'

        # Add a timestamp
        if when is None:
            when = datetime.now(utc)
        self.values['time'] = self.values['changetime'] = when

        # The owner field defaults to the component owner
        if self.values.get('component') and not self.values.get('owner'):
            try:
                component = Component(self.env, self['component'], db=db)
                if component.owner:
                    self['owner'] = component.owner
            except ResourceNotFound:
                # No such component exists
                pass

        # Perform type conversions
        values = dict(self.values)
        for field in self.time_fields:
            if field in values:
                values[field] = to_utimestamp(values[field])
        
        # Insert ticket record
        std_fields = []
        custom_fields = []
        link_fields = []
        for f in self.fields:
            fname = f['name']
            if fname in self.values:
                # ignore link fields
                if f.get('link'):
                    link_fields.append(fname)
                elif f.get('custom'):
                    custom_fields.append(fname)
                else:
                    std_fields.append(fname)

        tkt_id = [None]
        @self.env.with_transaction(db)
        def do_insert(db):
            cursor = db.cursor()
            cursor.execute("INSERT INTO ticket (%s) VALUES (%s)"
                           % (','.join(std_fields),
                              ','.join(['%s'] * len(std_fields))),
                           [values[name] for name in std_fields])
            tkt_id[0] = db.get_last_id(cursor, 'ticket')

            # Insert custom fields
            if custom_fields:
                cursor.executemany("""
                INSERT INTO ticket_custom (ticket,name,value) VALUES (%s,%s,%s)
                """, [(tkt_id[0], name, self[name]) for name in custom_fields])
				
            # Insert links
            for end in link_fields:
                ticket_system = TicketSystem(self.env)
                dst_ids =  ticket_system.parse_links(self[end])
                # TODO: check if target exists!
                if len(dst_ids) > 0:
                    cursor.executemany("""
                        INSERT INTO ticket_links (source,destination,type)
                        VALUES (%s,%s,%s)
                        """, [(tkt_id[0], int(dst_id), end)
                              for dst_id in dst_ids])
                    # insert other side for bidirectional links
                    other_end = ticket_system.link_ends_map[end]
                    if other_end:
                        cursor.executemany("""
                            INSERT INTO ticket_links (source,destination,type)
                            VALUES (%s,%s,%s)
                            """, [(int(dst_id), tkt_id[0], other_end)
                              for dst_id in dst_ids])

        self.id = tkt_id[0]
        self.resource = self.resource(id=tkt_id[0])
        self._old = {}

        for listener in TicketSystem(self.env).change_listeners:
            listener.ticket_created(self)

        return self.id

    def save_changes(self, author=None, comment=None, when=None, db=None, cnum=''):
        """
        Store ticket changes in the database. The ticket must already exist in
        the database.  Returns False if there were no changes to save, True
        otherwise.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot update a new ticket'
        api = TicketSystem(self.env)

        if not self._old and not comment:
            return False # Not modified

        if when is None:
            when = datetime.now(utc)
        when_ts = to_utimestamp(when)

        if 'component' in self.values:
            # If the component is changed on a 'new' ticket
            # then owner field is updated accordingly. (#623).
            if self.values.get('status') == 'new' \
                    and 'component' in self._old \
                    and 'owner' not in self._old:
                try:
                    old_comp = Component(self.env, self._old['component'])
                    old_owner = old_comp.owner or ''
                    current_owner = self.values.get('owner') or ''
                    if old_owner == current_owner:
                        new_comp = Component(self.env, self['component'])
                        if new_comp.owner:
                            self['owner'] = new_comp.owner
                except TracError:
                    # If the old component has been removed from the database
                    # we just leave the owner as is.
                    pass

        # Fix up cc list separators and remove duplicates
        if 'cc' in self.values:
            cclist = []
            for cc in re.split(r'[;,\s]+', self.values['cc']):
                if cc not in cclist:
                    cclist.append(cc)
            self.values['cc'] = ', '.join(cclist)

        @self.env.with_transaction(db)
        def do_save(db):
            cursor = db.cursor()

            # find cnum if it isn't provided
            comment_num = cnum
            if not comment_num:
                num = 0
                cursor.execute("""
                    SELECT DISTINCT tc1.time,COALESCE(tc2.oldvalue,'')
                    FROM ticket_change AS tc1
                      LEFT OUTER JOIN
                        (SELECT time,oldvalue FROM ticket_change
                         WHERE field='comment') AS tc2
                      ON (tc1.time = tc2.time)
                    WHERE ticket=%s ORDER BY tc1.time DESC
                    """, (self.id,))
                for ts, old in cursor:
                    # Use oldvalue if available, else count edits
                    try:
                        num += int(old.rsplit('.', 1)[-1])
                        break
                    except ValueError:
                        num += 1
                comment_num = str(num + 1)

            # store fields
            custom_fields = [f['name'] for f in self.fields if f.get('custom')]
            link_fields = [f['name'] for f in self.fields if f.get('link')]
            for name in self._old.keys():
                # ignore link fields here
                if name in link_fields:
                    continue
                if name in custom_fields:
                    cursor.execute("""
                        SELECT * FROM ticket_custom 
                        WHERE ticket=%s and name=%s
                        """, (self.id, name))
                    if cursor.fetchone():
                        cursor.execute("""
                            UPDATE ticket_custom SET value=%s
                            WHERE ticket=%s AND name=%s
                            """, (self[name], self.id, name))
                    else:
                        cursor.execute("""
                            INSERT INTO ticket_custom (ticket,name,value)
                            VALUES(%s,%s,%s)
                            """, (self.id, name, self[name]))
                else:
                    cursor.execute("UPDATE ticket SET %s=%%s WHERE id=%%s" 
                                   % name, (self[name], self.id))
                cursor.execute("""
                    INSERT INTO ticket_change
                        (ticket,time,author,field,oldvalue,newvalue)
                    VALUES (%s, %s, %s, %s, %s, %s)
                    """, (self.id, when_ts, author, name, self._old[name],
                          self[name]))
            
            # always save comment, even if empty 
            # (numbering support for timeline)
            cursor.execute("""
                INSERT INTO ticket_change
                    (ticket,time,author,field,oldvalue,newvalue)
                VALUES (%s,%s,%s,'comment',%s,%s)
                """, (self.id, when_ts, author, comment_num, comment))
    
            cursor.execute("UPDATE ticket SET changetime=%s WHERE id=%s",
                           (when_ts, self.id))

            # Update links
            for end in (e for e in link_fields if e in self._old):
                new_ids = set(api.parse_links(self[end]))
                old_ids = set(api.parse_links(self._old[end]))
                # New links added
                for id in new_ids - old_ids:
                    cursor.execute("""
                        INSERT INTO ticket_links (source,destination,type)
                        VALUES (%s,%s,%s)
                        """, [self.id, id, end])
                    other_end = api.link_ends_map[end]
                    if other_end:
                        cursor.execute("""
                            INSERT INTO ticket_links (source,destination,type)
                            VALUES (%s,%s,%s)
                            """, [id, self.id, other_end])
                # Old links removed
                for id in old_ids - new_ids:
                    cursor.execute("""
                        DELETE FROM ticket_links 
                        WHERE source=%s AND destination=%s AND type=%s
                        """, [self.id, id, end])
                    other_end = api.link_ends_map[end]
                    if other_end:
                        cursor.execute("""
                            DELETE FROM ticket_links
                            WHERE source=%s AND destination=%s AND type=%s
                            """, [id, self.id, other_end])
                if old_ids ^ new_ids:
                    cursor.execute("""
                        INSERT INTO ticket_change
                            (ticket,time,author,field,oldvalue,newvalue)
                        VALUES (%s, %s, %s, %s, %s, %s)
                        """, (self.id, when_ts, author, end, 
                              self._old[end], self[end]))

        old_values = self._old
        self._old = {}
        self.values['changetime'] = when
        
        for listener in api.change_listeners:
            listener.ticket_changed(self, comment, author, old_values)
        return True
    
    def get_changelog(self, when=None, db=None):
        """Return the changelog as a list of tuples of the form
        (time, author, field, oldvalue, newvalue, permanent).

        While the other tuple elements are quite self-explanatory,
        the `permanent` flag is used to distinguish collateral changes
        that are not yet immutable (like attachments, currently).
        """
        db = self._get_db(db)
        cursor = db.cursor()
        sid = str(self.id)
        when_ts = to_utimestamp(when)
        if when_ts:
            cursor.execute("""
                SELECT time,author,field,oldvalue,newvalue, 1 AS permanent
                FROM ticket_change WHERE ticket=%s AND time=%s 
                  UNION 
                SELECT time,author,'attachment',null,filename, 0 AS permanent
                FROM attachment WHERE id=%s AND time=%s 
                  UNION 
                SELECT time,author,'comment',null,description, 0 AS permanent
                FROM attachment WHERE id=%s AND time=%s
                ORDER BY time,permanent,author
                """, (self.id, when_ts, sid, when_ts, sid, when_ts))
        else:
            cursor.execute("""
                SELECT time,author,field,oldvalue,newvalue, 1 AS permanent
                FROM ticket_change WHERE ticket=%s
                  UNION 
                SELECT time,author,'attachment',null,filename, 0 AS permanent
                FROM attachment WHERE id=%s 
                  UNION 
                SELECT time,author,'comment',null,description, 0 AS permanent
                FROM attachment WHERE id=%s 
                ORDER BY time,permanent,author
                """, (self.id, sid, sid))
        log = []
        for t, author, field, oldvalue, newvalue, permanent in cursor:
            log.append((from_utimestamp(t), author, field,
                        oldvalue or '', newvalue or '', permanent))
        return log

    def delete(self, db=None):
        """Delete the ticket.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        @self.env.with_transaction(db)
        def do_delete(db):
            Attachment.delete_all(self.env, 'ticket', self.id, db)
            cursor = db.cursor()
            cursor.execute("DELETE FROM ticket WHERE id=%s", (self.id,))
            cursor.execute("DELETE FROM ticket_change WHERE ticket=%s",
                           (self.id,))
            cursor.execute("DELETE FROM ticket_custom WHERE ticket=%s",
                           (self.id,))
            cursor.execute("DELETE FROM ticket_links WHERE source=%s OR destination=%s", 
                           (self.id,self.id))

        for listener in TicketSystem(self.env).change_listeners:
            listener.ticket_deleted(self)

    def get_change(self, cnum, db=None):
        """Return a ticket change by its number."""
        db = self._get_db(db)
        cursor = db.cursor()
        row = self._find_change(cnum, db)
        if row:
            ts, author, comment = row
            cursor.execute("""
                SELECT field,author,oldvalue,newvalue 
                FROM ticket_change WHERE ticket=%s AND time=%s
                """, (self.id, ts))
            fields = {}
            change = {'date': from_utimestamp(ts),
                      'author': author, 'fields': fields}
            for field, author, old, new in cursor:
                fields[field] = {'author': author, 'old': old, 'new': new}
            return change

    def delete_change(self, cnum):
        """Delete a ticket change."""
        @self.env.with_transaction()
        def do_delete(db):
            cursor = db.cursor()
            row = self._find_change(cnum, db)
            if not row:
                return
            ts = row[0]
            
            custom_fields = set(f['name'] for f in self.fields
                                if f.get('custom'))

            # Find modified fields and their previous value
            cursor.execute("""
                SELECT field, oldvalue, newvalue FROM ticket_change
                WHERE ticket=%s AND time=%s
                """, (self.id, ts))
            fields = [(field, old, new) for field, old, new in cursor
                      if field != 'comment' and not field.startswith('_')]
            for field, oldvalue, newvalue in fields:
                # Find the next change
                cursor.execute("""
                    SELECT time FROM ticket_change
                    WHERE ticket=%s AND time>%s AND field=%s
                    LIMIT 1
                    """, (self.id, ts, field))
                for next_ts, in cursor:
                    # Modify the old value of the next change if it is equal
                    # to the new value of the deleted change
                    cursor.execute("""
                        UPDATE ticket_change SET oldvalue=%s
                        WHERE ticket=%s AND time=%s AND field=%s
                              AND oldvalue=%s
                        """, (oldvalue, self.id, next_ts, field, newvalue))
                    break
                else:
                    # No next change, edit ticket field
                    if field in custom_fields:
                        cursor.execute("""
                            UPDATE ticket_custom SET value=%s
                            WHERE ticket=%s AND name=%s
                            """, (oldvalue, self.id, field))
                    else:
                        cursor.execute("""
                            UPDATE ticket SET %s=%%s WHERE id=%%s
                            """ % field, (oldvalue, self.id))
            
            # Delete the change
            cursor.execute("""
                DELETE FROM ticket_change WHERE ticket=%s AND time=%s
                """, (self.id, ts))
            
            # Fix the last modification time
            cursor.execute("""
                UPDATE ticket SET changetime=(
                    SELECT time FROM ticket_change WHERE ticket=%s
                    ORDER BY time DESC LIMIT 1)
                WHERE id=%s
                """, (self.id, self.id))
        
        self._fetch_ticket(self.id)

    def modify_comment(self, cdate, author, comment, when=None):
        """Modify a ticket comment specified by its date, while keeping a
        history of edits.
        """
        ts = to_utimestamp(cdate)
        if when is None:
            when = datetime.now(utc)
        when_ts = to_utimestamp(when)

        @self.env.with_transaction()
        def do_modify(db):
            cursor = db.cursor()
            # Find the current value of the comment
            cursor.execute("""
                SELECT newvalue FROM ticket_change 
                WHERE ticket=%s AND time=%s AND field='comment'
                """, (self.id, ts))
            old_comment = False
            for old_comment, in cursor:
                break
            if comment == (old_comment or ''):
                return
        
            # Comment history is stored in fields named "_comment%d"
            # Find the next edit number
            cursor.execute("""
                SELECT field FROM ticket_change 
                WHERE ticket=%%s AND time=%%s AND field %s
                """ % db.like(), (self.id, ts,
                                  db.like_escape('_comment') + '%'))
            fields = list(cursor)
            rev = fields and max(int(field[8:]) for field, in fields) + 1 or 0
            cursor.execute("""
                INSERT INTO ticket_change
                    (ticket,time,author,field,oldvalue,newvalue) 
                VALUES (%s,%s,%s,%s,%s,%s)
                """, (self.id, ts, author, '_comment%d' % rev,
                      old_comment or '', str(when_ts)))
            if old_comment is False:
                # There was no comment field, add one, find the original author
                # in one of the other changed fields
                cursor.execute("""
                    SELECT author FROM ticket_change 
                    WHERE ticket=%%s AND time=%%s AND NOT field %s
                    LIMIT 1
                    """ % db.like(), (self.id, ts, db.like_escape('_') + '%'))
                old_author = None
                for old_author, in cursor:
                    break
                cursor.execute("""
                    INSERT INTO ticket_change 
                        (ticket,time,author,field,oldvalue,newvalue) 
                    VALUES (%s,%s,%s,'comment','',%s)
                    """, (self.id, ts, old_author, comment))
            else:
                cursor.execute("""
                    UPDATE ticket_change SET newvalue=%s 
                    WHERE ticket=%s AND time=%s AND 
                    field='comment'
                    """, (comment, self.id, ts))

    def get_comment_history(self, cnum, db=None):
        db = self._get_db(db)
        history = []
        cursor = db.cursor()
        row = self._find_change(cnum, db)
        if row:
            ts0, author0, last_comment = row
            # Get all fields of the form "_comment%d"
            cursor.execute("""
                SELECT field,author,oldvalue,newvalue 
                FROM ticket_change 
                WHERE ticket=%%s AND time=%%s AND field %s
                """ % db.like(), (self.id, ts0,
                                  db.like_escape('_comment') + '%'))
            rows = sorted((int(field[8:]), author, old, new)
                          for field, author, old, new in cursor)
            for rev, author, comment, ts in rows:
                history.append((rev, from_utimestamp(long(ts0)), author0,
                                comment))
                ts0, author0 = ts, author
            history.sort()
            rev = history and (history[-1][0] + 1) or 0
            history.append((rev, from_utimestamp(long(ts0)), author0,
                            last_comment))
        return history

    def _find_change(self, cnum, db):
        """Find a comment by its number."""
        scnum = str(cnum)
        cursor = db.cursor()
        cursor.execute("""
            SELECT time,author,newvalue FROM ticket_change 
            WHERE ticket=%%s AND field='comment' 
                AND (oldvalue=%%s OR oldvalue %s)
            """ % db.like(), (self.id, scnum,
                              '%' + db.like_escape('.' + scnum)))
        for row in cursor:
            return row
        
        # Fallback when comment number is not available in oldvalue
        num = 0
        cursor.execute("""
            SELECT DISTINCT tc1.time,COALESCE(tc2.oldvalue,''), 
               tc2.author,COALESCE(tc2.newvalue,'') 
               FROM ticket_change AS tc1 
                   LEFT OUTER JOIN 
                          (SELECT time,author,oldvalue,newvalue 
                           FROM ticket_change 
                           WHERE field='comment') AS tc2 
                        ON (tc1.time = tc2.time) 
               WHERE ticket=%s 
               ORDER BY tc1.time
               """, (self.id,))
        for ts, old, author, comment in cursor:
            # Use oldvalue if available, else count edits
            try:
                num = int(old.rsplit('.', 1)[-1])
            except ValueError:
                num += 1
            if num == cnum:
                break
        else:
            return
        
        # Find author if NULL
        if author is None:
            cursor.execute("""
                SELECT author FROM ticket_change 
                WHERE ticket=%%s AND time=%%s AND NOT field %s 
                LIMIT 1
                """ % db.like(), (self.id, ts, db.like_escape('_') + '%'))
            for author, in cursor:
                break
        return (ts, author, comment)


def simplify_whitespace(name):
    """Strip spaces and remove duplicate spaces within names"""
    if name:
        return ' '.join(name.split())
    return name
        

class AbstractEnum(object):
    type = None
    ticket_col = None

    def __init__(self, env, name=None, db=None):
        if not self.ticket_col:
            self.ticket_col = self.type
        self.env = env
        if name:
            if not db:
                db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute("SELECT value FROM enum WHERE type=%s AND name=%s",
                           (self.type, name))
            row = cursor.fetchone()
            if not row:
                raise ResourceNotFound(_('%(type)s %(name)s does not exist.',
                                         type=self.type, name=name))
            self.value = self._old_value = row[0]
            self.name = self._old_name = name
        else:
            self.value = self._old_value = None
            self.name = self._old_name = None

    exists = property(fget=lambda self: self._old_value is not None)

    def delete(self, db=None):
        """Delete the enum value.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot delete non-existent %s' % self.type

        @self.env.with_transaction(db)
        def do_delete(db):
            cursor = db.cursor()
            self.env.log.info('Deleting %s %s' % (self.type, self.name))
            cursor.execute("DELETE FROM enum WHERE type=%s AND value=%s",
                           (self.type, self._old_value))
            # Re-order any enums that have higher value than deleted
            # (close gap)
            for enum in list(self.select(self.env, db)):
                try:
                    if int(enum.value) > int(self._old_value):
                        enum.value = unicode(int(enum.value) - 1)
                        enum.update()
                except ValueError:
                    pass # Ignore cast error for this non-essential operation
            TicketSystem(self.env).reset_ticket_fields()
        self.value = self._old_value = None
        self.name = self._old_name = None

    def insert(self, db=None):
        """Add a new enum value.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert not self.exists, 'Cannot insert existing %s' % self.type
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid %(type)s name.', type=self.type))

        @self.env.with_transaction(db)
        def do_insert(db):
            cursor = db.cursor()
            self.env.log.debug("Creating new %s '%s'" % (self.type, self.name))
            if not self.value:
                cursor.execute("""
                    SELECT COALESCE(MAX(%s),0) FROM enum WHERE type=%%s
                """ % db.cast('value', 'int'), (self.type,))
                self.value = int(float(cursor.fetchone()[0])) + 1
            cursor.execute("INSERT INTO enum (type,name,value) "
                           "VALUES (%s,%s,%s)",
                           (self.type, self.name, self.value))
            TicketSystem(self.env).reset_ticket_fields()

        self._old_name = self.name
        self._old_value = self.value

    def update(self, db=None):
        """Update the enum value.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot update non-existent %s' % self.type
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid %(type)s name.', type=self.type))

        @self.env.with_transaction(db)
        def do_update(db):
            cursor = db.cursor()
            self.env.log.info('Updating %s "%s"' % (self.type, self.name))
            cursor.execute("""
                UPDATE enum SET name=%s,value=%s 
                WHERE type=%s AND name=%s
                """, (self.name, self.value, self.type, self._old_name))
            if self.name != self._old_name:
                # Update tickets
                cursor.execute("UPDATE ticket SET %s=%%s WHERE %s=%%s" %
                               (self.ticket_col, self.ticket_col),
                               (self.name, self._old_name))
            TicketSystem(self.env).reset_ticket_fields()

        self._old_name = self.name
        self._old_value = self.value

    @classmethod
    def select(cls, env, db=None):
        if not db:
            db = env.get_read_db()
        cursor = db.cursor()
        cursor.execute("""
            SELECT name,value FROM enum WHERE type=%s 
            ORDER BY
            """ + db.cast('value', 'int'), (cls.type,))
        for name, value in cursor:
            obj = cls(env)
            obj.name = obj._old_name = name
            obj.value = obj._old_value = value
            yield obj


class Type(AbstractEnum):
    type = 'ticket_type'
    ticket_col = 'type'


class Status(object):
    def __init__(self, env):
        self.env = env

    @classmethod
    def select(cls, env, db=None):
        for state in TicketSystem(env).get_all_status():
            status = cls(env)
            status.name = state
            yield status


class Resolution(AbstractEnum):
    type = 'resolution'


class Priority(AbstractEnum):
    type = 'priority'


class Severity(AbstractEnum):
    type = 'severity'


class Component(object):

    def __init__(self, env, name=None, db=None):
        self.env = env
        if name:
            if not db:
                db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute("""
                SELECT owner,description FROM component WHERE name=%s
                """, (name,))
            row = cursor.fetchone()
            if not row:
                raise ResourceNotFound(_('Component %(name)s does not exist.',
                                         name=name))
            self.name = self._old_name = name
            self.owner = row[0] or None
            self.description = row[1] or ''
        else:
            self.name = self._old_name = None
            self.owner = None
            self.description = None

    exists = property(fget=lambda self: self._old_name is not None)

    def delete(self, db=None):
        """Delete the component.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot delete non-existent component'

        @self.env.with_transaction(db)
        def do_delete(db):
            cursor = db.cursor()
            self.env.log.info('Deleting component %s' % self.name)
            cursor.execute("DELETE FROM component WHERE name=%s", (self.name,))
            self.name = self._old_name = None
            TicketSystem(self.env).reset_ticket_fields()

    def insert(self, db=None):
        """Insert a new component.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert not self.exists, 'Cannot insert existing component'
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid component name.'))

        @self.env.with_transaction(db)
        def do_insert(db):
            cursor = db.cursor()
            self.env.log.debug("Creating new component '%s'" % self.name)
            cursor.execute("""
                INSERT INTO component (name,owner,description)
                VALUES (%s,%s,%s)
                """, (self.name, self.owner, self.description))
            self._old_name = self.name
            TicketSystem(self.env).reset_ticket_fields()

    def update(self, db=None):
        """Update the component.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot update non-existent component'
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid component name.'))

        @self.env.with_transaction(db)
        def do_update(db):
            cursor = db.cursor()
            self.env.log.info('Updating component "%s"' % self.name)
            cursor.execute("""
                UPDATE component SET name=%s,owner=%s, description=%s
                WHERE name=%s
                """, (self.name, self.owner, self.description, self._old_name))
            if self.name != self._old_name:
                # Update tickets
                cursor.execute("""
                    UPDATE ticket SET component=%s WHERE component=%s
                    """, (self.name, self._old_name))
                self._old_name = self.name
            TicketSystem(self.env).reset_ticket_fields()

    @classmethod
    def select(cls, env, db=None):
        if not db:
            db = env.get_read_db()
        cursor = db.cursor()
        cursor.execute("""
            SELECT name,owner,description FROM component ORDER BY name
            """)
        for name, owner, description in cursor:
            component = cls(env)
            component.name = component._old_name = name
            component.owner = owner or None
            component.description = description or ''
            yield component


class Milestone(object):

    def __init__(self, env, name=None, db=None):
        self.env = env
        if name:
            self._fetch(name, db)
        else:
            self.name = None
            self.due = self.completed = None
            self.description = ''
            self._to_old()

    def _get_resource(self):
        return Resource('milestone', self.name) ### .version !!!
    resource = property(_get_resource)

    def _fetch(self, name, db=None):
        if not db:
            db = self.env.get_read_db()
        cursor = db.cursor()
        cursor.execute("""
            SELECT name,due,completed,description 
            FROM milestone WHERE name=%s
            """, (name,))
        row = cursor.fetchone()
        if not row:
            raise ResourceNotFound(_('Milestone %(name)s does not exist.',
                                   name=name), _('Invalid milestone name'))
        self._from_database(row)

    exists = property(fget=lambda self: self._old['name'] is not None)
    is_completed = property(fget=lambda self: self.completed is not None)
    is_late = property(fget=lambda self: self.due and \
                                         self.due.date() < date.today())

    def _from_database(self, row):
        name, due, completed, description = row
        self.name = name
        self.due = due and from_utimestamp(due) or None
        self.completed = completed and from_utimestamp(completed) or None
        self.description = description or ''
        self._to_old()

    def _to_old(self):
        self._old = {'name': self.name, 'due': self.due,
                     'completed': self.completed,
                     'description': self.description}

    def delete(self, retarget_to=None, author=None, db=None):
        """Delete the milestone.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        @self.env.with_transaction(db)
        def do_delete(db):
            cursor = db.cursor()
            self.env.log.info('Deleting milestone %s' % self.name)
            cursor.execute("DELETE FROM milestone WHERE name=%s", (self.name,))

            # Retarget/reset tickets associated with this milestone
            now = datetime.now(utc)
            cursor.execute("SELECT id FROM ticket WHERE milestone=%s",
                           (self.name,))
            tkt_ids = [int(row[0]) for row in cursor]
            for tkt_id in tkt_ids:
                ticket = Ticket(self.env, tkt_id, db)
                ticket['milestone'] = retarget_to
                ticket.save_changes(author, 'Milestone %s deleted' % self.name,
                                    now)
            self._old['name'] = None
            TicketSystem(self.env).reset_ticket_fields()

        for listener in TicketSystem(self.env).milestone_change_listeners:
            listener.milestone_deleted(self)

    def insert(self, db=None):
        """Insert a new milestone.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid milestone name.'))

        @self.env.with_transaction(db)
        def do_insert(db):
            cursor = db.cursor()
            self.env.log.debug("Creating new milestone '%s'" % self.name)
            cursor.execute("""
                INSERT INTO milestone (name,due,completed,description) 
                VALUES (%s,%s,%s,%s)
                """, (self.name, to_utimestamp(self.due),
                      to_utimestamp(self.completed), self.description))
            self._to_old()
            TicketSystem(self.env).reset_ticket_fields()

        for listener in TicketSystem(self.env).milestone_change_listeners:
            listener.milestone_created(self)

    def update(self, db=None):
        """Update the milestone.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid milestone name.'))

        @self.env.with_transaction(db)
        def do_update(db):
            cursor = db.cursor()
            old_name = self._old['name']
            self.env.log.info('Updating milestone "%s"' % self.name)
            cursor.execute("""
                UPDATE milestone
                SET name=%s,due=%s,completed=%s,description=%s WHERE name=%s
                """, (self.name, to_utimestamp(self.due),
                      to_utimestamp(self.completed),
                      self.description, old_name))

            if self.name != old_name:
                # Update milestone field in tickets
                self.env.log.info('Updating milestone field of all tickets '
                                  'associated with milestone "%s"' % self.name)
                cursor.execute("""
                    UPDATE ticket SET milestone=%s WHERE milestone=%s
                    """, (self.name, old_name))
                TicketSystem(self.env).reset_ticket_fields()

                # Reparent attachments
                Attachment.reparent_all(self.env, 'milestone', old_name,
                                        'milestone', self.name)

        old_values = dict((k, v) for k, v in self._old.iteritems()
                          if getattr(self, k) != v)
        self._to_old()
        for listener in TicketSystem(self.env).milestone_change_listeners:
            listener.milestone_changed(self, old_values)

    @classmethod
    def select(cls, env, include_completed=True, db=None):
        if not db:
            db = env.get_read_db()
        sql = "SELECT name,due,completed,description FROM milestone "
        if not include_completed:
            sql += "WHERE COALESCE(completed,0)=0 "
        cursor = db.cursor()
        cursor.execute(sql)
        milestones = []
        for row in cursor:
            milestone = Milestone(env)
            milestone._from_database(row)
            milestones.append(milestone)
        def milestone_order(m):
            return (m.completed or utcmax,
                    m.due or utcmax,
                    embedded_numbers(m.name))
        return sorted(milestones, key=milestone_order)


def group_milestones(milestones, include_completed):
    """Group milestones into "open with due date", "open with no due date",
    and possibly "completed". Return a list of (label, milestones) tuples."""
    def category(m):
        return m.is_completed and 1 or m.due and 2 or 3
    open_due_milestones, open_not_due_milestones, \
        closed_milestones = partition([(m, category(m))
            for m in milestones], (2, 3, 1))
    groups = [
        (_('Open (by due date)'), open_due_milestones),
        (_('Open (no due date)'), open_not_due_milestones),
    ]
    if include_completed:
        groups.append((_('Closed'), closed_milestones))
    return groups


class Version(object):

    def __init__(self, env, name=None, db=None):
        self.env = env
        if name:
            if not db:
                db = self.env.get_read_db()
            cursor = db.cursor()
            cursor.execute("""
                SELECT time,description FROM version WHERE name=%s
                """, (name,))
            row = cursor.fetchone()
            if not row:
                raise ResourceNotFound(_('Version %(name)s does not exist.',
                                         name=name))
            self.name = self._old_name = name
            self.time = row[0] and from_utimestamp(row[0]) or None
            self.description = row[1] or ''
        else:
            self.name = self._old_name = None
            self.time = None
            self.description = None

    exists = property(fget=lambda self: self._old_name is not None)

    def delete(self, db=None):
        """Delete the version.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot delete non-existent version'

        @self.env.with_transaction(db)
        def do_delete(db):
            cursor = db.cursor()
            self.env.log.info('Deleting version %s' % self.name)
            cursor.execute("DELETE FROM version WHERE name=%s", (self.name,))
            self.name = self._old_name = None
            TicketSystem(self.env).reset_ticket_fields()

    def insert(self, db=None):
        """Insert a new version.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert not self.exists, 'Cannot insert existing version'
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid version name.'))

        @self.env.with_transaction(db)
        def do_insert(db):
            cursor = db.cursor()
            self.env.log.debug("Creating new version '%s'" % self.name)
            cursor.execute("""
                INSERT INTO version (name,time,description) VALUES (%s,%s,%s)
                """, (self.name, to_utimestamp(self.time), self.description))
            self._old_name = self.name
            TicketSystem(self.env).reset_ticket_fields()

    def update(self, db=None):
        """Update the version.
        
        The `db` argument is deprecated in favor of `with_transaction()`.
        """
        assert self.exists, 'Cannot update non-existent version'
        self.name = simplify_whitespace(self.name)
        if not self.name:
            raise TracError(_('Invalid version name.'))

        @self.env.with_transaction(db)
        def do_update(db):
            cursor = db.cursor()
            self.env.log.info('Updating version "%s"' % self.name)
            cursor.execute("""
                UPDATE version SET name=%s,time=%s,description=%s WHERE name=%s
                """, (self.name, to_utimestamp(self.time),
                      self.description, self._old_name))
            if self.name != self._old_name:
                # Update tickets
                cursor.execute("UPDATE ticket SET version=%s WHERE version=%s",
                               (self.name, self._old_name))
                self._old_name = self.name
            TicketSystem(self.env).reset_ticket_fields()

    @classmethod
    def select(cls, env, db=None):
        if not db:
            db = env.get_read_db()
        cursor = db.cursor()
        cursor.execute("SELECT name,time,description FROM version")
        versions = []
        for name, time, description in cursor:
            version = cls(env)
            version.name = version._old_name = name
            version.time = time and from_utimestamp(time) or None
            version.description = description or ''
            versions.append(version)
        def version_order(v):
            return (v.time or utcmax, embedded_numbers(v.name))
        return sorted(versions, key=version_order, reverse=True)