| 1 |
""" |
| 2 |
Support code for attaching scripts to objects. |
| 3 |
|
| 4 |
Scripts can be either in python or in SQL. They always live on |
| 5 |
make instances. For details, see Scripting in the reference |
| 6 |
documentation. |
| 7 |
""" |
| 8 |
|
| 9 |
#c Copyright 2008-2025, the GAVO project <[email protected]> |
| 10 |
#c |
| 11 |
#c This program is free software, covered by the GNU GPL. See the |
| 12 |
#c COPYING file in the source distribution. |
| 13 |
|
| 14 |
|
| 15 |
from gavo import base |
| 16 |
from gavo import utils |
| 17 |
from gavo.base import sqlsupport |
| 18 |
from gavo.rscdef import rmkfuncs |
| 19 |
from gavo.utils.parsetricks import ( |
| 20 |
OneOrMore, ZeroOrMore, QuotedString, Forward, |
| 21 |
SkipTo, StringEnd, Regex, Suppress, |
| 22 |
Literal, pyparsingWhitechars) |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
class Error(base.Error): |
| 27 |
pass |
| 28 |
|
| 29 |
|
| 30 |
def _getSQLScriptGrammar(): |
| 31 |
"""returns a pyparsing ParserElement that splits SQL scripts into |
| 32 |
individual commands. |
| 33 |
|
| 34 |
The rules are: Statements are separated by semicolons, empty statements |
| 35 |
are allowed. |
| 36 |
""" |
| 37 |
with pyparsingWhitechars(" \t"): |
| 38 |
atom = Forward() |
| 39 |
atom.setName("Atom") |
| 40 |
|
| 41 |
sqlComment = Literal("--")+SkipTo("\n", include=True) |
| 42 |
cStyleComment = Literal("/*")+SkipTo("*/", include=True) |
| 43 |
comment = sqlComment | cStyleComment |
| 44 |
lineEnd = Literal("\n") |
| 45 |
|
| 46 |
simpleStr = QuotedString(quoteChar="'", escChar="\\", |
| 47 |
multiline=True, unquoteResults=False) |
| 48 |
quotedId = QuotedString(quoteChar='"', escChar="\\", unquoteResults=False) |
| 49 |
dollarQuoted = Regex(r"(?s)\$(\w*)\$.*?\$\1\$") |
| 50 |
dollarQuoted.setName("dollarQuoted") |
| 51 |
# well, quotedId is not exactly a string literal. I hate it, and so |
| 52 |
# it's lumped in here. |
| 53 |
strLiteral = simpleStr | dollarQuoted | quotedId |
| 54 |
strLiteral.setName("strLiteral") |
| 55 |
|
| 56 |
other = Regex("[^;'\"$]+") |
| 57 |
other.setName("other") |
| 58 |
|
| 59 |
literalDollar = Literal("$") + ~ Literal("$") |
| 60 |
statementEnd = ( Literal(';') + ZeroOrMore(lineEnd) | StringEnd() ) |
| 61 |
|
| 62 |
atom << ( Suppress(comment) | other | strLiteral | literalDollar ) |
| 63 |
statement = OneOrMore(atom) + Suppress( statementEnd ) |
| 64 |
statement.setName("statement") |
| 65 |
statement.setParseAction(lambda s, p, toks: " ".join(toks)) |
| 66 |
|
| 67 |
script = OneOrMore( statement ) + StringEnd() |
| 68 |
script.setName("script") |
| 69 |
script.setParseAction(lambda s, p, toks: [t for t in toks.asList() |
| 70 |
if str(t).strip()]) |
| 71 |
|
| 72 |
if False: |
| 73 |
atom.setDebug(True) |
| 74 |
comment.setDebug(True) |
| 75 |
other.setDebug(True) |
| 76 |
strLiteral.setDebug(True) |
| 77 |
statement.setDebug(True) |
| 78 |
statementEnd.setDebug(True) |
| 79 |
dollarQuoted.setDebug(True) |
| 80 |
literalDollar.setDebug(True) |
| 81 |
return script |
| 82 |
|
| 83 |
|
| 84 |
getSQLScriptGrammar = utils.CachedGetter(_getSQLScriptGrammar) |
| 85 |
|
| 86 |
|
| 87 |
class ScriptRunner(object): |
| 88 |
"""An object encapsulating the preparation and execution of |
| 89 |
scripts. |
| 90 |
|
| 91 |
They are constructed with instances of Script below and have |
| 92 |
a method ``run(dbTable, **kwargs)``. |
| 93 |
|
| 94 |
You probably should not override ``__init__`` but instead override |
| 95 |
``_prepare(script)`` which is called by ``__init__``. |
| 96 |
""" |
| 97 |
def __init__(self, script): |
| 98 |
self.name, self.notify = script.name, script.notify |
| 99 |
self.pos = script.getSourcePosition() |
| 100 |
self._prepare(script) |
| 101 |
|
| 102 |
def _prepare(self, script): |
| 103 |
raise ValueError("Cannot instantiate plain ScriptRunners") |
| 104 |
|
| 105 |
|
| 106 |
class SQLScriptRunner(ScriptRunner): |
| 107 |
"""A runner for SQL scripts. |
| 108 |
|
| 109 |
These will always use the table's querier to execute the statements. |
| 110 |
|
| 111 |
Keyword arguments to run are ignored. |
| 112 |
""" |
| 113 |
def _prepare(self, script): |
| 114 |
self.statements = utils.pyparseString(getSQLScriptGrammar(), |
| 115 |
script.getSource()) |
| 116 |
|
| 117 |
def run(self, dbTable, **kwargs): |
| 118 |
try: |
| 119 |
for statement in self.statements: |
| 120 |
dbTable.connection.execute( |
| 121 |
dbTable.expand(statement.replace("%", "%%"))) |
| 122 |
except Exception as msg: |
| 123 |
raise base.ui.logOldExc( |
| 124 |
base.StructureError( |
| 125 |
"Execution of SQL script %s failed: %s"%(self.name, msg), |
| 126 |
self.pos)) |
| 127 |
|
| 128 |
|
| 129 |
class ACSQLScriptRunner(SQLScriptRunner): |
| 130 |
"""A runner for "autocommitted" SQL scripts. |
| 131 |
|
| 132 |
These are like SQLScriptRunners, except that for every statement, |
| 133 |
a savepoint is created, and for SQL errors, the savepoint is restored |
| 134 |
(in other words ACSQL scripts turn SQL errors into warnings). |
| 135 |
""" |
| 136 |
def run(self, dbTable, **kwargs): |
| 137 |
conn = dbTable.connection |
| 138 |
for statement in self.statements: |
| 139 |
try: |
| 140 |
conn.execute("SAVEPOINT beforeStatement") |
| 141 |
try: |
| 142 |
conn.execute(statement.replace("%", "%%")) |
| 143 |
except sqlsupport.DBError as msg: |
| 144 |
conn.execute("ROLLBACK TO SAVEPOINT beforeStatement") |
| 145 |
base.ui.notifyError("Ignored error during script execution: %s"% |
| 146 |
msg) |
| 147 |
finally: |
| 148 |
conn.execute("RELEASE SAVEPOINT beforeStatement") |
| 149 |
|
| 150 |
|
| 151 |
class PythonScriptRunner(ScriptRunner): |
| 152 |
"""A runner for python scripts. |
| 153 |
|
| 154 |
The scripts can access the current table as table (and thus run |
| 155 |
SQL statements through table.connection.execute(query, pars)). |
| 156 |
|
| 157 |
Additional keyword arguments are available under their names. |
| 158 |
|
| 159 |
You are in the namespace of usual procApps (like procs, rowgens, and |
| 160 |
the like). |
| 161 |
""" |
| 162 |
def __init__(self, script): |
| 163 |
# I need to memorize the script as I may need to recompile |
| 164 |
# it if there's special arguments (yikes!) |
| 165 |
self.code = ("def scriptFun(table, **kwargs):\n"+ |
| 166 |
utils.fixIndentation(script.getSource(), " ")+"\n") |
| 167 |
self.srcPosition = script.getSourcePosition() |
| 168 |
ScriptRunner.__init__(self, script) |
| 169 |
|
| 170 |
def _compile(self, moreNames={}): |
| 171 |
return rmkfuncs.makeProc( |
| 172 |
"scriptFun", self.code, "", self, |
| 173 |
self.srcPosition, |
| 174 |
**moreNames) |
| 175 |
|
| 176 |
def _prepare(self, script, moreNames={}): |
| 177 |
self.scriptFun = self._compile() |
| 178 |
|
| 179 |
def run(self, dbTable, **kwargs): |
| 180 |
# I want the names from kwargs to be visible as such in scriptFun -- if |
| 181 |
# given. Since I do not want to manipulate func_globals, the only |
| 182 |
# way I can see to do this is to compile the script. I don't think |
| 183 |
# this is going to be a major performance issue. |
| 184 |
try: |
| 185 |
if kwargs: |
| 186 |
func = self._compile(kwargs) |
| 187 |
else: |
| 188 |
func = self.scriptFun |
| 189 |
func(dbTable, **kwargs) |
| 190 |
except Exception as msg: |
| 191 |
raise base.ui.logOldExc( |
| 192 |
base.StructureError( |
| 193 |
"Execution of python script %s failed: %s"%(self.name, msg), |
| 194 |
self.pos)) |
| 195 |
|
| 196 |
|
| 197 |
RUNNER_CLASSES = { |
| 198 |
"SQL": SQLScriptRunner, |
| 199 |
"python": PythonScriptRunner, |
| 200 |
"AC_SQL": ACSQLScriptRunner, |
| 201 |
} |
| 202 |
|
| 203 |
class Script(base.Structure, base.RestrictionMixin): |
| 204 |
"""A script, i.e., some executable item within a resource descriptor. |
| 205 |
|
| 206 |
The content of scripts is given by their type -- usually, they are |
| 207 |
either python scripts or SQL with special rules for breaking the |
| 208 |
script into individual statements (which are basically like python's). |
| 209 |
|
| 210 |
The special language AC_SQL is like SQL, but execution errors are |
| 211 |
ignored. This is not what you want for most data RDs (it's intended |
| 212 |
for housekeeping scripts). |
| 213 |
|
| 214 |
See `Scripting`_. |
| 215 |
""" |
| 216 |
name_ = "script" |
| 217 |
typeDesc_ = "Embedded executable code with a type definition" |
| 218 |
|
| 219 |
_lang = base.EnumeratedUnicodeAttribute("lang", default=base.Undefined, |
| 220 |
description="Language of the script.", |
| 221 |
validValues=RUNNER_CLASSES.keys(), copyable=True) |
| 222 |
_type = base.EnumeratedUnicodeAttribute("type", default=base.Undefined, |
| 223 |
description="Point of time at which script is to run (not all" |
| 224 |
" script types are allowed on all elements).", |
| 225 |
validValues=["preImport", "newSource", "preIndex", "preCreation", |
| 226 |
"postCreation", "afterMeta", |
| 227 |
"beforeDrop", "sourceDone"], copyable=True) |
| 228 |
_name = base.UnicodeAttribute("name", default=base.NotGiven, |
| 229 |
description="A human-consumable designation of the script.", |
| 230 |
copyable=True) |
| 231 |
_notify = base.BooleanAttribute("notify", default=True, |
| 232 |
description="Send out a notification when running this" |
| 233 |
" script.", copyable=True) |
| 234 |
_content = base.DataContent(copyable=True, description="The script body.") |
| 235 |
_original = base.OriginalAttribute() |
| 236 |
|
| 237 |
def getSource(self): |
| 238 |
"""returns the content with all macros expanded. |
| 239 |
""" |
| 240 |
return self.parent.getExpander().expand(self.content_) |
| 241 |
|
| 242 |
def validate(self): |
| 243 |
if self.parent and self.type not in self.parent.acceptedScriptTypes: |
| 244 |
raise base.StructureError("Invalid script type %s for %s elements"%( |
| 245 |
self.type, self.parent.name_)) |
| 246 |
|
| 247 |
super().validate() |
| 248 |
|
| 249 |
def completeElement(self, ctx): |
| 250 |
if self.name is base.NotGiven: |
| 251 |
if self.id: |
| 252 |
self.name = self.id |
| 253 |
else: |
| 254 |
self.name = "anonymous" |
| 255 |
super().completeElement(ctx) |
| 256 |
|
| 257 |
|
| 258 |
class ScriptingMixin(base.StructCallbacks): |
| 259 |
"""A mixin that gives objects a getRunner method and a script attribute. |
| 260 |
|
| 261 |
The getRunner() method returns a callable that takes the current table |
| 262 |
(we expect db tables, really), the phase and possibly further keyword |
| 263 |
arguments, as appropriate for the phase. |
| 264 |
|
| 265 |
Objects mixing this in must define an acceptedScriptTypes attribute |
| 266 |
containing a set of script types they support. Any other script type |
| 267 |
will be rejected. |
| 268 |
|
| 269 |
Objects mixing this in must also support define a method |
| 270 |
getExpander() returning an object mixin in a MacroPackage. |
| 271 |
""" |
| 272 |
acceptedScriptTypes = {} |
| 273 |
|
| 274 |
_scripts = base.StructListAttribute("scripts", childFactory=Script, |
| 275 |
description="Code snippets attached to this object. See Scripting_ .", |
| 276 |
copyable=False) |
| 277 |
|
| 278 |
def getRunner(self): |
| 279 |
if not hasattr(self, "_runScriptsCache"): |
| 280 |
runnersByPhase = {} |
| 281 |
for rawScript in self.scripts: |
| 282 |
runner = RUNNER_CLASSES[rawScript.lang](rawScript) |
| 283 |
runnersByPhase.setdefault(rawScript.type, []).append(runner) |
| 284 |
|
| 285 |
def runScripts(table, phase, **kwargs): |
| 286 |
for runner in runnersByPhase.get(phase, []): |
| 287 |
if runner.notify: |
| 288 |
base.ui.notifyScriptRunning(runner, self) |
| 289 |
runner.run(table, **kwargs) |
| 290 |
|
| 291 |
self._runScriptsCache = runScripts |
| 292 |
|
| 293 |
return self._runScriptsCache |