blob: 9cdb65099c13376c51a9736e37bac7a8febebbd5 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# Unix SMB/CIFS implementation.
#
# Query class for the ORM to the Ldb database.
#
# Copyright (C) Catalyst.Net Ltd. 2023
#
# Written by Rob van der Linde <rob@catalyst.net.nz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import re
from .exceptions import DoesNotExist, MultipleObjectsReturned
RE_SPLIT_CAMELCASE = re.compile(r"[A-Z](?:[a-z]+|[A-Z]*(?=[A-Z]|$))")
class Query:
"""Simple Query class used by the `Model.query` method."""
def __init__(self, model, ldb, result):
self.model = model
self.ldb = ldb
self.result = result
self.count = result.count
self.name = " ".join(RE_SPLIT_CAMELCASE.findall(model.__name__)).lower()
def __iter__(self):
"""Loop over Query class yields Model instances."""
for message in self.result:
yield self.model.from_message(self.ldb, message)
def first(self):
"""Returns the first item in the Query or None for no results."""
if self.result.count:
return self.model.from_message(self.ldb, self.result[0])
def last(self):
"""Returns the last item in the Query or None for no results."""
if self.result.count:
return self.model.from_message(self.ldb, self.result[-1])
def get(self):
"""Returns one item or None if no results were found.
:returns: Model instance or None if not found.
:raises MultipleObjectsReturned: if more than one results were returned
"""
if self.count > 1:
raise MultipleObjectsReturned(
f"More than one {self.name} objects returned (got {self.count}).")
elif self.count:
return self.model.from_message(self.ldb, self.result[0])
def one(self):
"""Must return EXACTLY one item or raise an exception.
:returns: Model instance
:raises DoesNotExist: if no results were returned
:raises MultipleObjectsReturned: if more than one results were returned
"""
if self.count < 1:
raise DoesNotExist(
f"{self.name.capitalize()} matching query not found")
elif self.count > 1:
raise MultipleObjectsReturned(
f"More than one {self.name} objects returned (got {self.count}).")
else:
return self.model.from_message(self.ldb, self.result[0])
|