4 from ...types import Timestamp
5 from ...util import none_or
6 from .collection import Collection
8 logger = logging.getLogger("mw.database.collections.users")
11 class Users(Collection):
12 CREATION_ACTIONS = {'newusers', 'create', 'create2', 'autocreate',
15 def get(self, user_id=None, user_name=None):
17 Gets a single user row from the database. Raises a :class:`KeyError`
18 if a user cannot be found.
29 user_id = none_or(user_id, int)
30 user_name = none_or(user_name, str)
38 if user_id is not None:
42 values.append(user_id)
44 elif user_name is not None:
48 values.append(user_name)
51 raise TypeError("Must specify a user identifier.")
53 cursor = self.db.shared_connection.cursor()
62 raise KeyError(user_id if user_id is not None else user_name)
64 def query(self, registered_before=None, registered_after=None,
65 before_id=None, after_id=None, limit=None,
66 direction=None, self_created_only=False):
68 Queries users based on various filtering parameters.
71 registered_before : :class:`mw.Timestamp`
72 A timestamp to search before (inclusive)
73 registered_after : :class:`mw.Timestamp`
74 A timestamp to search after (inclusive)
76 A user_id to search before (inclusive)
78 A user_ud to search after (inclusive)
82 Limit the results to at most this number
83 self_creations_only : bool
84 limit results to self_created user accounts
87 an iterator over ``user`` table rows
89 start_time = time.time()
91 registered_before = none_or(registered_before, Timestamp)
92 registered_after = none_or(registered_after, Timestamp)
93 before_id = none_or(before_id, str)
94 after_id = none_or(after_id, str)
95 direction = none_or(direction, levels=self.DIRECTIONS)
96 limit = none_or(limit, int)
97 self_created_only = bool(self_created_only)
105 if self_created_only:
107 INNER JOIN logging ON
109 log_type = "newusers" AND
110 log_action = "create"
115 if registered_before is not None:
116 query += "AND user_registration <= %s "
117 values.append(registered_before.short_format())
118 if registered_after is not None:
119 query += "AND user_registration >= %s "
120 values.append(registered_after.short_format())
121 if before_id is not None:
122 query += "AND user_id <= %s "
123 values.append(before_id)
124 if after_id is not None:
125 query += "AND user_id >= %s "
126 values.append(after_id)
128 query += "GROUP BY user_id " # In case of duplicate log events
130 if direction is not None:
131 if registered_before is not None or registered_after is not None:
132 if direction == "newer":
133 query += "ORDER BY user_registration ASC "
135 query += "ORDER BY user_registration DESC "
137 if direction == "newer":
138 query += "ORDER BY user_id ASC "
140 query += "ORDER BY user_id DESC "
142 if limit is not None:
146 cursor = self.db.shared_connection.cursor()
147 cursor.execute(query, values)
154 logger.debug("%s users queried in %s seconds" % (count, time.time() - start_time))