Coverage for python/lsst/daf/butler/core/simpleQuery.py: 36%
Shortcuts 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
Shortcuts 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 Any, ClassVar, List, Optional, Type, TypeVar, Union
28import sqlalchemy
30T = TypeVar("T")
33class SimpleQuery:
34 """A struct that combines SQLAlchemy objects.
36 Represents SELECT, FROM, and WHERE clauses.
37 """
39 def __init__(self) -> None:
40 self.columns = []
41 self.where = []
42 self._from: Optional[sqlalchemy.sql.FromClause] = None
44 class Select:
45 """Tag class for SELECT queries.
47 Used to indicate that a field should be returned in
48 a SELECT query.
49 """
51 Or: ClassVar[Any]
53 Select.Or = Union[T, Type[Select]]
54 """A type annotation for arguments that can take the `Select` type or some
55 other value.
56 """
58 def join(
59 self,
60 table: sqlalchemy.sql.FromClause,
61 *,
62 onclause: Optional[sqlalchemy.sql.ColumnElement] = None,
63 isouter: bool = False,
64 full: bool = False,
65 **kwargs: Any,
66 ) -> None:
67 """Add a table or subquery join to the query.
69 Possibly also adding SELECT columns or WHERE expressions at the same
70 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 """Return 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.
143 Returns the copy with new lists for the `where` and
144 `columns` attributes that can be modified without changing the
145 original.
147 Returns
148 -------
149 copy : `SimpleQuery`
150 A copy of ``self``.
151 """
152 result = SimpleQuery()
153 result.columns = list(self.columns)
154 result.where = list(self.where)
155 result._from = self._from
156 return result
158 columns: List[sqlalchemy.sql.ColumnElement]
159 """The columns in the SELECT clause
160 (`list` [ `sqlalchemy.sql.ColumnElement` ]).
161 """
163 where: List[sqlalchemy.sql.ColumnElement]
164 """Boolean expressions that will be combined with AND to form the WHERE
165 clause (`list` [ `sqlalchemy.sql.ColumnElement` ]).
166 """