本文整理汇总了Python中trac.db.DatabaseManager类的典型用法代码示例。如果您正苦于以下问题:Python DatabaseManager类的具体用法?Python DatabaseManager怎么用?Python DatabaseManager使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DatabaseManager类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: setUp
def setUp(self):
self.env = EnvironmentStub(enable=['trac.*', 'bitten.notify.*',
'bitten.tests.notify.*'])
db = self.env.get_db_cnx()
cursor = db.cursor()
connector, _ = DatabaseManager(self.env)._get_connector()
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
db.commit()
# Hook up a dummy repository
self.repos = Mock(
get_changeset=lambda rev: Mock(author='author', rev=rev),
normalize_rev=lambda rev: rev)
self.env.get_repository = lambda authname=None: self.repos # 0.11
try: # 0.12+
from trac.core import Component, implements
from trac.versioncontrol.api import IRepositoryConnector, \
IRepositoryProvider
class DummyRepos(Component):
implements(IRepositoryConnector, IRepositoryProvider)
def get_supported_types(self):
yield ('dummy', 9)
def get_repository(this, repos_type, repos_dir, params):
return self.repos # Note: 'this' vs 'self' usage
def get_repositories(self):
yield ('', {'dir': 'dummy_dir', 'type': 'dummy'})
self.dummy = DummyRepos
except ImportError:
self.dummy = None # not supported, will use get_repository()
开发者ID:hefloryd,项目名称:bitten,代码行数:32,代码来源:notify.py
示例2: create_table
def create_table(env, table, conn=None):
"""
Creates a the given table in the given environment. The Table
has to be of type trac.db.Table, and the Environment a
trac.env.Environment.
"""
assert isinstance(env, Environment), \
"[DB]: env should be an instance of trac.env.Environment, got %s" % type(env)
assert isinstance(table, Table), \
"[DB]: table should be an instance of trac.sb.Table, got %s" % type(table)
# Get The Databse Manager
dbm = DatabaseManager(env)
# Get the Connector Object for the current DB schema
connector, args = dbm._get_connector()
# Ask the connector to generate the proper DDL for the table
ddl_gen = connector.to_sql(table)
# Get a DB Connection from the pool, create a cursor and the table
conn, handle_ta = get_db_for_write(env, conn)
try:
cursor = conn.cursor()
for statement in ddl_gen:
debug(env, "[DB]: Table: %s\n%s" % (table.name, statement))
cursor.execute(statement)
if handle_ta:
conn.commit()
debug(env, "[DB]: Successfully Created Table %s" % table.name)
except Exception, e:
if handle_ta:
conn.rollback()
error(env, "[DB]: Unable to Create Table %s, an error occurred: %s" % \
(table.name, exception_to_unicode(e)))
raise
开发者ID:djangsters,项目名称:agilo,代码行数:32,代码来源:db.py
示例3: setUp
def setUp(self):
self.env = EnvironmentStub(enable=['trac.*', 'bitten.*'])
self.env.path = tempfile.mkdtemp()
db = self.env.get_db_cnx()
cursor = db.cursor()
connector, _ = DatabaseManager(self.env)._get_connector()
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
self.config = BuildConfig(self.env, name='test', path='somepath')
self.config.insert(db=db)
self.platform = TargetPlatform(self.env, config='test', name='Foo')
self.platform.insert(db=db)
db.commit()
# Hook up a dummy repository
self.repos = Mock()
self.env.get_repository = lambda authname=None: self.repos # 0.11
try: # 0.12+
from trac.core import Component, implements
from trac.versioncontrol.api import IRepositoryConnector, \
IRepositoryProvider
class DummyRepos(Component):
implements(IRepositoryConnector, IRepositoryProvider)
def get_supported_types(self):
yield ('dummy', 9)
def get_repository(this, repos_type, repos_dir, params):
return self.repos # Note: 'this' vs 'self' usage
def get_repositories(self):
yield ('', {'dir': 'dummy_dir', 'type': 'dummy'})
self.dummy = DummyRepos
except ImportError:
self.dummy = None # not supported, will use get_repository()
开发者ID:hefloryd,项目名称:bitten,代码行数:35,代码来源:queue.py
示例4: do_upgrade
def do_upgrade(env, cursor):
db_connector, _ = DatabaseManager(env)._get_connector()
# Backup old topic table
cursor.execute("CREATE TEMPORARY TABLE topic_old AS "
"SELECT * "
"FROM topic")
cursor.execute("DROP TABLE topic")
# Create tables.
for table in tables:
for statement in db_connector.to_sql(table):
cursor.execute(statement)
# Add two columns that uses constraints.
# TODO: No other way how to do it.
cursor.execute("ALTER TABLE topic ADD COLUMN status INT DEFAULT 0 NOT NULL")
cursor.execute("ALTER TABLE topic ADD COLUMN priority INT DEFAULT 0 NOT NULL")
# Copy old topics.
cursor.execute("INSERT INTO topic "
"(id, forum, time, author, subscribers, subject, body, "
"status, priority) "
"SELECT id, forum, time, author, subscribers, subject, "
"body, 0, 0 "
"FROM topic_old")
cursor.execute("DROP TABLE topic_old")
# Set database schema version.
cursor.execute("UPDATE system "
"SET value = '5' "
"WHERE name = 'discussion_version'")
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:db5.py
示例5: do_upgrade
def do_upgrade(env, cursor):
db_connector, _ = DatabaseManager(env)._get_connector()
# Backup old forum table.
cursor.execute("CREATE TEMPORARY TABLE forum_old AS "
"SELECT * "
"FROM forum")
cursor.execute("DROP TABLE forum")
# Create tables.
for table in tables:
for statement in db_connector.to_sql(table):
cursor.execute(statement)
# Copy old forums.
cursor.execute("INSERT INTO forum "
"(id, name, time, moderators, subject, description) "
"SELECT id, name, time, moderators, subject, description "
"FROM forum_old")
cursor.execute("DROP TABLE forum_old")
# Set database schema version.
cursor.execute("UPDATE system "
"SET value = '2' "
"WHERE name = 'discussion_version'")
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:25,代码来源:db2.py
示例6: do_upgrade
def do_upgrade(env):
""" Upgrade the database schema so that it is compatible with version 1
of the plugin.
:param env: the current Trac environment
"""
db_connector, _ = DatabaseManager(env)._get_connector()
db = env.get_db_cnx()
cursor = db.cursor()
# add 'ticket_split' table to the schema
split_ticket_table = Table('ticket_split', key=('ticket', 'split_to'))[
Column('ticket', type='int'),
Column('split_to', type='int'),
Column('split_at', type='int')
]
for statement in db_connector.to_sql(split_ticket_table):
cursor.execute(statement)
# update stored schema version for the plugin
sql = ("INSERT INTO system(name, value) "
"VALUES ('splitticket_plugin_version', '1')")
cursor.execute(sql)
开发者ID:trac-hacks,项目名称:trac-split-ticket,代码行数:26,代码来源:db1.py
示例7: upgrade_environment
def upgrade_environment(self, db):
self.log.debug("Upgrading schema for bi history plugin")
cursor = db.cursor()
db_connector, _ = DatabaseManager(self.env).get_connector()
found_version = self._check_schema_version(db)
if not found_version:
# Create tables
self.environment_created()
elif found_version == 2:
# We've not released anywhere yet, so this seems more practical
# than writing a database-agnostic way to convert the isclosed column
cursor.execute("DROP table ticket_bi_historical")
for table in self.schema:
for statement in db_connector.to_sql(table):
cursor.execute(statement)
cursor.execute("UPDATE system SET value = %s WHERE name = 'bi_history_schema'",
(str(self._schema_version),))
elif found_version == 3:
cursor.execute("CREATE INDEX ticket_bi_historical_isclosed "
"ON ticket_bi_historical (isclosed)")
cursor.execute("CREATE INDEX ticket_bi_historical_id "
"ON ticket_bi_historical (id)")
cursor.execute("CREATE INDEX ticket_bi_historical_milestone "
"ON ticket_bi_historical (milestone)")
cursor.execute("UPDATE system SET value = %s "
"WHERE name = 'bi_history_schema'",
(str(self._schema_version),))
elif found_version == 4:
if self.env.config.get('trac', 'database').startswith('postgres'):
cursor.execute("ALTER TABLE ticket_bi_historical ALTER COLUMN _snapshottime SET NOT NULL")
cursor.execute("UPDATE system SET value = %s "
"WHERE name = 'bi_history_schema'",
(str(self._schema_version),))
开发者ID:CGI-define-and-primeportal,项目名称:trac-plugin-kettle,代码行数:35,代码来源:history.py
示例8: do_upgrade
def do_upgrade(env, ver, cursor):
"""Add new table for tag change records."""
connector = DatabaseManager(env)._get_connector()[0]
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
开发者ID:t-kenji,项目名称:trac-tags-plugin,代码行数:7,代码来源:db4.py
示例9: add_ticket_template_store
def add_ticket_template_store(env, db):
"""Add table ticket_template_store."""
from tickettemplate.model import schema, schema_version, TT_Template
from trac.db import DatabaseManager
connector, _ = DatabaseManager(env)._get_connector()
cursor = db.cursor()
table = schema[0]
for stmt in connector.to_sql(table):
try:
cursor.execute(stmt)
except:
pass
from default_templates import DEFAULT_TEMPLATES
from ttadmin import SYSTEM_USER
now = int(time.time())
for tt_name, tt_value in DEFAULT_TEMPLATES:
record = (now, SYSTEM_USER, tt_name, "description", tt_value,)
TT_Template.insert(env, record)
for id, modi_time, tt_name, tt_text in cursor.fetchall():
record = (modi_time, SYSTEM_USER, tt_name, "description", tt_text,)
TT_Template.insert(env, record)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:26,代码来源:upgrades.py
示例10: test_db_table
def test_db_table():
# Create a EnvironmentStub
env = EnvironmentStub()
# Create a test table
table = Table('test', key=['id'])[
Column('id', type='integer'),
Column(Key.NAME, type='text')
]
# Get The Databse Manager
dbm = DatabaseManager(env)
# Get the Connector Object for the current DB schema
connector, args = dbm._get_connector()
# Ask the connector to generate the proper DDL for the table
ddl_gen = connector.to_sql(table)
# Get a DB Connection from the pool, create a cursor and the table
conn = dbm.get_connection()
try:
cursor = conn.cursor()
for statement in ddl_gen:
print "Table: %s\n%s" % (table.name, statement)
cursor.execute(statement)
conn.commit()
print "Successfully Created Table %s" % table.name
except Exception, e:
conn.rollback()
print "[ERROR]: Unable to Create Table %s, an error occurred: %s" % \
(table.name, str(e))
开发者ID:djangsters,项目名称:agilo,代码行数:28,代码来源:breaking_env.py
示例11: upgrade_environment
def upgrade_environment(self, db):
if not type(self).__dict__.get('applySchema', False):
self.log.debug("""Not updating schema for \"%s\",
since applySchema is not defined or is False.
""" % type(self).__name__)
return
installed = self.get_installed_version(db)
if installed is None:
self.log.info(
'Installing TracForm plugin schema %s' % db_version)
db_connector, _ = DatabaseManager(self.env)._get_connector()
db = self._get_db(db)
cursor = db.cursor()
for table in schema:
for stmt in db_connector.to_sql(table):
cursor.execute(stmt)
self.set_installed_version(db, db_version)
self.log.info('Installation of %s successful.' % db_version)
return
self.log.debug(
'Upgrading schema for "%s".' % type(self).__name__)
for version, fn in self.get_schema_functions():
if version > installed:
self.log.info(
'Upgrading TracForm plugin schema to %s' % version)
self.log.info('- %s: %s' % (fn.__name__, fn.__doc__))
db = self._get_db(db)
cursor = db.cursor()
fn(self.env, cursor)
self.set_installed_version(db, version)
installed = version
self.log.info('Upgrade to %s successful.' % version)
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:32,代码来源:tracdb.py
示例12: upgrade_environment
def upgrade_environment(self, db):
old_version = current_version = self.get_version(db)
db_connector, dummy = DatabaseManager(self.env)._get_connector()
while current_version < self.version:
if current_version > 0:
db("CREATE TEMPORARY TABLE dummy_table_old AS "
"SELECT * FROM dummy_table")
db("DROP TABLE dummy_table")
table = self.construct_dummy_table(current_version+1)
for statement in db_connector.to_sql(table):
db(statement)
if current_version > 0:
cols = ['id'] + ['v%i' % (i+1)
for i in range(current_version+1)]
db("""INSERT INTO dummy_table (%s)
SELECT %s, '' FROM dummy_table_old
""" % (', '.join(cols), ', '.join(cols[:-1])))
db("DROP TABLE dummy_table_old")
current_version += 1
if current_version != old_version:
self.update_version(db, current_version)
开发者ID:thimalk,项目名称:bloodhound,代码行数:26,代码来源:upgrade.py
示例13: do_upgrade
def do_upgrade(env, ver, cursor):
"""Changes to subscription db table:
- 'subscriptions.destination', 'subscriptions.format'
+ 'subscriptions.authenticated', 'subscriptions.transport'
'subscriptions.managed' type='int' --> (default == char)
"""
cursor.execute("""
CREATE TEMPORARY TABLE subscriptions_old
AS SELECT * FROM subscriptions
""")
cursor.execute("DROP TABLE subscriptions")
connector = DatabaseManager(env)._get_connector()[0]
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
cursor.execute("""
INSERT INTO subscriptions
(sid,authenticated,enabled,managed,
realm,category,rule,transport)
SELECT o.sid,s.authenticated,o.enabled,'watcher',
o.realm,o.category,rule,'email'
FROM subscriptions_old AS o
LEFT JOIN session AS s
ON o.sid=s.sid
""")
cursor.execute("DROP TABLE subscriptions_old")
开发者ID:lkraav,项目名称:trachacks,代码行数:28,代码来源:db2.py
示例14: _create_multiproduct_tables
def _create_multiproduct_tables(self, db):
self.log.debug("Creating initial db tables for %s plugin." %
PLUGIN_NAME)
db_connector, dummy = DatabaseManager(self.env)._get_connector()
for table in self.SCHEMA:
for statement in db_connector.to_sql(table):
db(statement)
开发者ID:thimalk,项目名称:bloodhound-789,代码行数:7,代码来源:api.py
示例15: setUp
def setUp(self):
self.env = EnvironmentStub()
if hasattr(self.env, 'dburi'):
# Trac gained support for testing against different databases in 0.11.5
# If this support is available, we copy the test db uri configuration
# into the main test config so it can be picked up by
# upgrades.parse_scheme()
self.env.config.set('trac', 'database', self.env.dburi)
self.env.path = tempfile.mkdtemp()
logs_dir = self.env.config.get("bitten", "logs_dir", "log/bitten")
if os.path.isabs(logs_dir):
raise ValueError("Should not have absolute logs directory for temporary test")
logs_dir = os.path.join(self.env.path, logs_dir)
self.logs_dir = logs_dir
db = self.env.get_db_cnx()
cursor = db.cursor()
for table_name in self.other_tables:
cursor.execute("DROP TABLE IF EXISTS %s" % (table_name,))
connector, _ = DatabaseManager(self.env)._get_connector()
for table in self.schema:
cursor.execute("DROP TABLE IF EXISTS %s" % (table.name,))
for stmt in connector.to_sql(table):
cursor.execute(stmt)
db.commit()
开发者ID:hefloryd,项目名称:bitten,代码行数:28,代码来源:upgrades.py
示例16: setUp
def setUp(self):
self.env = EnvironmentStub(enable=['trac.*', 'bitten.*'])
self.env.path = tempfile.mkdtemp()
# Create tables
db = self.env.get_db_cnx()
cursor = db.cursor()
connector, _ = DatabaseManager(self.env)._get_connector()
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
# Set up permissions
self.env.config.set('trac', 'permission_store',
'DefaultPermissionStore')
PermissionSystem(self.env).grant_permission('joe', 'BUILD_ADMIN')
if DefaultPermissionPolicy is not None and hasattr(DefaultPermissionPolicy, "CACHE_EXPIRY"):
self.old_perm_cache_expiry = DefaultPermissionPolicy.CACHE_EXPIRY
DefaultPermissionPolicy.CACHE_EXPIRY = -1
# Hook up a dummy repository
self.repos = Mock(
get_node=lambda path, rev=None: Mock(get_history=lambda: [],
isdir=True),
normalize_path=lambda path: path,
sync=lambda: None
)
self.env.get_repository = lambda authname=None: self.repos
开发者ID:lkraav,项目名称:trachacks,代码行数:28,代码来源:admin.py
示例17: do_upgrade
def do_upgrade(env, ver, cursor):
"""Convert time values from integer seconds to integer microseconds."""
tables = [
('attachment', {'time': ('int', 'int64')}),
('wiki', {'time': ('int', 'int64')}),
('revision', {'time': ('int', 'int64')}),
('ticket', {'time': ('int', 'int64'),
'changetime': ('int', 'int64')}),
('ticket_change', {'time': ('int', 'int64')}),
('milestone', {'due': ('int', 'int64'),
'completed': ('int', 'int64')}),
('version', {'time': ('int', 'int64')}),
]
db_connector, _ = DatabaseManager(env).get_connector()
db = env.get_db_cnx()
for table, columns in tables:
# Alter column types
for sql in db_connector.alter_column_types(table, columns):
cursor.execute(sql)
# Convert timestamps to microseconds
cursor.execute("UPDATE %s SET %s" % (table,
', '.join("%s=%s*1000000" % (column, column)
for column in columns)))
# Convert comment edit timestamps to microseconds
cursor.execute("UPDATE ticket_change SET newvalue=%s*1000000 "
"WHERE field %s" % (db.cast('newvalue', 'int64'),
db.like()),
('_comment%',))
开发者ID:wiraqutra,项目名称:photrackjp,代码行数:31,代码来源:db25.py
示例18: environment_created
def environment_created(self):
# Create the required tables
db = self.env.get_db_cnx()
connector, _ = DatabaseManager(self.env)._get_connector()
cursor = db.cursor()
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
# Insert a global version flag
cursor.execute("INSERT INTO system (name,value) "
"VALUES ('tt_version',%s)", (schema_version,))
# Create some default templates
now = int(time.time())
from default_templates import DEFAULT_TEMPLATES
for tt_name, tt_value in DEFAULT_TEMPLATES:
record = [
now,
SYSTEM_USER,
tt_name,
"description",
tt_value,
]
TT_Template.insert(self.env, record)
db.commit()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:27,代码来源:ttadmin.py
示例19: setUp
def setUp(self):
self.env = EnvironmentStub(enable=['trac.*', 'bitten.*'])
self.env.path = tempfile.mkdtemp()
# Create tables
db = self.env.get_db_cnx()
cursor = db.cursor()
connector, _ = DatabaseManager(self.env)._get_connector()
for table in schema:
for stmt in connector.to_sql(table):
cursor.execute(stmt)
# Set up permissions
self.env.config.set('trac', 'permission_store',
'DefaultPermissionStore')
# Hook up a dummy repository
self.repos = Mock(
get_node=lambda path, rev=None: Mock(get_history=lambda: [],
isdir=True),
normalize_path=lambda path: path,
sync=lambda: None,
)
self.repos.authz = Mock(has_permission=lambda path: True, assert_permission=lambda path: None)
self.env.get_repository = lambda authname=None: self.repos
开发者ID:blaxter,项目名称:Bitten,代码行数:25,代码来源:web_ui.py
示例20: upgrade_to_0_2_4
def upgrade_to_0_2_4(env, db, installed_version):
if installed_version>=[0,2,4]:
return True
milestones_shema_ext = [
Table('milestone_change', key=('milestone', 'time', 'field'))[
Column('milestone'),
Column('time', type='int'),
Column('author'),
Column('field'),
Column('oldvalue'),
Column('newvalue'),
Index(['milestone']),
Index(['time'])],
Table('milestone_custom', key=('milestone', 'name'))[
Column('milestone'),
Column('name'),
Column('value')]
]
db = db or env.get_db_cnx()
cursor = db.cursor()
db_backend, _ = DatabaseManager(env)._get_connector()
for table in milestones_shema_ext:
for stmt in db_backend.to_sql(table):
cursor.execute(stmt)
return True
开发者ID:esogs,项目名称:IttecoTracPlugin,代码行数:29,代码来源:config2.py
注:本文中的trac.db.DatabaseManager类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论