<?xml version="1.0" encoding="UTF-8"?>
<changelog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.liquigraph.org/schema/1.0/liquigraph.xsd">
    <changeset id="ARTARCH-600_uppercase_lsrs:1" author="owright" run-on-change="true">
        <query>
            <![CDATA[
                // Find all LSRs with abnormal ISRCs, group them by normalized ISRC & label
                MATCH (lsr:LabelSoundRecording)
                WHERE lsr.isrc <> toUpper(lsr.isrc)
                WITH toUpper(lsr.isrc) AS isrc, lsr.vendorId as vendorId, lsr.subaccountId as subaccountId, collect(lsr) as lsrs

                // Find or create a normalized ISRC node, and add it to the list
                MERGE (lsr:LabelSoundRecording { isrc: isrc, vendorId: vendorId, subaccountId: subaccountId })
                WITH isrc, vendorId, subaccountId, lsrs + [lsr] as lsrs

                // Lock all the nodes so that new participations cannot be attached before this TX finishes.
                CALL apoc.lock.nodes(lsrs)

                // Filter out any cases where we have multiple nodes with participations as they cannot be directly merged.
                WITH isrc, vendorId, subaccountId, lsrs
                WHERE reduce(participations = 0, lsr IN lsrs | CASE WHEN exists((lsr)-[:ON_LABEL_SOUND_RECORDING]-(:LabelSoundRecordingParticipation)) THEN 1 ELSE 0 END + participations) <= 1

                // Merge together LSRs
                CALL apoc.refactor.mergeNodes(
                    lsrs,
                    {
                        properties: "discard",
                        mergeRels: true
                    }
                )
                YIELD node
                // Finally, make sure that we end up with the normalized ISRC on the node
                SET node.isrc = isrc;
            ]]>
        </query>
    </changeset>
</changelog>
