package migrations_test

import (
	"context"
	"database/sql"
	"fmt"
	"testing"

	"github.com/stretchr/testify/require"

	"github.com/operator-framework/operator-registry/pkg/registry"
	"github.com/operator-framework/operator-registry/pkg/sqlite/migrations"
)

func TestAssociateApisWithBundleUp(t *testing.T) {
	db, migrator, cleanup := CreateTestDBAt(t, migrations.AssociateApisWithBundleMigrationKey-1)
	defer cleanup()

	_, err := db.Exec(`PRAGMA foreign_keys = 0`)
	require.NoError(t, err)

	tx, err := db.Begin()
	require.NoError(t, err)
	testCSV := `{"apiVersion":"operators.coreos.com/v1alpha1","kind":"ClusterServiceVersion","metadata":{"annotations":{"tectonic-visibility":"ocs"},"name":"etcdoperator.v0.6.1","namespace":"placeholder"},"spec":{"customresourcedefinitions":{"provided":[{"description":"Represents a cluster of etcd nodes.","displayName":"etcd Cluster","kind":"EtcdCluster","name":"etcdclusters.etcd.database.coreos.com","resources":[{"kind":"Service","version":"v1"},{"kind":"Pod","version":"v1"}],"specDescriptors":[{"description":"The desired number of member Pods for the etcd cluster.","displayName":"Size","path":"size","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podCount"]}],"statusDescriptors":[{"description":"The status of each of the member Pods for the etcd cluster.","displayName":"Member Status","path":"members","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podStatuses"]},{"description":"The service at which the running etcd cluster can be accessed.","displayName":"Service","path":"service","x-descriptors":["urn:alm:descriptor:io.kubernetes:Service"]},{"description":"The current size of the etcd cluster.","displayName":"Cluster Size","path":"size"},{"description":"The current version of the etcd cluster.","displayName":"Current version","path":"currentVersion"},{"description":"The target version of the etcd cluster, after upgrading.","displayName":"Target version","path":"targetVersion"},{"description":"The current status of the etcd cluster.","displayName":"Status","path":"phase","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase"]},{"description":"Explanation for the current status of the cluster.","displayName":"Status Details","path":"reason","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase:reason"]}],"version":"v1beta2"}]},"description":"etcd is a distributed key value store that provides a reliable way to store data across a cluster of machines. It’s open-source and available on GitHub. etcd gracefully handles leader elections during network partitions and will tolerate machine failure, including the leader. Your applications can read and write data into etcd.\nA simple use-case is to store database connection details or feature flags within etcd as key value pairs. These values can be watched, allowing your app to reconfigure itself when they change. Advanced uses take advantage of the consistency guarantees to implement database leader elections or do distributed locking across a cluster of workers.\n\n_The etcd Open Cloud Service is Public Alpha. The goal before Beta is to fully implement backup features._\n\n### Reading and writing to etcd\n\nCommunicate with etcd though its command line utility etcdctl or with the API using the Kubernetes Service.\n\n[Read the complete guide to using the etcd Open Cloud Service](https://coreos.com/tectonic/docs/latest/alm/etcd-ocs.html)\n\n### Supported Features\n**High availability**\nMultiple instances of etcd are networked together and secured. Individual failures or networking issues are transparently handled to keep your cluster up and running.\n**Automated updates**\nRolling out a new etcd version works like all Kubernetes rolling updates. Simply declare the desired version, and the etcd service starts a safe rolling update to the new version automatically.\n**Backups included**\nComing soon, the ability to schedule backups to happen on or off cluster.\n","displayName":"etcd","icon":[{"base64data":" ","mediatype":"image/png"}],"install":{"spec":{"deployments":[{"name":"etcd-operator","spec":{"replicas":1,"selector":{"matchLabels":{"name":"etcd-operator-alm-owned"}},"template":{"metadata":{"labels":{"name":"etcd-operator-alm-owned"},"name":"etcd-operator-alm-owned"},"spec":{"containers":[{"command":["etcd-operator","--create-crd=false"],"env":[{"name":"MY_POD_NAMESPACE","valueFrom":{"fieldRef":{"fieldPath":"metadata.namespace"}}},{"name":"MY_POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}}],"image":"quay.io/coreos/etcd-operator@sha256:bd944a211eaf8f31da5e6d69e8541e7cada8f16a9f7a5a570b22478997819943","name":"etcd-operator"}],"serviceAccountName":"etcd-operator"}}}}],"permissions":[{"rules":[{"apiGroups":["etcd.database.coreos.com"],"resources":["etcdclusters"],"verbs":["*"]},{"apiGroups":["storage.k8s.io"],"resources":["storageclasses"],"verbs":["*"]},{"apiGroups":[""],"resources":["pods","services","endpoints","persistentvolumeclaims","events"],"verbs":["*"]},{"apiGroups":["apps"],"resources":["deployments"],"verbs":["*"]},{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}],"serviceAccountName":"etcd-operator"}]},"strategy":"deployment"},"keywords":["etcd","key value","database","coreos","open source"],"labels":{"alm-owner-etcd":"etcdoperator","alm-status-descriptors":"etcdoperator.v0.6.1","operated-by":"etcdoperator"},"links":[{"name":"Blog","url":"https://coreos.com/etcd"},{"name":"Documentation","url":"https://coreos.com/operators/etcd/docs/latest/"},{"name":"etcd Operator Source Code","url":"https://github.com/coreos/etcd-operator"}],"maintainers":[{"email":"support@coreos.com","name":"CoreOS, Inc"}],"maturity":"alpha","provider":{"name":"CoreOS, Inc"},"selector":{"matchLabels":{"alm-owner-etcd":"etcdoperator","operated-by":"etcdoperator"}},"version":"0.6.1"}}`
	testBundle := `{"apiVersion":"apiextensions.k8s.io/v1beta1","kind":"CustomResourceDefinition","metadata":{"name":"etcdclusters.etcd.database.coreos.com"},"spec":{"group":"etcd.database.coreos.com","names":{"kind":"EtcdCluster","listKind":"EtcdClusterList","plural":"etcdclusters","shortNames":["etcdclus","etcd"],"singular":"etcdcluster"},"scope":"Namespaced","version":"v1beta2"}}{"apiVersion":"operators.coreos.com/v1alpha1","kind":"ClusterServiceVersion","metadata":{"annotations":{"tectonic-visibility":"ocs"},"name":"etcdoperator.v0.6.1","namespace":"placeholder"},"spec":{"customresourcedefinitions":{"required":[{"description":"Represents a cluster of etcd nodes.","displayName":"etcd Cluster","kind":"EtcdCluster","name":"etcdclusters.etcd.database.coreos.com","resources":[{"kind":"Service","version":"v1"},{"kind":"Pod","version":"v1"}],"specDescriptors":[{"description":"The desired number of member Pods for the etcd cluster.","displayName":"Size","path":"size","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podCount"]}],"statusDescriptors":[{"description":"The status of each of the member Pods for the etcd cluster.","displayName":"Member Status","path":"members","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podStatuses"]},{"description":"The service at which the running etcd cluster can be accessed.","displayName":"Service","path":"service","x-descriptors":["urn:alm:descriptor:io.kubernetes:Service"]},{"description":"The current size of the etcd cluster.","displayName":"Cluster Size","path":"size"},{"description":"The current version of the etcd cluster.","displayName":"Current version","path":"currentVersion"},{"description":"The target version of the etcd cluster, after upgrading.","displayName":"Target version","path":"targetVersion"},{"description":"The current status of the etcd cluster.","displayName":"Status","path":"phase","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase"]},{"description":"Explanation for the current status of the cluster.","displayName":"Status Details","path":"reason","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase:reason"]}],"version":"v1beta2"}]},"description":"etcd is a distributed key value store that provides a reliable way to store data across a cluster of machines. It’s open-source and available on GitHub. etcd gracefully handles leader elections during network partitions and will tolerate machine failure, including the leader. Your applications can read and write data into etcd.\nA simple use-case is to store database connection details or feature flags within etcd as key value pairs. These values can be watched, allowing your app to reconfigure itself when they change. Advanced uses take advantage of the consistency guarantees to implement database leader elections or do distributed locking across a cluster of workers.\n\n_The etcd Open Cloud Service is Public Alpha. The goal before Beta is to fully implement backup features._\n\n### Reading and writing to etcd\n\nCommunicate with etcd though its command line utility etcdctl or with the API using the Kubernetes Service.\n\n[Read the complete guide to using the etcd Open Cloud Service](https://coreos.com/tectonic/docs/latest/alm/etcd-ocs.html)\n\n### Supported Features\n**High availability**\nMultiple instances of etcd are networked together and secured. Individual failures or networking issues are transparently handled to keep your cluster up and running.\n**Automated updates**\nRolling out a new etcd version works like all Kubernetes rolling updates. Simply declare the desired version, and the etcd service starts a safe rolling update to the new version automatically.\n**Backups included**\nComing soon, the ability to schedule backups to happen on or off cluster.\n","displayName":"etcd","icon":[{"base64data":" ","mediatype":"image/png"}],"install":{"spec":{"deployments":[{"name":"etcd-operator","spec":{"replicas":1,"selector":{"matchLabels":{"name":"etcd-operator-alm-owned"}},"template":{"metadata":{"labels":{"name":"etcd-operator-alm-owned"},"name":"etcd-operator-alm-owned"},"spec":{"containers":[{"command":["etcd-operator","--create-crd=false"],"env":[{"name":"MY_POD_NAMESPACE","valueFrom":{"fieldRef":{"fieldPath":"metadata.namespace"}}},{"name":"MY_POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}}],"image":"quay.io/coreos/etcd-operator@sha256:bd944a211eaf8f31da5e6d69e8541e7cada8f16a9f7a5a570b22478997819943","name":"etcd-operator"}],"serviceAccountName":"etcd-operator"}}}}],"permissions":[{"rules":[{"apiGroups":["etcd.database.coreos.com"],"resources":["etcdclusters"],"verbs":["*"]},{"apiGroups":["storage.k8s.io"],"resources":["storageclasses"],"verbs":["*"]},{"apiGroups":[""],"resources":["pods","services","endpoints","persistentvolumeclaims","events"],"verbs":["*"]},{"apiGroups":["apps"],"resources":["deployments"],"verbs":["*"]},{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}],"serviceAccountName":"etcd-operator"}]},"strategy":"deployment"},"keywords":["etcd","key value","database","coreos","open source"],"labels":{"alm-owner-etcd":"etcdoperator","alm-status-descriptors":"etcdoperator.v0.6.1","operated-by":"etcdoperator"},"links":[{"name":"Blog","url":"https://coreos.com/etcd"},{"name":"Documentation","url":"https://coreos.com/operators/etcd/docs/latest/"},{"name":"etcd Operator Source Code","url":"https://github.com/coreos/etcd-operator"}],"maintainers":[{"email":"support@coreos.com","name":"CoreOS, Inc"}],"maturity":"alpha","provider":{"name":"CoreOS, Inc"},"selector":{"matchLabels":{"alm-owner-etcd":"etcdoperator","operated-by":"etcdoperator"}},"version":"0.6.1"}}`
	insert := "insert into operatorbundle(name, csv, bundle) values(?, ?, ?)"
	_, err = tx.Exec(insert, "etcdoperator.v0.6.1", testCSV, testBundle)
	require.NoError(t, err)
	_, err = tx.Exec("insert into package(name, default_channel) values(?,?)", "etcd", "alpha")
	require.NoError(t, err)
	_, err = tx.Exec("insert into channel(name, package_name, head_operatorbundle_name) values(?,?,?)", "alpha", "etcd", "etcdoperator.v0.6.1")
	require.NoError(t, err)
	result, err := tx.Exec("insert into channel_entry(channel_name, package_name, operatorbundle_name, depth) values(?, ?, ?, ?)", "alpha", "etcd", "etcdoperator.v0.6.1", 0)
	require.NoError(t, err)
	entryID, err := result.LastInsertId()
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdClusters", "etcdclusters")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdBackups", "etcdbackups")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdRestores", "etcdrestores")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, channel_entry_id) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdClusters", entryID)
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, channel_entry_id) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdBackups", entryID)
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, channel_entry_id) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdRestores", entryID)
	require.NoError(t, err)
	require.NoError(t, tx.Commit())
	_, err = db.Exec(`PRAGMA foreign_keys = 1`)
	require.NoError(t, err)

	// Use the old query to find the channel entries
	oldEntries, err := oldGetChannelEntriesThatProvide(db, "etcd.database.coreos.com", "v1alpha1", "EtcdRestores")
	require.NoError(t, err)
	require.Len(t, oldEntries, 1)
	require.Equal(t, "etcdoperator.v0.6.1", oldEntries[0].BundleName)

	// Up the migration with backfill
	err = migrator.Up(context.TODO(), migrations.Only(migrations.AssociateApisWithBundleMigrationKey))
	require.NoError(t, err)

	// check that we can still query for provided apis
	entries, err := newGetChannelEntriesThatProvide(db, "etcd.database.coreos.com", "v1alpha1", "EtcdRestores")
	require.NoError(t, err)
	require.Len(t, entries, 1)
	require.Equal(t, "etcdoperator.v0.6.1", entries[0].BundleName)

	require.Equal(t, oldEntries, entries)
}

func TestAssociateApisWithBundleDown(t *testing.T) {
	db, migrator, cleanup := CreateTestDBAt(t, migrations.AssociateApisWithBundleMigrationKey)
	defer cleanup()

	_, err := db.Exec(`PRAGMA foreign_keys = 0`)
	require.NoError(t, err)

	tx, err := db.Begin()
	require.NoError(t, err)
	testCSV := `{"apiVersion":"operators.coreos.com/v1alpha1","kind":"ClusterServiceVersion","metadata":{"annotations":{"tectonic-visibility":"ocs"},"name":"etcdoperator.v0.6.1","namespace":"placeholder"},"spec":{"customresourcedefinitions":{"provided":[{"description":"Represents a cluster of etcd nodes.","displayName":"etcd Cluster","kind":"EtcdCluster","name":"etcdclusters.etcd.database.coreos.com","resources":[{"kind":"Service","version":"v1"},{"kind":"Pod","version":"v1"}],"specDescriptors":[{"description":"The desired number of member Pods for the etcd cluster.","displayName":"Size","path":"size","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podCount"]}],"statusDescriptors":[{"description":"The status of each of the member Pods for the etcd cluster.","displayName":"Member Status","path":"members","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podStatuses"]},{"description":"The service at which the running etcd cluster can be accessed.","displayName":"Service","path":"service","x-descriptors":["urn:alm:descriptor:io.kubernetes:Service"]},{"description":"The current size of the etcd cluster.","displayName":"Cluster Size","path":"size"},{"description":"The current version of the etcd cluster.","displayName":"Current version","path":"currentVersion"},{"description":"The target version of the etcd cluster, after upgrading.","displayName":"Target version","path":"targetVersion"},{"description":"The current status of the etcd cluster.","displayName":"Status","path":"phase","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase"]},{"description":"Explanation for the current status of the cluster.","displayName":"Status Details","path":"reason","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase:reason"]}],"version":"v1beta2"}]},"description":"etcd is a distributed key value store that provides a reliable way to store data across a cluster of machines. It’s open-source and available on GitHub. etcd gracefully handles leader elections during network partitions and will tolerate machine failure, including the leader. Your applications can read and write data into etcd.\nA simple use-case is to store database connection details or feature flags within etcd as key value pairs. These values can be watched, allowing your app to reconfigure itself when they change. Advanced uses take advantage of the consistency guarantees to implement database leader elections or do distributed locking across a cluster of workers.\n\n_The etcd Open Cloud Service is Public Alpha. The goal before Beta is to fully implement backup features._\n\n### Reading and writing to etcd\n\nCommunicate with etcd though its command line utility etcdctl or with the API using the Kubernetes Service.\n\n[Read the complete guide to using the etcd Open Cloud Service](https://coreos.com/tectonic/docs/latest/alm/etcd-ocs.html)\n\n### Supported Features\n**High availability**\nMultiple instances of etcd are networked together and secured. Individual failures or networking issues are transparently handled to keep your cluster up and running.\n**Automated updates**\nRolling out a new etcd version works like all Kubernetes rolling updates. Simply declare the desired version, and the etcd service starts a safe rolling update to the new version automatically.\n**Backups included**\nComing soon, the ability to schedule backups to happen on or off cluster.\n","displayName":"etcd","icon":[{"base64data":" ","mediatype":"image/png"}],"install":{"spec":{"deployments":[{"name":"etcd-operator","spec":{"replicas":1,"selector":{"matchLabels":{"name":"etcd-operator-alm-owned"}},"template":{"metadata":{"labels":{"name":"etcd-operator-alm-owned"},"name":"etcd-operator-alm-owned"},"spec":{"containers":[{"command":["etcd-operator","--create-crd=false"],"env":[{"name":"MY_POD_NAMESPACE","valueFrom":{"fieldRef":{"fieldPath":"metadata.namespace"}}},{"name":"MY_POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}}],"image":"quay.io/coreos/etcd-operator@sha256:bd944a211eaf8f31da5e6d69e8541e7cada8f16a9f7a5a570b22478997819943","name":"etcd-operator"}],"serviceAccountName":"etcd-operator"}}}}],"permissions":[{"rules":[{"apiGroups":["etcd.database.coreos.com"],"resources":["etcdclusters"],"verbs":["*"]},{"apiGroups":["storage.k8s.io"],"resources":["storageclasses"],"verbs":["*"]},{"apiGroups":[""],"resources":["pods","services","endpoints","persistentvolumeclaims","events"],"verbs":["*"]},{"apiGroups":["apps"],"resources":["deployments"],"verbs":["*"]},{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}],"serviceAccountName":"etcd-operator"}]},"strategy":"deployment"},"keywords":["etcd","key value","database","coreos","open source"],"labels":{"alm-owner-etcd":"etcdoperator","alm-status-descriptors":"etcdoperator.v0.6.1","operated-by":"etcdoperator"},"links":[{"name":"Blog","url":"https://coreos.com/etcd"},{"name":"Documentation","url":"https://coreos.com/operators/etcd/docs/latest/"},{"name":"etcd Operator Source Code","url":"https://github.com/coreos/etcd-operator"}],"maintainers":[{"email":"support@coreos.com","name":"CoreOS, Inc"}],"maturity":"alpha","provider":{"name":"CoreOS, Inc"},"selector":{"matchLabels":{"alm-owner-etcd":"etcdoperator","operated-by":"etcdoperator"}},"version":"0.6.1"}}`
	testBundle := `{"apiVersion":"apiextensions.k8s.io/v1beta1","kind":"CustomResourceDefinition","metadata":{"name":"etcdclusters.etcd.database.coreos.com"},"spec":{"group":"etcd.database.coreos.com","names":{"kind":"EtcdCluster","listKind":"EtcdClusterList","plural":"etcdclusters","shortNames":["etcdclus","etcd"],"singular":"etcdcluster"},"scope":"Namespaced","version":"v1beta2"}}{"apiVersion":"operators.coreos.com/v1alpha1","kind":"ClusterServiceVersion","metadata":{"annotations":{"tectonic-visibility":"ocs"},"name":"etcdoperator.v0.6.1","namespace":"placeholder"},"spec":{"customresourcedefinitions":{"required":[{"description":"Represents a cluster of etcd nodes.","displayName":"etcd Cluster","kind":"EtcdCluster","name":"etcdclusters.etcd.database.coreos.com","resources":[{"kind":"Service","version":"v1"},{"kind":"Pod","version":"v1"}],"specDescriptors":[{"description":"The desired number of member Pods for the etcd cluster.","displayName":"Size","path":"size","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podCount"]}],"statusDescriptors":[{"description":"The status of each of the member Pods for the etcd cluster.","displayName":"Member Status","path":"members","x-descriptors":["urn:alm:descriptor:com.tectonic.ui:podStatuses"]},{"description":"The service at which the running etcd cluster can be accessed.","displayName":"Service","path":"service","x-descriptors":["urn:alm:descriptor:io.kubernetes:Service"]},{"description":"The current size of the etcd cluster.","displayName":"Cluster Size","path":"size"},{"description":"The current version of the etcd cluster.","displayName":"Current version","path":"currentVersion"},{"description":"The target version of the etcd cluster, after upgrading.","displayName":"Target version","path":"targetVersion"},{"description":"The current status of the etcd cluster.","displayName":"Status","path":"phase","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase"]},{"description":"Explanation for the current status of the cluster.","displayName":"Status Details","path":"reason","x-descriptors":["urn:alm:descriptor:io.kubernetes.phase:reason"]}],"version":"v1beta2"}]},"description":"etcd is a distributed key value store that provides a reliable way to store data across a cluster of machines. It’s open-source and available on GitHub. etcd gracefully handles leader elections during network partitions and will tolerate machine failure, including the leader. Your applications can read and write data into etcd.\nA simple use-case is to store database connection details or feature flags within etcd as key value pairs. These values can be watched, allowing your app to reconfigure itself when they change. Advanced uses take advantage of the consistency guarantees to implement database leader elections or do distributed locking across a cluster of workers.\n\n_The etcd Open Cloud Service is Public Alpha. The goal before Beta is to fully implement backup features._\n\n### Reading and writing to etcd\n\nCommunicate with etcd though its command line utility etcdctl or with the API using the Kubernetes Service.\n\n[Read the complete guide to using the etcd Open Cloud Service](https://coreos.com/tectonic/docs/latest/alm/etcd-ocs.html)\n\n### Supported Features\n**High availability**\nMultiple instances of etcd are networked together and secured. Individual failures or networking issues are transparently handled to keep your cluster up and running.\n**Automated updates**\nRolling out a new etcd version works like all Kubernetes rolling updates. Simply declare the desired version, and the etcd service starts a safe rolling update to the new version automatically.\n**Backups included**\nComing soon, the ability to schedule backups to happen on or off cluster.\n","displayName":"etcd","icon":[{"base64data":" ","mediatype":"image/png"}],"install":{"spec":{"deployments":[{"name":"etcd-operator","spec":{"replicas":1,"selector":{"matchLabels":{"name":"etcd-operator-alm-owned"}},"template":{"metadata":{"labels":{"name":"etcd-operator-alm-owned"},"name":"etcd-operator-alm-owned"},"spec":{"containers":[{"command":["etcd-operator","--create-crd=false"],"env":[{"name":"MY_POD_NAMESPACE","valueFrom":{"fieldRef":{"fieldPath":"metadata.namespace"}}},{"name":"MY_POD_NAME","valueFrom":{"fieldRef":{"fieldPath":"metadata.name"}}}],"image":"quay.io/coreos/etcd-operator@sha256:bd944a211eaf8f31da5e6d69e8541e7cada8f16a9f7a5a570b22478997819943","name":"etcd-operator"}],"serviceAccountName":"etcd-operator"}}}}],"permissions":[{"rules":[{"apiGroups":["etcd.database.coreos.com"],"resources":["etcdclusters"],"verbs":["*"]},{"apiGroups":["storage.k8s.io"],"resources":["storageclasses"],"verbs":["*"]},{"apiGroups":[""],"resources":["pods","services","endpoints","persistentvolumeclaims","events"],"verbs":["*"]},{"apiGroups":["apps"],"resources":["deployments"],"verbs":["*"]},{"apiGroups":[""],"resources":["secrets"],"verbs":["get"]}],"serviceAccountName":"etcd-operator"}]},"strategy":"deployment"},"keywords":["etcd","key value","database","coreos","open source"],"labels":{"alm-owner-etcd":"etcdoperator","alm-status-descriptors":"etcdoperator.v0.6.1","operated-by":"etcdoperator"},"links":[{"name":"Blog","url":"https://coreos.com/etcd"},{"name":"Documentation","url":"https://coreos.com/operators/etcd/docs/latest/"},{"name":"etcd Operator Source Code","url":"https://github.com/coreos/etcd-operator"}],"maintainers":[{"email":"support@coreos.com","name":"CoreOS, Inc"}],"maturity":"alpha","provider":{"name":"CoreOS, Inc"},"selector":{"matchLabels":{"alm-owner-etcd":"etcdoperator","operated-by":"etcdoperator"}},"version":"0.6.1"}}`
	insert := "insert into operatorbundle(name, csv, bundle, version) values(?, ?, ?, ?)"
	_, err = tx.Exec(insert, "etcdoperator.v0.6.1", testCSV, testBundle, "0.6.1")
	require.NoError(t, err)
	_, err = tx.Exec("insert into package(name, default_channel) values(?,?)", "etcd", "alpha")
	require.NoError(t, err)
	_, err = tx.Exec("insert into channel(name, package_name, head_operatorbundle_name) values(?,?,?)", "alpha", "etcd", "etcdoperator.v0.6.1")
	require.NoError(t, err)
	_, err = tx.Exec("insert into channel_entry(channel_name, package_name, operatorbundle_name, depth) values(?, ?, ?, ?)", "alpha", "etcd", "etcdoperator.v0.6.1", 0)
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdClusters", "etcdclusters")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdBackups", "etcdbackups")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api(group_name, version, kind, plural) values(?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdRestores", "etcdrestores")
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, operatorbundle_name, operatorbundle_version, operatorbundle_path) values(?, ?, ?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdClusters", "etcdoperator.v0.6.1", "0.6.1", nil)
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, operatorbundle_name, operatorbundle_version, operatorbundle_path) values(?, ?, ?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdBackups", "etcdoperator.v0.6.1", "0.6.1", nil)
	require.NoError(t, err)
	_, err = tx.Exec("insert into api_provider(group_name, version, kind, operatorbundle_name, operatorbundle_version, operatorbundle_path) values(?, ?, ?, ?, ?, ?)", "etcd.database.coreos.com", "v1alpha1", "EtcdRestores", "etcdoperator.v0.6.1", "0.6.1", nil)
	require.NoError(t, err)
	require.NoError(t, tx.Commit())
	_, err = db.Exec(`PRAGMA foreign_keys = 1`)
	require.NoError(t, err)

	entriesBeforeMigration, err := newGetChannelEntriesThatProvide(db, "etcd.database.coreos.com", "v1alpha1", "EtcdRestores")
	require.NoError(t, err)

	err = migrator.Down(context.TODO(), migrations.Only(migrations.AssociateApisWithBundleMigrationKey))
	require.NoError(t, err)

	entriesAfterMigration, err := oldGetChannelEntriesThatProvide(db, "etcd.database.coreos.com", "v1alpha1", "EtcdRestores")
	require.NoError(t, err)

	// Migrating down entails sensitive operations. Ensure data is preserved across down migration
	require.Equal(t, entriesBeforeMigration, entriesAfterMigration)
}

func oldGetChannelEntriesThatProvide(db *sql.DB, group, version, kind string) ([]*registry.ChannelEntry, error) {
	query := `SELECT DISTINCT channel_entry.package_name, channel_entry.channel_name, channel_entry.operatorbundle_name, replaces.operatorbundle_name
        	  FROM channel_entry
              INNER JOIN api_provider ON channel_entry.entry_id = api_provider.channel_entry_id
              LEFT OUTER JOIN channel_entry replaces ON channel_entry.replaces = replaces.entry_id
		      WHERE api_provider.group_name = ? AND api_provider.version = ? AND api_provider.kind = ?`

	rows, err := db.Query(query, group, version, kind)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var entries = []*registry.ChannelEntry{}

	for rows.Next() {
		var pkgNameSQL sql.NullString
		var channelNameSQL sql.NullString
		var bundleNameSQL sql.NullString
		var replacesSQL sql.NullString
		if err = rows.Scan(&pkgNameSQL, &channelNameSQL, &bundleNameSQL, &replacesSQL); err != nil {
			return nil, err
		}

		entries = append(entries, &registry.ChannelEntry{
			PackageName: pkgNameSQL.String,
			ChannelName: channelNameSQL.String,
			BundleName:  bundleNameSQL.String,
			Replaces:    replacesSQL.String,
		})
	}
	if len(entries) == 0 {
		err = fmt.Errorf("no channel entries found that provide %s %s %s", group, version, kind)
		return nil, err
	}
	return entries, nil
}

func newGetChannelEntriesThatProvide(db *sql.DB, group, version, kind string) ([]*registry.ChannelEntry, error) {
	query := `SELECT DISTINCT channel_entry.package_name, channel_entry.channel_name, channel_entry.operatorbundle_name, replaces.operatorbundle_name
          FROM channel_entry
          INNER JOIN api_provider ON channel_entry.operatorbundle_name = api_provider.operatorbundle_name
          LEFT OUTER JOIN channel_entry replaces ON channel_entry.replaces = replaces.entry_id
		  WHERE api_provider.group_name = ? AND api_provider.version = ? AND api_provider.kind = ?`

	rows, err := db.Query(query, group, version, kind)
	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var entries = []*registry.ChannelEntry{}

	for rows.Next() {
		var pkgNameSQL sql.NullString
		var channelNameSQL sql.NullString
		var bundleNameSQL sql.NullString
		var replacesSQL sql.NullString
		if err = rows.Scan(&pkgNameSQL, &channelNameSQL, &bundleNameSQL, &replacesSQL); err != nil {
			return nil, err
		}

		entries = append(entries, &registry.ChannelEntry{
			PackageName: pkgNameSQL.String,
			ChannelName: channelNameSQL.String,
			BundleName:  bundleNameSQL.String,
			Replaces:    replacesSQL.String,
		})
	}
	if len(entries) == 0 {
		err = fmt.Errorf("no channel entries found that provide %s %s %s", group, version, kind)
		return nil, err
	}
	return entries, nil
}
