PostgresqlPatch: pgsql_patch_05.diff

File pgsql_patch_05.diff, 53.2 kB (added by brad, 4 years ago)

see changelog

  • scripts/trac-admin

    old new  
    2727import time 
    2828import cmd 
    2929import shlex 
    30 import sqlite 
    3130import StringIO 
     31import traceback 
    3232 
    3333from trac import util 
    3434from trac import sync 
     
    9292            return 0 
    9393        return 1 
    9494         
    95     def env_create(self): 
     95    def env_create(self, db_str): 
    9696        try: 
    97             self.__env = trac.Environment.Environment (self.envname, create=1
     97            self.__env = trac.Environment.Environment (self.envname, 1, db_str
    9898            return self.__env 
    9999        except Exception, e: 
    100100            print 'Failed to create environment.', e 
     
    111111 
    112112    def db_execsql (self, sql, cursor=None): 
    113113        data = [] 
     114        row = None 
    114115        if not cursor: 
    115116            cnx=self.db_open() 
    116117            cursor = cnx.cursor() 
     
    118119            cnx = None 
    119120        cursor.execute(sql) 
    120121        while 1: 
    121             row = cursor.fetchone() 
     122            try: 
     123                row = cursor.fetchone() 
     124            except: 
     125                pass 
    122126            if row == None: 
    123127                break 
    124128            data.append(row) 
     
    457461 
    458462    ## Initenv 
    459463    _help_initenv = [('initenv', 'Create and initialize a new environment interactively'), 
    460                      ('initenv <projectname> <repospath> <templatepath>', 
     464                     ('initenv <projectname> <repospath> <templatepath> <dbms> [dbms options]', 
    461465                      'Create and initialize a new environment from arguments')] 
    462466 
    463467    def do_initdb(self, line): 
     
    490494        dt = trac.siteconfig.__default_templates_dir__ 
    491495        prompt = 'Templates directory [%s]> ' % dt 
    492496        returnvals.append(raw_input(prompt) or dt) 
     497        print 
     498        print " Please enter the database in which you wish to store Trac data." 
     499        print " Default is 'sqlite', but others are supported:" 
     500        print " 'sqlite' - SQLite       http://www.sqlite.org" 
     501        print " 'pgsql'  - PostgreSQL   http://www.postgresql.org" 
     502        print 
     503        ddb = "sqlite" 
     504        prompt =  'database system [%s]> ' % ddb 
     505        dbms = raw_input(prompt) or ddb 
     506        returnvals.append(dbms) 
     507         
     508        # PostgreSQL - additional questions 
     509        if dbms == "pgsql": 
     510            print 
     511            print " Please enter the host of your PostgreSQL database." 
     512            print " Default is 'localhost'" 
     513            print 
     514            host = "localhost" 
     515            prompt = "PostgreSQL host [%s]> " % host 
     516            returnvals.append(raw_input(prompt) or host) 
     517             
     518            print 
     519            print " Please enter the port of your PostgreSQL database." 
     520            print " Default is '5432'" 
     521            print 
     522            port = "5432" 
     523            prompt = "PostgreSQL port [%s]> " % port 
     524            returnvals.append(raw_input(prompt) or port) 
     525             
     526            print 
     527            print " Please enter the name of your PostgreSQL database." 
     528            print " Default is 'trac'" 
     529            print " Note: This database should not exist, as trac-admin will" \ 
     530                  " attempt to create it." 
     531            print 
     532            name = "trac" 
     533            prompt = "PostgreSQL database [%s]> " % name 
     534            returnvals.append(raw_input(prompt) or name) 
     535             
     536            print 
     537            print " Please enter the user of your PostgreSQL database." 
     538            print " Default is 'trac'" 
     539            print 
     540            user = "trac" 
     541            prompt = "PostgreSQL user [%s]> " % user 
     542            returnvals.append(raw_input(prompt) or user) 
     543             
     544            print 
     545            print " Please enter the password of your PostgreSQL database." 
     546            print " Default is 'trac'" 
     547            print 
     548            password = "trac" 
     549            prompt = "PostgreSQL password [%s]> " % password 
     550            returnvals.append(raw_input(prompt) or password) 
     551             
    493552        return returnvals 
    494553          
    495554    def do_initenv(self, line): 
     
    500559        project_name = None 
    501560        repository_dir = None 
    502561        templates_dir = None 
     562        db_str = None 
    503563        if len(arg) == 1: 
    504564            returnvals = self.get_initenv_args() 
    505565            project_name = returnvals[0] 
    506566            repository_dir = returnvals[1] 
    507567            templates_dir = returnvals[2] 
    508         elif len(arg)!= 3: 
     568            db_str = returnvals[3] 
     569        elif len(arg) < 4: 
    509570            print 'Wrong number of arguments to initenv %d' % len(arg) 
    510571            return 
    511572        else: 
    512573            project_name = arg[0] 
    513574            repository_dir = arg[1] 
    514575            templates_dir = arg[2] 
     576            db_str = arg[3] 
     577         
     578        # sqlite-specific stuff 
     579        if db_str.lower() == "sqlite": 
     580            db_str = 'sqlite:"db/trac.db",timeout=10000' 
     581         
     582        # postgres-specific stuff 
     583        if db_str.lower() == "pgsql": 
     584            if len(arg) == 1: 
     585                host = returnvals[4] 
     586                port = returnvals[5] 
     587                database = returnvals[6] 
     588                user = returnvals[7] 
     589                password = returnvals[8] 
     590            elif len(arg) != 9: 
     591                print 'Wrong number of arguments to initenv %d' % len(arg) 
     592                print 'For PostgreSQL (after pgsql): <host> <port> <database>' \ 
     593                      ' <user> <password>' 
     594                return 
     595            else: 
     596                host = arg[4] 
     597                port = arg[5] 
     598                database = arg[6] 
     599                user = arg[7] 
     600                password = arg[8] 
     601            db_str = "pgsql:\"\",host='%s:%s',database='%s',user='%s'," \ 
     602                     "password='%s'" \ 
     603                     % (host, port, database, user, password) 
     604            createdb_str = "createdb --host=%s --port=%s --owner=%s " \ 
     605                           "--username=%s %s\n" \ 
     606                           % (host, port, user, user, database) 
     607            print createdb_str 
     608            try: 
     609                # TODO: this is not cross-platform. 
     610                # for Windows, look at win32pipe.popen() 
     611                os.popen(createdb_str) 
     612            except Exception, e: 
     613                print "Error creating PostgreSQL database: %s" % e 
     614                print "command: %s" % createdb_str 
     615         
    515616        from svn import util, repos, core 
    516617        core.apr_initialize() 
    517618        pool = core.svn_pool_create(None) 
     
    530631            return 
    531632        try: 
    532633            print 'Creating and Initializing Project' 
    533             self.env_create(
     634            self.env_create(db_str
    534635            cnx = self.__env.get_db_cnx() 
    535636            print ' Inserting default data' 
    536637            self.__env.insert_default_data() 
     
    669770                self.do_help ('wiki') 
    670771        except Exception, e: 
    671772            print 'Wiki %s failed:' % arg[0], e 
     773            print traceback.print_exc() 
     774             
    672775 
    673776    def _do_wiki_list(self): 
    674777        data = self.db_execsql('SELECT name,max(version),time' 
     
    694797        data = data.replace("'", "''") # Escape ' for safe SQL 
    695798        f.close() 
    696799         
    697         sql = ("INSERT INTO wiki('version','name','time','author','ipnr','text') " 
    698                " SELECT 1+ifnull(max(version),0),'%(title)s','%(time)s','%(author)s'," 
    699                "   '%(ipnr)s','%(text)s' FROM wiki WHERE name='%(title)s'"  
     800        sql = ("INSERT INTO wiki(version,name,time,author,ipnr,text) " 
     801               " SELECT 1+COALESCE(max(version),0),'%(title)s','%(time)s'," 
     802               "'%(author)s','%(ipnr)s','%(text)s' " 
     803               "FROM wiki WHERE name='%(title)s'"  
    700804               % {'title':title, 
    701805                  'time':int(time.time()), 
    702806                  'author':'trac', 
     
    10071111                    print "Upgrade: Backup of old database saved in " \ 
    10081112                          "%s/db/trac.db.%i.bak" % (self.envname, curr) 
    10091113                else: 
    1010                     print "Upgrade: Backup disabled. Non-existant warranty voided." 
     1114                    print "Upgrade: Backup disabled. Non-existent warranty voided." 
    10111115                self.__env.upgrade(do_backup) 
    10121116            else: 
    10131117                print "Upgrade: Database is up to date, no upgrade necessary." 
  • trac/db_default.py

    old new  
    3030    result = [] 
    3131    i = 1 
    3232    for r in reps: 
    33         result.append ((i, None, r[0], r[2], r[1])) 
     33        result.append ((None, r[0], r[2], r[1])) 
    3434        i = i + 1 
    3535    return result 
    3636 
     
    174174CREATE INDEX session_idx        ON session(sid,var_name); 
    175175""" 
    176176 
     177schema_pgsql = """ 
     178CREATE TABLE revision ( 
     179        rev             integer, 
     180        time            integer, 
     181        author          text, 
     182        message         text, 
     183        CONSTRAINT revision_pkey PRIMARY KEY (rev) 
     184); 
     185 
     186CREATE TABLE node_change ( 
     187        rev             integer, 
     188        name            text, 
     189        change          char(1), 
     190        CONSTRAINT node_change_pkey PRIMARY KEY (rev, name, change) 
     191); 
     192 
     193CREATE TABLE auth_cookie ( 
     194        cookie          text, 
     195        name            text, 
     196        ipnr            text, 
     197        time            integer, 
     198        CONSTRAINT auth_cookie_pkey PRIMARY KEY(cookie, name, ipnr) 
     199); 
     200 
     201CREATE TABLE enum ( 
     202        type            text, 
     203        name            text, 
     204        value           integer, 
     205        CONSTRAINT enum_pkey PRIMARY KEY(name,type) 
     206); 
     207 
     208CREATE TABLE system ( 
     209        name            text, 
     210        value           text, 
     211        CONSTRAINT system_pkey PRIMARY KEY(name) 
     212); 
     213 
     214CREATE TABLE lock ( 
     215        name            text, 
     216        owner           text, 
     217        ipnr            text, 
     218        time            integer, 
     219        CONSTRAINT lock_pkey PRIMARY KEY(name) 
     220); 
     221 
     222--CREATE SEQUENCE ticket_id_seq; 
     223CREATE TABLE ticket ( 
     224        id              serial, 
     225        time            integer,        -- the time it was created 
     226        changetime      integer, 
     227        component       text, 
     228        severity        text, 
     229        priority        text, 
     230        owner           text,           -- who is this ticket assigned to 
     231        reporter        text, 
     232        cc              text,           -- email addresses to notify 
     233        url             text,           -- url related to this ticket 
     234        version         text,           --  
     235        milestone       text,           --  
     236        status          text, 
     237        resolution      text, 
     238        summary         text,           -- one-line summary 
     239        description     text,           -- problem description (long) 
     240        keywords        text, 
     241        CONSTRAINT ticket_pkey PRIMARY KEY(id) 
     242); 
     243 
     244CREATE TABLE ticket_change ( 
     245        ticket          integer, 
     246        time            integer, 
     247        author          text, 
     248        field           text, 
     249        oldvalue        text, 
     250        newvalue        text, 
     251        CONSTRAINT ticket_change_pkey PRIMARY KEY(ticket, time, field) 
     252); 
     253 
     254CREATE TABLE ticket_custom ( 
     255       ticket           integer, 
     256       name             text, 
     257       value            text, 
     258       CONSTRAINT ticket_custom_pkey PRIMARY KEY(ticket,name) 
     259); 
     260 
     261--CREATE SEQUENCE report_id_seq; 
     262CREATE TABLE report ( 
     263        id              serial, 
     264        author          text, 
     265        title           text, 
     266        sql             text, 
     267        description     text, 
     268        CONSTRAINT report_pkey PRIMARY KEY(id) 
     269); 
     270 
     271CREATE TABLE permission ( 
     272        username        text,           --  
     273        action          text,           -- allowable activity 
     274        CONSTRAINT permission_pkey PRIMARY KEY(username,action) 
     275); 
     276 
     277CREATE TABLE component ( 
     278         name            text, 
     279         owner           text, 
     280         CONSTRAINT component_pkey PRIMARY KEY(name) 
     281); 
     282 
     283CREATE TABLE milestone ( 
     284         name            text, 
     285         due             integer, -- Due date/time 
     286         completed       integer, -- Completed date/time 
     287         description     text, 
     288         CONSTRAINT milestone_pkey PRIMARY KEY(name) 
     289); 
     290 
     291CREATE TABLE version ( 
     292         name            text, 
     293         time            integer, 
     294         CONSTRAINT version_pkey PRIMARY KEY(name) 
     295); 
     296 
     297CREATE TABLE wiki ( 
     298         name            text, 
     299         version         integer, 
     300         time            integer, 
     301         author          text, 
     302         ipnr            text, 
     303         text            text, 
     304         comment         text, 
     305         readonly        integer, 
     306         CONSTRAINT wiki_pkey PRIMARY KEY(name,version) 
     307); 
     308 
     309CREATE TABLE attachment ( 
     310         type            text, 
     311         id              text, 
     312         filename        text, 
     313         size            integer, 
     314         time            integer, 
     315         description     text, 
     316         author          text, 
     317         ipnr            text, 
     318         CONSTRAINT attachment_pkey PRIMARY KEY(type,id,filename) 
     319); 
     320 
     321CREATE TABLE session ( 
     322         sid             text, 
     323         username        text, 
     324         var_name        text, 
     325         var_value       text, 
     326         CONSTRAINT session_pkey PRIMARY KEY(sid,var_name) 
     327); 
     328 
     329""" 
     330 
    177331## 
    178332## Default Reports 
    179333## 
     
    295449  FROM ticket t,enum p 
    296450  WHERE p.name=t.priority AND p.type='priority' 
    297451  ORDER BY (milestone IS NULL), milestone DESC, (status = 'closed'),  
    298         (CASE status WHEN 'closed' THEN modified ELSE -p.value END) DESC 
     452        (CASE status WHEN 'closed' THEN changetime ELSE (-1)*p.value END) DESC 
    299453"""), 
    300454#---------------------------------------------------------------------------- 
    301455('My Tickets', 
     
    406560             ('name', 'value'), 
    407561               (('database_version', str(db_version)),)), 
    408562           ('report', 
    409              ('id', 'author', 'title', 'sql', 'description'), 
     563             ('author', 'title', 'sql', 'description'), 
    410564               __mkreports(reports))) 
    411565 
    412566default_config = \ 
    413567 (('trac', 'htdocs_location', '/trac/'), 
    414568  ('trac', 'repository_dir', '/var/svn/myrep'), 
    415569  ('trac', 'templates_dir', '/usr/lib/trac/templates'), 
    416   ('trac', 'database', 'sqlite:db/trac.db'), 
     570  ('trac', 'database', 'sqlite:"db/trac.db",timeout=10000'), 
    417571  ('trac', 'default_charset', 'iso-8859-15'), 
    418572  ('logging', 'log_type', 'none'), 
    419573  ('logging', 'log_file', 'trac.log'), 
  • trac/Milestone.py

    old new  
    157157        cursor = self.db.cursor() 
    158158        self.log.debug("Creating new milestone '%s'" % name) 
    159159        cursor.execute("INSERT INTO milestone (name,due,completed,description) " 
    160                        "VALUES (%s,%d,%d,%s)", name, due, completed, 
     160                       "VALUES (%s,%s,%s,%s)", name, due, completed, 
    161161                       description) 
    162162        self.db.commit() 
    163163        self.req.redirect(self.env.href.milestone(name)) 
     
    196196                          'associated with milestone %s' % id) 
    197197            cursor.execute("UPDATE ticket SET milestone = %s " 
    198198                           "WHERE milestone = %s", name, id) 
    199             cursor.execute("UPDATE milestone SET name = %s, due = %d, " 
    200                            "completed = %d, description = %s WHERE name = %s", 
     199            cursor.execute("UPDATE milestone SET name = %s, due = %s, " 
     200                           "completed = %s, description = %s WHERE name = %s", 
    201201                           name, due, completed, description, id) 
    202202            self.db.commit() 
    203203            self.req.redirect(self.env.href.milestone(name)) 
     
    209209        groups = [] 
    210210        if by in ['status', 'resolution', 'severity', 'priority']: 
    211211            cursor.execute("SELECT name FROM enum WHERE type = %s " 
    212                            "AND IFNULL(name,'') != '' ORDER BY value", by) 
     212                           "AND COALESCE(name,'') != '' ORDER BY value", by) 
    213213        elif by in ['component', 'milestone', 'version']: 
    214214            cursor.execute("SELECT name FROM %s " 
    215                            "WHERE IFNULL(name,'') != '' ORDER BY name" % by) 
     215                           "WHERE COALESCE(name,'') != '' ORDER BY name" % by) 
    216216        elif by == 'owner': 
    217217            cursor.execute("SELECT DISTINCT owner AS name FROM ticket " 
    218218                           "ORDER BY owner") 
  • trac/Search.py

    old new  
    117117 
    118118        cursor = self.db.cursor () 
    119119 
     120        # ugly 'cast' hack for sqlite vs other dbms 
     121        # and UNION ALL requiring like column datatypes 
     122        data_changeset = 'rev' 
     123        data_tickets = 'a.id' 
     124        dbms = self.env.dbms 
     125        if dbms != 'sqlite': 
     126            data_changeset = 'cast(rev as text)' 
     127            data_tickets = 'cast(a.id as text)' 
     128 
    120129        q = [] 
    121130        if changeset: 
    122131            q.append('SELECT 1 as type, message AS title, message, author, ' 
    123                      ' \'\' AS keywords, rev AS data, time,0 AS ver' 
     132                     ' \'\' AS keywords, %s AS data, time,0 AS ver' 
    124133                     ' FROM revision WHERE %s OR %s' %  
    125                      (self.query_to_sql(query, 'message'), 
     134                     (data_changeset, 
     135                      self.query_to_sql(query, 'message'), 
    126136                      self.query_to_sql(query, 'author'))) 
    127137        if tickets: 
    128138            q.append('SELECT DISTINCT 2 as type, a.summary AS title, ' 
    129139                     ' a.description AS message, a.reporter AS author, ' 
    130                      ' a.keywords as keywords, a.id AS data, a.time as time, 0 AS ver' 
    131                      ' FROM ticket a LEFT JOIN ticket_change b ON a.id = b.ticket' 
    132                      ' WHERE (b.field=\'comment\' AND %s ) OR' 
    133                      ' %s OR %s OR %s OR %s OR %s' % 
    134                       (self.query_to_sql(query, 'b.newvalue'), 
     140                     ' a.keywords as keywords, %s AS data, a.time as time' 
     141                     ' , 0 AS ver FROM ticket a LEFT JOIN ticket_change b' 
     142                     ' ON a.id = b.ticket WHERE (b.field=\'comment\' AND %s )' 
     143                     ' OR %s OR %s OR %s OR %s OR %s' % 
     144                      (data_tickets, 
     145                       self.query_to_sql(query, 'b.newvalue'), 
    135146                       self.query_to_sql(query, 'summary'), 
    136147                       self.query_to_sql(query, 'keywords'), 
    137148                       self.query_to_sql(query, 'description'), 
  • trac/Query.py

    old new  
    154154        sql.append("\nFROM ticket") 
    155155        for k in [k for k in cols if k in custom_fields]: 
    156156           sql.append("\n  LEFT OUTER JOIN ticket_custom AS %s ON " \ 
    157                       "(id=%s.ticket AND %s.name='%s')" % (k, k, k, k)) 
     157                      "(id=%s.ticket AND %s.name='%s') tc" % (k, k, k, k)) 
    158158 
    159159        for col in [c for c in ['status', 'resolution', 'priority', 'severity'] 
    160160                    if c == self.order or c == self.group]: 
    161161            sql.append("\n  LEFT OUTER JOIN (SELECT name AS %s_name, " \ 
    162162                                            "value AS %s_value " \ 
    163                                             "FROM enum WHERE type='%s')" \ 
     163                                            "FROM enum WHERE type='%s') e" \ 
    164164                       " ON %s_name=%s" % (col, col, col, col, col)) 
    165165        for col in [c for c in ['milestone', 'version'] 
    166166                    if c == self.order or c == self.group]: 
    167167            time_col = col == 'milestone' and 'due' or 'time' 
    168168            sql.append("\n  LEFT OUTER JOIN (SELECT name AS %s_name, " \ 
    169                                             "%s AS %s_time FROM %s)" \ 
     169                                            "%s AS %s_time FROM %s) a" \ 
    170170                       " ON %s_name=%s" % (col, time_col, col, col, col, col)) 
    171171 
    172172        def get_constraint_sql(name, value, mode, neg): 
    173173            value = sql_escape(value[len(mode and '!' or '' + mode):]) 
    174174            if mode == '~' and value: 
    175                 return "IFNULL(%s,'') %sLIKE '%%%s%%'" % ( 
     175                return "COALESCE(%s,'') %sLIKE '%%%s%%'" % ( 
    176176                       name, neg and 'NOT ' or '', value) 
    177177            elif mode == '^' and value: 
    178                 return "IFNULL(%s,'') %sLIKE '%s%%'" % ( 
     178                return "COALESCE(%s,'') %sLIKE '%s%%'" % ( 
    179179                       name, neg and 'NOT ' or '', value) 
    180180            elif mode == '$' and value: 
    181                 return "IFNULL(%s,'') %sLIKE '%%%s'" % ( 
     181                return "COALESCE(%s,'') %sLIKE '%%%s'" % ( 
    182182                       name, neg and 'NOT ' or '', value) 
    183183            elif mode == '': 
    184                 return "IFNULL(%s,'')%s='%s'" % (name, neg and '!' or '', value) 
     184                return "COALESCE(%s,'')%s='%s'" % (name, neg and '!' or '', value) 
    185185 
    186186        clauses = [] 
    187187        for k, v in self.constraints.items(): 
     
    195195            # Special case for exact matches on multiple values 
    196196            if not mode and len(v) > 1: 
    197197                inlist = ",".join(["'" + sql_escape(val[neg and 1 or 0:]) + "'" for val in v]) 
    198                 clauses.append("IFNULL(%s,'') %sIN (%s)" % (k, neg and "NOT " or "", inlist)) 
     198                clauses.append("COALESCE(%s,'') %sIN (%s)" % (k, neg and "NOT " or "", inlist)) 
    199199            elif len(v) > 1: 
    200200                constraint_sql = [get_constraint_sql(k, val, mode, neg) for val in v] 
    201201                if neg: 
     
    214214        if self.group and self.group != self.order: 
    215215            order_cols.insert(0, (self.group, self.groupdesc)) 
    216216        for col, desc in order_cols: 
    217             if desc: 
    218                 sql.append("IFNULL(%s,'')='' DESC," % col) 
     217            if col == 'id': 
     218                # TODO: this is a somewhat ugly hack.  Can we also have the 
     219                #       column type for this?  If it's an integer, we do first 
     220                #       one, if text, we do 'else' 
     221                if desc: 
     222                    sql.append("COALESCE(%s,0)=0 DESC," % col) 
     223                else: 
     224                    sql.append("COALESCE(%s,0)=0," % col) 
    219225            else: 
    220                 sql.append("IFNULL(%s,'')=''," % col) 
     226                if desc: 
     227                    sql.append("COALESCE(%s,'')='' DESC," % col) 
     228                else: 
     229                    sql.append("COALESCE(%s,'')=''," % col) 
    221230            if col in ['status', 'resolution', 'priority', 'severity']: 
    222231                if desc: 
    223232                    sql.append("%s_value DESC" % col) 
     
    225234                    sql.append("%s_value" % col) 
    226235            elif col in ['milestone', 'version']: 
    227236                if desc: 
    228                     sql.append("IFNULL(%s_time,0)=0 DESC,%s_time DESC,%s DESC" 
     237                    sql.append("COALESCE(%s_time,0)=0 DESC,%s_time DESC,%s DESC" 
    229238                               % (col, col, col)) 
    230239                else: 
    231                     sql.append("IFNULL(%s_time,0)=0,%s_time,%s" 
     240                    sql.append("COALESCE(%s_time,0)=0,%s_time,%s" 
    232241                               % (col, col, col)) 
    233242            else: 
    234243                if desc: 
  • trac/Timeline.py

    old new  
    142142                if max_node != 0: 
    143143                    cursor_node = self.db.cursor () 
    144144                    cursor_node.execute("SELECT name, change " 
    145                                         "FROM node_change WHERE rev=%d" % item['idata']) 
     145                                        "FROM node_change WHERE rev=%s", item['idata']) 
    146146                    node_list = '' 
    147147                    node_data = '' 
    148148                    node_count = 0; 
  • trac/Report.py

    old new  
    110110    def create_report(self, title, description, sql): 
    111111        self.perm.assert_permission(perm.REPORT_CREATE) 
    112112 
     113        dbms = self.env.get_dbms() 
    113114        cursor = self.db.cursor() 
    114         cursor.execute('INSERT INTO report (id, title, sql, description)' 
    115                         'VALUES (NULL, %s, %s, %s)', title, sql, description) 
    116         id = self.db.db.sqlite_last_insert_rowid() 
     115        cursor.execute('INSERT INTO report (title, sql, description)' 
     116                       'VALUES (%s, %s, %s)', (title, sql, description,)) 
     117                         
     118        if dbms == 'pgsql': 
     119            cursor.execute("SELECT id FROM report " \ 
     120                           "WHERE id = CURRVAL('report_id_seq')") 
     121            id = cursor.fetchone()[0] 
     122        else: # sqlite way 
     123            id = self.db.db.sqlite_last_insert_rowid() 
     124             
    117125        self.db.commit() 
    118126        self.req.redirect(self.env.href.report(id)) 
    119127 
     
    140148 
    141149        # FIXME: fetchall should probably not be used. 
    142150        info = cursor.fetchall() 
    143         cols = cursor.rs.col_defs 
     151        cols = cursor.description 
    144152        # Escape the values so that they are safe to have as html parameters 
    145153        #info = map(lambda row: map(lambda x: escape(x), row), info) 
    146154 
  • trac/sync.py

    old new  
    3535              (util.SVN_VER_MAJOR, util.SVN_VER_MINOR, util.SVN_VER_MICRO) 
    3636 
    3737    cursor = db.cursor() 
    38     cursor.execute('SELECT ifnull(max(rev), 0) FROM revision') 
     38    cursor.execute('SELECT COALESCE(max(rev), 0) FROM revision') 
    3939    youngest_stored =  int(cursor.fetchone()[0]) 
    4040    max_rev = fs.youngest_rev(fs_ptr, pool) 
    4141    num = max_rev - youngest_stored 
  • trac/Roadmap.py

    old new  
    4444        if show == 'all': 
    4545            icalhref += '&show=all' 
    4646            query = "SELECT name,due,completed,description FROM milestone " \ 
    47                     "WHERE IFNULL(name,'')!='' " \ 
    48                     "ORDER BY IFNULL(due,0)=0,due,name" 
     47                    "WHERE COALESCE(name,'')!='' " \ 
     48                    "ORDER BY COALESCE(due,0)=0,due,name" 
    4949        else: 
    5050            self.req.hdf.setValue('roadmap.showall', '1') 
    5151            query = "SELECT name,due,completed,description FROM milestone " \ 
    52                     "WHERE IFNULL(name,'')!='' " \ 
    53                     "AND IFNULL(completed,0)=0 " \ 
    54                     "ORDER BY IFNULL(due,0)=0,due,name" 
     52                    "WHERE COALESCE(name,'')!='' " \ 
     53                    "AND COALESCE(completed,0)=0 " \ 
     54                    "ORDER BY COALESCE(due,0)=0,due,name" 
    5555 
    5656        if self.req.authname and self.req.authname != 'anonymous': 
    5757            icalhref += '&user=' + self.req.authname 
     
    176176                if ticket['status'] == 'closed': 
    177177                    cursor = self.db.cursor() 
    178178                    cursor.execute("SELECT time FROM ticket_change " 
    179                                    "WHERE ticket = %i AND field = 'status' " 
     179                                   "WHERE ticket = %s AND field = 'status' " 
    180180                                   "ORDER BY time desc LIMIT 1", ticket['id']) 
    181181                    row = cursor.fetchone() 
    182182                    if row: write_utctime('COMPLETED', localtime(row['time'])) 
  • trac/Session.py

    old new  
    103103    def get_session(self, sid): 
    104104        self.sid = sid 
    105105        curs = self.db.cursor() 
    106         curs.execute("SELECT username,var_name,var_value FROM session" 
    107                     " WHERE sid=%s", self.sid
     106        curs.execute("SELECT username,var_name,var_value FROM session"  
     107                    " WHERE sid=%s", (self.sid,)
    108108        rows = curs.fetchall() 
    109109        if (not rows                              # No session data yet 
    110110            or rows[0][0] == 'anonymous'          # Anon session 
     
    138138                self.purge_expired()  
    139139            curs.execute('INSERT INTO session(sid,username,var_name,var_value)' 
    140140                         ' VALUES(%s,%s,%s,%s)', 
    141                          self.sid, self.req.authname, key, val
     141                         (self.sid, self.req.authname, key, val,)
    142142        else: 
    143143            curs.execute('UPDATE session SET username=%s,var_value=%s' 
    144144                         ' WHERE sid=%s AND var_name=%s', 
    145                          self.req.authname, val, self.sid, key
     145                         (self.req.authname, val, self.sid, key,)
    146146        self.db.commit() 
    147147        self.vars[key] = val 
    148148 
     
    172172        curs = self.db.cursor() 
    173173        curs.execute("DELETE FROM session WHERE sid IN" 
    174174                     " (SELECT sid FROM session WHERE var_name='mod_time'" 
    175                      "  AND var_value  < %i)", mintime) 
     175                     "  AND var_value  < %s)", mintime) 
    176176        self.db.commit() 
    177177 
  • trac/auth.py

    old new  
    3232            cookie = req.incookie['trac_auth'].value 
    3333            cursor.execute ("SELECT name FROM auth_cookie " 
    3434                            "WHERE cookie=%s AND ipnr=%s" 
    35                             ,cookie, req.remote_addr
    36             if cursor.rowcount >= 1
     35                            , (cookie, req.remote_addr,)
     36            try
    3737                self.authname = cursor.fetchone()[0] 
     38            except: 
     39                pass 
    3840 
    3941    def login(self, req): 
    4042        cursor = self.db.cursor () 
    4143        cookie = util.hex_entropy() 
    4244        cursor.execute ("INSERT INTO auth_cookie (cookie, name, ipnr, time)" + 
    43                         "VALUES (%s, %s, %s, %d)", 
    44                         cookie, req.remote_user, req.remote_addr, 
    45                         int(time.time())); 
     45                        "VALUES (%s, %s, %s, %s)", 
     46                        (cookie, req.remote_user, req.remote_addr, 
     47                        int(time.time()),)); 
    4648        self.db.commit () 
    4749        self.authname = req.remote_user 
    4850        req.outcookie['trac_auth'] = cookie 
     
    5153    def logout(self): 
    5254        cursor = self.db.cursor () 
    5355        cursor.execute ("DELETE FROM auth_cookie WHERE name=%s", 
    54                         self.authname
     56                        (self.authname,)
    5557        self.db.commit () 
  • trac/Wiki.py

    old new  
    5959        if version: 
    6060            cursor.execute ('SELECT version, text, readonly FROM wiki ' 
    6161                            'WHERE name=%s AND version=%s', 
    62                             name, version
     62                            (name, version,)
    6363        else: 
    6464            cursor.execute ('SELECT version, text, readonly FROM wiki ' 
    65                             'WHERE name=%s ORDER BY version DESC LIMIT 1', name) 
     65                            'WHERE name=%s ORDER BY version DESC LIMIT 1',  
     66                            (name,)) 
    6667        row = cursor.fetchone() 
    6768        if row: 
    6869            self.new = 0 
  • trac/Environment.py

    old new  
    3434import Logging 
    3535import Mimeview 
    3636import unicodedata 
     37import types 
    3738 
    38 import sqlite 
    39  
    4039db_version = db_default.db_version 
    4140 
    4241class Environment: 
     
    4645    A Trac environment consists of a directory structure containing 
    4746    among other things: 
    4847     * a configuration file. 
    49      * a sqlite database (stores tickets, wiki pages...) 
     48     * a database (stores tickets, wiki pages...) 
    5049     * Project specific templates and wiki macros. 
    5150     * wiki and ticket attachments. 
    5251    """ 
    53     def __init__(self, path, create=0): 
     52    def __init__(self, path, create=0, db_str=None): 
    5453        self.path = path 
    5554        if create: 
    56             self.create(
     55            self.create(db_str
    5756        self.verify() 
    5857        self.load_config() 
    5958        try: # Use binary I/O on Windows 
     
    6463            pass 
    6564        self.setup_log() 
    6665        self.setup_mimeviewer() 
     66        self.dbms = self.get_dbms() 
    6767 
    6868    def verify(self): 
    6969        """Verifies that self.path is a compatible trac environment""" 
     
    7171        assert fd.read(26) == 'Trac Environment Version 1' 
    7272        fd.close() 
    7373 
    74     def get_db_cnx(self): 
    75         db_str = self.get_config('trac', 'database', 'sqlite:db/trac.db') 
    76         assert db_str[:7] == 'sqlite:' 
    77         db_name = os.path.join(self.path, db_str[7:]) 
    78         if not os.access(db_name, os.F_OK): 
    79             raise EnvironmentError, 'Database "%s" not found.' % db_name 
     74    def get_dbms(self): 
     75        db_str = self.get_config('trac', 'database') 
     76        if not db_str: 
     77            return 'sqlite' 
     78        pos = db_str.find(':') 
     79        if pos == -1: 
     80            raise EnvironmentError, 'Connection param must be of form ' \ 
     81                  '(db_module_name):(db_connect_params), the value "%s ' \ 
     82                  'does not match' % db_str 
    8083         
    81         directory = os.path.dirname(db_name) 
    82         if not os.access(db_name, os.R_OK + os.W_OK) or \ 
    83                not os.access(directory, os.R_OK + os.W_OK): 
    84             raise EnvironmentError, \ 
    85                   'The web server user requires read _and_ write permission\n' \ 
    86                   'to the database %s and the directory this file is located in.' % db_name 
    87         return sqlite.connect(os.path.join(self.path, db_str[7:]), 
    88                               timeout=10000) 
     84        dbms = db_str[:pos] 
     85        return dbms 
     86         
     87         
     88    def get_db_cnx(self, check_exists=1): 
     89        db_str = self.get_config('trac',  
     90                                 'database',  
     91                                 'sqlite:"db/trac.db",timeout=10000') 
     92                                  
     93        pos = db_str.find(':') 
     94        if pos == -1: 
     95            raise EnvironmentError, 'Connection param must be of form ' \ 
     96                  '(db_module_name):(db_connect_params), the value "%s ' \ 
     97                  'does not match' % db_str 
     98         
     99        module_name = db_str[:pos] 
     100        connect_params = db_str[pos+1:].split(',') 
     101         
     102        # following is very crude code for parsing the arguments in the 
     103        # db_connect_params string 
     104        kargs = {} 
     105        arg_list = [] 
     106        for x in connect_params: 
     107            pos1 = x.find('=') 
     108            pos2 = x.find('"') 
     109            pos3 = x.find("'") 
     110            if pos1 > -1: 
     111                if pos2 > -1 and pos2 < pos1: 
     112                    arg_list.append(eval(x)) 
     113                elif pos3 > -1 and pos3 < pos1: 
     114                    arg_list.append(eval(x)) 
     115                else: 
     116                    name = x[:pos1].strip() 
     117                    value = eval(x[pos1+1:].strip()) 
     118                    kargs[name] = value 
     119            else: 
     120                # self.log.debug("Environment - get_db_cnx - x: %s" % x) 
     121                arg_list.append(eval(x)) 
     122        args = tuple(arg_list) 
     123         
     124        import_str = 'import %s' % module_name 
    89125 
    90     def create(self): 
     126        # since Trac has a slightly closer relationship with sqlite than 
     127        # other db's, there's a special case setup here so that when the 
     128        # path to the sqlite db is specified, its relative to TRAC_ENV 
     129        if module_name == 'sqlite': 
     130            db_name = os.path.join(self.path, args[0]) 
     131            args = list(args) 
     132