Supplies are limited. Contact info@espc.tech right away to save your spot before the conference sells out.
Get your discountScore big with last-minute savings on the final tickets to FabCon Vienna. Secure your discount
08-12-2025 14:54 PM - last edited 08-12-2025 15:42 PM
Selected Positions =
IF(
ISFILTERED( 'Grid Position'[Position] ),
TOJSON( VALUES( 'Grid Position'[Position] ) )
)
import fabric.functions as fn
import json
from datetime import datetime
udf = fn.UserDataFunctions()
@udf.connection(argName="sqlDB", alias="Game")
@udf.function()
def toggle_pencil_mark(sqlDB: fn.FabricSqlConnection, gameId: int, position: str, pencilValue: int) -> str:
"""
Toggle a pencil mark in a Sudoku cell
Args:
gameId: The game ID
position: JSON string with cell positions
pencilValue: Pencil mark value (1-9)
Returns:
JSON string with operation result
"""
# Parse positions from JSON
positions_data = json.loads(position)
positions = [pos[0] for pos in positions_data["data"]]
## Open connection and SQL database and write values to cells
conn = sqlDB.connect()
cursor = conn.cursor()
processed_positions = []
last_action_type = None
last_is_active = False
for pos in positions:
# Skip cells with values
cursor.execute("SELECT CurrentValue FROM GameState WHERE GameId = ? AND Position = ?", (gameId, pos))
if cursor.fetchone()[0] is not None:
continue
# Toggle pencil mark
cursor.execute("EXEC sp_TogglePencilMark ?, ?, ?", (gameId, pos, pencilValue))
conn.commit()
# Check if added or removed
cursor.execute("SELECT IsActive FROM PencilMarks WHERE GameId = ? AND Position = ? AND PencilValue = ?",
(gameId, pos, pencilValue))
is_active = cursor.fetchone()[0]
last_action_type = "added" if is_active else "removed"
last_is_active = is_active
processed_positions.append(pos)
cursor.close()
conn.close()
return json.dumps({
"status": "SUCCESS",
"message": f"Pencil mark {pencilValue} {last_action_type} at position(s) {processed_positions}",
"game_id": gameId,
"positions_processed": processed_positions,
"pencil_value": pencilValue,
"is_active": last_is_active,
"action_type": last_action_type,
"action_time": datetime.now().isoformat()
})
Solution
This approach is highly versatile and can be used as a template for any scenario where you need to pass multiple selected items from a Power BI report to a UDF.
More in-depth details can be found at these blog posts: