I’m trying to perform a query using the Do expression, but it doesn’t seem to be working as expected. I’m trying to first create a collection, and then create an index whose source is that collection.
The python code doing this is below:
def create_migrations_collection_and_indexes(fauna_client):
"""Create the required migrations collection and index if they do not already exist."""
# This contains the query used to check if the migrations collection already exists,
# and create it if it doesn't.
create_migrations_collection = query.if_(
query.exists(query.collection("migrations")),
None,
query.create_collection({"name": "migrations", "history_days": 0}),
)
# This contains the query used to check if the unique constraint on migrations
# already exists, and create it if it doesn't.
create_migrations_unique_index = query.if_(
query.exists(query.index("migrations_unique_name_and_namespace")),
None,
query.create_index(
{
"name": "migrations_unique_name_and_namespace",
"source": query.collection("migrations"),
"terms": [
{"field": ["data", "name"]},
{"field": ["data", "namespace"]},
],
"unique": True,
}
),
)
logger.debug(
"Attempting to create the migrations collection and"
" migrations_unique_name_and_namespace index."
)
fauna_client.query(
query.do(create_migrations_collection, create_migrations_unique_index)
)
logger.debug(
"Successfully created the migrations collection and"
" migrations_unique_name_and_namespace index."
)
If I try to run this function, I get the following error:
faunadb.errors.BadRequest: ErrorData(code='validation failed', description='document data is not valid.', position=['do', 1, 'else'], failures=[Failure(code='invalid reference', description='Cannot read reference.', field=['do', '1', 'else', 'source'])])
This seems to indicate the reference to the created collection is not valid. If I create the collection before running this code, everything works fine.
Looking at the Do documentation it states:
The Do function evaluates a list of expressions which are provided as arguments. This evaluation occurs sequentially, from left to right, ensuring that modifications made by earlier expressions are seen by later expressions.
However, based on the error it seems this is not the case. What am I doing wrong?