import frappe

def execute():
	frappe.reload_doc('desk', 'doctype', 'todo')

	query = '''
		SELECT
			name, reference_type, reference_name, {} as assignees
		FROM
			`tabToDo`
		WHERE
			COALESCE(reference_type, '') != '' AND
			COALESCE(reference_name, '') != '' AND
			status != 'Cancelled'
		GROUP BY
			reference_type, reference_name
	'''

	assignments = frappe.db.multisql({
		'mariadb': query.format('GROUP_CONCAT(DISTINCT `owner`)'),
		'postgres': query.format('STRING_AGG(DISTINCT "owner", ",")')
	}, as_dict=True)

	for doc in assignments:
		assignments = doc.assignees.split(',')
		frappe.db.set_value(
			doc.reference_type,
			doc.reference_name,
			'_assign',
			frappe.as_json(assignments),
			update_modified=False
		)

@@ -583,16 +583,24 @@
 it(',')%0A
+%09%09try:%0A%09
 %09%09frappe
@@ -613,24 +613,25 @@
 t_value(%0A%09%09%09
+%09
 doc.referenc
@@ -638,16 +638,17 @@
 e_type,%0A
+%09
 %09%09%09doc.r
@@ -665,16 +665,17 @@
 ame,%0A%09%09%09
+%09
 '_assign
@@ -677,16 +677,17 @@
 ssign',%0A
+%09
 %09%09%09frapp
@@ -713,16 +713,17 @@
 ts),%0A%09%09%09
+%09
 update_m
@@ -738,10 +738,57 @@
 False%0A%09%09
+%09
 )%0A
+%0A%09%09except frappe.db.ProgrammingError:%0A%09%09%09pass%0A

patch breaks if reference doctype doesn't exist