Coverage for python/lsst/daf/butler/core/simpleQuery.py : 32%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
22from __future__ import annotations
24__all__ = ("SimpleQuery",)
26from typing import (
27 Any,
28 ClassVar,
29 List,
30 Optional,
31 Union,
32 Type,
33 TypeVar,
34)
36import sqlalchemy
39T = TypeVar("T")
42class SimpleQuery:
43 """A struct that combines SQLAlchemy objects representing SELECT, FROM,
44 and WHERE clauses.
45 """
47 def __init__(self) -> None:
48 self.columns = []
49 self.where = []
50 self._from: Optional[sqlalchemy.sql.FromClause] = None
52 class Select:
53 """Tag class used to indicate that a field should be returned in
54 a SELECT query.
55 """
57 Or: ClassVar[Any]
59 Select.Or = Union[T, Type[Select]]
60 """A type annotation for arguments that can take the `Select` type or some
61 other value.
62 """
64 def join(self, table: sqlalchemy.sql.FromClause, *,
65 onclause: Optional[sqlalchemy.sql.ColumnElement] = None,
66 isouter: bool = False,
67 full: bool = False,
68 **kwargs: Any) -> None:
69 """Add a table or subquery join to the query, possibly adding
70 SELECT columns or WHERE expressions at the same time.
72 Parameters
73 ----------
74 table : `sqlalchemy.sql.FromClause`
75 Table or subquery to include.
76 onclause : `sqlalchemy.sql.ColumnElement`, optional
77 Expression used to join the new table or subquery to those already
78 present. Passed directly to `sqlalchemy.sql.FromClause.join`, but
79 ignored if this is the first call to `SimpleQuery.join`.
80 isouter : `bool`, optional
81 If `True`, make this an LEFT OUTER JOIN. Passed directly to
82 `sqlalchemy.sql.FromClause.join`.
83 full : `bool`, optional
84 If `True`, make this a FULL OUTER JOIN. Passed directly to
85 `sqlalchemy.sql.FromClause.join`.
86 **kwargs
87 Additional keyword arguments correspond to columns in the joined
88 table or subquery. Values may be:
90 - `Select` (a special tag type) to indicate that this column
91 should be added to the SELECT clause as a query result;
92 - `None` to do nothing (equivalent to no keyword argument);
93 - Any other value to add an equality constraint to the WHERE
94 clause that constrains this column to the given value. Note
95 that this cannot be used to add ``IS NULL`` constraints, because
96 the previous condition for `None` is checked first.
97 """
98 if self._from is None:
99 self._from = table
100 elif onclause is not None:
101 self._from = self._from.join(table, onclause=onclause, isouter=isouter, full=full)
102 else:
103 # New table is completely unrelated to all already-included
104 # tables. We need a cross join here but SQLAlchemy does not
105 # have a specific method for that. Using join() without
106 # `onclause` will try to join on FK and will raise an exception
107 # for unrelated tables, so we have to use `onclause` which is
108 # always true.
109 self._from = self._from.join(table, sqlalchemy.sql.literal(True))
110 for name, arg in kwargs.items():
111 if arg is self.Select:
112 self.columns.append(table.columns[name].label(name))
113 elif arg is not None:
114 self.where.append(table.columns[name] == arg)
116 def combine(self) -> sqlalchemy.sql.Select:
117 """Combine all terms into a single query object.
119 Returns
120 -------
121 sql : `sqlalchemy.sql.Select`
122 A SQLAlchemy object representing the full query.
123 """
124 result = sqlalchemy.sql.select(self.columns)
125 if self._from is not None:
126 result = result.select_from(self._from)
127 if self.where:
128 result = result.where(sqlalchemy.sql.and_(*self.where))
129 return result
131 @property
132 def from_(self) -> sqlalchemy.sql.FromClause:
133 """The FROM clause of the query (`sqlalchemy.sql.FromClause`).
135 This property cannot be set. To add tables to the FROM clause, call
136 `join`.
137 """
138 return self._from
140 def copy(self) -> SimpleQuery:
141 """Return a copy of this object, with new lists for the `where` and
142 `columns` attributes that can be modified without changing the
143 original.
145 Returns
146 -------
147 copy : `SimpleQuery`
148 A copy of ``self``.
149 """
150 result = SimpleQuery()
151 result.columns = list(self.columns)
152 result.where = list(self.where)
153 result._from = self._from
154 return result
156 columns: List[sqlalchemy.sql.ColumnElement]
157 """The columns in the SELECT clause
158 (`list` [ `sqlalchemy.sql.ColumnElement` ]).
159 """
161 where: List[sqlalchemy.sql.ColumnElement]
162 """Boolean expressions that will be combined with AND to form the WHERE
163 clause (`list` [ `sqlalchemy.sql.ColumnElement` ]).
164 """