8 from .collections import AllRevisions, Archives, Pages, Revisions, Users
10 logger = logging.getLogger("mw.database.db")
15 Represents a connection to a MySQL database.
18 connection = :class:`oursql.Connection`
19 A connection to a MediaWiki database
22 def __init__(self, connection):
23 self.shared_connection = connection
24 self.shared_connection.cursorclass = pymysql.cursors.DictCursor
26 self.revisions = Revisions(self)
28 An instance of :class:`mw.database.Revisions`.
31 self.archives = Archives(self)
33 An instance of :class:`mw.database.Archives`.
36 self.all_revisions = AllRevisions(self)
38 An instance of :class:`mw.database.AllRevisions`.
41 self.pages = Pages(self)
43 An instance of :class:`mw.database.Pages`.
46 self.users = Users(self)
48 An instance of :class:`mw.database.Users`.
53 self.__class__.__name__,
55 [repr(arg) for arg in self.args] +
56 ["%s=%r" % (k, v) for k, v in self.kwargs.items()]
61 return self.__repr__()
64 def add_arguments(cls, parser, defaults=None):
66 Adds the arguments to an :class:`argparse.ArgumentParser` in order to
67 create a database connection.
69 defaults = defaults if defaults is not None else defaults
71 default_host = defaults.get('host', "localhost")
74 help="MySQL database host to connect to (defaults to {0})".format(default_host),
78 default_database = defaults.get('database', getpass.getuser())
81 help="MySQL database name to connect to (defaults to {0})".format(default_database),
82 default=default_database
85 default_defaults_file = defaults.get('defaults-file', os.path.expanduser("~/.my.cnf"))
88 help="MySQL defaults file (defaults to {0})".format(default_defaults_file),
89 default=default_defaults_file
92 default_user = defaults.get('user', getpass.getuser())
95 help="MySQL user (defaults to %s)".format(default_user),
101 def from_arguments(cls, args):
103 Constructs a :class:`~mw.database.DB`.
104 Consumes :class:`argparse.ArgumentParser` arguments given by
105 :meth:`add_arguments` in order to create a :class:`DB`.
108 args : :class:`argparse.Namespace`
109 A collection of argument values returned by :class:`argparse.ArgumentParser`'s :meth:`parse_args()`
111 connection = pymysql.connect(
114 database=args.database,
115 read_default_file=args.defaults_file
117 return cls(connection)
120 def from_params(cls, *args, **kwargs):
122 Constructs a :class:`~mw.database.DB`. Passes `*args` and `**kwargs`
123 to :meth:`oursql.connect` and configures the connection.
126 args : :class:`argparse.Namespace`
127 A collection of argument values returned by :class:`argparse.ArgumentParser`'s :meth:`parse_args()`
129 kwargs['cursorclass'] = pymysql.cursors.DictCursor
131 kwargs['database'] = kwargs['db']
133 connection = pymysql.connect(*args, **kwargs)
134 return cls(connection)