当前位置: 首页>>代码示例>>Python>>正文


Python StatementCursor.insert方法代码示例

本文整理汇总了Python中useless.db.midlevel.StatementCursor.insert方法的典型用法代码示例。如果您正苦于以下问题:Python StatementCursor.insert方法的具体用法?Python StatementCursor.insert怎么用?Python StatementCursor.insert使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在useless.db.midlevel.StatementCursor的用法示例。


在下文中一共展示了StatementCursor.insert方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_new_mount

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_new_mount(conn, name, mtpt, fstype, opts,
                  dump='0', pass_='0'):
    cursor = StatementCursor(conn)
    data = dict(mnt_name=name, mnt_point=mtpt,
                fstype=fstype, mnt_opts=opts,
                dump=dump)
    data['pass'] = pass_
    cursor.insert(table='mounts', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:10,代码来源:oldmain.py

示例2: TableEditor

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class TableEditor(ListWin):
    def __init__(self, conn, table, pkey=None, fields=[],
                 command_data=dict(new='new entry', edit='edit entry')):
        ListWin.__init__(self)
        self.conn = conn
        self.cursor = StatementCursor(self.conn)
        self.cursor.set_table(table)
        self._cdata = command_data
        self.tbar.add_button('new', self._cdata['new'], self.toolbar_button_pressed)
        self.tbar.add_button('edit', self._cdata['edit'], self.toolbar_button_pressed)
        if pkey is None:
            print get_pkey_info(StatementCursor(conn), table)
        self._pkey = pkey
        self.reset_rows()
        self._fields = fields
        self.fields = [pkey] + self._fields
        self.dialogs = {}.fromkeys(self._cdata.keys())

    def reset_rows(self):
        self.set_rows(self.cursor.select(order=self._pkey))

    def toolbar_button_pressed(self, button, data):
        row = None
        if data == 'new':
            if self.dialogs['new'] is None:
                row = self.cursor.select()[0]
                self._make_dialog('new', row, self.add_new_record)
        elif data == 'edit':
            if self.dialogs['edit'] is None:
                row = get_single_row(self.listbox, self._pkey)
                if row is not None:
                    self._make_dialog('edit', row, self.edit_record, row[self._pkey])
            
                
                
    def _make_dialog(self, name, row, okfun, pkey=None):
        if name == 'edit':
            fields = self._fields
        else:
            fields = self.fields
        make_record_dialog(self, name, row, okfun, pkey, fields, self._cdata)
        
    def add_new_record(self, *args):
        dialog = self.dialogs['new']
        self.cursor.insert(data=dict(dialog.items()))
        self.destroy_dialog(dialog)
        self.reset_rows()

    def edit_record(self, *args):
        dialog = self.dialogs['edit']
        clause = Eq(self._pkey, dialog.pkey)
        data = dict(dialog.items())
        self.cursor.update(data=data, clause=clause)
        self.destroy_dialog(dialog)
        self.reset_rows()
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:57,代码来源:base.py

示例3: TextFileManager

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class TextFileManager(object):
    def __init__(self, conn):
        object.__init__(self)
        self.conn = conn
        self.cursor = StatementCursor(self.conn)
        self.cursor.set_table('textfiles')

    def insert_file(self, datafile):
        md5 = self._md5sum(datafile)
        data = datafile.read()
        md5size = '_'.join([md5, str(len(data))])
        return self._insert_data(md5size, data)

    def insert_data(self, data):
        md5 = md5sum(strfile(data))
        md5size = '_'.join([md5, str(len(data))])
        return self._insert_data(md5size, data)
    
    def _insert_data(self, md5size, data):
        clause=Eq('md5size', md5size)
        try:
            row = self.cursor.select_row(clause=clause)
        except NoExistError:
            row = None
        if not row:
            self.cursor.insert(data={'md5size' : md5size, 'data' : data})
            row = self.cursor.select_row(clause=clause)
        return row.fileid

    def get_data(self, id):
        row = self.cursor.select_row(clause=Eq('fileid', id))
        return row.data

    def get_strfile(self, id):
        return strfile(self.get_data(id))

    def _md5sum(self, datafile):
        datafile.seek(0)
        md5 = md5sum(datafile)
        datafile.seek(0)
        return md5
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:43,代码来源:objects.py

示例4: SuiteHandler

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class SuiteHandler(object):
    def __init__(self, conn, cfg):
        self.conn = conn
        self.cfg = cfg
        self.cursor = StatementCursor(self.conn)
        self.http_mirror = 'http://%s' % self.cfg.get('debrepos', 'repos_host')
        self.local_mirror = 'file:/tmp/paellamirror'
        self.suite = None
        self.sources_rows = []

    def set_suite(self, suite):
        self.suite = suite
        self.sources_rows = self.get_sources_rows(self.suite)

    def make_suite(self):
        if self.suite is None:
            raise Error, 'the suite needs to be set first'
        self._make_suite_tables()
        self.update_packagelists()
        for row in self.sources_rows:
            self._insert_packages(row)
            
    def _make_suite_tables(self):
        tables = suite_tables(self.suite)
        map(self.cursor.create_table, tables)
        self.cursor.execute(grant_public([x.name for x in tables]))
        
    def update_packagelists(self):
        self._update_suite_packages(self.suite)
        
    def get_sources_rows(self, suite):
        table = 'apt_sources natural join suite_apt_sources'
        rows = self.cursor.select(table=table, clause=Eq('suite', suite), order=['ord'])
        return rows

    def _insert_some_packages(self, table, packages):
        for package in packages:
            try:
                self.cursor.insert(table, data=package_to_row(package))
            except OperationalError:
                pass
            
    def _insert_packages(self, src_row):
        table = '%s_packages' % self.suite
        repos = self._row2repos(src_row)
        prow = package_to_row
        local = repos.local
        if local.source.sections:
            repos.update()
            local.parse_release()
            for section in local.source.sections:
                packages = local.full_parse(section).values()
                self._insert_some_packages(table, packages)
        else:
            packages = local.full_parse().values()
            self._insert_some_packages(table, packages)
            
            
        
    def _row2repsource(self, row, http_mirror):
        lp = row.local_path
        while lp[0] == '/':
            lp = lp[1:]
        uri = os.path.join(http_mirror, lp)
        suite = row.dist
        src = 'deb %s %s' % (uri, suite)
        if not suite.endswith('/'):
            src = '%s %s' % (src, row.sections)
        r = RepositorySource(src)
        return r

    def _row2repos(self, row):
        rsource = self._row2repsource(row, self.http_mirror)
        lsource = self._row2repsource(row, self.local_mirror)
        return RemoteRepos(rsource, lsource)
                
    def _get_packages_file(self, repos):
        if repos.source.has_release():
            repos.update()
        else:
            rpath = os.path.join(repos.source.uri, repos.source.suite, 'Packages.gz')
            # the [5:] slice is to remove file: from local uri
            lpath = os.path.join(repos.local.source.uri, repos.source.suite, 'Packages.gz')[5:]
            if not os.path.isfile(lpath):
                print 'lpath is --->', lpath
                makepaths(os.path.dirname(lpath))
                print rpath, lpath, 'getting now'
                wget(rpath, lpath)
            
    def _update_suite_packages(self, suite):
        rows = self.get_sources_rows(suite)
        for row in rows:
            repos = self._row2repos(row)
            self._get_packages_file(repos)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:96,代码来源:paellascheme.py

示例5: Family

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class Family(object):
    def __init__(self, conn):
        object.__init__(self)
        self.conn = conn
        self.cursor = StatementCursor(self.conn)
        self.current = None
        self.parent = SimpleRelation(self.conn, 'family_parent', 'family')
        self.env = FamilyEnvironment(self.conn)
        
    def set_family(self, family):
        self.current = family
        self.parent.set_current(family)
        self.env.set_family(family)

    def _check_family(self, family):
        if family is not None:
            return family
        else:
            family = self.current
        if family is None:
            raise Error, 'either pass a family arguement or call set_family on this object'
        return family
    
    def add_family(self, family, type='general'):
        pass

    def get_related_families(self, families=[]):
        rows = self.cursor.select(table='family_parent')
        graph = kjGraph([(r.family, r.parent) for r in rows])
        dfamilies = Set()
        for fam in families:
            dfamilies |= Set([fam]) | Set(graph.reachable(fam).items())
        return dfamilies

    def parent_rows(self, family=None):
        family = self._check_family(family)
        self.parent.set_clause(family)
        rows = self.parent.cmd.select(fields=['parent'], order='parent')
        self.parent.reset_clause()
        return rows

    def parents(self, family=None):
        family = self._check_family(family)
        rows = self.parent_rows(family)
        return [x.parent for x in rows]
    
    def environment_rows(self, family=None):
        family = self._check_family(family)
        clause = Eq('family', family)
        args = dict(fields=['trait', 'name', 'value'], clause=clause, order=['trait', 'name'])
        return self.env.cursor.select(**args)

    def family_rows(self):
        return self.cursor.select(fields=['family'], table='families', order='family')

    def all_families(self):
        return [r.family for r in self.family_rows()]

    def get_all_defaults(self):
        suite_cursor = SuiteCursor(self.conn)
        suites = suite_cursor.get_suites()
        stmt = select_multisuite_union(suites, 'variables')
        print stmt
        self.cursor.execute(stmt)
        return self.cursor.fetchall()

    def create_family(self, family):
        if family not in self.all_families():
            self.cursor.insert(table='families', data=dict(family=family))
        else:
            raise ExistsError, '%s already exists' % family

    def insert_parents(self, parents, family=None):
        family = self._check_family(family)
        self.parent.insert('parent', parents)

    def FamilyData(self, families=[]):
        if families is None:
            families = [self.current]
        all = self.make_familylist(families)
        superdict = {}
        for f in all:
            superdict.update(self.env.make_tagdict(f))
        return superdict
            
        
            
    def make_familylist(self, families):
        deps = families
        all = list(self.get_related_families(families))
        setfun = self.set_family
        parfun = self.parents
        return make_deplist(deps, all, setfun, parfun)

    def export_family(self, family=None):
        if family is None:
            family = self.current
        element = FamilyElement(family)
        element.append_parents(self.parents(family))
        element.append_variables(self.environment_rows(family))
#.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:103,代码来源:main.py

示例6: add_new_kernel

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_new_kernel(conn, kernel):
    cursor = StatementCursor(conn)
    data = dict(kernel=kernel)
    cursor.insert(table='kernels', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:6,代码来源:oldmain.py

示例7: PaellaProfiles

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class PaellaProfiles(Element):
    def __init__(self, conn):
        Element.__init__(self, 'profiles')
        self.conn = conn
        self.stmt = StatementCursor(self.conn)
        self.env = ProfileEnvironment(self.conn)
        self.profiletraits = ProfileTrait(self.conn)
        self._profiles = {}
        self._profile = Profile(self.conn)
        
        for row in self.stmt.select(table='profiles', order='profile'):
            self._append_profile(row.profile, row.suite)
                
    def _append_profile(self, profile, suite):
        element = self.export_profile(profile, suite)
        self._profiles[profile] = element
        self.appendChild(self._profiles[profile])

    def export_profile(self, profile, suite=None):
        if suite is None:
            row = self.stmt.select_row(table='profiles',clause=Eq('profile', profile))
            suite = row['suite']
        suite = str(suite)
        profile = str(profile)
        self.env.set_profile(profile)
        element = ProfileElement(profile, suite)
        element.append_traits(self.profiletraits.trait_rows(profile))
        element.append_families(self._profile.family_rows(profile))
        element.append_variables(self.env.get_rows())
        return element

    def insert_profile(self, profile):
        idata = {'profile' : profile.name,
                 'suite' : profile.suite}
        self.stmt.insert(table='profiles', data=idata)
        idata = {'profile' : profile.name,
                 'trait' : None,
                 'ord' : 0}
        for trait, ord in profile.traits:
            print trait, ord
            idata['trait'] = trait
            idata['ord'] = ord #str(ord)
            self.stmt.insert(table='profile_trait', data=idata)
        idata = {'profile' : profile.name,
                 'trait' : None,
                 'name' : None,
                 'value': None}
        idata = dict(profile=profile.name)
        for family in profile.families:
            idata['family'] = family
            self.stmt.insert(table='profile_family', data=idata)
        idata = dict(profile=profile.name)
        for trait, name, value in profile.vars:
            idata['trait'] = trait
            idata['name'] = name
            idata['value'] = value
            self.stmt.insert(table='profile_variables', data=idata)

    def export_profiles(self, path):
        rows = self.stmt.select(fields='profile', table='profiles', clause=None)
        for row in rows:
            self.write_profile(row.profile, path)
        
    def write_profile(self, profile, path):
        xmlfile = file(join(path, '%s.xml' % profile), 'w')
        data = self.export_profile(profile)
        data.writexml(xmlfile, indent='\t', newl='\n', addindent='\t')
        xmlfile.close()
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:70,代码来源:xmlgen.py

示例8: RelationalBrowser

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class RelationalBrowser(ListNoteBook, HasDialogs):
    def __init__(self, conn, maintable, reltable, pkey, fields):
        self.menu = make_menu(['insert', 'update', 'done'], self.pkey_command)
        ListNoteBook.__init__(self)
        self.conn = conn
        self.main = StatementCursor(self.conn)
        self.main.set_table(maintable)
        self.rel = StatementCursor(self.conn)
        self.rel.set_table(reltable)
        self.pkey = pkey
        self._fields = fields
        self.fields = [self.pkey] + self._fields
        self.reset_rows()
        self.dialogs = {}.fromkeys(['insert', 'update', 'delete'])
        self.relmenu = make_menu(['insert', 'update', 'delete'], self.relmenu_command)
        
        
    def reset_rows(self):
        self.set_rows(self.main.select(order=self.pkey))
        self.set_row_select(self.pkey_selected)
        
    def pkey_selected(self, listbox, row, column, event):
        value = listbox.get_selected_data()[0][0]
        self.current_value = value
        if value not in self.pages:
            rows  = self.rel.select(clause=Eq(self.pkey, value), order=self.pkey)
            rtable = ScrollCList(rcmenu=self.relmenu)
            rtable.set_rows(rows)
            self.append_page(rtable, value)
        self.set_current_page(value)

    def pkey_command(self, menuitem, command):
        if command == 'insert':
            if self.dialogs['insert'] is None:
                dialog = dialogs.Entry('insert a %s' % self.pkey, name='insert')
                dialog.set_ok(self.pkey_insert_ok)
                dialog.set_cancel(self.destroy_dialog)
                self.dialogs['insert'] = dialog
        elif command == 'update':
            dialogs.Message('need to set update to cascade in db')
        elif command == 'done':
            value = None
            try:
                value = self.listbox.get_selected_data()[0][0]
            except IndexError:
                dialogs.Message('need to select %s first' % self.pkey)
            if value is not None:
                self.remove_page(value)
                

    def pkey_insert_ok(self, *args):
        dialog = self.dialogs['insert'] 
        value = dialog.get()
        print value
        try:
            self.main.insert(data={self.pkey : value})
            inserted = True
        except OperationalError:
            dialogs.Message('bad query\n%s is not allowed' % value)
        if inserted:
            self.destroy_dialog(dialog)
            self.reset_rows()
            
    def relmenu_command(self, menuitem, command):
        print command
        if command in ['insert', 'update', 'delete']:
            if self.dialogs[command] is None:
                clause = Eq(self.pkey, self.current_value)
                try:
                    row = self.rel.select(clause=clause)[0]
                except IndexError:
                    row = dict.fromkeys(self.fields)
                row[self.pkey] = self.current_value
                if command in ['insert', 'delete']:
                    fields = self.fields
                    clause = None
                else:
                    fields = self._fields
                    clause = Eq(self.pkey, self.current_value)
                make_record_dialog(self, command, row,
                                   self.relmenu_command_selected,
                                   self.pkey, fields, {command:command})
            print self.dialogs.items()
    

    def relmenu_command_selected(self, button, *data):
        command = button.get_name()
        dialog = self.dialogs[command]
        items = dialog.items()
        if command == 'insert':
            self.rel.insert(data=dict(items))
        elif command == 'delete':
            print 'delete delete delete delete'
            clause = SimpleClause(items, '=', 'and')
            dialogs.Message(self.rel.stmt.delete(clause=clause))
            
        if False:
            dialog = self.dialogs['insert']
            print dialog
            items = dialog.items()
#.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:103,代码来源:simple.py

示例9: add_new_filesystem

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_new_filesystem(conn, filesystem):
    cursor = StatementCursor(conn)
    data = dict(filesystem=filesystem)
    cursor.insert(table='filesystems', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:6,代码来源:oldmain.py

示例10: add_machine_type

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_machine_type(conn, mtype):
    cursor = StatementCursor(conn)
    data = dict(machine_type=mtype)
    cursor.insert(table='machine_types', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:6,代码来源:oldmain.py

示例11: add_disk_to_machine_type

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_disk_to_machine_type(conn,
                             diskname, mtype, device='/dev/hda'):
    cursor = StatementCursor(conn)
    data = dict(machine_type=mtype, diskname=diskname,
                device=device)
    cursor.insert(table='machine_disks', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:8,代码来源:oldmain.py

示例12: make_a_machine

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def make_a_machine(conn, machine, mtype, profile, fs):
    cursor = StatementCursor(conn)
    data = dict(machine=machine, machine_type=mtype,
                profile=profile, filesystem=fs)
    cursor.insert(table='machines', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:7,代码来源:oldmain.py

示例13: add_mount_to_filesystem

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
def add_mount_to_filesystem(conn, mnt_name, filesystem, ord, partition, size):
    cursor = StatementCursor(conn)
    data = dict(mnt_name=mnt_name, filesystem=filesystem,
                ord=str(ord), partition=partition, size=size)
    cursor.insert(table='filesystem_mounts', data=data)
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:7,代码来源:oldmain.py

示例14: BaseDatabase

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class BaseDatabase(QSqlDatabase):
    def __init__(self, dsn, name, parent=None, objname=None):
        deprecated('useless.kdedb.BaseDatabase is deprecated')
        QSqlDatabase.__init__(self, 'QPSQL7', name, parent, objname)
        if hasattr(dsn, 'items'): #if dsn is dictionary
            self.conn = BasicConnection(**dsn)
            self.setDatabaseName(dsn['dbname'])
            self.setHostName(dsn['host'])
            self.dbuser = dsn['user']
        else: #else a conn was passed as dsn
            self.conn = dsn
            self.setDatabaseName(self.conn.conn.db)
            self.setHostName(self.conn.conn.host)
            self.dbuser = self.conn.conn.user
        self.setUserName(self.dbuser)
        self.stmt = Statement()
        self.mcursor = StatementCursor(self.conn)
        
    def set_table(self, table):
        self.stmt.table = table

    def set_clause(self, items, cmp='=', join='and'):
        self.stmt.set_clause(items, cmp=cmp, join=join)

    def set_data(self, data):
        self.stmt.set(data)

    def set_fields(self, fields):
        self.stmt.fields = fields

    def qdelete(self, table=None, clause=None):
        query = self.stmt.delete(table=table, clause=clause)
        return self.execStatement(query)

    def qinsert(self, table=None, data=None):
        query = self.stmt.insert(table=table, data=data)
        return self.execStatement(query)

    def qupdate(self, table=None, data=None, clause=None):
        query = self.stmt.update(table=table, data=data, clause=clause)
        return self.execStatement(query)

    def qselect(self, fields=None, table=None, clause=None,
               group=None, having=None, order=None):
        query = self.stmt.select(fields=fields, table=table, clause=clause,
                                 group=group, having=having, order=order)
        return self.execStatement(query)

    def delete(self, table=None, clause=None):
        query = self.stmt.delete(table=table, clause=clause)
        return self.mcursor.execute(query)

    def insert(self, table=None, data=None):
        query = self.stmt.insert(table=table, data=data)
        return self.mcursor.execute(query)

    def update(self, table=None, data=None, clause=None):
        query = self.stmt.update(table=table, data=data, clause=clause)
        return self.mcursor.execute(query)

    def select(self, fields=None, table=None, clause=None,
               group=None, having=None, order=None):
        query = self.stmt.select(fields=fields, table=table, clause=clause,
                                 group=group, having=having, order=order)
        self.mcursor.execute(query)
        return self.mcursor.fetchall()

    def select_row(self, fields=None, table=None, clause=None,
               group=None, having=None, order=None):
        query = self.stmt.select(fields=fields, table=table, clause=clause,
                                 group=group, having=having, order=order)
        self.mcursor.execute(query)
        rows = len(self.mcursor)
        if rows == 1:
            return self.mcursor.next()
        elif rows == 0:
            raise NoExistError
        else:
            raise RuntimeError, 'bad row count %s' % rows

    def clear(self, **args):
        self.stmt.clear(**args)

    def stdclause(self, data):
        return reduce(and_, [Eq(k, v) for k,v in data.items()])

    def insertData(self, idcol, table, data, commit=True):
        clause = self.stdclause(data)
        try:
            self.mcursor.select_row(fields=[idcol], table=table, clause=clause)
        except NoExistError:
            self.mcursor.insert(table=table, data=data)
            if commit:
                self.conn.commit()
            
    def identifyData(self, idcol, table, data, commit=True):
        clause = self.stdclause(data)
        self.insertData(idcol, table, data, commit=commit)
        return self.mcursor.select_row(fields=['*'], table=table, clause=clause)
开发者ID:BackupTheBerlios,项目名称:useless-svn,代码行数:101,代码来源:__init__.py

示例15: VariablesConfig

# 需要导入模块: from useless.db.midlevel import StatementCursor [as 别名]
# 或者: from useless.db.midlevel.StatementCursor import insert [as 别名]
class VariablesConfig(RawConfigParser):
    def __init__(self, conn, table, section, mainfield=None, mainvalue=None, option="name", value="value"):
        self.conn = conn
        self.cursor = StatementCursor(self.conn)
        self.cursor.set_table(table)
        self._secfield = section
        bothnone = mainfield is None and mainvalue is None
        bothset = mainfield and mainvalue
        if not bothnone and not bothset:
            raise Error, "both mainfield and mainvalue need to be set/unset"
        self._mainclause = None
        if bothset:
            self._mainclause = Eq(mainfield, mainvalue)
        self._fields = [self._secfield, option, value]
        RawConfigParser.__init__(self)
        for row in self.cursor.select(fields=self._fields, clause=self._mainclause):
            if row[0] not in self.sections():
                self.add_section(row[0])
            self.set(*row)

    def write(self, cfile):
        sections = self.sections()
        sections.sort()
        for section in sections:
            cfile.write("[%s]\n" % section)
            keys = self.options(section)
            keys.sort()
            for k in keys:
                if k != "__name__":
                    v = str(self.get(section, k)).replace("\n", "\n\t")
                    cfile.write("%s:\t%s\n" % (k, v))
            cfile.write("\n")

    def edit(self):
        tmp, path = tempfile.mkstemp("variables", "config")
        tmp = file(path, "w")
        self.write(tmp)
        tmp.close()
        os.system("$EDITOR %s" % path)
        tmp = file(path, "r")
        newconfig = RawConfigParser()
        newconfig.readfp(tmp)
        tmp.close()
        os.remove(path)
        return newconfig

    def diff(self, other):
        ltmp, lpath = tempfile.mkstemp("variables", "config")
        ltmp = file(lpath, "w")
        self.write(ltmp)
        ltmp.close()
        rtmp, rpath = tempfile.mkstemp("variables", "config")
        rtmp = file(rpath, "w")
        other.write(rtmp)
        rtmp.close()
        os.system("xxdiff %s %s" % (lpath, rpath))
        ltmp, rtmp = file(lpath, "r"), file(rpath, "r")
        lcfg, rcfg = RawConfigParser(), RawConfigParser()
        lcfg.readfp(ltmp)
        rcfg.readfp(rtmp)
        ltmp.close()
        rtmp.close()
        self.update(lcfg)
        other.update(rcfg)

    def update(self, newconfig):
        removed = [x for x in self.sections() if x not in newconfig.sections()]
        for section in removed:
            print "removing", section
            sclause = Eq(self._secfield, section)
            if self._mainclause:
                sclause &= self._mainclause
            self.cursor.delete(clause=sclause)
        for section in newconfig.sections():
            print section
            sclause = Eq(self._secfield, section)
            if self._mainclause:
                sclause = self._mainclause & Eq(self._secfield, section)
            if not self.has_section(section):
                for k, v in newconfig.items(section):
                    idata = dict(zip(self._fields, [section, k, v]))
                    if self._mainclause:
                        idata[self._mainclause.left] = self._mainclause.right
                    print idata
                    self.cursor.insert(data=idata)
            else:
                for name, value in newconfig.items(section):
                    nclause = sclause & Eq(self._fields[1], name)
                    # print 'nclause', nclause
                    # print 'value', self.get(section, name)
                    if self.has_option(section, name):
                        if value != self.get(section, name):
                            # print 'updating'
                            self.cursor.update(data={self._fields[2]: value}, clause=nclause)
                    else:
                        idata = dict(zip(self._fields, [section, name, value]))
                        if self._mainclause:
                            idata[self._mainclause.left] = self._mainclause.right
                        self.cursor.insert(data=idata)
                    if self.has_section(section):
#.........这里部分代码省略.........
开发者ID:BackupTheBerlios,项目名称:paella-svn,代码行数:103,代码来源:oldbase.py


注:本文中的useless.db.midlevel.StatementCursor.insert方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。