Merge lp:~stefanor/ibid/db-import-export into lp:~ibid-core/ibid/old-trunk-pack-0.92

Proposed by Stefano Rivera
Status: Superseded
Proposed branch: lp:~stefanor/ibid/db-import-export
Merge into: lp:~ibid-core/ibid/old-trunk-pack-0.92
Diff against target: None lines
To merge this branch: bzr merge lp:~stefanor/ibid/db-import-export
Reviewer Review Type Date Requested Status
Ibid Core Team Pending
Review via email: mp+9844@code.launchpad.net

This proposal has been superseded by a proposal from 2009-08-07.

To post a comment you must log in.
lp:~stefanor/ibid/db-import-export updated
728. By Stefano Rivera

DC: Treat a share of '' as 0
https://code.edge.launchpad.net/~stefanor/ibid/dc-null-share/+merge/9369

729. By Stefano Rivera

"dict" is now a synonym for "define" (for those command-driven-bot users)
https://code.edge.launchpad.net/~stefanor/ibid/dict-synonym-405702/+merge/9358

730. By Stefano Rivera

Some improvements to and use of human_join
https://code.edge.launchpad.net/~stefanor/ibid/human-join-generator/+merge/9317

731. By Stefano Rivera

Don't pick up e-mail addresses even with three domain components
https://code.edge.launchpad.net/~stefanor/ibid/url-za-net-403172/+merge/9158

732. By Stefano Rivera

MLIA page layout changed.
https://code.edge.launchpad.net/~stefanor/ibid/mlia-410481/+merge/9856

733. By Stefano Rivera

ibid-plugin wasn't unusable when load is specified in the config file
https://code.edge.launchpad.net/~stefanor/ibid/ibid-plugin-407386/+merge/9509

734. By Stefano Rivera

Bnet: Allow whitespace in game name and channel
https://code.edge.launchpad.net/~stefanor/ibid/gameservers-dota-match/+merge/9461

735. By Michael Gorven

Add Zen of Python factpack.
https://code.launchpad.net/~mgorven/ibid/zen-factpack/+merge/9237

736. By Stefano Rivera

DC: The bot was seeing itself in the user-list
https://code.edge.launchpad.net/~stefanor/ibid/dc-self-410782/+merge/9880

737. By Stefano Rivera

Surround URLs in <brackets>, makes for slightly more parseable output
https://code.edge.launchpad.net/~stefanor/ibid/url-output-404159/+merge/9250

738. By Stefano Rivera

Allow "also" on either side of the factoid setting verb
https://code.edge.launchpad.net/~stefanor/ibid/factoid-407752/+merge/9537

739. By Stefano Rivera

* Stop Old SQLAlchemy 0.4 from doing cartesian join instead of inner join
* Add configurable SQLAlchemy echo mode
* Don't cascade account deletion to identities
https://code.edge.launchpad.net/~stefanor/ibid/identity-421169/+merge/10875

740. By Stefano Rivera

Use the Event.sender values more consistently:
['nick'] The name to use in messages
['id'] Uniquely identifies the person. Use for direct (out of the blue) messages
['connection'] Identify a connection. Use for all private replies

https://code.launchpad.net/~stefanor/ibid/event-sender-401485/+merge/9852

741. By Stefano Rivera

Log with the correct timezone difference rather than +0000.
Changes internal timestamps to datetime instances.
https://code.edge.launchpad.net/~stefanor/ibid/log-tz-417182/+merge/10881

742. By Stefano Rivera

Put PostgreSQL into UTC mode at connection time
https://code.launchpad.net/~stefanor/ibid/pg-tz-417184/+merge/10880

743. By Stefano Rivera

Handle unknown modes in MyINFO
https://code.launchpad.net/~stefanor/ibid/dc-414577/+merge/10878

744. By Stefano Rivera

Add a permission that allows users to speak to the bot in public.
Useful in busy channels when newbie<->bot traffic dwarfs everything else

https://code.launchpad.net/~stefanor/ibid/public-ignore/+merge/10043

745. By Stefano Rivera

* Log exception-causing event
* Simplify tvrage date conversion to allow for year-only information
https://code.launchpad.net/~stefanor/ibid/tvshow-412447/+merge/10021

746. By Michael Gorven

Add explicit URL lengthen command, and recognise more URL shortening services.
https://code.launchpad.net/~mgorven/ibid/url-services/+merge/10164

747. By Stefano Rivera

Catch XML systax error in FML, and move quote URLs to end of output
https://code.launchpad.net/~stefanor/ibid/fml-421146/+merge/11005

748. By Stefano Rivera

Don't walk into strings, only dictionaries, in config get and set
https://code.launchpad.net/~stefanor/ibid/config-412937/+merge/11000

749. By Stefano Rivera

Mistake in TVRage merge

750. By Stefano Rivera

Reduce 'checking permission from cache' messages from INFO to DEBUG

751. By Michael Gorven

Make plugins.core.ignore a List Option.
https://code.launchpad.net/~mgorven/ibid/ignore-default-401009/+merge/11056

752. By Jonathan Hitchcock

minor update to INSTALL: wokkel is no longer shipped with ibid, needs to be installed - jabber is a core source

753. By Stefano Rivera

Don't try and download multiple copies of the same file.
https://code.launchpad.net/~stefanor/ibid/download-414574/+merge/11021

754. By Stefano Rivera

Don't include possibly ambiguous characters in auth token
https://code.launchpad.net/~stefanor/ibid/token-426349/+merge/11375

755. By Stefano Rivera

Don't use func.current_timestamp() - doesn't work when Postgres is used in UTC mode
and Timestamp columns are timezone-unaware.

https://code.launchpad.net/~stefanor/ibid/memo-date-426341/+merge/11374

756. By Stefano Rivera

Typo in memo-date-426341

757. By Stefano Rivera

Remove <brackets> from URLs. Use "text - URL" or "text. URL" instead
https://code.launchpad.net/~stefanor/ibid/prettyurl/+merge/12374

758. By Stefano Rivera

Add regex-based static-factoids.
https://code.launchpad.net/~stefanor/ibid/regex-factoids-397725/+merge/12379

759. By Stefano Rivera

Use Google's new country-specific API-search
https://code.launchpad.net/~stefanor/ibid/google-local-api/+merge/13270

760. By Stefano Rivera

Strip trailing white-space

763. By Stefano Rivera

Restore in correct dependancy order

764. By Stefano Rivera

Set sequence start values on restore for PostgreSQL

765. By Stefano Rivera

Increase index length on Unique identity constraint

766. By Stefano Rivera

Whitespace: setup.py

767. By Stefano Rivera

Install ibid-db

768. By Stefano Rivera

Whitespace

769. By Stefano Rivera

Unused import

770. By Stefano Rivera

Merge from trunk

771. By Stefano Rivera

Ignore header comment on import

772. By Stefano Rivera

ibid_import: Don't touch the Knab DB

773. By Stefano Rivera

ibid_import: Use local.ini

774. By Stefano Rivera

Check for over-length items

775. By Stefano Rivera

Double-guess chardet

776. By Stefano Rivera

Arbitrary length factoid names

777. By Stefano Rivera

Spelling

Unmerged revisions

777. By Stefano Rivera

Spelling

776. By Stefano Rivera

Arbitrary length factoid names

775. By Stefano Rivera

Double-guess chardet

774. By Stefano Rivera

Check for over-length items

773. By Stefano Rivera

ibid_import: Use local.ini

772. By Stefano Rivera

ibid_import: Don't touch the Knab DB

771. By Stefano Rivera

Ignore header comment on import

770. By Stefano Rivera

Merge from trunk

769. By Stefano Rivera

Unused import

768. By Stefano Rivera

Whitespace

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== modified file 'ibid/core.py'
2--- ibid/core.py 2009-07-15 22:28:01 +0000
3+++ ibid/core.py 2009-08-07 19:15:43 +0000
4@@ -218,7 +218,10 @@
5 else:
6 self.log.debug("Skipping Processor: %s.%s", name, klass.__name__)
7
8- ibid.models.check_schema_versions(ibid.databases['ibid'])
9+ try:
10+ ibid.models.check_schema_versions(ibid.databases['ibid'])
11+ except ibid.models.SchemaVersionException, e:
12+ self.log.error(u'Tables out of date: %s. Run "ibid-db --upgrade"', e.message)
13
14 except Exception, e:
15 self.log.exception(u"Couldn't instantiate %s processor of %s plugin", classname, name)
16@@ -284,7 +287,11 @@
17 self.load(database)
18
19 if check_schema_versions:
20- ibid.models.check_schema_versions(self['ibid'])
21+ try:
22+ ibid.models.check_schema_versions(self['ibid'])
23+ except ibid.models.SchemaVersionException, e:
24+ self.log.error(u'Tables out of date: %s. Run "ibid-db --upgrade"', e.message)
25+ raise
26
27 def load(self, name):
28 uri = ibid.config.databases[name]
29
30=== modified file 'ibid/models.py'
31--- ibid/models.py 2009-07-14 21:11:49 +0000
32+++ ibid/models.py 2009-08-07 19:15:43 +0000
33@@ -509,6 +509,14 @@
34 def __repr__(self):
35 return '<Account %s>' % self.username
36
37+
38+class SchemaVersionException(Exception):
39+ """There is an out-of-date table.
40+ The message should be a list of out of date tables.
41+ """
42+ pass
43+
44+
45 def check_schema_versions(sessionmaker):
46 """Pass through all tables, log out of date ones,
47 and except if not all up to date"""
48@@ -526,7 +534,7 @@
49 if not upgrades:
50 return
51
52- raise Exception(u"Tables %s are out of date. Run ibid-setup" % u", ".join(upgrades))
53+ raise SchemaVersionException(u", ".join(upgrades))
54
55 def upgrade_schemas(sessionmaker):
56 "Pass through all tables and update schemas"
57
58=== added file 'scripts/ibid-db'
59--- scripts/ibid-db 1970-01-01 00:00:00 +0000
60+++ scripts/ibid-db 2009-08-07 19:09:12 +0000
61@@ -0,0 +1,167 @@
62+#!/usr/bin/env python
63+
64+from datetime import datetime
65+import gzip
66+import logging
67+from optparse import OptionParser, OptionGroup
68+from os.path import exists
69+import re
70+from sys import stdin, stdout, stderr, exit
71+
72+from sqlalchemy import select, DateTime, Unicode, UnicodeText
73+from twisted.python.modules import getModule
74+# json only in Python >=2.6
75+try:
76+ import simplejson as json
77+except ImportError:
78+ import json
79+
80+import ibid
81+from ibid.config import FileConfig
82+from ibid.core import DatabaseManager
83+from ibid.models import metadata, upgrade_schemas
84+from ibid.utils import ibid_version
85+
86+parser = OptionParser(usage='%prog [options...]',
87+ description="""Ibid Database management tool. Used for import, export,
88+and upgrades. Export format is a header-line followed by JSON. FILE can be -
89+for stdin/stdout or can end in .gz for automatic Gzip compression.""")
90+commands = OptionGroup(parser, 'Modes')
91+commands.add_option('-e', '--export', dest='export', metavar='FILE',
92+ help='Export DB contents to FILE.')
93+commands.add_option('-i', '--import', dest='import_', metavar='FILE',
94+ help='Import DB contents from FILE. DB must be empty first.')
95+commands.add_option('-u', '--upgrade', dest='upgrade', action='store_true',
96+ help='Upgrade DB schema. You should backup first.')
97+parser.add_option_group(commands)
98+parser.add_option('-v', '--verbose', dest='verbose', action='store_true',
99+ default=False, help='Turn on debugging output to STDERR.')
100+
101+(options, args) = parser.parse_args()
102+
103+modes = sum(1 for mode in (options.import_, options.export, options.upgrade)
104+ if mode is not None)
105+if modes > 1:
106+ parser.error('Only one mode can be specified.')
107+elif modes == 0:
108+ parser.error('You must specify a mode.')
109+
110+if options.verbose:
111+ logging.basicConfig(level=logging.DEBUG)
112+else:
113+ logging.basicConfig(level=logging.ERROR)
114+
115+for module in getModule('ibid.plugins').iterModules():
116+ try:
117+ __import__(module.name)
118+ except Exception, e:
119+ print >> stderr, u"Couldn't load %s plugin: %s" % (
120+ module.name.replace('ibid.plugins.', ''), unicode(e))
121+
122+ibid.options = {'base': '.'}
123+ibid.config = FileConfig('ibid.ini')
124+ibid.config.merge(FileConfig('local.ini'))
125+
126+def dump_table(table, db):
127+ sql = select([table])
128+ rows = []
129+ for row in db.execute(sql):
130+ out = {}
131+ for key in row.iterkeys():
132+ value = row[key]
133+ if isinstance(value, datetime):
134+ value = value.strftime('%Y-%m-%dT%H:%M:%SZ')
135+ out[key] = value
136+ rows.append(out)
137+ return rows
138+
139+if options.upgrade is not None:
140+ db = DatabaseManager(check_schema_versions=False)['ibid']
141+ if not db.bind.has_table('schema'):
142+ print >> stderr, ("Database doesn't appear to contain an Ibid. "
143+ 'Run ibid-setup.')
144+ exit(1)
145+ upgrade_schemas(db)
146+
147+elif options.export is not None:
148+ if options.export == '-':
149+ output = stdout
150+ elif exists(options.export):
151+ print >> stderr, (
152+ 'Output file (%s) exists, refusing to clobber it' %
153+ options.export)
154+ exit(1)
155+ elif options.export.endswith('.gz'):
156+ output = gzip.open(options.export, 'wb')
157+ else:
158+ output = open(options.export, 'wb')
159+
160+ output.write(('# Ibid %(version)s Database dump for %(botname)s '
161+ 'made on %(date)s\n') % {
162+ 'version': ibid_version() or 'bzr',
163+ 'botname': ibid.config['botname'],
164+ 'date': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ'),
165+ })
166+
167+ db = DatabaseManager()['ibid']
168+ dump = dict((table.name, dump_table(table, db))
169+ for table in metadata.tables.itervalues())
170+
171+ output.write(json.dumps(dump, sort_keys=True, indent=4))
172+ output.close()
173+
174+elif options.import_ is not None:
175+ db = DatabaseManager(check_schema_versions=False)['ibid']
176+ if db.bind.has_table('schema'):
177+ print >> stderr, ('Database looks like it already contains an Ibid. '
178+ 'Refusing to clobber it.')
179+ exit(1)
180+
181+ upgrade_schemas(db)
182+
183+ if options.import_ == '-':
184+ input = stdin
185+ elif options.import_.endswith('.gz'):
186+ input = gzip.open(options.import_, 'rb')
187+ else:
188+ input = open(options.import_, 'rb')
189+
190+ version = input.readline().strip()
191+ version = re.match(r'^# Ibid (.+) Database dump for', version).group(1)
192+ if version != (ibid_version() or 'bzr'):
193+ print >> stderr, (
194+ 'Ibid version differs between dump (%(dump)s) and '
195+ 'local install (%(local)s). Aborting.') % {
196+ 'dump': version,
197+ 'local': ibid_version() or 'bzr',
198+ }
199+ exit(1)
200+
201+ dump = json.loads(input.read())
202+
203+ dump_schema = dict((table['table'], table['version'])
204+ for table in dump['schema'])
205+ db_schema = dict((table['table'], table['version'])
206+ for table in dump_table(metadata.tables['schema'], db))
207+ if dump_schema != db_schema:
208+ print >> stderr, (
209+ "Dump schema doesn't match DB Schema. "
210+ 'You must use the same version of ibid that you dumped with. '
211+ 'Aborting.')
212+ exit(1)
213+
214+ for table_name, table in dump.iteritems():
215+ if table_name == 'schema':
216+ continue
217+ dbtable = metadata.tables[table_name]
218+ for row in table:
219+ for field in row.iterkeys():
220+ if isinstance(dbtable.c[field].type, DateTime):
221+ row[field] = datetime.strptime(row[field],
222+ '%Y-%m-%dT%H:%M:%SZ')
223+ elif isinstance(dbtable.c[field].type, (Unicode, UnicodeText)):
224+ row[field] = unicode(row[field])
225+ sql = dbtable.insert().values(**row)
226+ db.execute(sql)
227+ db.commit()
228+ db.close()

Subscribers

People subscribed via source and target branches