Import Scripts
An Import Script reads a file you upload and creates objects in the TrialGrid system by reading the contents of the file and executing commands to modify data in the system.
You write an Import Script once for your Organization. Other people in your Organization then run it whenever they have a file to load.
Note
Import Scripts are being built in stages. At present you can register a script, write its code, test it against a file to see what it would do, and then apply what it asked for. Commands that act on your Organization or on a URL can be applied, and a command can say which URL it means. See Applying a run and Saying where a command acts below.
More on Import Scripts
Registering a script
To see the Import Scripts for your Organization:
Go to your Organization home page.
Click the "Import Scripts" card.
You will see the scripts already registered, with the Scope of each and whether each one is Active.
Click "Add Import Script" to register a new one. You will be asked for:
- Name
What the script is called. Names must be different from each other within your Organization.
- Description
What the script does, so that someone choosing a script knows which one they want.
- Scope
The level the script runs at. See Choosing a Scope below.
- Active
An Inactive script is kept but is not offered to be run. New scripts start as Inactive so you can finish writing and testing one before anyone can use it.
Choosing a Scope
The Scope sets the level the script runs at. It decides what the script is told about its environment when it runs.
Scope |
The script is told about |
|---|---|
Organization |
The Organization |
URL |
The Organization and the URL |
Project |
The Organization, the URL and the Project |
Draft |
The Organization, the URL, the Project and the Draft |
Pick the level the file belongs to. A file listing forms to copy into a new Draft belongs to a Project, so that script has Project scope. A file that creates a set of Projects belongs to a URL, so that script has URL scope.
The Scope also sets where a command acts by default. A command can say otherwise, which is how one script can build the same things in several URLs. See Saying where a command acts below.
Writing the code
The Code tab holds the body of the script. The editor shows line numbers and colors the code as you type.
When you save, TrialGrid checks that the code is valid. If it is not, the page tells you what is wrong and which line it is on, and your work is kept on screen so you can correct it. Nothing is run at this point. The check only confirms that the code can be read.
You can save a script with no code in it. This lets you register a script and come back to write it.
What your script is given
Your code is handed one name, importer, and everything it can reach hangs off that.
What |
For |
|---|---|
|
The values the person running the script filled in, and the files they chose |
|
The object the run is pointed at, and the levels above it |
|
Where the run is pointed, as a location a command can be given |
|
Writing to the run's log |
|
Asking for a command to be executed |
|
Keeping a table or a single value to show with the run |
|
Building a location from an object the script has access to, with |
Your script is ordinary Python, with some things left out for safety. You cannot import modules, open files, or reach the network. If you use a name that is not available the system will show an error and which line the error is on.
You can write your own functions with def, and use lambda, list comprehensions, +=, and
the methods of text, lists and dictionaries such as startswith, split and append. A list
can be passed as a call's arguments with *, and a dictionary as its named arguments with **,
as in importer.execute("CreatePropertyDefinition", applies_to="Form", **prop). Names starting
with an underscore are not allowed.
These built-in functions are available, along with True, False, None and the usual
exceptions such as ValueError:
abs, all, any, bool, bytes, callable, chr, compare,
compare_to_standard, complex, delattr, dict, divmod, enumerate, float,
frozenset, hash, hex, id, int, isinstance, issubclass, len, list,
max, min, oct, ord, parse_json, pow, range, repr, reversed,
round, set, setattr, slice, sorted, str, sum, tuple, zip
parse_json reads JSON text into dictionaries, lists, text, numbers and None. Use it where
text you are reading holds JSON, such as a Custom Property or a spreadsheet cell. A JSON File
setting needs none of this: it arrives already read, through .root. parse_json raises
ValueError when the text is not JSON, so a script can name what was wrong and carry on:
for form in importer.context.draft.als_forms_set.all():
mapping_property = form.properties["field mapping"]
if not mapping_property.is_set:
continue
try:
mapping = parse_json(mapping_property.value)
except ValueError as error:
importer.log(f"{form.OID}: the field mapping is not valid JSON. {error}")
continue
importer.log(f"{form.OID} maps {len(mapping)} fields")
NaN, Infinity and -Infinity are refused the same way. Some programs write them into
JSON, but JSON itself does not define them, and NaN is not equal to anything, not even to
itself. A row your script reports now is easier to deal with than one that silently matches nothing
later. A JSON File setting holding one of them, or a YAML File setting holding .nan or .inf,
is refused for the same reason, when the file is read.
compare_to_standard compares an object with its Library Standard, and compare compares two
objects of the same kind directly, as the Compare dialog does. Each returns the differences, Standard
Rules and explanations as dictionaries and lists, which
Comparing Objects describes. compare_to_standard returns None when
the object has no Library Standard you can view. Both raise ValueError when the objects cannot be
compared, such as a Form and a Folder:
forms = importer.context.draft.als_forms_set.order_by("Ordinal")
for form in forms:
result = compare_to_standard(form)
if result is None:
importer.log(f"No Library Standard for {form.OID}")
continue
for row in result["attributes"]:
if row["state"] not in ("same", "not_compared"):
values = f"{row['source_value']} / {row['target_value']}"
importer.log(f"Against its Standard, {form.OID} {row['name']}: {values} ({row['state']})")
for collection in result["children"]:
for child in collection["objects"]:
if child["state"] not in ("same", "not_compared"):
name = f"{collection['name']} {child['name']}"
importer.log(f"Against its Standard, {form.OID} {name}: {child['change']} ({child['state']})")
try:
compare(forms.first(), importer.context.draft)
except ValueError as error:
importer.log(f"Not compared: {error}")
Others you might expect, such as map, filter, getattr and type, are not. Use a list
comprehension instead of map or filter. print writes nothing: use importer.log, which
takes text, so write importer.log(f"{count} fields") rather than importer.log(count).
A script changes nothing by itself. It asks for changes with importer.execute, and the
Command Reference lists every command it can ask for. Commands create, copy
and link things, set which Forms are in each folder of a Matrix, change a Project's settings and
custom properties, and write a Project's wiki pages, which keep their earlier versions.
UpdateDraftObject changes a Form, Folder or other object a Draft already holds, and the change is
recorded in that object's history. No command deletes an object a Draft holds. Taking a Form out of
a Matrix folder, and clearing a value of an object or a Project, are the only things a command
removes.
A command has the same side effects as making its change on the page. Your auto actions run for what it creates or changes, and labels are removed where your label removal conditions say a change removes them. Those can change labels, custom properties and assignments on other objects, such as an Edit Check that adds a Matrix whose folders a script changed.
A file is one of the settings a script declares, so it is read as importer.settings["name"] like
any other value. What it offers depends on the kind of file the setting is for. An Excel file has
sheets and a JSON or YAML file has a document, and both are covered in
Reading a file.
Writing to the log
The log is how a script explains itself to whoever runs it. It is useful to add logging statement to show what decisions or actions your script is taking.
importer.log("Reading the form list")
importer.warn("No Notes column, so notes will be left empty")
importer.error("This file has no Fields sheet")
importer.error records a problem but does not stop the run. Use it to report every bad row
rather than only the first. To stop, raise instead:
raise ValueError("This file is not one this script can read")
The run then ends, and the log says where:
Exception on line 2: This file is not one this script can read
Keeping results
A script that answers a question, rather than one that creates something, can keep what it found as named results. A test run shows them on a tab of their own.
draft = importer.context.draft
out.value("Forms", draft.als_forms_set.count())
out.table(
"Active forms",
draft.als_forms_set.filter(DraftFormActive=True),
columns=["OID", "DraftFormName"],
)
out.table keeps a table. Given a list of objects, such as a Draft's forms, the columns name what
to show of each one, and the first column links to the object the row is about, unless that column
holds an object of its own, which links to itself instead. Otherwise each row is a list, a
dictionary or a single value. A cell can itself be an object, and is shown as a link to it where
that kind of object has a page of its own, so put the object in the cell rather than its name and
whoever reads the result can open it. Objects without a page, such as a person, are shown as their
name.
Given dictionaries without columns, the table shows every key any row holds, so one dictionary per
object holding only what that object has still shows all of it.
out.value keeps one value, such as a count. Given a dictionary it keeps a table of keys and
values.
A run can keep up to 12 results, and a table up to 2,000 rows of up to 20 columns. The test run shows the first 200 rows of each table and says how many it has.
To count, write the addition out in full. counts[key] += 1 is not allowed in a script, but
this is:
counts = {}
for control_type in importer.context.draft.als_fields_set.values_list("ControlType", flat=True):
counts[control_type] = counts.get(control_type, 0) + 1
out.value("Fields by control type", counts)
Settings
A script is given its inputs as settings. A file is one of them, and so is anything a file could not tell the script: a script that copies forms from a library has to be told which library, and no spreadsheet column can answer that.
You declare the settings a script needs on the Settings tab. The person running the script is then asked for those values each time. You are asked for them when you test a script, so you can try a script with different values.
Each setting has:
- Name
The name the script uses to read the setting. Keep it short and do not change it once the code uses it.
- Display Name
The label shown to the person running the script.
- Description
Help text shown under the field.
- Type
What kind of value it is. See the table below.
- Options
For a Choice setting, the values to choose from, separated by commas.
An option cannot contain a comma. If you type
Yes, please,Noyou get three options,Yes,pleaseandNo, not two. Space around a comma is removed, soYes, NoandYes,Nogive the same two options.- Default Value
The value the run form starts with. The person running can change it or clear it. Clearing it means the script gets no value for that setting, not the default.
- Required
Whether the script can be run without a value.
Setting types
Type |
What the person running the script gives |
|---|---|
Text |
Any text |
Boolean |
True or False |
Choice |
One of the options you list |
Integer |
A whole number |
Draft |
A Draft to copy from |
Project |
A Project |
URL |
A URL |
Excel File |
An .xlsx file to upload |
JSON File |
A .json file to upload |
YAML File |
A .yaml or .yml file to upload |
Draft, Project and URL settings hold an object rather than a typed value. These cannot have a default value, because an object belongs to one Organization and not everyone may use it. Leave the Default Value empty for them, and the person running the script chooses the object each time.
The three file settings hold an uploaded file, and they cannot have a default value either: the file is chosen when the script is run. Declare one for each file your script reads. A script may declare none, in which case it is simply run and reads nothing, or several, in which case the person running it is asked for each one.
The order of the rows is the order the settings are shown in. Drag a row to move it.
Checks on the settings you enter
Two settings on the same script cannot share a Name or a Display Name. A Choice setting needs at least one option, and its default has to be one of them. A Boolean default has to be True or False, and an Integer default has to be a whole number. An object or file setting cannot have a default at all. If any row has a problem the page tells you which row and does not save, and your rows are kept on screen.
TrialGrid also compares the settings you declared against the settings your code reads. If your code reads a setting you have not declared, or you declare one the code does not appear to read, you are told after the save. These are notes, not errors. The script is saved either way, because there are good reasons for the two to differ: your code might read a setting only in certain cases, or work out the name while it runs.
Testing a script
The Code tab has a Test panel beside the editor. Use it to run your script against a real file and see what it would do, without anything being created or changed.
Choose the target, choose a file, fill in any settings your script declares, and select Run Test. TrialGrid runs the saved script, so save your changes first. The panel tells you if you have unsaved work.
Choosing the target
The target is the object your script works in. Which kind it is comes from the script's scope: a Draft scope script is pointed at a Draft, a Project scope script at a Project, and a URL scope script at a URL. An Organization scope script has no target to choose. It runs against your Organization.
Start typing in the target box to search. The list holds only the objects you are allowed to see, inside the Organization that owns the script. It is searched as you type because an Organization can hold many thousands of Drafts.
Drafts and Projects are listed under the URL and Project they belong to. A Project that holds Standard libraries is marked with a library icon, so you can tell a library Draft from a study Draft before you choose one.
Your choice is checked again when the run starts. If your permission has changed since you chose it, the run stops and tells you to choose another.
Reading the target
Your script reads the target as importer.context:
draft = importer.context.draft
importer.log(draft.DraftName)
for form in draft.als_forms_set.all():
importer.log(form.OID)
The target also tells your script about the levels above it. A Draft knows its Project, and that
Project knows its URL, so importer.context.project and importer.context.url work without you
choosing them.
You do not have to read every object in a set to find the ones you want. Ask for them instead, and the Draft is searched for you, which matters in a Draft holding thousands of Fields:
draft = importer.context.draft
checkboxes = (
draft.als_fields_set.filter(ControlType="CheckBox").select_related("Form").order_by("Form__Ordinal", "Ordinal")
)
current_form = None
for field in checkboxes:
if field.Form.OID != current_form:
current_form = field.Form.OID
importer.log(f"Form {current_form}")
importer.log(f" {field.FieldOID}")
Choosing and Counting Objects lists every method a set offers, such as
filter, exclude, order_by, count and first, with examples. They are the same in a
script and in a Document Template.
The names you use are the same ones a Document Template uses. See the Object Model Reference for what each kind of object gives you. Reading something the reference does not list stops the run and names the line, so a mistyped attribute is reported rather than silently empty.
Text in a filter must match exactly, including its case. If a filter such as
draft.als_fields_set.filter(ControlType="checkbox") finds nothing because no Field has that
value, the log says so and helps you correct it. It names any value that would match if case were
ignored, for example "CheckBox", or otherwise lists the values that are there. Your script carries
on either way. Only the first few such filters in a run are reported.
Custom properties work the same way as in a Document Template. Every property defined for the URL is there, including ones nobody has filled in:
for name, prop in importer.context.draft.properties.items():
importer.log(f"{name} = {prop.value}")
You can write a property's name in any case: properties["TA"] and properties["ta"] are the
same property. If you ask for a name that is not defined, your script stops and says which names
are. With properties.get(name), the script carries on and the log says the same thing once.
The properties you get are the ones defined for the URL the object is in. If your script follows a
link to an object in a different URL, such as a Standards Draft reached through
get_compliance_chain(), you are shown the properties that URL defines, with the values set there.
You can also ask an object type what properties it has, without needing an object of that type. This is useful when a Draft does not hold one yet, for example to check the column headings of a workbook before loading it. A type lists every property defined for it, none of them set:
spec = importer.context.url.customobjectdefinition_set.get(name="Report Specification")
for name, prop in spec.properties.items():
importer.log(f"{name} is a {prop.value_type} property")
A type also tells you what identifies its objects, which is what you need to copy one. A Draft
download writes the objects of a type your Organization defined to a sheet named after its
external_name, one column per property, and identifier_parts names the columns whose values
make up an object's identifier, in the order they are joined:
kind = importer.context.url.customobjectdefinition_set.get(name="Stock")
importer.log(f"A {kind.name} is written to the {kind.external_name} sheet")
importer.log(f"Its identifier is {kind.identifier_parts} joined with {kind.identifier_separator}")
So a script can read a sheet of a download and build the identifier of each object on it, without being told which of the columns is the identifier:
workbook = importer.settings["workbook"]
kind = importer.context.url.customobjectdefinition_set.get(name="Stock")
for row in workbook.sheet(kind.external_name).rows():
parts = []
for heading in kind.identifier_parts:
parts.append(row.get(heading))
importer.log(kind.identifier_separator.join(parts))
An external_name is at most 31 characters and never uses a character Excel refuses in a sheet
name or the name History, which Excel reserves, so the sheet a download writes has exactly that
name.
A built-in type such as Forms or Edit Checks answers identifier_parts too, with the one column
of the object that holds its identifier. Take care with a download there: the built-in sheets are
the fixed sheets of the Rave ALS format, so neither the sheet name nor the column heading always
matches. A Standard Rule is written to the TG_Rules sheet, and its rule_id is written under
the heading Identifier.
An Organization script is not pointed at a URL. It reads the URLs of its Organization instead. The list holds only the URLs that the person running the script has permission to view, of the types your Organization is licensed for:
for url in importer.context.organization.raveurl_set.all():
for kind in url.customobjectdefinition_set.all():
importer.log(f"{url.name}: {kind.name} has {len(kind.properties)} properties")
A URL lists its Projects in the same way, again only the ones the person running the script has permission to view:
for project in importer.context.url.project_set.all():
area = project.properties["therapeutic area"]
if area.is_set:
importer.log(f"{project.ProjectName}: {area.value}")
A Form, Edit Check, Test Case or other object a ticket can be about lists its tickets in
ticket_relations. This script names the open tickets of each Edit Check in the Draft:
checks = importer.context.draft.als_checks_set.filter(ticket_relations__ticket__open=True).distinct()
for check in checks.order_by("CheckName").prefetch_related("ticket_relations__ticket"):
tickets = sorted(
[relation.ticket for relation in check.ticket_relations if relation.ticket.open],
key=lambda ticket: ticket.iid,
)
importer.log(f"{check.CheckName}: " + ", ".join(f"#{ticket.iid} {ticket.title}" for ticket in tickets))
prefetch_related reads the tickets of every Edit Check together, rather than asking again for
each one. The loop reads check.ticket_relations without .all(), because .all() would ask
the database again and leave the tickets already read unused.
To go from a ticket to the objects it is about, see Objects of any kind.
Reading activity
An object's activities is its own history, oldest first:
form = importer.context.draft.als_forms_set.get(OID="DM")
for record in form.activities:
importer.log(f"{record.who.username}: {record.description}")
A URL and an Organization list their activity with activityrecord_set, newest first. As with
their URLs and Projects, the list holds only the activity the person running the script has
permission to view: activity of a Project they cannot view is left out before the script reads it.
Each record's content_object is the object it is about. It is None when that object has been
deleted, is a kind of object a script cannot read, such as a generated document, or is no longer in
the Project, URL or Organization the record names, so check it before reading from it:
recent = importer.context.url.activityrecord_set.prefetch_related("content_object")[:20]
for record in recent:
item = record.content_object
if item is None:
importer.log(record.description)
else:
importer.log(f"{record.description} ({item.verbose_name()} {item})")
An Organization script reads its Organization's activity in the same way, from
importer.context.organization.activityrecord_set. A long list is best read a slice at a time, as
above, rather than all at once.
Settings that name an object
A Draft, Project or URL setting is chosen the same way as the target, from its own searchable box in the Test panel, with the same library icon on Projects that hold Standard libraries. A Draft box offers only Drafts that allow importing.
What you choose stays chosen when you save the script, so you can edit and run without picking your test values again each time.
Your script reads the choice as it reads anything else:
library = importer.settings["source_library"]
for row in importer.settings["form_list"].sheet("Forms").rows():
form_oid = row["Form OID"]
importer.log(f"looking for {form_oid} in {library.DraftName}")
If you leave one empty, reading it stops the run and says nothing was chosen. If the object you chose is one you can no longer use, the run stops before it starts and asks you to choose again.
What you get back
There are up to four tabs. Results shows what your script kept with out.table and
out.value, as a line for each value and a table for each table, with a cell that stands for an
object linking to it. What it does and Values sit together and list the commands your
script asked for, the first in words and the second with what each one carries. Log shows every
line your script wrote with importer.log, importer.warn or importer.error, in the order it wrote
them. The commands are checked, so a command with values it will not accept is reported here
rather than when the script is run for real. The commands are listed only. Nothing is created
and nothing is changed.
A tab you are not offered is one this run has nothing for, and a run with one thing to show is given no tabs at all. Results and Log say how much they hold. A script that answers a question and asks for no commands has Results and Log, and opens on Results, which is what you ran it for. A run that asked for commands opens on What it does, which is what you decide from.
If your script stops with a problem, the tabs open on Log, which says which line of your code failed and why. Anything the script did before that point is still shown, so a run that logged forty rows and then failed on the forty-first tells you about the forty, and keeps whatever results it had kept by then.
What is kept
A test run is not listed on the Runs tab. Its commands are kept with it, so that it can be applied and its commands downloaded, until one of these happens:
You run the test of the same script again. The commands of your earlier runs are then discarded, unless a run has been applied or is being applied.
About 30 days pass since the run, or up to a week beyond that. The run and its commands are then removed, whether or not it was applied.
The file you chose is kept so that you can run the test again without choosing it again, and is removed about a day after you chose it, or within a week of that.
What a test run cannot do yet
A test run never carries out the commands your script asks for. They are listed instead, so you can see what would happen without anything being created or changed. Applying the run afterwards is what carries them out.
Limits
A test run has limits, so one script cannot tie up the system:
it can run for up to 3 minutes, and reading a large sheet counts towards that
it can write up to 500 log lines, and any beyond that are not kept
it can build up to 20,000 commands
the file can be up to 20 MB, and a run reads up to a million cells from it. A row counts as at least four cells however narrow it is, because holding a row costs about that much whether it has one value in it or four
Applying a run
A test run changes nothing. It reads your file, works out what it would do, and lists it.
The list is shown two ways. What it does is a sentence for each command, which is what you read to decide whether the run is right. Values shows the same commands with the values each one carries, which is what you read when you are working out why a command is not what you expected.
A run of more than 50 commands is too long to read one by one, so What it does counts them instead: one line for each kind of command and where it acts, such as Create Data Dictionary Entry × 999 in a Draft. After 49 such lines, the rest are counted together as Other commands. Values shows the first 50. Either tab offers the whole list as a download: What it does as text, a sentence for each command, and Values as JSON, every command with the values the script gave it. A command the script sent somewhere other than where the run is pointed also says where.
A long value is shortened so that one command cannot bury the rest, because an icon's drawing runs to thousands of characters. Select Show all beside it to read the whole thing.
If you are happy with the list, select Apply these commands. TrialGrid then carries them out, all of them together: if any one cannot be done, none of them are, and nothing is left half finished.
Your permissions are checked again at this point, for every command. A run that built a command you are not allowed to make stops and tells you which one, and nothing is created.
When the apply finishes it says how many commands it carried out, followed by anything you should know about the result: a value that was changed on its way in, such as a tab replaced by a space, or an object that was already in the Draft and so was not copied. Objects already in a Draft are counted, with one line for each Project, Draft and kind, up to 50 lines. The first 50 of the rest are listed. Anything beyond either limit is counted together at the end.
An apply can run for up to 30 minutes. A very large run, such as many thousands of records added to a Draft that already holds many, can take longer than that. It is then stopped, and nothing is written.
A run can only be applied once. Applying is not undoable, so read the list first.
Only your latest test run of a script can be applied. Running the test again discards the commands of your earlier runs that were not applied, so a run still showing in another browser tab says its commands were not kept.
Saying where a command acts
Every command acts somewhere, and that place is a location: your Organization, a URL, a Project
and a Draft. Written down, a location reads as a path - Acme / Study A / Project 1 / Draft 1 -
and that is what you see beside each command in a run's list, so two commands doing the same thing
in different places can be told apart.
The path shown against a command is the path to where that command acts, which can be shorter than the one the run is pointed at. An icon belongs to your whole Organization, so a command creating one shows only your Organization, even in a run pointed at a Draft.
A command with nothing more said about it acts where the run is pointed. You choose that when you start the run, and a script set to Project or Draft scope reaches the URL that Project or Draft sits in. Most scripts never say where at all:
importer.execute("CreateObjectDefinition", name="Visit", plural_name="Visits",
external_name="VIS")
A command's values can also be collected in a dictionary and unpacked into the call with **,
which is useful when your script builds them up as it goes:
values = {"name": "Visit", "plural_name": "Visits", "external_name": "VIS"}
importer.execute("CreateObjectDefinition", **values)
To act somewhere else, give the command a location. The name of the argument says which level the
command needs: a command that acts on a URL takes url_location, one that acts on a Draft takes
draft_location. Anything ending in _location takes a location; everything else is a
value. Start from where the run is pointed and say what is different:
for url_name in ["Study A", "Study B"]:
importer.execute("CreateObjectDefinition", name="Visit", plural_name="Visits",
external_name="VIS",
url_location=importer.context.location.with_url(url_name))
importer.context.location is where the run is pointed. with_url, with_project and
with_draft each give you a new location with that part changed.
Naming a URL drops the Project and the Draft that were in the old location, because those belonged to the URL you have just moved away from. If you need them, say them as well:
somewhere = importer.context.location.with_url("sandbox").with_project("Test Project 1")
You can also take the location of something the script is already holding, such as a Draft supplied as a setting:
library = importer.settings["source_library"]
somewhere = Location.from_object(library)
A few commands work between two places, and then both are named for what they are.
CopyDraftObject copies from one Draft into another, so it takes source_draft_location and
target_draft_location rather than one draft_location that would not say which end is
which.
Naming the parts yourself
Start from where the run is pointed and name the parts you want:
somewhere = importer.context.location.with_url("Study A").with_project("Project 1").with_draft("Draft 1")
How far down a location names is what decides which commands can use it. That one names a Draft, so it can be given to a command that acts on a Draft, and equally to one that acts on a Project, a URL or your Organization. A command takes the part of the location it needs and ignores what is below it.
A location that stops higher up cannot be used lower down. This one names a Project:
somewhere = importer.context.location.with_url("Study A").with_project("Project 1")
Give that to a command acting on a Draft and the run stops, saying the command acts on a draft and your location does not reach one. Add the Draft to use it there:
somewhere = importer.context.location.with_url("Study A").with_project("Project 1").with_draft("Draft 1")
Starting from importer.context.location matters, because it carries your Organization and a
location has to be unbroken from your Organization down. Writing one out with Location(...) and
leaving the Organization off gives you a location that reaches nothing, and the run stops with the
same message. If you do write one out, name your Organization too:
somewhere = Location(organization_name="Acme", url_name="Study A", project_name="Project 1")
A location written from names is refused in two cases where one from Location.from_object is
not. A location built from an object carries that object's id as well as its name: the name is what
decides which thing the command acts on, and the id only chooses between things of the same name.
Two things share the name. If the Project holds two Drafts called "Draft 1", a location naming "Draft 1" cannot say which, and the run stops and tells you so.
Some arguments need the id.
CopyDraftObjectwill not accept asource_draft_locationbuilt from names alone, and neither willLinkDraftToLibraryfor itslibrary_draft_location. Both want the Draft the id names, because what you are copying from has to be the exact Draft somebody approved copying from, not whatever now carries that name.
So use Location.from_object for anything the script is holding, and name the parts yourself when
you are reaching something it is not, such as a URL named in your file.
What you need to be allowed
You need permission on whatever the location names, for each command. Naming a URL does not give you access to it. A location naming a URL you cannot use is refused exactly as one naming a URL that does not exist is, and for the same reason: a script must not be able to work out what is in your Organization that you are not allowed to see.
The permission asked for is the one the same action needs elsewhere in TrialGrid. Creating an object type or a property asks for Manage Metadata, a document template asks for Manage Document Templates, and a custom diagnostic asks for Manage Custom Diagnostics. Your permissions are read when you apply, not when the run was made, so a permission taken away in between stops the command.
The URL's Organization must be licensed for the system that URL belongs to. A run against a URL whose Organization is not licensed for it stops and says so.
When a location is refused
A location has to reach the level the command acts on. A script set to Organization scope is not pointed at a URL, so a command that acts on one has to name a location that reaches a URL. If it does not, the run stops and says which command and how far its path got.
A location also has to name one thing. If two URLs in your Organization share a name, or two Projects in a URL, or two Drafts in a Project, a location cannot tell them apart. Applying the run stops rather than guessing, so you will see this when you apply rather than when you run. Point a setting at the one you mean, or give them different names. A setting holds the one object that was chosen when the run was set up, so a location taken from it can tell two objects of the same name apart. The name still has to match when you apply: if the object is renamed between running the script and applying it, the run stops, because the name you approved is no longer the name it points at.
Note
If the script's scope is changed after a run is made, that run can no longer be applied. The list you approved was built for a different scope, so it is not the list the changed script would produce. Run the script again.
Names that belong to your Organization
Some things are named across the whole system rather than within your Organization. An icon is one.
So that two Organizations can each have an icon called circle, TrialGrid puts your Organization
in front of the name you give, exactly as it does when you add an icon by hand.
Write the plain name in your script:
importer.execute("CreateIcon", name="circle", svg_content=svg)
and for an Organization called Acme the command will read Create icon acme-circle, which is the
icon you will get. The list you approve always shows the name that will exist, not the one you
typed.
Do not put your Organization in the name yourself. name="acme-circle" would make
acme-acme-circle, so it is refused and the run tells you to write circle instead.
Creating records from a file
A script can create records of the object types defined on your URL. This is the usual reason for writing one: a file holds rows of information, and each row should become a record.
CreateDraftObject creates one record. You give it the object type and the values the record
holds:
importer.execute(
"CreateDraftObject",
type="Visit",
attributes={"Name": "Screening", "Day": "1"},
)
The attribute names are the properties of that object type, named as they are named there. Capital letters do not have to match. An attribute the object type does not have stops the apply, so a misspelled column name is reported rather than quietly dropped.
A sheet of rows then reads like this:
for row in importer.settings["visits"].sheet("Visits").rows():
importer.execute(
"CreateDraftObject",
type="Visit",
attributes={"Name": row["Name"], "Day": row["Day"]},
)
If the same kind of information is spread over several sheets, walk the sheets as well:
for sheet_name in importer.settings["visits"].sheet_names:
for row in importer.settings["visits"].sheet(sheet_name).rows():
importer.execute(
"CreateDraftObject",
type="Visit",
attributes={"Name": row["Name"], "Day": row["Day"]},
)
The identifier of each new record is worked out from its values, the same way it is when somebody fills the form in. A record the Draft already holds under that identifier is refused, so a file loaded twice does not quietly create everything a second time.
That check needs an identifier with no question mark in it. A row that leaves out one of the values its object type is told apart by is still loaded, and the record is named with a question mark where that value would be, exactly as it is when somebody leaves the box empty in the editor. A question mark written as part of a value, as in "Pregnant?", counts the same way. Records whose identifier holds a question mark are not compared with each other, so loading the same file twice does create them twice. The same is true of an object type told apart by nothing at all.
If that matters for your file, check it in the script: read the column that fills the identifier and report the row rather than issuing a command for it. That way the run log names the rows you left out, which is more use than a record nobody can tell from another.
for row in importer.settings["visits"].sheet("Visits").rows():
if not row["Name"]:
importer.warn(f"Row {row.number} has no Name, so no Visit was created from it")
continue
importer.execute(
"CreateDraftObject",
type="Visit",
attributes={"Name": row["Name"], "Day": row["Day"]},
)
Records that sit inside other records
Some object types sit inside another, so a record has to say which record it belongs in. Name it
with parent_identifier, using the identifier of the parent record:
importer.execute(
"CreateDraftObject",
type="Assessment",
parent_identifier="Screening",
attributes={"Name": "Weight"},
)
The parent has to be there before the child is created. Create the parents first and the children afterwards, which for a file holding both means reading it twice.
If the Draft holds two parent records answering to that identifier, the apply stops rather than choosing one of them for you.
Copying works the same way. CopyDraftObject takes parent_identifier too, and uses it at both
ends: it finds the record inside that parent in the Draft you are copying from, and puts the copy
inside the record of the same identifier in the Draft you are copying into. So the parent has to be
in the target Draft already. Copy the parent first, or copy the whole parent and the records inside
it come with it.
Values that point at something
Two kinds of property hold something other than text, and for both of them you write the name a person would use.
A property that refers to another record takes the identifier of that record, and the record has to be in the same Draft:
importer.execute(
"CreateDraftObject",
type="Observation",
attributes={"Name": "Weight", "At": "Screening"},
)
A property that holds a person takes their username.
Built-in object types
Forms are created the same way. The attributes are the columns a Form has rather than properties somebody defined, and they are named as the ALS workbook names them, so a file exported from Rave already heads its columns the way the command expects:
for row in importer.settings["visits"].sheet("Visits").rows():
name = row["Name"]
if not name:
continue
oid = "".join(character for character in name.upper() if character.isalnum() or character == "_")
importer.execute(
"CreateDraftObject",
type="Form",
attributes={"OID": oid, "DraftFormName": name, "HelpText": "Loaded from a file"},
)
Any custom properties your URL has added to Forms are named alongside those columns, and a name that is neither stops the apply with the full list of what a Form will take.
A Form OID takes letters, digits and the underscore only, cannot start with a digit, and is at most 50 characters. A column of names from a spreadsheet will not usually pass that, which is why the example above works the OID out from the name rather than using it as it stands.
A Form has to be given an OID and a name, and the Draft must not already hold a Form with either of them. Where a Form sits among the others is not chosen here, and neither is where a copy of it came from: a new Form goes on the end.
Values are read the way the same cell is read when you upload a workbook, so a value that has to be changed slightly to be stored - a tab becoming a space - is reported while the apply runs rather than refused.
Folders and Custom Functions are created the same way, with type="Folder" or
type="Custom Function" and the columns of the Folders or CustomFunctions sheet. Any
custom properties your URL has added to them are named alongside those columns.
A Folder has to be given an OID and a name, and neither may be SUBJECT. The day columns, such as
Targetdays, take a whole number from 0 up to 1000000, written either as text or as a number. A
Folder that is not given IsReusable is reusable, as it is when you add one in the editor.
ParentFolderOID names a Folder already in the Draft, other than SUBJECT. A new Folder goes on the
end.
A Custom Function has to be given a name and its source code. The name can be up to 50 characters
and cannot contain quotation marks or the | character. The source code can be as long as Rave
accepts, counting each line break as two characters. Lang is C# unless you give SQL.
The source code is not checked for errors when the Custom Function is created, so open it in the
editor and click Validate to see whether Rave would accept it.
Fields are created with type="Field" and the columns of the Fields sheet. Name the Form the
Field goes in by its OID in parent_identifier, not in a FormOID attribute. The Form has to be
in the Draft already, so create it first. The Ordinal column and the columns that record where a
Field was copied from, such as FSourceObjectId, are not taken either:
importer.execute(
"CreateDraftObject",
type="Form",
attributes={"OID": "VS", "DraftFormName": "Vital Signs"},
)
importer.execute(
"CreateDraftObject",
type="Field",
parent_identifier="VS",
attributes={"FieldOID": "VSHEAD", "DraftFieldName": "Heading", "PreText": "Record the vital signs"},
)
importer.execute(
"CreateDraftObject",
type="Field",
parent_identifier="VS",
attributes={
"FieldOID": "PULSE",
"DraftFieldName": "Pulse",
"VariableOID": "PULSE",
"DataFormat": "3",
"PreText": "Pulse (beats per minute)",
"LowerRange": "30",
"UpperRange": "200",
},
)
A Field has to be given a FieldOID and a DraftFieldName, and its Form must not already hold a
Field with either of them. A Field on another Form can have the same OID. A new Field goes on the end
of its Form. Any custom properties your URL has added to Fields are named alongside the columns.
The same checks apply as in the Form editor. A Field that holds data needs a VariableOID and a
DataFormat that suits its ControlType, a range can only be set on a numeric Field, and a
control type that shows a list of choices needs a Data Dictionary. Name a dictionary in
DataDictionaryName or UnitDictionaryName by its name. It has to be in the Draft already. Fields
in the Draft that share a VariableOID must have the same DataFormat, dictionaries and
CodingDictionary. A Field with IsLog=True can only go into a Form that has a LogDirection.
A Field you do not give a ControlType is a Text Field, and a new Field is active and visible unless
you say otherwise. On a Classic URL, a label is a Text Field with no VariableOID and no
DataFormat, like the first Field in the example. On a Designer URL, a label has
ControlType="Label", and a Field that holds data but has no VariableOID is given the one
Designer would give it, made from the Form OID and the Field OID.
Fields created one after another for the same Form are added together. If one of them is refused, none of them is created. Adding Fields is recorded in the history of each Field and of its Form, and your URL's auto actions run for the Form, as they do when you save it in the editor.
Some columns apply only to Classic Rave, such as DraftFieldNumber and IsVisualVerify on a Field,
and IsTemplate and LinkFormOID on a Form. On a Designer URL, giving one of them a value stops
the apply, and the command says which one. A blank value sets nothing, so an empty column in your file
is fine. A record created on a Designer URL leaves them empty.
Test Cases are created with type="Test Case". The attributes are Name, Script,
IsTemplate and Priority, and any custom properties your URL has added to Test Cases. A Test
Case has to be given a name and a script. The same limits apply as in the Test Case editor: the name
must not already be used in the Draft, the priority is a whole number from 1 to 999999, the script
cannot be longer than TrialGrid allows, and a template cannot include another template.
A Test Case whose script is not valid does not stop the apply. The Test Case is created and marked as not valid, as it is when you save one in the editor, and the apply reports the errors so that you can correct them before the Test Case is run.
Creating a Test Case needs the Manage Tests permission, which is what the Test Case editor asks for. Every other record needs Edit Objects.
Matrices are created with type="Matrix" and the columns of the Matrices sheet. A Matrix has
to be given an OID and a name. The OID takes letters, digits and the underscore only, and the Draft
must not already hold a Matrix with that OID or that name. Maximum is a whole number from 0 to
9999, and is 0 if you leave it out. A Matrix created this way is not made the Draft's Default Matrix.
Any custom properties your URL has added to Matrices are named alongside those columns.
A new Matrix is empty. SetMatrixFolderForm puts a Form in a Folder of the Matrix, or takes it
out, which is the same as ticking or clearing one cell of the Matrices grid. Give it the OIDs of the
Matrix, the Folder and the Form, and on=True to tick the cell or on=False to clear it. The
SUBJECT Folder can be used like any other. Each command sets one cell, so a script sets only the
cells it means to change, and the Matrix, Folder and Form all have to be in the Draft already:
importer.execute(
"CreateDraftObject",
type="Matrix",
attributes={"OID": "VISITS", "MatrixName": "Visits", "Addable": False},
)
for row in importer.settings["visits"].sheet("Visits").rows():
name = row["Name"]
if not name:
continue
folder_oid = "".join(character for character in name.upper() if character.isalnum() or character == "_")
importer.execute("SetMatrixFolderForm", matrix_oid="VISITS", folder_oid=folder_oid, form_oid="VS", on=True)
Ticking a cell that is already ticked, or clearing one that is already clear, changes nothing. A cell that does change is recorded in the Matrix's history, and the Matrix is treated as changed, just as it is when you save the grid: labels that are removed when a Matrix changes are removed, and your URL's auto actions run. Setting cells needs the Edit Objects permission.
Data Dictionaries and Unit Dictionaries are created with type="Data Dictionary" or
type="Unit Dictionary", giving the name as DataDictionaryName or UnitDictionaryName. The
Draft must not already hold a dictionary of that kind with that name. A new dictionary is empty. Each
entry is then created with type="Data Dictionary Entry" or type="Unit Dictionary Entry",
naming its dictionary in parent_identifier:
importer.execute(
"CreateDraftObject",
type="Data Dictionary",
attributes={"DataDictionaryName": "VISIT_DAY"},
)
for row in importer.settings["visits"].sheet("Visits").rows():
if not row["Name"]:
continue
importer.execute(
"CreateDraftObject",
type="Data Dictionary Entry",
parent_identifier="VISIT_DAY",
attributes={"CodedData": row["Day"], "UserDataString": row["Name"]},
)
A Data Dictionary Entry takes CodedData, UserDataString and Specify. A Unit Dictionary
Entry takes CodedUnit, UnitString, ConstantA, ConstantB, ConstantC,
ConstantK and StandardUnit. Any custom properties your URL has added to dictionary entries
are named alongside those columns. Each entry goes on the end of its dictionary, and an entry can be
added to any dictionary in the Draft, not only one the script created.
The same rules apply as in the dictionary editor. An entry needs both its code and its text, and its
code cannot already be in that dictionary. Codes that differ only in upper and lower case count as
different codes. A Unit Dictionary Entry needs all four constants, except the one you mark with
StandardUnit=True, which takes 1, 1, 0 and 0 unless you give them. A Unit Dictionary has one
Standard Unit, so marking a second one stops the apply. The Standard Unit is known by its Unit
String, so an entry added from a script cannot have the same Unit String as the Standard Unit.
The dictionary editor will not save a dictionary with no entries, but a dictionary created this way is empty until its first entry is added, so add its entries in the same script.
Adding an entry is recorded in the dictionary's history, and your URL's auto actions run for the dictionary, as they do when you save it in the editor.
Standard Rules are created with type="Standard Rule", in a library Draft only. The attributes
are the columns of the TG_Rules sheet: Identifier, Logic, RuleType, ObjectType,
ObjectIdentifier, ObjectIdentifierIsWildcard, AttributeName, AttributeValue,
ValueAttributeIsWildcard, Description, Active and Priority, and any custom properties
your URL has added to Standard Rules. Write the rule type and the object type by name, as the sheet
does, for example RuleType="Must Exist" and ObjectType="Form". The object type can also be
one of your URL's own object types.
A Standard Rule has to be given a RuleType, an ObjectType and an ObjectIdentifier, and a
"Must have Attribute" rule an AttributeName as well. A rule you do not give an Identifier is
given the next free one. The same checks apply as in the Standard Rule editor, and the Draft must not
already hold a rule with that Identifier. Identifiers that differ only in upper and lower case count
as the same Identifier.
Saving a Standard Rule recalculates every Draft linked to the library, so Standard Rules created one after another in a script are saved together, up to 100 at a time, and the linked Drafts are recalculated once for each group rather than once for each rule. Keep the commands that create your rules together to get the most from this. If one of them is refused, none of them is created.
Edit Checks and Derivations are created the way an ALS workbook holds them. Create the Edit Check
first, then each of its steps with type="Check Step" and each of its actions with
type="Check Action", naming the check by its name in parent_identifier. A Derivation works
the same way, with type="Derivation Step" for its steps.
importer.execute("CreateDraftObject", type="Edit Check", attributes={"CheckName": "VSDAT_REQUIRED"})
for step in (
{"DataFormat": "StandardValue", "VariableOID": "VSDAT", "FormOID": "VS", "FieldOID": "VSDAT", "RecordPosition": 0},
{"CheckFunction": "IsEmpty"},
):
importer.execute("CreateDraftObject", type="Check Step", parent_identifier="VSDAT_REQUIRED", attributes=step)
importer.execute(
"CreateDraftObject",
type="Check Action",
parent_identifier="VSDAT_REQUIRED",
attributes={
"FormOID": "VS",
"FieldOID": "VSDAT",
"VariableOID": "VSDAT",
"RecordPosition": 0,
"ActionType": "OpenQuery",
"ActionString": "Please enter the visit date.",
"ActionOptions": "Site from System,RequiresResponse",
},
)
An Edit Check takes CheckName, CheckActive, BypassDuringMigration, NeedsRetesting,
RetestingReason and CopySource, and any custom properties your URL has added to Edit Checks.
It has to be given a CheckName, unless it is given a QuickEdit, described below.
A step takes the columns of the CheckSteps sheet and an action the columns of the
CheckActions sheet, apart from the check's name, which is the parent_identifier, and the
StepOrdinal. Steps and actions are added in the order the commands come in. Every action needs an
ActionType.
A Derivation takes DerivationName, Active, BypassDuringMigration,
AllVariablesInFolders, AllVariablesInFields, NeedsRetesting, RetestingReason and
CopySource, and the variable it sets: FolderOID, FormOID, FieldOID, VariableOID,
RecordPosition, FormRepeatNumber and FolderRepeatNumber. It has to be given a
DerivationName and a VariableOID, unless it is given a QuickEdit, and a Draft can have only one
Derivation for each variable. Its steps take the
columns of the DerivationSteps sheet.
Instead of steps, you can give an Edit Check or a Derivation its whole logic at once, with
QuickEdit or CQL. You cannot give both.
CQL is the logic alone, as the editor's CQL tab shows it. An Edit Check given its logic as CQL
still needs its actions, so add them afterwards with type="Check Action":
importer.execute(
"CreateDraftObject",
type="Edit Check",
attributes={"CheckName": "WEIGHT_LOW", "CQL": "*.VS.WEIGHT[0] < 20"},
)
importer.execute(
"CreateDraftObject",
type="Check Action",
parent_identifier="WEIGHT_LOW",
attributes={
"FormOID": "VS",
"FieldOID": "WEIGHT",
"VariableOID": "WEIGHT",
"RecordPosition": 0,
"ActionType": "OpenQuery",
"ActionString": "Weight is below 20. Please check it.",
"ActionOptions": "Site from System,RequiresResponse",
},
)
A Derivation given its logic as CQL is complete once it is created:
importer.execute(
"CreateDraftObject",
type="Derivation",
attributes={
"DerivationName": "VSDY_FROM_VSDAT",
"FormOID": "VS",
"FieldOID": "VSDY",
"VariableOID": "VSDY",
"RecordPosition": 0,
"CQL": "*.VS.VSDAYNUM[0] + 1",
},
)
QuickEdit is the text the editor's QuickEdit tab shows. On an Edit Check it holds everything: the
first line gives the check's name, whether it is active and whether it is bypassed during migration,
then come the steps, then the actions. So an Edit Check created from a QuickEdit needs no Check Step
or Check Action commands:
quickedit = "\n".join(
[
"|HEIGHT_LOW|True|False",
"",
"||StandardValue|HEIGHT||VS|HEIGHT|0||||||",
"|100|3|||||||||||",
"IsLessThan|||||||||||||",
"",
"|VS|HEIGHT|HEIGHT|0||||||OpenQuery|Height is below 100. Please check it.|Site from System,RequiresResponse|",
]
)
importer.execute(
"CreateDraftObject",
type="Edit Check",
attributes={"QuickEdit": quickedit},
)
On a Derivation, the QuickEdit holds the variable it sets as well, so leave out FolderOID,
FormOID, FieldOID, VariableOID, RecordPosition and the repeat numbers.
Because the QuickEdit's first line already gives the name and the settings, you do not need
CheckName, DerivationName, CheckActive, Active or BypassDuringMigration as well,
and the example above gives none of them. If you do give them, they have to say the same as the
QuickEdit. If they say something different, the script is asking for two different things at once,
so the apply stops rather than choosing one. Without a QuickEdit, CheckName or
DerivationName is needed.
The same checks apply as in the editor. A step, action or variable that names a Folder, Form, Field,
Custom Function or Matrix the Draft does not have stops the apply, and so does an action the editor
would not accept, such as a query with no marking group. A QuickEdit or CQL that the editor
would refuse stops the apply too.
An Edit Check or Derivation is built up over several commands, so it is saved even while its steps do not yet make sense or it has no actions yet, with the same error the editor would show for it. When every command has been applied, the result lists each one that is still incomplete, so you can see what to fix.
The other built-in object types, Lab Settings and the rest, cannot be created from a script yet. The command names the type and says so. Object types kept in step with a connected system are never created this way.
Changing a record
UpdateDraftObject changes a record the Draft already holds. You give it the object type, the
record's identifier, and the attributes to change. The attributes are named as CreateDraftObject
names them, and anything you do not name is left as it is:
importer.execute(
"UpdateDraftObject",
type="Form",
identifier="SCREENING",
attributes={"DraftFormName": "Screening visit", "HelpText": ""},
)
The record is named the way CopyDraftObject names one: a Form, Folder, Matrix or Field by its OID,
a Custom Function by its name, a dictionary, Edit Check, Derivation or Test Case by its name, and a
Standard Rule or a record of a type your Organization defined by its identifier. A record that sits
inside another also names its parent in parent_identifier: a Field its Form, a dictionary entry its
dictionary, and a step or action its Edit Check or Derivation.
A dictionary entry is named by its code exactly as it is written, because two entries of a dictionary
can differ only in upper and lower case. A step or action is named by its place in its Edit Check or
Derivation, counted from 1 in the order the editor lists them, so "2" is the second step:
for oid, text in (("VSHEAD", "Record the vital signs at rest"), ("PULSE", "Pulse at rest (beats per minute)")):
importer.execute(
"UpdateDraftObject",
type="Field",
identifier=oid,
parent_identifier="VS",
attributes={"PreText": text},
)
importer.execute(
"UpdateDraftObject",
type="Check Action",
identifier="1",
parent_identifier="VSDAT_REQUIRED",
attributes={"ActionString": "Please enter the date of the visit."},
)
Giving an attribute nothing clears it, as HelpText is cleared in the first example. A custom
property loses its value, and a column is emptied. An attribute a record cannot be without, such as a
Form's name, and a True or False column cannot be cleared. A record of a type your Organization
defined has to keep at least one value.
The values are checked as they are when a record is created, and as the editor checks a change to an
existing record. A Folder cannot be made the parent of a Folder above it, and the SUBJECT folder
cannot be changed. A Test Case that other Test Cases include as a template cannot be renamed. A Field
is checked against the other Fields of its Form and the other Fields using its Variable OID. A Unit
Dictionary keeps one Standard Unit: giving another entry StandardUnit True moves it there, but it
cannot be taken away from an entry without giving it to another. A custom property reserved for
Actions cannot be set, and an inactive one can only be changed or cleared on a record that already
has a value for it. Changing a Test Case needs the Manage Tests permission, and changing any other
record needs Edit Objects.
Giving an Edit Check a QuickEdit replaces its steps and its actions, as saving the QuickEdit tab
does, and giving it CQL replaces its steps and keeps its actions, as saving the CQL tab does. Giving
a Derivation a QuickEdit replaces its logic and the variable it sets, and giving it CQL replaces
its logic and keeps the variable it sets. A QuickEdit has to hold steps, because one without them
would take all the logic away. Its first line gives the name and whether the check or derivation is
active, so a CheckName or DerivationName, active or bypass value given with it has to agree with
that line. Changing one step or action leaves the others as they were.
You can change a record's identifier, as long as no other record of its type in the Draft has the new one, and a Field's Variable OID. Whatever the editor updates when you change an identifier, such as the Edit Checks that name a Form or a Field, is updated in the same way. It is updated as the command is applied, so a later command in the same script names the record by its new identifier, and a script can rename several records, or the same one twice, or swap two names over.
A script cannot rename anything in a Draft while a rename made outside it, such as in the editor, is still updating what names what it renamed. Nor can it change an Edit Check or a Derivation, their steps or actions, or a Field's Variable OID, because saving those rewrites what they name too. The command says which rename that is and when it was made. Run the script again once that rename has finished.
Each change is recorded in the record's history, with the names of the attributes that changed. A change to a dictionary entry, step or action is recorded in the history of its dictionary, Edit Check or Derivation, naming the entry by its code or the step or action by its place, with the attributes that changed in it. A command that changes nothing is not recorded. As when you save in the editor, the labels the change removes are removed, and your URL's auto actions run for the record.
Changes to the Fields of one Form, the entries of one dictionary, or the steps or the actions of one Edit Check or Derivation, made one after another, are made together, as saving the Form, dictionary, check or derivation in the editor makes them. Its history records the change once, and its labels and auto actions are dealt with once. Changes to Standard Rules made one after another are made together too, and the Drafts linked to the library are recalculated once for them. If one of them is refused, none of them is made. A command that changes what a Field, an entry or a Standard Rule is named by is made on its own, so the commands after it can use the new name. So is a command that marks a Unit Dictionary's Standard Unit, so marking several entries one after another leaves the last one marked.
Lab Settings cannot be changed from a script yet. The command names the type and says so.
Permission
To add, change or delete an Import Script you need the "Can manage Import Scripts" permission. Permissions come from your Organization Role, so ask someone who can administer permissions to put you on a role that has it. They choose the role on the organization team page.
Being able to administer permissions does not give you this permission by itself. Someone who administers permissions and also wants to manage Import Scripts puts themselves on a role that has both.
An Import Script is code that other people in your Organization will run. Give this permission only to people you trust to write it.
Anyone in your Organization can see the Import Scripts card and open a script to read it, including its code. The fields are shown but cannot be changed, there is no Save button, and Delete is not offered. Only the permission decides who can change a script, not who can see one.