Hide keyboard shortcuts

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/>. 

21 

22from __future__ import annotations 

23 

24__all__ = ("SimpleQuery",) 

25 

26from typing import ( 

27 Any, 

28 ClassVar, 

29 List, 

30 Optional, 

31 Union, 

32 Type, 

33 TypeVar, 

34) 

35 

36import sqlalchemy 

37 

38 

39T = TypeVar("T") 

40 

41 

42class SimpleQuery: 

43 """A struct that combines SQLAlchemy objects. 

44 

45 Represents SELECT, FROM, and WHERE clauses. 

46 """ 

47 

48 def __init__(self) -> None: 

49 self.columns = [] 

50 self.where = [] 

51 self._from: Optional[sqlalchemy.sql.FromClause] = None 

52 

53 class Select: 

54 """Tag class for SELECT queries. 

55 

56 Used to indicate that a field should be returned in 

57 a SELECT query. 

58 """ 

59 

60 Or: ClassVar[Any] 

61 

62 Select.Or = Union[T, Type[Select]] 

63 """A type annotation for arguments that can take the `Select` type or some 

64 other value. 

65 """ 

66 

67 def join(self, table: sqlalchemy.sql.FromClause, *, 

68 onclause: Optional[sqlalchemy.sql.ColumnElement] = None, 

69 isouter: bool = False, 

70 full: bool = False, 

71 **kwargs: Any) -> None: 

72 """Add a table or subquery join to the query. 

73 

74 Possibly also adding SELECT columns or WHERE expressions at the same 

75 time. 

76 

77 Parameters 

78 ---------- 

79 table : `sqlalchemy.sql.FromClause` 

80 Table or subquery to include. 

81 onclause : `sqlalchemy.sql.ColumnElement`, optional 

82 Expression used to join the new table or subquery to those already 

83 present. Passed directly to `sqlalchemy.sql.FromClause.join`, but 

84 ignored if this is the first call to `SimpleQuery.join`. 

85 isouter : `bool`, optional 

86 If `True`, make this an LEFT OUTER JOIN. Passed directly to 

87 `sqlalchemy.sql.FromClause.join`. 

88 full : `bool`, optional 

89 If `True`, make this a FULL OUTER JOIN. Passed directly to 

90 `sqlalchemy.sql.FromClause.join`. 

91 **kwargs 

92 Additional keyword arguments correspond to columns in the joined 

93 table or subquery. Values may be: 

94 

95 - `Select` (a special tag type) to indicate that this column 

96 should be added to the SELECT clause as a query result; 

97 - `None` to do nothing (equivalent to no keyword argument); 

98 - Any other value to add an equality constraint to the WHERE 

99 clause that constrains this column to the given value. Note 

100 that this cannot be used to add ``IS NULL`` constraints, because 

101 the previous condition for `None` is checked first. 

102 """ 

103 if self._from is None: 

104 self._from = table 

105 elif onclause is not None: 

106 self._from = self._from.join(table, onclause=onclause, isouter=isouter, full=full) 

107 else: 

108 # New table is completely unrelated to all already-included 

109 # tables. We need a cross join here but SQLAlchemy does not 

110 # have a specific method for that. Using join() without 

111 # `onclause` will try to join on FK and will raise an exception 

112 # for unrelated tables, so we have to use `onclause` which is 

113 # always true. 

114 self._from = self._from.join(table, sqlalchemy.sql.literal(True)) 

115 for name, arg in kwargs.items(): 

116 if arg is self.Select: 

117 self.columns.append(table.columns[name].label(name)) 

118 elif arg is not None: 

119 self.where.append(table.columns[name] == arg) 

120 

121 def combine(self) -> sqlalchemy.sql.Select: 

122 """Combine all terms into a single query object. 

123 

124 Returns 

125 ------- 

126 sql : `sqlalchemy.sql.Select` 

127 A SQLAlchemy object representing the full query. 

128 """ 

129 result = sqlalchemy.sql.select(*self.columns) 

130 if self._from is not None: 

131 result = result.select_from(self._from) 

132 if self.where: 

133 result = result.where(sqlalchemy.sql.and_(*self.where)) 

134 return result 

135 

136 @property 

137 def from_(self) -> sqlalchemy.sql.FromClause: 

138 """Return the FROM clause of the query (`sqlalchemy.sql.FromClause`). 

139 

140 This property cannot be set. To add tables to the FROM clause, call 

141 `join`. 

142 """ 

143 return self._from 

144 

145 def copy(self) -> SimpleQuery: 

146 """Return a copy of this object. 

147 

148 Returns the copy with new lists for the `where` and 

149 `columns` attributes that can be modified without changing the 

150 original. 

151 

152 Returns 

153 ------- 

154 copy : `SimpleQuery` 

155 A copy of ``self``. 

156 """ 

157 result = SimpleQuery() 

158 result.columns = list(self.columns) 

159 result.where = list(self.where) 

160 result._from = self._from 

161 return result 

162 

163 columns: List[sqlalchemy.sql.ColumnElement] 

164 """The columns in the SELECT clause 

165 (`list` [ `sqlalchemy.sql.ColumnElement` ]). 

166 """ 

167 

168 where: List[sqlalchemy.sql.ColumnElement] 

169 """Boolean expressions that will be combined with AND to form the WHERE 

170 clause (`list` [ `sqlalchemy.sql.ColumnElement` ]). 

171 """