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

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

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

# This file is part of daf_butler. 

# 

# Developed for the LSST Data Management System. 

# This product includes software developed by the LSST Project 

# (http://www.lsst.org). 

# See the COPYRIGHT file at the top-level directory of this distribution 

# for details of code ownership. 

# 

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

 

from .utils import iterable, stripIfNotNone 

from .views import View 

from .config import ConfigSubset 

from sqlalchemy import Column, String, Integer, Boolean, LargeBinary, DateTime,\ 

Float, ForeignKeyConstraint, Table, MetaData 

 

metadata = None # Needed to make disabled test_hsc not fail on import 

 

__all__ = ("SchemaConfig", "Schema", "SchemaBuilder") 

 

 

class SchemaConfig(ConfigSubset): 

component = "schema" 

requiredKeys = ("version", "tables") 

defaultConfigFile = "schema.yaml" 

 

 

class Schema: 

"""The SQL schema for a Butler Registry. 

 

Parameters 

---------- 

config : `SchemaConfig` or `str`, optional 

Load configuration. Defaults will be read if ``config`` is not 

a `SchemaConfig`. 

limited : `bool` 

If `True`, ignore tables, views, and associated foreign keys whose 

config descriptions include a "limited" key set to `False`. 

 

Attributes 

---------- 

metadata : `sqlalchemy.MetaData` 

The sqlalchemy schema description. 

tables : `dict` 

A mapping from table or view name to the associated SQLAlchemy object. 

Note that this contains both true tables and views. 

views : `frozenset` 

The names of entries in ``tables`` that are actually implemented as 

views. 

""" 

def __init__(self, config=None, limited=False): 

if config is None or not isinstance(config, SchemaConfig): 

config = SchemaConfig(config) 

builder = SchemaBuilder(config, limited=limited) 

self.datasetTable = builder.metadata.tables["Dataset"] 

self.metadata = builder.metadata 

self.views = frozenset(builder.views) 

self.tables = builder.tables 

 

 

class SchemaBuilder: 

"""Builds a Schema step-by-step. 

 

Parameters 

---------- 

config : `SchemaConfig` 

Configuration to parse. 

limited : `bool` 

If `True`, ignore tables, views, and associated foreign keys whose 

config descriptions include a "limited" key set to `False`. 

 

Attributes 

---------- 

metadata : `sqlalchemy.MetaData` 

The sqlalchemy schema description. 

tables : `dict` 

A mapping from table or view name to the associated SQLAlchemy object. 

Note that this contains both true tables and views. 

views : `set` 

The names of all entries in ``tables`` that are actually implemented as 

views. 

""" 

VALID_COLUMN_TYPES = {"string": String, "int": Integer, "float": Float, "region": LargeBinary, 

"bool": Boolean, "blob": LargeBinary, "datetime": DateTime} 

 

def __init__(self, config, limited=False): 

self.config = config 

self.metadata = MetaData() 

self.tables = {} 

self.views = set() 

self._limited = limited 

for tableName, tableDescription in self.config["tables"].items(): 

self.addTable(tableName, tableDescription) 

 

def isView(self, name): 

"""Return True if the named table should be added / has been added as a view. 

 

Parameters 

---------- 

name : `str` 

Name of a table or view. Does not need to have been added. 

 

Returns 

------- 

view : `bool` 

Whether the table should be added / has been added as a view. 

""" 

if name in self.views: 

return True 

description = self.config["tables"][name] 

return "sql" in description and not description.get("materialize", False) 

 

def isIncluded(self, name): 

"""Return True if the named table or view should be included in this schema. 

 

Parameters 

---------- 

name : `str` 

Name of a table or view. Does not need to have been added. 

 

Returns 

------- 

included : `bool` 

Whether the table or view should be included in the schema. 

""" 

if name in self.tables: 

return True 

description = self.config["tables"].get(name, None) 

140 ↛ 141line 140 didn't jump to line 141, because the condition on line 140 was never true if description is None: 

return False 

if self._limited: 

return description.get("limited", True) 

return True 

 

def addTable(self, tableName, tableDescription): 

"""Add a table to the schema metadata. 

 

Parameters 

---------- 

tableName : `str` 

Key of the table. 

tableDescription : `dict` 

Table description. 

 

Requires: 

- columns, a list of column descriptions 

- foreignKeys, a list of foreign-key constraint descriptions 

 

Raises 

------ 

ValueError 

If a table with the given name already exists. 

""" 

165 ↛ 166line 165 didn't jump to line 166, because the condition on line 165 was never true if tableName in self.metadata.tables: 

raise ValueError("Table with name {} already exists".format(tableName)) 

if not self.isIncluded(tableName): 

return None 

doc = stripIfNotNone(tableDescription.get("doc", None)) 

# Create a Table object (attaches itself to metadata) 

if self.isView(tableName): 

table = View(tableName, self.metadata, selectable=tableDescription["sql"], comment=doc, 

info=tableDescription) 

self.tables[tableName] = table 

self.views.add(tableName) 

else: 

table = Table(tableName, self.metadata, comment=doc, info=tableDescription) 

self.tables[tableName] = table 

179 ↛ 180line 179 didn't jump to line 180, because the condition on line 179 was never true if "columns" not in tableDescription: 

raise ValueError("No columns in table: {}".format(tableName)) 

for columnDescription in tableDescription["columns"]: 

self.addColumn(table, columnDescription) 

if "foreignKeys" in tableDescription: 

for constraintDescription in tableDescription["foreignKeys"]: 

self.addForeignKeyConstraint(table, constraintDescription) 

return table 

 

def addColumn(self, table, columnDescription): 

"""Add a column to a table. 

 

Parameters 

---------- 

table : `sqlalchemy.Table`, `sqlalchemy.expression.TableClause` or `str` 

The table. 

columnDescription : `dict` 

Description of the column to be created. 

Should always contain: 

- name, descriptive name 

- type, valid column type 

May contain: 

- nullable, entry can be null 

- primary_key, mark this column as primary key 

- foreign_key, link to other table 

- doc, docstring 

""" 

206 ↛ 207line 206 didn't jump to line 207, because the condition on line 206 was never true if isinstance(table, str): 

table = self.metadata.tables[table] 

table.append_column(self.makeColumn(columnDescription)) 

 

def addForeignKeyConstraint(self, table, constraintDescription): 

"""Add a ForeignKeyConstraint to a table. 

 

If the table or the ForeignKeyConstraint's target are views, or should 

not be included in this schema (because it is limited), does nothing. 

 

Parameters 

---------- 

table : `sqlalchemy.Table` or `str` 

The table. 

constraintDescription : `dict` 

Description of the ForeignKeyConstraint to be created. 

Should always contain: 

- src, list of source column names 

- tgt, list of target column names 

""" 

226 ↛ 227line 226 didn't jump to line 227, because the condition on line 226 was never true if isinstance(table, str): 

table = self.metadata.tables[table] 

src, tgt, tgtTable = self.normalizeForeignKeyConstraint(constraintDescription) 

if not self.isIncluded(table.name) or not self.isIncluded(tgtTable): 

return 

if self.isView(table.name) or self.isView(tgtTable): 

return 

table.append_constraint(ForeignKeyConstraint(src, tgt)) 

 

def makeColumn(self, columnDescription): 

"""Make a Column entry for addition to a Table. 

 

Parameters 

---------- 

columnDescription : `dict` 

Description of the column to be created. 

Should always contain: 

- name, descriptive name 

- type, valid column type 

May contain: 

- nullable, entry can be null 

- primary_key, mark this column as primary key 

- doc, docstring 

 

Returns 

------- 

c : `sqlalchemy.Column` 

The created `Column` entry. 

 

Raises 

------ 

ValueError 

If the column description contains unsupported arguments 

""" 

description = columnDescription.copy() 

# required 

columnName = description.pop("name") 

args = (columnName, self.VALID_COLUMN_TYPES[description.pop("type")]) 

# additional optional arguments can be passed through directly 

kwargs = {} 

for opt in ("nullable", "primary_key"): 

if opt in description: 

value = description.pop(opt) 

kwargs[opt] = value 

kwargs["comment"] = stripIfNotNone(description.pop("doc", None)) 

271 ↛ 272line 271 didn't jump to line 272, because the condition on line 271 was never true if description: 

raise ValueError("Unhandled extra kwargs: {} for column: {}".format(description, columnName)) 

return Column(*args, **kwargs) 

 

def normalizeForeignKeyConstraint(self, constraintDescription): 

"""Convert configuration for a ForeignKeyConstraint to standard form 

and return the target table. 

 

Parameters 

---------- 

constraintDescription : `dict` 

Description of the ForeignKeyConstraint to be created. 

Should always contain: 

- src, list of source column names or single source column name 

- tgt, list of (table-qualified) target column names or single target column name 

 

Returns 

------- 

src : `tuple` 

Sequence of field names in the local table. 

tgt : `tuple` 

Sequence of table-qualified field names in the remote table. 

tgtTable : `str` 

Name of the target table. 

""" 

src = tuple(iterable(constraintDescription["src"])) 

tgt = tuple(iterable(constraintDescription["tgt"])) 

tgtTable, _ = tgt[0].split(".") 

assert all(t.split(".")[0] == tgtTable for t in tgt[1:]) 

return src, tgt, tgtTable