Merge pull request #14 from 30x/genericsqlite

Genericsqlite
diff --git a/api.go b/api.go
index 1020414..b0b6402 100644
--- a/api.go
+++ b/api.go
@@ -11,7 +11,7 @@
 type sucResponseDetail struct {
 	Key             string `json:"key"`
 	ExpiresAt       int64  `json:"expiresAt"`
-	IssuedAt        int64  `json:"issuedAt"`
+	IssuedAt        string `json:"issuedAt"`
 	Status          string `json:"status"`
 	Type            string `json:"cType"`
 	RedirectionURIs string `json:"redirectionURIs"`
@@ -91,12 +91,13 @@
 
 	db := getDB()
 
-	// DANGER: This relies on an external TABLE - DATA_SCOPE is maintained by apidApigeeSync
+	// DANGER: This relies on an external TABLE - EDGEX_DATA_SCOPE is maintained by apidApigeeSync
 	var env, tenantId string
-	error := db.QueryRow("SELECT env, scope FROM DATA_SCOPE WHERE id = ?;", scopeuuid).Scan(&env, &tenantId)
+	error := db.QueryRow("SELECT env, scope FROM EDGEX_DATA_SCOPE WHERE id = ?;", scopeuuid).Scan(&env, &tenantId)
 
 	switch {
 	case error == sql.ErrNoRows:
+		log.Error("verifyAPIKey: sql.ErrNoRows")
 		reason := "ENV Validation Failed"
 		errorCode := "ENV_VALIDATION_FAILED"
 		return errorResponse(reason, errorCode)
@@ -119,13 +120,13 @@
 			ad.id,
 			"developer" as ctype
 		FROM
-			APP_CREDENTIAL AS c 
-			INNER JOIN APP AS a ON c.app_id = a.id
-			INNER JOIN DEVELOPER AS ad 
+			KMS_APP_CREDENTIAL AS c
+			INNER JOIN KMS_APP AS a ON c.app_id = a.id
+			INNER JOIN KMS_DEVELOPER AS ad
 				ON ad.id = a.developer_id
-			INNER JOIN APP_CREDENTIAL_APIPRODUCT_MAPPER as mp 
+			INNER JOIN KMS_APP_CREDENTIAL_APIPRODUCT_MAPPER as mp
 				ON mp.appcred_id = c.id 
-			INNER JOIN API_PRODUCT as ap ON ap.id = mp.apiprdt_id
+			INNER JOIN KMS_API_PRODUCT as ap ON ap.id = mp.apiprdt_id
 		WHERE (UPPER(ad.status) = 'ACTIVE' 
 			AND mp.apiprdt_id = ap.id 
 			AND mp.app_id = a.id
@@ -145,13 +146,13 @@
 			ad.id,
 			"company" as ctype
 		FROM
-			APP_CREDENTIAL AS c
-			INNER JOIN APP AS a ON c.app_id = a.id
-			INNER JOIN COMPANY AS ad
+			KMS_APP_CREDENTIAL AS c
+			INNER JOIN KMS_APP AS a ON c.app_id = a.id
+			INNER JOIN KMS_COMPANY AS ad
 				ON ad.id = a.company_id
-			INNER JOIN APP_CREDENTIAL_APIPRODUCT_MAPPER as mp
+			INNER JOIN KMS_APP_CREDENTIAL_APIPRODUCT_MAPPER as mp
 				ON mp.appcred_id = c.id
-			INNER JOIN API_PRODUCT as ap ON ap.id = mp.apiprdt_id
+			INNER JOIN KMS_API_PRODUCT as ap ON ap.id = mp.apiprdt_id
 		WHERE (UPPER(ad.status) = 'ACTIVE'
 			AND mp.apiprdt_id = ap.id
 			AND mp.app_id = a.id
@@ -162,8 +163,11 @@
 			AND c.tenant_id = $2)
 	;`
 
-	var status, redirectionURIs, appName, appId, resName, resEnv, cType string
-	var issuedAt int64
+	/* these fields need to be nullable types for scanning.  This is because when using json snapshots,
+	   and therefore being responsible for inserts, we were able to default everything to be not null.  With
+	   sqlite snapshots, we are not necessarily guaranteed that
+	*/
+	var status, redirectionURIs, appName, appId, resName, resEnv, issuedAt, cType sql.NullString
 	err := db.QueryRow(sSql, key, tenantId).Scan(&resName, &resEnv, &issuedAt, &status,
 		&redirectionURIs, &appName, &appId, &cType)
 	switch {
@@ -182,18 +186,18 @@
 	 * Perform all validations related to the Query made with the data
 	 * we just retrieved
 	 */
-	result := validatePath(resName, path)
+	result := validatePath(resName.String, path)
 	if result == false {
-		reason := "Path Validation Failed (" + resName + " vs " + path + ")"
+		reason := "Path Validation Failed (" + resName.String + " vs " + path + ")"
 		errorCode := "PATH_VALIDATION_FAILED"
 		return errorResponse(reason, errorCode)
 
 	}
 
 	/* Verify if the ENV matches */
-	result = validateEnv(resEnv, env)
+	result = validateEnv(resEnv.String, env)
 	if result == false {
-		reason := "ENV Validation Failed (" + resEnv + " vs " + env + ")"
+		reason := "ENV Validation Failed (" + resEnv.String + " vs " + env + ")"
 		errorCode := "ENV_VALIDATION_FAILED"
 		return errorResponse(reason, errorCode)
 	}
@@ -204,12 +208,12 @@
 		RspInfo: sucResponseDetail{
 			Key:             key,
 			ExpiresAt:       expiresAt,
-			IssuedAt:        issuedAt,
-			Status:          status,
-			RedirectionURIs: redirectionURIs,
-			Type:            cType,
-			AppId:           appId,
-			AppName:         appName},
+			IssuedAt:        issuedAt.String,
+			Status:          status.String,
+			RedirectionURIs: redirectionURIs.String,
+			Type:            cType.String,
+			AppId:           appId.String,
+			AppName:         appName.String},
 	}
 	return json.Marshal(resp)
 }
diff --git a/api_test.go b/api_test.go
index 7222341..0432193 100644
--- a/api_test.go
+++ b/api_test.go
@@ -2,7 +2,7 @@
 
 import (
 	"encoding/json"
-	"github.com/apigee-labs/transicator/common"
+	"github.com/30x/apid-core"
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/gomega"
 	"io/ioutil"
@@ -16,98 +16,6 @@
 
 	Context("DB Inserts/Deletes verification", func() {
 
-		It("Positive DB test for Insert operations", func() {
-			db := getDB()
-			txn, err := db.Begin()
-			Expect(err).ShouldNot(HaveOccurred())
-			// api products
-			for i := 0; i < 10; i++ {
-				row := generateTestApiProduct(i)
-				res := insertAPIproducts([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-			// developers
-			for i := 0; i < 10; i++ {
-				row := generateTestDeveloper(i)
-				res := insertDevelopers([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			// application
-			var j, k int
-			for i := 0; i < 10; i++ {
-				for j = k; j < 10+k; j++ {
-					row := generateTestApp(j, i)
-					res := insertApplications([]common.Row{row}, txn)
-					Expect(res).Should(BeTrue())
-				}
-				k = j
-			}
-			// app credentials
-			for i := 0; i < 10; i++ {
-				row := generateTestAppCreds(i)
-				res := insertCredentials([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-			// api product mapper
-			for i := 0; i < 10; i++ {
-				row := generateTestApiProductMapper(i)
-				res := insertAPIProductMappers([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			// Following are data for company
-			// api products
-			for i := 100; i < 110; i++ {
-				row := generateTestApiProduct(i)
-				res := insertAPIproducts([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			// companies
-			for i := 100; i < 110; i++ {
-				row := generateTestCompany(i)
-				res := insertCompanies([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			// company developers
-			for i := 100; i < 110; i++ {
-				row := generateTestCompanyDeveloper(i)
-				res := insertCompanyDevelopers([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			// application
-			k = 100
-			for i := 100; i < 110; i++ {
-				for j = k; j < 100+k; j++ {
-					row := generateTestAppCompany(j, i)
-					res := insertApplications([]common.Row{row}, txn)
-					Expect(res).Should(BeTrue())
-				}
-				k = j
-			}
-			// app credentials
-			for i := 100; i < 110; i++ {
-				row := generateTestAppCreds(i)
-				res := insertCredentials([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-			// api product mapper
-			for i := 100; i < 110; i++ {
-				row := generateTestApiProductMapper(i)
-				res := insertAPIProductMappers([]common.Row{row}, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			txn.Commit()
-			var count int64
-			db.QueryRow("select count(*) from data_scope").Scan(&count)
-			log.Info("Found ", count)
-
-		})
-
 		It("should reject a bad key", func() {
 			v := url.Values{
 				"key":       []string{"credential_x"},
@@ -165,109 +73,6 @@
 			}
 		})
 
-		It("Positive DB test for Delete operations", func() {
-			db := getDB()
-			txn, err := db.Begin()
-			Expect(err).ShouldNot(HaveOccurred())
-
-			for i := 0; i < 10; i++ {
-				row := generateTestApiProductMapper(i)
-				res := deleteAPIproductMapper(row, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			for i := 0; i < 10; i++ {
-				row := generateTestAppCreds(i)
-				res := deleteObject("APP_CREDENTIAL", row, txn)
-				Expect(res).Should(BeTrue())
-			}
-			for i := 0; i < 100; i++ {
-				row := generateTestApp(i, 999) //TODO we use j in above insertions
-				res := deleteObject("APP", row, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			for i := 0; i < 10; i++ {
-				row := generateTestDeveloper(i)
-				res := deleteObject("DEVELOPER", row, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			for i := 0; i < 10; i++ {
-				row := generateTestApiProduct(i)
-				res := deleteObject("API_PRODUCT", row, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			for i := 100; i < 110; i++ {
-				row := generateTestCompanyDeveloper(i)
-				res := deleteCompanyDeveloper(row, txn)
-				Expect(res).Should(BeTrue())
-			}
-
-			txn.Commit()
-		})
-
-		It("Negative cases for DB Deletes on KMS tables", func() {
-			db := getDB()
-			txn, err := db.Begin()
-			Expect(err).ShouldNot(HaveOccurred())
-
-			row := generateTestApiProductMapper(999)
-
-			res := deleteAPIproductMapper(row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteObject("API_PRODUCT", row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteObject("APP_CREDENTIAL", row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteObject("DEVELOPER", row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteObject("APP", row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteObject("COMPANY", row, txn)
-			Expect(res).Should(BeFalse())
-
-			res = deleteCompanyDeveloper(row, txn)
-			Expect(res).Should(BeFalse())
-
-			txn.Rollback()
-
-		})
-
-		It("Negative cases for DB Inserts/updates on KMS tables", func() {
-
-			db := getDB()
-			txn, err := db.Begin()
-			Expect(err).ShouldNot(HaveOccurred())
-
-			row := generateTestApiProduct(999)
-			row["id"] = nil
-			res := insertAPIproducts([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-			res = insertApplications([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-			res = insertCredentials([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-			res = insertAPIProductMappers([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-			res = insertCompanies([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-			res = insertCompanyDevelopers([]common.Row{row}, txn)
-			Expect(res).Should(BeFalse())
-
-		})
-
 		It("should reject a bad key", func() {
 
 			uri, err := url.Parse(testServer.URL)
@@ -294,5 +99,55 @@
 			Expect(respj.Type).Should(Equal("ErrorResult"))
 			Expect(respj.ErrInfo.ErrorCode).Should(Equal("REQ_ENTRY_NOT_FOUND"))
 		})
+
+		It("should report error for no scopes", func() {
+			v := url.Values{
+				"key":       []string{"credential_x"},
+				"uriPath":   []string{"/test"},
+				"scopeuuid": []string{"ABCDE"},
+				"action":    []string{"verify"},
+			}
+
+			clearDataScopeTable(getDB())
+			rsp, err := verifyAPIKey(v)
+			Expect(err).ShouldNot(HaveOccurred())
+
+			var respj kmsResponseFail
+			json.Unmarshal(rsp, &respj)
+			Expect(respj.Type).Should(Equal("ErrorResult"))
+			Expect(respj.ErrInfo.ErrorCode).Should(Equal("ENV_VALIDATION_FAILED"))
+
+		})
+
+		It("should report error for invalid requests", func() {
+			v := url.Values{
+				"key":       []string{"credential_x"},
+				"uriPath":   []string{"/test"},
+				"scopeuuid": []string{"ABCDE"},
+				"action":    []string{"verify"},
+			}
+
+			fields := []string{"key", "uriPath", "scopeuuid", "action"}
+			for _, field := range fields {
+				tmp := v.Get(field)
+				v.Del(field)
+
+				rsp, err := verifyAPIKey(v)
+				Expect(err).ShouldNot(HaveOccurred())
+				var respj kmsResponseFail
+				json.Unmarshal(rsp, &respj)
+				Expect(respj.Type).Should(Equal("ErrorResult"))
+				Expect(respj.ErrInfo.ErrorCode).Should(Equal("INCORRECT_USER_INPUT"))
+
+				v.Set(field, tmp)
+			}
+		})
 	})
 })
+
+func clearDataScopeTable(db apid.DB) {
+	txn, _ := db.Begin()
+	txn.Exec("DELETE FROM EDGEX_DATA_SCOPE")
+	log.Info("clear EDGEX_DATA_SCOPE for test")
+	txn.Commit()
+}
diff --git a/init.go b/init.go
index 7a1ad38..f0a70aa 100644
--- a/init.go
+++ b/init.go
@@ -52,7 +52,7 @@
 
 func createTables(db apid.DB) {
 	_, err := db.Exec(`
-CREATE TABLE IF NOT EXISTS api_product (
+CREATE TABLE IF NOT EXISTS kms_api_product (
     id text,
     tenant_id text,
     name text,
@@ -71,7 +71,7 @@
     updated_at int64,
     updated_by text,
     PRIMARY KEY (tenant_id, id));
-CREATE TABLE IF NOT EXISTS developer (
+CREATE TABLE IF NOT EXISTS kms_developer (
     id text,
     tenant_id text,
     username text,
@@ -89,7 +89,7 @@
     updated_by text,
     PRIMARY KEY (tenant_id, id)
 );
-CREATE TABLE IF NOT EXISTS company (
+CREATE TABLE IF NOT EXISTS kms_company (
     id text,
     tenant_id text,
     name text,
@@ -102,7 +102,7 @@
     _change_selector text,
     PRIMARY KEY (tenant_id, id)
 );
-CREATE TABLE IF NOT EXISTS company_developer (
+CREATE TABLE IF NOT EXISTS kms_company_developer (
      tenant_id text,
      company_id text,
      developer_id text,
@@ -114,7 +114,7 @@
     _change_selector text,
     PRIMARY KEY (tenant_id, company_id,developer_id)
 );
-CREATE TABLE IF NOT EXISTS app (
+CREATE TABLE IF NOT EXISTS kms_app (
     id text,
     tenant_id text,
     name text,
@@ -134,7 +134,7 @@
     _change_selector text,
     PRIMARY KEY (tenant_id, id)
 );
-CREATE TABLE IF NOT EXISTS app_credential (
+CREATE TABLE IF NOT EXISTS kms_app_credential (
     id text,
     tenant_id text,
     consumer_secret text,
@@ -147,7 +147,7 @@
     _change_selector text,
     PRIMARY KEY (tenant_id, id)
 );
-CREATE TABLE IF NOT EXISTS app_credential_apiproduct_mapper (
+CREATE TABLE IF NOT EXISTS kms_app_credential_apiproduct_mapper (
     tenant_id text,
     appcred_id text,
     app_id text,
@@ -156,10 +156,10 @@
     status text,
     PRIMARY KEY (appcred_id, app_id, apiprdt_id,tenant_id)
 );
-CREATE INDEX IF NOT EXISTS company_id ON company (id);
-CREATE INDEX IF NOT EXISTS developer_id ON developer (id);
-CREATE INDEX IF NOT EXISTS api_product_id ON api_product (id);
-CREATE INDEX IF NOT EXISTS app_id ON app (id);
+CREATE INDEX IF NOT EXISTS company_id ON kms_company (id);
+CREATE INDEX IF NOT EXISTS developer_id ON kms_developer (id);
+CREATE INDEX IF NOT EXISTS api_product_id ON kms_api_product (id);
+CREATE INDEX IF NOT EXISTS app_id ON kms_app (id);
 `)
 	if err != nil {
 		log.Panic("Unable to initialize DB", err)
@@ -168,7 +168,7 @@
 
 func createApidClusterTables(db apid.DB) {
 	_, err := db.Exec(`
-CREATE TABLE apid_cluster (
+CREATE TABLE edgex_apid_cluster (
     id text,
     instance_id text,
     name text,
@@ -183,7 +183,7 @@
     lastSequence text,
     PRIMARY KEY (id)
 );
-CREATE TABLE data_scope (
+CREATE TABLE edgex_data_scope (
     id text,
     apid_cluster_id text,
     scope text,
diff --git a/listener.go b/listener.go
index 3fae5c0..8c66d25 100644
--- a/listener.go
+++ b/listener.go
@@ -1,8 +1,6 @@
 package apidVerifyApiKey
 
 import (
-	"database/sql"
-
 	"github.com/30x/apid-core"
 	"github.com/apigee-labs/transicator/common"
 )
@@ -19,13 +17,6 @@
 	snapData, ok := e.(*common.Snapshot)
 	if ok {
 		processSnapshot(snapData)
-	} else {
-		changeSet, ok := e.(*common.ChangeList)
-		if ok {
-			processChange(changeSet)
-		} else {
-			log.Debugf("Received Invalid event. Ignoring. %v", e)
-		}
 	}
 	return
 }
@@ -39,647 +30,6 @@
 		log.Panicf("Unable to access database: %v", err)
 	}
 
-	createTables(db)
-
-	if len(snapshot.Tables) > 0 {
-		txn, err := db.Begin()
-		if err != nil {
-			log.Panicf("Unable to create transaction: %v", err)
-			return
-		}
-
-		/*
-		 * Iterate the tables, and insert the rows,
-		 * Commit them in bulk.
-		 */
-		ok := true
-		for _, payload := range snapshot.Tables {
-			switch payload.Name {
-			case "kms.developer":
-				ok = insertDevelopers(payload.Rows, txn)
-			case "kms.app":
-				ok = insertApplications(payload.Rows, txn)
-			case "kms.app_credential":
-				ok = insertCredentials(payload.Rows, txn)
-			case "kms.api_product":
-				ok = insertAPIproducts(payload.Rows, txn)
-			case "kms.app_credential_apiproduct_mapper":
-				ok = insertAPIProductMappers(payload.Rows, txn)
-			case "kms.company":
-				ok = insertCompanies(payload.Rows, txn)
-			case "kms.company_developer":
-				ok = insertCompanyDevelopers(payload.Rows, txn)
-			}
-			if !ok {
-				log.Error("Error encountered in Downloading Snapshot for VerifyApiKey")
-				txn.Rollback()
-				return
-			}
-		}
-		log.Debug("Downloading Snapshot for VerifyApiKey complete")
-		txn.Commit()
-	}
-
 	setDB(db)
 	return
 }
-
-/*
- * Performs bulk insert of credentials
- */
-func insertCredentials(rows []common.Row, txn *sql.Tx) bool {
-
-	var scope, id, appId, consumerSecret, appstatus, status, tenantId string
-	var issuedAt int64
-
-	prep, err := txn.Prepare("INSERT INTO APP_CREDENTIAL (_change_selector, id, app_id, consumer_secret, app_status, status, issued_at, tenant_id)VALUES($1,$2,$3,$4,$5,$6,$7,$8);")
-	if err != nil {
-		log.Error("INSERT Cred Failed: ", err)
-		return false
-	}
-	defer prep.Close()
-	for _, ele := range rows {
-		ele.Get("_change_selector", &scope)
-		ele.Get("id", &id)
-		ele.Get("app_id", &appId)
-		ele.Get("consumer_secret", &consumerSecret)
-		ele.Get("app_status", &appstatus)
-		ele.Get("status", &status)
-		ele.Get("issued_at", &issuedAt)
-		ele.Get("tenant_id", &tenantId)
-
-		/* Mandatory params check */
-		if id == "" || scope == "" || tenantId == "" {
-			log.Error("INSERT APP_CREDENTIAL: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			scope,
-			id,
-			appId,
-			consumerSecret,
-			appstatus,
-			status,
-			issuedAt,
-			tenantId)
-
-		if err != nil {
-			log.Error("INSERT CRED Failed: ", id, ", ", scope, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT CRED Success: (", id, ", ", scope, ")")
-		}
-	}
-	return true
-}
-
-/*
- * Performs Bulk insert of Applications
- */
-func insertApplications(rows []common.Row, txn *sql.Tx) bool {
-
-	var scope, EntityIdentifier, DeveloperId, CompanyId, ParentId, CallbackUrl, Status, AppName, AppFamily, tenantId, CreatedBy, LastModifiedBy string
-	var CreatedAt, LastModifiedAt int64
-
-	prep, err := txn.Prepare("INSERT INTO APP (_change_selector, id, developer_id, company_id, parent_id, callback_url,status, name, app_family, created_at, created_by,updated_at, updated_by,tenant_id) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14);")
-	if err != nil {
-		log.Error("INSERT APP Failed: ", err)
-		return false
-	}
-
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("_change_selector", &scope)
-		ele.Get("id", &EntityIdentifier)
-		ele.Get("developer_id", &DeveloperId)
-		ele.Get("company_id", &CompanyId)
-		ele.Get("parent_id", &ParentId)
-		ele.Get("callback_url", &CallbackUrl)
-		ele.Get("status", &Status)
-		ele.Get("name", &AppName)
-		ele.Get("app_family", &AppFamily)
-		ele.Get("created_at", &CreatedAt)
-		ele.Get("created_by", &CreatedBy)
-		ele.Get("updated_at", &LastModifiedAt)
-		ele.Get("updated_by", &LastModifiedBy)
-		ele.Get("tenant_id", &tenantId)
-
-		/* Mandatory params check */
-		if EntityIdentifier == "" || scope == "" || tenantId == "" {
-			log.Error("INSERT APP: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			scope,
-			EntityIdentifier,
-			DeveloperId,
-			CompanyId,
-			ParentId,
-			CallbackUrl,
-			Status,
-			AppName,
-			AppFamily,
-			CreatedAt,
-			CreatedBy,
-			LastModifiedAt,
-			LastModifiedBy,
-			tenantId)
-
-		if err != nil {
-			log.Error("INSERT APP Failed: (", EntityIdentifier, ", ", tenantId, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT APP Success: (", EntityIdentifier, ", ", tenantId, ")")
-		}
-	}
-	return true
-
-}
-
-/*
- * Performs bulk insert of Developers
- */
-func insertDevelopers(rows []common.Row, txn *sql.Tx) bool {
-
-	var scope, EntityIdentifier, Email, Status, UserName, FirstName, LastName, tenantId, CreatedBy, LastModifiedBy, Username string
-	var CreatedAt, LastModifiedAt int64
-
-	prep, err := txn.Prepare("INSERT INTO DEVELOPER (_change_selector,email,id,tenant_id,status,username,first_name,last_name,created_at,created_by,updated_at,updated_by) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12);")
-	if err != nil {
-		log.Error("INSERT DEVELOPER Failed: ", err)
-		return false
-	}
-
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("_change_selector", &scope)
-		ele.Get("email", &Email)
-		ele.Get("id", &EntityIdentifier)
-		ele.Get("tenant_id", &tenantId)
-		ele.Get("status", &Status)
-		ele.Get("username", &Username)
-		ele.Get("first_name", &FirstName)
-		ele.Get("last_name", &LastName)
-		ele.Get("created_at", &CreatedAt)
-		ele.Get("created_by", &CreatedBy)
-		ele.Get("updated_at", &LastModifiedAt)
-		ele.Get("updated_by", &LastModifiedBy)
-
-		/* Mandatory params check */
-		if EntityIdentifier == "" || scope == "" || tenantId == "" {
-			log.Error("INSERT DEVELOPER: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			scope,
-			Email,
-			EntityIdentifier,
-			tenantId,
-			Status,
-			UserName,
-			FirstName,
-			LastName,
-			CreatedAt,
-			CreatedBy,
-			LastModifiedAt,
-			LastModifiedBy)
-
-		if err != nil {
-			log.Error("INSERT DEVELOPER Failed: (", EntityIdentifier, ", ", scope, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT DEVELOPER Success: (", EntityIdentifier, ", ", scope, ")")
-		}
-	}
-	return true
-}
-
-/*
- * Performs Bulk insert of Company Developers
- */
-func insertCompanyDevelopers(rows []common.Row, txn *sql.Tx) bool {
-	var scope, CompanyId, DeveloperId, tenantId, CreatedBy, LastModifiedBy string
-	var CreatedAt, LastModifiedAt int64
-
-	prep, err := txn.Prepare("INSERT INTO COMPANY_DEVELOPER (_change_selector,company_id,tenant_id,developer_id,created_at,created_by,updated_at,updated_by) VALUES($1,$2,$3,$4,$5,$6,$7,$8);")
-	if err != nil {
-		log.Error("INSERT COMPANY_DEVELOPER Failed: ", err)
-		return false
-	}
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("_change_selector", &scope)
-		ele.Get("company_id", &CompanyId)
-		ele.Get("tenant_id", &tenantId)
-		ele.Get("developer_id", &DeveloperId)
-		ele.Get("created_at", &CreatedAt)
-		ele.Get("created_by", &CreatedBy)
-		ele.Get("updated_at", &LastModifiedAt)
-		ele.Get("updated_by", &LastModifiedBy)
-
-		/* Mandatory params check */
-		if scope == "" || tenantId == "" || CompanyId == "" || DeveloperId == "" {
-			log.Error("INSERT COMPANY_DEVELOPER: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			scope,
-			CompanyId,
-			tenantId,
-			DeveloperId,
-			CreatedAt,
-			CreatedBy,
-			LastModifiedAt,
-			LastModifiedBy)
-
-		if err != nil {
-			log.Error("INSERT COMPANY_DEVELOPER Failed: (", DeveloperId, ", ", CompanyId, ", ", scope, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT COMPANY_DEVELOPER Success: (", DeveloperId, ", ", CompanyId, ", ", scope, ")")
-		}
-	}
-	return true
-}
-
-/*
- * Performs Bulk insert of Companies
- */
-func insertCompanies(rows []common.Row, txn *sql.Tx) bool {
-	var scope, EntityIdentifier, Name, DisplayName, Status, tenantId, CreatedBy, LastModifiedBy string
-	var CreatedAt, LastModifiedAt int64
-
-	prep, err := txn.Prepare("INSERT INTO COMPANY (_change_selector,id,tenant_id,status,name,display_name,created_at,created_by,updated_at,updated_by) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10);")
-	if err != nil {
-		log.Error("INSERT COMPANY Failed: ", err)
-		return false
-	}
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("_change_selector", &scope)
-		ele.Get("id", &EntityIdentifier)
-		ele.Get("tenant_id", &tenantId)
-		ele.Get("status", &Status)
-		ele.Get("name", &Name)
-		ele.Get("display_name", &DisplayName)
-		ele.Get("created_at", &CreatedAt)
-		ele.Get("created_by", &CreatedBy)
-		ele.Get("updated_at", &LastModifiedAt)
-		ele.Get("updated_by", &LastModifiedBy)
-
-		/* Mandatory params check */
-		if EntityIdentifier == "" || scope == "" || tenantId == "" {
-			log.Error("INSERT COMPANY: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			scope,
-			EntityIdentifier,
-			tenantId,
-			Status,
-			Name,
-			DisplayName,
-			CreatedAt,
-			CreatedBy,
-			LastModifiedAt,
-			LastModifiedBy)
-
-		if err != nil {
-			log.Error("INSERT COMPANY Failed: (", EntityIdentifier, ", ", scope, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT COMPANY Success: (", EntityIdentifier, ", ", scope, ")")
-		}
-	}
-	return true
-}
-
-/*
- * Performs Bulk insert of API products
- */
-func insertAPIproducts(rows []common.Row, txn *sql.Tx) bool {
-
-	var scope, apiProduct, res, env, tenantId string
-
-	prep, err := txn.Prepare("INSERT INTO API_PRODUCT (id, api_resources, environments, tenant_id,_change_selector) VALUES($1,$2,$3,$4,$5)")
-	if err != nil {
-		log.Error("INSERT API_PRODUCT Failed: ", err)
-		return false
-	}
-
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("_change_selector", &scope)
-		ele.Get("id", &apiProduct)
-		ele.Get("api_resources", &res)
-		ele.Get("environments", &env)
-		ele.Get("tenant_id", &tenantId)
-
-		/* Mandatory params check */
-		if apiProduct == "" || scope == "" || tenantId == "" {
-			log.Error("INSERT API_PRODUCT: i/p args missing")
-			return false
-		}
-		_, err = prep.Exec(
-			apiProduct,
-			res,
-			env,
-			tenantId,
-			scope)
-
-		if err != nil {
-			log.Error("INSERT API_PRODUCT Failed: (", apiProduct, ", ", tenantId, ")", err)
-			return false
-		} else {
-			log.Debug("INSERT API_PRODUCT Success: (", apiProduct, ", ", tenantId, ")")
-		}
-	}
-	return true
-}
-
-/*
- * Performs a bulk insert of all APP_CREDENTIAL_APIPRODUCT_MAPPER rows
- */
-func insertAPIProductMappers(rows []common.Row, txn *sql.Tx) bool {
-
-	var ApiProduct, AppId, EntityIdentifier, tenantId, Scope, Status string
-
-	prep, err := txn.Prepare("INSERT INTO APP_CREDENTIAL_APIPRODUCT_MAPPER(apiprdt_id, app_id, appcred_id, tenant_id, _change_selector, status) VALUES($1,$2,$3,$4,$5,$6);")
-	if err != nil {
-		log.Error("INSERT APP_CREDENTIAL_APIPRODUCT_MAPPER Failed: ", err)
-		return false
-	}
-
-	defer prep.Close()
-	for _, ele := range rows {
-
-		ele.Get("apiprdt_id", &ApiProduct)
-		ele.Get("app_id", &AppId)
-		ele.Get("appcred_id", &EntityIdentifier)
-		ele.Get("tenant_id", &tenantId)
-		ele.Get("_change_selector", &Scope)
-		ele.Get("status", &Status)
-
-		/* Mandatory params check */
-		if ApiProduct == "" || AppId == "" || EntityIdentifier == "" || tenantId == "" || Scope == "" {
-			log.Error("INSERT APP_CREDENTIAL_APIPRODUCT_MAPPER : i/p args missing")
-			return false
-		}
-
-		/*
-		 * If the credentials has been successfully inserted, insert the
-		 * mapping entries associated with the credential
-		 */
-
-		_, err = prep.Exec(
-			ApiProduct,
-			AppId,
-			EntityIdentifier,
-			tenantId,
-			Scope,
-			Status)
-
-		if err != nil {
-			log.Error("INSERT APP_CREDENTIAL_APIPRODUCT_MAPPER Failed: (",
-				ApiProduct, ", ",
-				AppId, ", ",
-				EntityIdentifier, ", ",
-				tenantId, ", ",
-				Scope, ", ",
-				Status,
-				")",
-				err)
-
-			return false
-		} else {
-			log.Debug("INSERT APP_CREDENTIAL_APIPRODUCT_MAPPER Success: (",
-				ApiProduct, ", ",
-				AppId, ", ",
-				EntityIdentifier, ", ",
-				tenantId, ", ",
-				Scope, ", ",
-				Status,
-				")")
-		}
-	}
-	return true
-}
-
-func processChange(changes *common.ChangeList) {
-
-	db := getDB()
-
-	txn, err := db.Begin()
-	if err != nil {
-		log.Error("Unable to create transaction")
-		return
-	}
-	defer txn.Rollback()
-
-	var rows []common.Row
-	ok := true
-
-	log.Debugf("apigeeSyncEvent: %d changes", len(changes.Changes))
-	for _, payload := range changes.Changes {
-		rows = nil
-		switch payload.Table {
-		case "kms.developer":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertDevelopers(rows, txn)
-
-			case common.Update:
-				ok = deleteObject("DEVELOPER", payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertDevelopers(rows, txn)
-
-			case common.Delete:
-				ok = deleteObject("DEVELOPER", payload.OldRow, txn)
-			}
-		case "kms.app":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertApplications(rows, txn)
-
-			case common.Update:
-				ok = deleteObject("APP", payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertApplications(rows, txn)
-
-			case common.Delete:
-				ok = deleteObject("APP", payload.OldRow, txn)
-			}
-		case "kms.company":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertCompanies(rows, txn)
-
-			case common.Update:
-				ok = deleteObject("COMPANY", payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertCompanies(rows, txn)
-
-			case common.Delete:
-				ok = deleteObject("COMPANY", payload.OldRow, txn)
-			}
-		case "kms.company_developer":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertCompanyDevelopers(rows, txn)
-
-			case common.Update:
-				ok = deleteCompanyDeveloper(payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertCompanyDevelopers(rows, txn)
-
-			case common.Delete:
-				ok = deleteCompanyDeveloper(payload.OldRow, txn)
-			}
-		case "kms.app_credential":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertCredentials(rows, txn)
-
-			case common.Update:
-				ok = deleteObject("APP_CREDENTIAL", payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertCredentials(rows, txn)
-
-			case common.Delete:
-				ok = deleteObject("APP_CREDENTIAL", payload.OldRow, txn)
-			}
-		case "kms.api_product":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertAPIproducts(rows, txn)
-
-			case common.Update:
-				ok = deleteObject("API_PRODUCT", payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertAPIproducts(rows, txn)
-
-			case common.Delete:
-				ok = deleteObject("API_PRODUCT", payload.OldRow, txn)
-			}
-
-		case "kms.app_credential_apiproduct_mapper":
-			switch payload.Operation {
-			case common.Insert:
-				rows = append(rows, payload.NewRow)
-				ok = insertAPIProductMappers(rows, txn)
-
-			case common.Update:
-				ok = deleteAPIproductMapper(payload.OldRow, txn)
-				rows = append(rows, payload.NewRow)
-				ok = insertAPIProductMappers(rows, txn)
-
-			case common.Delete:
-				ok = deleteAPIproductMapper(payload.OldRow, txn)
-			}
-		}
-		if !ok {
-			log.Error("Sql Operation error. Operation rollbacked")
-			return
-		}
-	}
-	txn.Commit()
-	return
-}
-
-/*
- * DELETE OBJECT as passed in the input
- */
-func deleteObject(object string, ele common.Row, txn *sql.Tx) bool {
-
-	var scope, objid string
-	ssql := "DELETE FROM " + object + " WHERE id = $1 AND _change_selector = $2"
-	prep, err := txn.Prepare(ssql)
-	if err != nil {
-		log.Error("DELETE ", object, " Failed: ", err)
-		return false
-	}
-	defer prep.Close()
-	ele.Get("_change_selector", &scope)
-	ele.Get("id", &objid)
-
-	res, err := prep.Exec(objid, scope)
-	if err == nil {
-		affect, err := res.RowsAffected()
-		if err == nil && affect != 0 {
-			log.Debugf("DELETE %s (%s, %s) success.", object, objid, scope)
-			return true
-		}
-	}
-	log.Errorf("DELETE %s (%s, %s) failed.", object, objid, scope)
-	return false
-
-}
-
-/*
- * DELETE  APIPRDT MAPPER
- */
-func deleteAPIproductMapper(ele common.Row, txn *sql.Tx) bool {
-	var ApiProduct, AppId, EntityIdentifier, apid_scope string
-
-	prep, err := txn.Prepare("DELETE FROM APP_CREDENTIAL_APIPRODUCT_MAPPER WHERE apiprdt_id=$1 AND app_id=$2 AND appcred_id=$3 AND _change_selector=$4;")
-	if err != nil {
-		log.Error("DELETE APP_CREDENTIAL_APIPRODUCT_MAPPER Failed: ", err)
-		return false
-	}
-
-	defer prep.Close()
-
-	ele.Get("apiprdt_id", &ApiProduct)
-	ele.Get("app_id", &AppId)
-	ele.Get("appcred_id", &EntityIdentifier)
-	ele.Get("_change_selector", &apid_scope)
-
-	res, err := prep.Exec(ApiProduct, AppId, EntityIdentifier, apid_scope)
-	if err == nil {
-		affect, err := res.RowsAffected()
-		if err == nil && affect != 0 {
-			log.Debugf("DELETE APP_CREDENTIAL_APIPRODUCT_MAPPER (%s, %s, %s, %s) success.", ApiProduct, AppId, EntityIdentifier, apid_scope)
-			return true
-		}
-	}
-	log.Errorf("DELETE APP_CREDENTIAL_APIPRODUCT_MAPPER (%s, %s, %s, %s) failed.", ApiProduct, AppId, EntityIdentifier, apid_scope, err)
-	return false
-}
-
-func deleteCompanyDeveloper(ele common.Row, txn *sql.Tx) bool {
-	prep, err := txn.Prepare(`
-	DELETE FROM COMPANY_DEVELOPER
-	WHERE tenant_id=$1 AND company_id=$2 AND developer_id=$3`)
-	if err != nil {
-		log.Errorf("DELETE COMPANY_DEVELOPER Failed: %v", err)
-		return false
-	}
-	defer prep.Close()
-
-	var tenantId, companyId, developerId string
-	ele.Get("tenant_id", &tenantId)
-	ele.Get("company_id", &companyId)
-	ele.Get("developer_id", &developerId)
-
-	res, err := prep.Exec(tenantId, companyId, developerId)
-	if err == nil {
-		affect, err := res.RowsAffected()
-		if err == nil && affect != 0 {
-			log.Debugf("DELETE COMPANY_DEVELOPER (%s, %s, %s) success.", tenantId, companyId, developerId)
-			return true
-		}
-	}
-	log.Errorf("DELETE COMPANY_DEVELOPER (%s, %s, %s) failed: %v", tenantId, companyId, developerId, err)
-	return false
-}
diff --git a/listener_test.go b/listener_test.go
index 195b2b9..fed281f 100644
--- a/listener_test.go
+++ b/listener_test.go
@@ -1,1157 +1,44 @@
 package apidVerifyApiKey
 
 import (
-	"encoding/json"
-	"fmt"
 	"github.com/30x/apid-core"
 	"github.com/apigee-labs/transicator/common"
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/gomega"
-	"io/ioutil"
-	"net/http"
-	"net/http/httptest"
-	"net/url"
 )
 
 var _ = Describe("listener", func() {
 
 	Context("KMS create/updates verification via changes for Developer", func() {
-		It("Create KMS tables via changes, and Verify via verifyApiKey", func(done Done) {
-			server := mockKMSserver()
-			var event = common.ChangeList{}
-			closed := 0
-			/* API Product */
-			srvItems := common.Row{
-				"id": {
-					Value: "ch_api_product_2",
-				},
-				"api_resources": {
-					Value: "{}",
-				},
-				"environments": {
-					Value: "{Env_0, Env_1}",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
+
+		handler := handler{}
+
+		It("should set DB to appropriate version", func() {
+
+			saveDb := getDB()
+
+			s := &common.Snapshot{
+				SnapshotInfo: "test_snapshot",
+				Tables:       []common.Table{},
 			}
 
-			/* DEVELOPER */
-			devItems := common.Row{
-				"id": {
-					Value: "ch_developer_id_2",
-				},
-				"status": {
-					Value: "Active",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-			}
+			handler.Handle(s)
 
-			/* APP */
-			appItems := common.Row{
-				"id": {
-					Value: "ch_application_id_2",
-				},
-				"developer_id": {
-					Value: "ch_developer_id_2",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"parent_id": {
-					Value: "ch_developer_id_2",
-				},
-			}
+			expectedDB, err := data.DBVersion(s.SnapshotInfo)
+			Expect(err).NotTo(HaveOccurred())
 
-			/* CRED */
-			credItems := common.Row{
-				"id": {
-					Value: "ch_app_credential_2",
-				},
-				"app_id": {
-					Value: "ch_application_id_2",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-			}
+			Expect(getDB() == expectedDB).Should(BeTrue())
 
-			/* APP_CRED_APIPRD_MAPPER */
-			mpItems := common.Row{
-				"apiprdt_id": {
-					Value: "ch_api_product_2",
-				},
-				"app_id": {
-					Value: "ch_application_id_2",
-				},
-				"appcred_id": {
-					Value: "ch_app_credential_2",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-			}
-
-			event.Changes = []common.Change{
-				{
-					Table:     "kms.api_product",
-					NewRow:    srvItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.developer",
-					NewRow:    devItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.app",
-					NewRow:    appItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.app_credential",
-					NewRow:    credItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.app_credential_apiproduct_mapper",
-					NewRow:    mpItems,
-					Operation: 1,
-				},
-			}
-
-			h := &test_handler{
-				"checkDatabase post Insertion",
-				func(e apid.Event) {
-					defer GinkgoRecover()
-
-					// ignore the first event, let standard listener process it
-					changeSet := e.(*common.ChangeList)
-					if len(changeSet.Changes) > 0 || closed == 1 {
-						return
-					}
-
-					rsp, err := http.PostForm(
-						fmt.Sprintf("%s/verifiers/apikey",
-							server.URL),
-						url.Values{"key": {"ch_app_credential_2"},
-							"uriPath":   {"/test"},
-							"scopeuuid": {"XYZ"},
-							"action":    {"verify"}})
-
-					Expect(err).Should(Succeed())
-					defer rsp.Body.Close()
-					body, readErr := ioutil.ReadAll(rsp.Body)
-					Expect(readErr).Should(Succeed())
-					var respj kmsResponseSuccess
-					json.Unmarshal(body, &respj)
-					Expect(respj.Type).Should(Equal("APIKeyContext"))
-					Expect(rsp.StatusCode).To(Equal(http.StatusOK))
-					Expect(respj.RspInfo.Key).Should(Equal("ch_app_credential_2"))
-					Expect(respj.RspInfo.Type).Should(Equal("developer"))
-					dataValue := rsp.Header.Get("Content-Type")
-					Expect(dataValue).To(Equal("application/json"))
-
-					rsp, err = http.PostForm(
-						fmt.Sprintf("%s/verifiers/apikey",
-							server.URL),
-						url.Values{"key": {"ch_app_credential_2"},
-							"uriPath":   {"/test"},
-							"scopeuuid": {"badscope"},
-							"action":    {"verify"}})
-
-					Expect(err).Should(Succeed())
-					defer rsp.Body.Close()
-					body, readErr = ioutil.ReadAll(rsp.Body)
-					Expect(readErr).Should(Succeed())
-					var respe kmsResponseFail
-					json.Unmarshal(body, &respe)
-					Expect(rsp.StatusCode).To(Equal(http.StatusOK))
-					dataValue = rsp.Header.Get("Content-Type")
-					Expect(dataValue).To(Equal("application/json"))
-					Expect(respe.Type).Should(Equal("ErrorResult"))
-					Expect(respe.ErrInfo.ErrorCode).Should(Equal("ENV_VALIDATION_FAILED"))
-
-					closed = 1
-					close(done)
-				},
-			}
-
-			apid.Events().Listen("ApigeeSync", h)
-			apid.Events().Emit("ApigeeSync", &event)
-			apid.Events().Emit("ApigeeSync", &common.ChangeList{})
+			//restore the db to the valid one
+			setDB(saveDb)
 		})
+
 	})
-
-	Context("KMS create/updates verification via changes for Company", func() {
-		It("Create KMS tables via changes, and Verify via verifyApiKey", func(done Done) {
-			server := mockKMSserver()
-			var event = common.ChangeList{}
-			closed := 0
-			/* API Product */
-			srvItems := common.Row{
-				"id": {
-					Value: "ch_api_product_5",
-				},
-				"api_resources": {
-					Value: "{}",
-				},
-				"environments": {
-					Value: "{Env_0, Env_1}",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-			}
-
-			/* COMPANY */
-			companyItems := common.Row{
-				"id": {
-					Value: "ch_company_id_5",
-				},
-				"status": {
-					Value: "Active",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"name": {
-					Value: "test_company_name0",
-				},
-				"display_name": {
-					Value: "test_company_display_name0",
-				},
-			}
-			/* COMPANY_DEVELOPER */
-			companyDeveloperItems := common.Row{
-				"id": {
-					Value: "ch_developer_id_5",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"company_id": {
-					Value: "ch_company_id_5",
-				},
-				"developer_id": {
-					Value: "ch_developer_id_5",
-				},
-			}
-
-			/* APP */
-			appItems := common.Row{
-				"id": {
-					Value: "ch_application_id_5",
-				},
-				"company_id": {
-					Value: "ch_company_id_5",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"parent_id": {
-					Value: "ch_company_id_5",
-				},
-			}
-
-			/* CRED */
-			credItems := common.Row{
-				"id": {
-					Value: "ch_app_credential_5",
-				},
-				"app_id": {
-					Value: "ch_application_id_5",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-			}
-
-			/* APP_CRED_APIPRD_MAPPER */
-			mpItems := common.Row{
-				"apiprdt_id": {
-					Value: "ch_api_product_5",
-				},
-				"app_id": {
-					Value: "ch_application_id_5",
-				},
-				"appcred_id": {
-					Value: "ch_app_credential_5",
-				},
-				"status": {
-					Value: "Approved",
-				},
-				"_change_selector": {
-					Value: "test_org0",
-				},
-				"tenant_id": {
-					Value: "tenant_id_0",
-				},
-			}
-
-			event.Changes = []common.Change{
-				{
-					Table:     "kms.api_product",
-					NewRow:    srvItems,
-					Operation: 1,
-				},
-
-				{
-					Table:     "kms.app",
-					NewRow:    appItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.app_credential",
-					NewRow:    credItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.app_credential_apiproduct_mapper",
-					NewRow:    mpItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.company",
-					NewRow:    companyItems,
-					Operation: 1,
-				},
-				{
-					Table:     "kms.company_developer",
-					NewRow:    companyDeveloperItems,
-					Operation: 1,
-				},
-			}
-
-			h := &test_handler{
-				"checkDatabase post Insertion",
-				func(e apid.Event) {
-					defer GinkgoRecover()
-
-					// ignore the first event, let standard listener process it
-					changeSet := e.(*common.ChangeList)
-					if len(changeSet.Changes) > 0 || closed == 1 {
-						return
-					}
-
-					rsp, err := http.PostForm(
-						fmt.Sprintf("%s/verifiers/apikey",
-							server.URL),
-						url.Values{"key": {"ch_app_credential_5"},
-							"uriPath":   {"/test"},
-							"scopeuuid": {"XYZ"},
-							"action":    {"verify"}})
-
-					Expect(err).Should(Succeed())
-					defer rsp.Body.Close()
-					body, readErr := ioutil.ReadAll(rsp.Body)
-					Expect(readErr).Should(Succeed())
-					var respj kmsResponseSuccess
-					json.Unmarshal(body, &respj)
-					Expect(rsp.StatusCode).To(Equal(http.StatusOK))
-					Expect(respj.RspInfo.Type).Should(Equal("company"))
-					Expect(respj.Type).Should(Equal("APIKeyContext"))
-					Expect(respj.RspInfo.Key).Should(Equal("ch_app_credential_5"))
-					dataValue := rsp.Header.Get("Content-Type")
-					Expect(dataValue).To(Equal("application/json"))
-
-					rsp, err = http.PostForm(
-						fmt.Sprintf("%s/verifiers/apikey",
-							server.URL),
-						url.Values{"key": {"ch_app_credential_5"},
-							"uriPath":   {"/test"},
-							"scopeuuid": {"badscope"},
-							"action":    {"verify"}})
-
-					Expect(err).Should(Succeed())
-					defer rsp.Body.Close()
-					body, readErr = ioutil.ReadAll(rsp.Body)
-					Expect(readErr).Should(Succeed())
-					var respe kmsResponseFail
-					json.Unmarshal(body, &respe)
-					Expect(rsp.StatusCode).To(Equal(http.StatusOK))
-					dataValue = rsp.Header.Get("Content-Type")
-					Expect(dataValue).To(Equal("application/json"))
-					Expect(respe.Type).Should(Equal("ErrorResult"))
-					Expect(respe.ErrInfo.ErrorCode).Should(Equal("ENV_VALIDATION_FAILED"))
-
-					closed = 1
-					close(done)
-				},
-			}
-
-			apid.Events().Listen("ApigeeSync", h)
-			apid.Events().Emit("ApigeeSync", &event)
-			apid.Events().Emit("ApigeeSync", &common.ChangeList{})
-		})
-	})
-
-	It("Modify tables in KMS tables, and verify via verifyApiKey for Developer", func(done Done) {
-		closed := 0
-		var event = common.ChangeList{}
-		var event2 = common.ChangeList{}
-
-		/* Orig data */
-		/* API Product */
-		srvItemsOld := common.Row{
-			"id": {
-				Value: "ch_api_product_0",
-			},
-			"api_resources": {
-				Value: "{}",
-			},
-			"environments": {
-				Value: "{Env_0, Env_1}",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* DEVELOPER */
-		devItemsOld := common.Row{
-			"id": {
-				Value: "ch_developer_id_0",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP */
-		appItemsOld := common.Row{
-			"id": {
-				Value: "ch_application_id_0",
-			},
-			"developer_id": {
-				Value: "ch_developer_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"parent_id": {
-				Value: "ch_developer_id_0",
-			},
-		}
-
-		/* CRED */
-		credItemsOld := common.Row{
-			"id": {
-				Value: "ch_app_credential_0",
-			},
-			"app_id": {
-				Value: "ch_application_id_0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP_CRED_APIPRD_MAPPER */
-		mpItemsOld := common.Row{
-			"apiprdt_id": {
-				Value: "ch_api_product_0",
-			},
-			"app_id": {
-				Value: "ch_application_id_0",
-			},
-			"appcred_id": {
-				Value: "ch_app_credential_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-		}
-
-		/* New to be replaced data */
-		/* API PRODUCT */
-		srvItemsNew := common.Row{
-			"id": {
-				Value: "ch_api_product_1",
-			},
-			"api_resources": {
-				Value: "{}",
-			},
-			"environments": {
-				Value: "{Env_0, Env_1}",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* DEVELOPER */
-		devItemsNew := common.Row{
-			"id": {
-				Value: "ch_developer_id_1",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP */
-		appItemsNew := common.Row{
-			"id": {
-				Value: "ch_application_id_1",
-			},
-			"developer_id": {
-				Value: "ch_developer_id_1",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"parent_id": {
-				Value: "ch_developer_id_1",
-			},
-		}
-
-		/* CRED */
-		credItemsNew := common.Row{
-			"id": {
-				Value: "ch_app_credential_1",
-			},
-			"app_id": {
-				Value: "ch_application_id_1",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP_CRED_APIPRD_MAPPER */
-		mpItemsNew := common.Row{
-			"apiprdt_id": {
-				Value: "ch_api_product_1",
-			},
-			"app_id": {
-				Value: "ch_application_id_1",
-			},
-			"appcred_id": {
-				Value: "ch_app_credential_1",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-		}
-
-		event.Changes = []common.Change{
-			{
-				Table:     "kms.api_product",
-				NewRow:    srvItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.developer",
-				NewRow:    devItemsOld,
-				Operation: 1,
-			},
-
-			{
-				Table:     "kms.app",
-				NewRow:    appItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.app_credential",
-				NewRow:    credItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.app_credential_apiproduct_mapper",
-				NewRow:    mpItemsOld,
-				Operation: 1,
-			},
-		}
-
-		event2.Changes = []common.Change{
-			{
-				Table:     "kms.api_product",
-				OldRow:    srvItemsOld,
-				NewRow:    srvItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.developer",
-				OldRow:    devItemsOld,
-				NewRow:    devItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app",
-				OldRow:    appItemsOld,
-				NewRow:    appItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app_credential",
-				OldRow:    credItemsOld,
-				NewRow:    credItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app_credential_apiproduct_mapper",
-				OldRow:    mpItemsOld,
-				NewRow:    mpItemsNew,
-				Operation: 2,
-			},
-		}
-
-		h := &test_handler{
-			"checkDatabase post Insertion",
-			func(e apid.Event) {
-				defer GinkgoRecover()
-
-				// ignore the first event, let standard listener process it
-				changeSet := e.(*common.ChangeList)
-				if len(changeSet.Changes) > 0 || closed == 1 {
-					return
-				}
-				v := url.Values{
-					"key":       []string{"ch_app_credential_1"},
-					"uriPath":   []string{"/test"},
-					"scopeuuid": []string{"XYZ"},
-					"action":    []string{"verify"},
-				}
-				rsp, err := verifyAPIKey(v)
-				Expect(err).ShouldNot(HaveOccurred())
-				var respj kmsResponseSuccess
-				json.Unmarshal(rsp, &respj)
-				Expect(respj.Type).Should(Equal("APIKeyContext"))
-				Expect(respj.RspInfo.Key).Should(Equal("ch_app_credential_1"))
-				Expect(respj.RspInfo.Type).Should(Equal("developer"))
-				closed = 1
-				close(done)
-			},
-		}
-
-		apid.Events().Listen("ApigeeSync", h)
-		apid.Events().Emit("ApigeeSync", &event)
-		apid.Events().Emit("ApigeeSync", &event2)
-		apid.Events().Emit("ApigeeSync", &common.ChangeList{})
-	})
-
-	It("Modify tables in KMS tables, and verify via verifyApiKey for Company", func(done Done) {
-		closed := 0
-		var event = common.ChangeList{}
-		var event2 = common.ChangeList{}
-
-		/* Orig data */
-		/* API Product */
-		srvItemsOld := common.Row{
-			"id": {
-				Value: "ch_api_product_0",
-			},
-			"api_resources": {
-				Value: "{}",
-			},
-			"environments": {
-				Value: "{Env_0, Env_1}",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* DEVELOPER */
-		devItemsOld := common.Row{
-			"id": {
-				Value: "ch_developer_id_0",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP */
-		appItemsOld := common.Row{
-			"id": {
-				Value: "ch_application_id_0",
-			},
-			"company_id": {
-				Value: "ch_company_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"parent_id": {
-				Value: "ch_company_id_0",
-			},
-		}
-
-		/* COMPANY */
-		companyItemsOld := common.Row{
-			"id": {
-				Value: "ch_company_id_0",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"name": {
-				Value: "test_company_name0",
-			},
-			"display_name": {
-				Value: "test_company_display_name0",
-			},
-		}
-
-		/* COMPANY_DEVELOPER */
-		companyDeveloperItemsOld := common.Row{
-			"id": {
-				Value: "ch_developer_id_0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"company_id": {
-				Value: "ch_company_id_0",
-			},
-			"developer_id": {
-				Value: "ch_developer_id_0",
-			},
-		}
-
-		/* CRED */
-		credItemsOld := common.Row{
-			"id": {
-				Value: "ch_app_credential_0",
-			},
-			"app_id": {
-				Value: "ch_application_id_0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP_CRED_APIPRD_MAPPER */
-		mpItemsOld := common.Row{
-			"apiprdt_id": {
-				Value: "ch_api_product_0",
-			},
-			"app_id": {
-				Value: "ch_application_id_0",
-			},
-			"appcred_id": {
-				Value: "ch_app_credential_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-		}
-
-		/* New to be replaced data */
-		/* API PRODUCT */
-		srvItemsNew := common.Row{
-			"id": {
-				Value: "ch_api_product_1",
-			},
-			"api_resources": {
-				Value: "{}",
-			},
-			"environments": {
-				Value: "{Env_0, Env_1}",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* DEVELOPER */
-		devItemsNew := common.Row{
-			"id": {
-				Value: "ch_developer_id_1",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* COMPANY */
-		companyItemsNew := common.Row{
-			"id": {
-				Value: "ch_company_id_1",
-			},
-			"status": {
-				Value: "Active",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"name": {
-				Value: "test_company_name0",
-			},
-			"display_name": {
-				Value: "test_company_display_name0",
-			},
-		}
-
-		/* COMPANY_DEVELOPER */
-		companyDeveloperItemsNew := common.Row{
-			"id": {
-				Value: "ch_developer_id_1",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"company_id": {
-				Value: "ch_company_id_1",
-			},
-			"developer_id": {
-				Value: "ch_developer_id_1",
-			},
-		}
-
-		/* APP */
-		appItemsNew := common.Row{
-			"id": {
-				Value: "ch_application_id_1",
-			},
-			"company_id": {
-				Value: "ch_company_id_1",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"parent_id": {
-				Value: "ch_company_id_1",
-			},
-		}
-
-		/* CRED */
-		credItemsNew := common.Row{
-			"id": {
-				Value: "ch_app_credential_1",
-			},
-			"app_id": {
-				Value: "ch_application_id_1",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-		}
-
-		/* APP_CRED_APIPRD_MAPPER */
-		mpItemsNew := common.Row{
-			"apiprdt_id": {
-				Value: "ch_api_product_1",
-			},
-			"app_id": {
-				Value: "ch_application_id_1",
-			},
-			"appcred_id": {
-				Value: "ch_app_credential_1",
-			},
-			"status": {
-				Value: "Approved",
-			},
-			"_change_selector": {
-				Value: "test_org0",
-			},
-			"tenant_id": {
-				Value: "tenant_id_0",
-			},
-		}
-
-		event.Changes = []common.Change{
-			{
-				Table:     "kms.api_product",
-				NewRow:    srvItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.developer",
-				NewRow:    devItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.company",
-				NewRow:    companyItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.company_developer",
-				NewRow:    companyDeveloperItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.app",
-				NewRow:    appItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.app_credential",
-				NewRow:    credItemsOld,
-				Operation: 1,
-			},
-			{
-				Table:     "kms.app_credential_apiproduct_mapper",
-				NewRow:    mpItemsOld,
-				Operation: 1,
-			},
-		}
-
-		event2.Changes = []common.Change{
-			{
-				Table:     "kms.api_product",
-				OldRow:    srvItemsOld,
-				NewRow:    srvItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.developer",
-				OldRow:    devItemsOld,
-				NewRow:    devItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.company",
-				OldRow:    companyItemsOld,
-				NewRow:    companyItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.company_developer",
-				OldRow:    companyDeveloperItemsOld,
-				NewRow:    companyDeveloperItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app",
-				OldRow:    appItemsOld,
-				NewRow:    appItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app_credential",
-				OldRow:    credItemsOld,
-				NewRow:    credItemsNew,
-				Operation: 2,
-			},
-			{
-				Table:     "kms.app_credential_apiproduct_mapper",
-				OldRow:    mpItemsOld,
-				NewRow:    mpItemsNew,
-				Operation: 2,
-			},
-		}
-
-		h := &test_handler{
-			"checkDatabase post Insertion",
-			func(e apid.Event) {
-				defer GinkgoRecover()
-
-				// ignore the first event, let standard listener process it
-				changeSet := e.(*common.ChangeList)
-				if len(changeSet.Changes) > 0 || closed == 1 {
-					return
-				}
-				v := url.Values{
-					"key":       []string{"ch_app_credential_1"},
-					"uriPath":   []string{"/test"},
-					"scopeuuid": []string{"XYZ"},
-					"action":    []string{"verify"},
-				}
-				rsp, err := verifyAPIKey(v)
-				Expect(err).ShouldNot(HaveOccurred())
-				var respj kmsResponseSuccess
-				json.Unmarshal(rsp, &respj)
-				Expect(respj.Type).Should(Equal("APIKeyContext"))
-				Expect(respj.RspInfo.Key).Should(Equal("ch_app_credential_1"))
-
-				closed = 1
-				close(done)
-			},
-		}
-
-		apid.Events().Listen("ApigeeSync", h)
-		apid.Events().Emit("ApigeeSync", &event)
-		apid.Events().Emit("ApigeeSync", &event2)
-		apid.Events().Emit("ApigeeSync", &common.ChangeList{})
-	})
-
 })
 
-type test_handler struct {
-	description string
-	f           func(event apid.Event)
-}
-
-func (t *test_handler) String() string {
-	return t.description
-}
-
-func (t *test_handler) Handle(event apid.Event) {
-	t.f(event)
-}
-
 func addScopes(db apid.DB) {
 	txn, _ := db.Begin()
-	txn.Exec("INSERT INTO DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
+	txn.Exec("INSERT INTO EDGEX_DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
 		"VALUES"+
 		"($1,$2,$3,$4,$5,$6)",
 		"ABCDE",
@@ -1161,7 +48,7 @@
 		"test_org0",
 		"Env_0",
 	)
-	txn.Exec("INSERT INTO DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
+	txn.Exec("INSERT INTO EDGEX_DATA_SCOPE (id, _change_selector, apid_cluster_id, scope, org, env) "+
 		"VALUES"+
 		"($1,$2,$3,$4,$5,$6)",
 		"XYZ",
@@ -1171,12 +58,6 @@
 		"test_org0",
 		"Env_0",
 	)
-	log.Info("Inserted DATA_SCOPE for test")
+	log.Info("Inserted EDGEX_DATA_SCOPE for test")
 	txn.Commit()
 }
-
-func mockKMSserver() *httptest.Server {
-	return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
-		handleRequest(w, r)
-	}))
-}
diff --git a/test_helper.go b/test_helper.go
index 44a341b..19eef1c 100644
--- a/test_helper.go
+++ b/test_helper.go
@@ -1,7 +1,7 @@
 package apidVerifyApiKey
 
 import (
-	"github.com/apigee-labs/transicator/common"
+	"database/sql"
 	"strconv"
 )
 
@@ -9,186 +9,79 @@
 	return strconv.FormatInt(int64(i), 10)
 }
 
-func generateTestApiProduct(suffix int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "api_product_" + convertSuffix(suffix),
-		},
-		"api_resources": {
-			Value: "{/**, /test}",
-		},
-		"environments": {
-			Value: "{Env_0, Env_1}",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
+func generateTestApiProduct(suffix int, txn *sql.Tx) {
+
+	s, err := txn.Prepare("INSERT INTO kms_api_product (id, api_resources, environments, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug : " + err.Error())
 	}
+	s.Exec("api_product_"+convertSuffix(suffix), "{/**, /test}", "{Env_0, Env_1}",
+		"tenant_id_xxxx", "Org_0")
 }
 
-func generateTestDeveloper(suffix int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "developer_id_" + convertSuffix(suffix),
-		},
-		"status": {
-			Value: "Active",
-		},
-		"email": {
-			Value: "test@apigee.com",
-		},
-		"first_name": {
-			Value: "Apigee",
-		},
-		"last_name": {
-			Value: "Google",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
+func generateTestDeveloper(suffix int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_developer (id, status, email, first_name, last_name, tenant_id, _change_selector)" +
+		"VALUES (?, ?, ?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug : " + err.Error())
 	}
+	s.Exec("developer_id_"+convertSuffix(suffix), "Active", "test@apigee.com", "Apigee", "Google", "tenant_id_xxxx", "Org_0")
 }
 
-func generateTestCompany(suffix int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "company_id_" + convertSuffix(suffix),
-		},
-		"status": {
-			Value: "Active",
-		},
-		"name": {
-			Value: "Apigee Corporation",
-		},
-		"display_name": {
-			Value: "Apigee",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
+func generateTestCompany(suffix int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_company (id, status, name, display_name, tenant_id, _change_selector)" +
+		"VALUES (?, ?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("company_id_"+convertSuffix(suffix), "Active", "Apigee Corporation", "Apigee", "tenant_id_xxxx", "Org_0")
 }
 
-func generateTestCompanyDeveloper(suffix int) common.Row {
-	return common.Row{
-		"developer_id": {
-			Value: "developer_id_" + convertSuffix(suffix),
-		},
-		"tenant_id": {
-			Value: "tenant_id_0",
-		},
-		"_change_selector": {
-			Value: "test_org0",
-		},
-		"company_id": {
-			Value: "company_id_" + convertSuffix(suffix),
-		},
+func generateTestCompanyDeveloper(suffix int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_company_developer (developer_id, tenant_id, _change_selector, company_id)" +
+		"VALUES (?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("developer_id_"+convertSuffix(suffix), "tenant_id_0", "test_org0", "company_id_"+convertSuffix(suffix))
 }
 
-func generateTestApp(suffix1, suffix2 int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "application_id_" + convertSuffix(suffix1),
-		},
-		"developer_id": {
-			Value: "developer_id_" + convertSuffix(suffix2),
-		},
-		"status": {
-			Value: "Approved",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"callback_url": {
-			Value: "http://apigee.com",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
-		"parent_id": {
-			Value: "developer_id_" + convertSuffix(suffix2),
-		},
+func generateTestApp(suffix1, suffix2 int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_app (id, developer_id, status, tenant_id, callback_url, _change_selector, parent_id)" +
+		" VALUES(?, ?, ?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("application_id_"+convertSuffix(suffix1), "developer_id_"+convertSuffix(suffix2), "Approved", "tenant_id_xxxx",
+		"http://apigee.com", "Org_0", "developer_id_"+convertSuffix(suffix2))
+
 }
 
-func generateTestAppCompany(suffix1, suffix2 int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "application_id_" + convertSuffix(suffix1),
-		},
-		"company_id": {
-			Value: "company_id_" + convertSuffix(suffix2),
-		},
-		"status": {
-			Value: "Approved",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"callback_url": {
-			Value: "http://apigee.com",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
-		"parent_id": {
-			Value: "company_id_" + convertSuffix(suffix2),
-		},
+func generateTestAppCompany(suffix1, suffix2 int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_app (id, company_id, status, tenant_id, callback_url, _change_selector, parent_id)" +
+		" VALUES(?, ?, ?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("application_id_"+convertSuffix(suffix1), "company_id_"+convertSuffix(suffix2), "Approved", "tenant_id_xxxx",
+		"http://apigee.com", "Org_0", "company_id_"+convertSuffix(suffix2))
+
 }
 
-func generateTestAppCreds(suffix int) common.Row {
-	return common.Row{
-		"id": {
-			Value: "app_credential_" + convertSuffix(suffix),
-		},
-		"app_id": {
-			Value: "application_id_" + convertSuffix(suffix),
-		},
-		"status": {
-			Value: "Approved",
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"callback_url": {
-			Value: "http://apigee.com",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
+func generateTestAppCreds(suffix int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_app_credential (id, app_id, status, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("app_credential_"+convertSuffix(suffix), "application_id_"+convertSuffix(suffix), "Approved",
+		"tenant_id_xxxx", "Org_0")
 }
 
-func generateTestApiProductMapper(suffix int) common.Row {
-	return common.Row{
-		"apiprdt_id": {
-			Value: "api_product_" + convertSuffix(suffix),
-		},
-		"status": {
-			Value: "Approved",
-		},
-		"app_id": {
-			Value: "application_id_" + convertSuffix(suffix),
-		},
-		"appcred_id": {
-			Value: "app_credential_" + convertSuffix(suffix),
-		},
-		"tenant_id": {
-			Value: "tenant_id_xxxx",
-		},
-		"_change_selector": {
-			Value: "Org_0",
-		},
+func generateTestApiProductMapper(suffix int, txn *sql.Tx) {
+	s, err := txn.Prepare("INSERT INTO kms_app_credential_apiproduct_mapper (apiprdt_id, status, app_id, appcred_id, tenant_id, _change_selector) VALUES(?, ?, ?, ?, ?, ?)")
+	if err != nil {
+		log.Panicf("This is a bug: " + err.Error())
 	}
+	s.Exec("api_product_"+convertSuffix(suffix), "Approved", "application_id_"+convertSuffix(suffix),
+		"app_credential_"+convertSuffix(suffix), "tenant_id_xxxx", "Org_0")
 }
diff --git a/verifyAPIKey_suite_test.go b/verifyAPIKey_suite_test.go
index e9dd358..131ce4e 100644
--- a/verifyAPIKey_suite_test.go
+++ b/verifyAPIKey_suite_test.go
@@ -42,6 +42,8 @@
 			handleRequest(w, req)
 		}
 	}))
+
+	createTestData(db)
 })
 
 var _ = AfterSuite(func() {
@@ -56,3 +58,71 @@
 	RegisterFailHandler(Fail)
 	RunSpecs(t, "VerifyAPIKey Suite")
 }
+
+func createTestData(db apid.DB) {
+	txn, err := db.Begin()
+	Expect(err).ShouldNot(HaveOccurred())
+	// api products
+	for i := 0; i < 10; i++ {
+		generateTestApiProduct(i, txn)
+	}
+	// developers
+	for i := 0; i < 10; i++ {
+		generateTestDeveloper(i, txn)
+	}
+
+	// application
+	var j, k int
+	for i := 0; i < 10; i++ {
+		for j = k; j < 10+k; j++ {
+			generateTestApp(j, i, txn)
+		}
+		k = j
+	}
+	// app credentials
+	for i := 0; i < 10; i++ {
+		generateTestAppCreds(i, txn)
+	}
+	// api product mapper
+	for i := 0; i < 10; i++ {
+		generateTestApiProductMapper(i, txn)
+	}
+
+	// Following are data for company
+	// api products
+	for i := 100; i < 110; i++ {
+		generateTestApiProduct(i, txn)
+	}
+
+	// companies
+	for i := 100; i < 110; i++ {
+		generateTestCompany(i, txn)
+	}
+
+	// company developers
+	for i := 100; i < 110; i++ {
+		generateTestCompanyDeveloper(i, txn)
+	}
+
+	// application
+	k = 100
+	for i := 100; i < 110; i++ {
+		for j = k; j < 100+k; j++ {
+			generateTestAppCompany(j, i, txn)
+		}
+		k = j
+	}
+	// app credentials
+	for i := 100; i < 110; i++ {
+		generateTestAppCreds(i, txn)
+	}
+	// api product mapper
+	for i := 100; i < 110; i++ {
+		generateTestApiProductMapper(i, txn)
+	}
+
+	txn.Commit()
+	var count int64
+	db.QueryRow("select count(*) from EDGEX_DATA_SCOPE").Scan(&count)
+	log.Info("Found ", count)
+}