import jingrow
from jingrow.query_builder import PageType


def execute():
	RATING_FIELD_TYPE = "decimal(3,2)"
	rating_fields = jingrow.get_all(
		"PageField", fields=["parent", "fieldname"], filters={"fieldtype": "Rating"}
	)

	custom_rating_fields = jingrow.get_all(
		"Custom Field", fields=["dt", "fieldname"], filters={"fieldtype": "Rating"}
	)

	for _field in rating_fields + custom_rating_fields:
		pagetype_name = _field.get("parent") or _field.get("dt")
		pagetype = PageType(pagetype_name)
		field = _field.fieldname

		# TODO: Add postgres support (for the check)
		if (
			jingrow.conf.db_type == "mariadb"
			and jingrow.db.get_column_type(pagetype_name, field) == RATING_FIELD_TYPE
		):
			continue

		# commit any changes so far for upcoming DDL
		jingrow.db.commit()

		# alter column types for rating fieldtype
		jingrow.db.change_column_type(pagetype_name, column=field, type=RATING_FIELD_TYPE, nullable=True)

		# update data: int => decimal
		jingrow.qb.update(pagetype).set(pagetype[field], pagetype[field] / 5).run()

		# commit to flush updated rows
		jingrow.db.commit()
