import re

import jingrow
from jingrow.query_builder import PageType


def execute():
	"""Replace temporarily available Database Aggregate APIs on jingrow (develop)

	APIs changed:
	        * jingrow.db.max => jingrow.qb.max
	        * jingrow.db.min => jingrow.qb.min
	        * jingrow.db.sum => jingrow.qb.sum
	        * jingrow.db.avg => jingrow.qb.avg
	"""
	ServerScript = PageType("Server Script")
	server_scripts = (
		jingrow.qb.from_(ServerScript)
		.where(
			ServerScript.script.like("%jingrow.db.max(%")
			| ServerScript.script.like("%jingrow.db.min(%")
			| ServerScript.script.like("%jingrow.db.sum(%")
			| ServerScript.script.like("%jingrow.db.avg(%")
		)
		.select("name", "script")
		.run(as_dict=True)
	)

	for server_script in server_scripts:
		name, script = server_script["name"], server_script["script"]

		for agg in ["avg", "max", "min", "sum"]:
			script = re.sub(f"jingrow.db.{agg}\\(", f"jingrow.qb.{agg}(", script)

		jingrow.db.set_value("Server Script", name, "script", script)
