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

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

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

"""Classes for representing SQL data-definition language (DDL; "CREATE TABLE", 

etc.) in Python. 

 

This provides an extra layer on top of SQLAlchemy's classes for these concepts, 

because we need a level of indirection between logical tables and the actual 

SQL, and SQLAlchemy's DDL classes always map 1-1 to SQL. 

 

We've opted for the rather more obscure "ddl" as the name of this module 

instead of "schema" because the latter is too overloaded; in most SQL 

databases, a "schema" is also another term for a namespace. 

""" 

from __future__ import annotations 

 

__all__ = ("TableSpec", "FieldSpec", "ForeignKeySpec", "Base64Bytes", "Base64Region") 

 

from base64 import b64encode, b64decode 

from math import ceil 

from dataclasses import dataclass 

from typing import Optional, Tuple, Sequence, Set 

 

import sqlalchemy 

 

from lsst.sphgeom import ConvexPolygon 

from .config import Config 

from .exceptions import ValidationError 

from .utils import iterable, stripIfNotNone, NamedValueSet 

 

 

class SchemaValidationError(ValidationError): 

"""Exceptions used to indicate problems in Registry schema configuration. 

""" 

 

@classmethod 

def translate(cls, caught, message): 

"""A decorator that re-raises exceptions as `SchemaValidationError`. 

 

Decorated functions must be class or instance methods, with a 

``config`` parameter as their first argument. This will be passed 

to ``message.format()`` as a keyword argument, along with ``err``, 

the original exception. 

 

Parameters 

---------- 

caught : `type` (`Exception` subclass) 

The type of exception to catch. 

message : `str` 

A `str.format` string that may contain named placeholders for 

``config``, ``err``, or any keyword-only argument accepted by 

the decorated function. 

""" 

def decorate(func): 

def decorated(self, config, *args, **kwds): 

try: 

return func(self, config, *args, **kwds) 

except caught as err: 

raise cls(message.format(config=str(config), err=err)) 

return decorated 

return decorate 

 

 

class Base64Bytes(sqlalchemy.TypeDecorator): 

"""A SQLAlchemy custom type that maps Python `bytes` to a base64-encoded 

`sqlalchemy.String`. 

""" 

 

impl = sqlalchemy.String 

 

def __init__(self, nbytes, *args, **kwds): 

length = 4*ceil(nbytes/3) 

super().__init__(*args, length=length, **kwds) 

self.nbytes = nbytes 

 

def process_bind_param(self, value, dialect): 

# 'value' is native `bytes`. We want to encode that to base64 `bytes` 

# and then ASCII `str`, because `str` is what SQLAlchemy expects for 

# String fields. 

if value is None: 

return None 

if not isinstance(value, bytes): 

raise TypeError( 

f"Base64Bytes fields require 'bytes' values; got '{value}' with type {type(value)}." 

) 

return b64encode(value).decode("ascii") 

 

def process_result_value(self, value, dialect): 

# 'value' is a `str` that must be ASCII because it's base64-encoded. 

# We want to transform that to base64-encoded `bytes` and then 

# native `bytes`. 

return b64decode(value.encode("ascii")) if value is not None else None 

 

 

class Base64Region(Base64Bytes): 

"""A SQLAlchemy custom type that maps Python `sphgeom.ConvexPolygon` to a 

base64-encoded `sqlalchemy.String`. 

""" 

 

def process_bind_param(self, value, dialect): 

if value is None: 

return None 

return super().process_bind_param(value.encode(), dialect) 

 

def process_result_value(self, value, dialect): 

if value is None: 

return None 

return ConvexPolygon.decode(super().process_result_value(value, dialect)) 

 

 

VALID_CONFIG_COLUMN_TYPES = { 

"string": sqlalchemy.String, 

"int": sqlalchemy.Integer, 

"float": sqlalchemy.Float, 

"region": Base64Region, 

"bool": sqlalchemy.Boolean, 

"blob": sqlalchemy.LargeBinary, 

"datetime": sqlalchemy.DateTime, 

"hash": Base64Bytes 

} 

 

 

@dataclass 

class FieldSpec: 

"""A struct-like class used to define a column in a logical `Registry` 

table. 

""" 

 

name: str 

"""Name of the column.""" 

 

dtype: type 

"""Type of the column; usually a `type` subclass provided by SQLAlchemy 

that defines both a Python type and a corresponding precise SQL type. 

""" 

 

length: Optional[int] = None 

"""Length of the type in the database, for variable-length types.""" 

 

nbytes: Optional[int] = None 

"""Natural length used for hash and encoded-region columns, to be converted 

into the post-encoding length. 

""" 

 

primaryKey: bool = False 

"""Whether this field is (part of) its table's primary key.""" 

 

autoincrement: bool = False 

"""Whether the database should insert automatically incremented values when 

no value is provided in an INSERT. 

""" 

 

nullable: bool = True 

"""Whether this field is allowed to be NULL.""" 

 

doc: Optional[str] = None 

"""Documentation for this field.""" 

 

def __eq__(self, other): 

return self.name == other.name 

 

def __hash__(self): 

return hash(self.name) 

 

@classmethod 

@SchemaValidationError.translate(KeyError, "Missing key {err} in column config '{config}'.") 

def fromConfig(cls, config: Config, **kwds) -> FieldSpec: 

"""Create a `FieldSpec` from a subset of a `SchemaConfig`. 

 

Parameters 

---------- 

config: `Config` 

Configuration describing the column. Nested configuration keys 

correspond to `FieldSpec` attributes. 

kwds 

Additional keyword arguments that provide defaults for values 

not present in config. 

 

Returns 

------- 

spec: `FieldSpec` 

Specification structure for the column. 

 

Raises 

------ 

SchemaValidationError 

Raised if configuration keys are missing or have invalid values. 

""" 

dtype = VALID_CONFIG_COLUMN_TYPES.get(config["type"]) 

if dtype is None: 

raise SchemaValidationError(f"Invalid field type string: '{config['type']}'.") 

if not config["name"].islower(): 

raise SchemaValidationError(f"Column name '{config['name']}' is not all lowercase.") 

self = cls(name=config["name"], dtype=dtype, **kwds) 

self.length = config.get("length", self.length) 

self.nbytes = config.get("nbytes", self.nbytes) 

if self.length is not None and self.nbytes is not None: 

raise SchemaValidationError(f"Both length and nbytes provided for field '{self.name}'.") 

self.primaryKey = config.get("primaryKey", self.primaryKey) 

self.autoincrement = config.get("autoincrement", self.autoincrement) 

self.nullable = config.get("nullable", False if self.primaryKey else self.nullable) 

self.doc = stripIfNotNone(config.get("doc", None)) 

return self 

 

def getSizedColumnType(self) -> sqlalchemy.types.TypeEngine: 

"""Return a sized version of the column type, utilizing either (or 

neither) of ``self.length`` and ``self.nbytes``. 

 

Returns 

------- 

dtype : `sqlalchemy.types.TypeEngine` 

A SQLAlchemy column type object. 

""" 

if self.length is not None: 

return self.dtype(length=self.length) 

if self.nbytes is not None: 

return self.dtype(nbytes=self.nbytes) 

return self.dtype 

 

 

@dataclass 

class ForeignKeySpec: 

"""A struct-like class used to define a foreign key constraint in a logical 

`Registry` table. 

""" 

 

table: str 

"""Name of the target table.""" 

 

source: Tuple[str, ...] 

"""Tuple of source table column names.""" 

 

target: Tuple[str, ...] 

"""Tuple of target table column names.""" 

 

onDelete: Optional[str] = None 

"""SQL clause indicating how to handle deletes to the target table. 

 

If not `None` (which indicates that a constraint violation exception should 

be raised), should be either "SET NULL" or "CASCADE". 

""" 

 

@classmethod 

@SchemaValidationError.translate(KeyError, "Missing key {err} in foreignKey config '{config}'.") 

def fromConfig(cls, config: Config) -> ForeignKeySpec: 

"""Create a `ForeignKeySpec` from a subset of a `SchemaConfig`. 

 

Parameters 

---------- 

config: `Config` 

Configuration describing the constraint. Nested configuration keys 

correspond to `ForeignKeySpec` attributes. 

 

Returns 

------- 

spec: `ForeignKeySpec` 

Specification structure for the constraint. 

 

Raises 

------ 

SchemaValidationError 

Raised if configuration keys are missing or have invalid values. 

""" 

return cls(table=config["table"], 

source=tuple(iterable(config["source"])), 

target=tuple(iterable(config["target"])), 

onDelete=config.get("onDelete", None)) 

 

 

@dataclass 

class TableSpec: 

"""A struct-like class used to define a table or table-like 

query interface. 

""" 

 

fields: NamedValueSet[FieldSpec] 

"""Specifications for the columns in this table.""" 

 

unique: Set[Tuple[str, ...]] = frozenset() 

"""Non-primary-key unique constraints for the table.""" 

 

indexes: Set[Tuple[str, ...]] = frozenset() 

"""Indexes for the table.""" 

 

foreignKeys: Sequence[ForeignKeySpec] = tuple() 

"""Foreign key constraints for the table.""" 

 

doc: Optional[str] = None 

"""Documentation for the table.""" 

 

def __post_init__(self): 

self.fields = NamedValueSet(self.fields) 

self.unique = set(self.unique) 

self.indexes = set(self.indexes) 

self.foreignKeys = list(self.foreignKeys) 

 

@classmethod 

@SchemaValidationError.translate(KeyError, "Missing key {err} in table config '{config}'.") 

def fromConfig(cls, config: Config) -> TableSpec: 

"""Create a `ForeignKeySpec` from a subset of a `SchemaConfig`. 

 

Parameters 

---------- 

config: `Config` 

Configuration describing the constraint. Nested configuration keys 

correspond to `TableSpec` attributes. 

 

Returns 

------- 

spec: `TableSpec` 

Specification structure for the table. 

 

Raises 

------ 

SchemaValidationError 

Raised if configuration keys are missing or have invalid values. 

""" 

return cls( 

fields=NamedValueSet(FieldSpec.fromConfig(c) for c in config["columns"]), 

unique={tuple(u) for u in config.get("unique", ())}, 

foreignKeys=[ForeignKeySpec.fromConfig(c) for c in config.get("foreignKeys", ())], 

sql=config.get("sql"), 

doc=stripIfNotNone(config.get("doc")), 

)