ExistsIndex checks for the existence of named index “in” on database table “tn”. The method returns true if the specified index exists and false if it does not.
This method is used internally in PublicDB.DropIndex and does not need to be called prior to dropping a database index.
The following structure ‘Depot’ has been used to create table “depot” in the target database with index “idx_depot_region_county”. We will check for the existence of “idx_depot_region_county” expecting a true result, then check for the existence of index “idx_depot_province_region” expecting a false result.
package main
import (
"log"
"github.com/1414C/sqac"
_ "github.com/SAP/go-hdb/driver"
_ "github.com/denisenkom/go-mssqldb"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
func main() {
var (
Handle sqac.PublicDB
)
// table depot declaration with index idx_depot_region_county declaration
type Depot struct {
DepotNum int `db:"depot_num" sqac:"primary_key:inc"`
CreateDate time.Time `db:"create_date" sqac:"nullable:false;default:now();"`
Country string `db:"country" sqac:"nullable:false;default:CA"`
Province string `db:"province" sqac:"nullable:false;default:AB"`
Region string `db:"region" sqac:"nullable:false;default:YYC;index:idx_depot_region_county"`
County string `db:"county" sqac:"nullable:false;index:idx_depot_region_county"`
Population int `db:"population" sqac:"nullable:false;default:0;index:non-unique"`
}
// Create a PublicDB instance to connect to the test sqlite db
Handle = sqac.Create("sqlite", false, false, "testdb.sqlite")
defer Handle.Close()
// Ensure table "depot" exists in the database
err := Handle.DestructiveResetTables(Depot{})
if err != nil {
log.Fatalf("%s", err.Error())
}
// Determine the table name in the database
tn := sqac.GetTableName(Depot{}) // "depot"
if tn == "" {
log.Fatalf("Unable to determine table name for struct %v", Depot{})
}
// Check for index "idx_depot_region_county" on table "depot"
ok = Handle.ExistsIndex(tn, "idx_depot_region_county")
if ok {
log.Printf("Index idx_depot_region_county exists in the db")
} else {
log.Errorf("expected idx_depot_region_county to exist in the db")
}
// Check for non-existent index "idx_depot_province_region" on table "depot"
ok = Handle.ExistsIndex(tn, "idx_depot_province_region")
if ok {
log.Errorf("did not expect index idx_depot_province_region to exist in the db")
} else {
log.Printf("Correctly determined that idx_depot_province_region does not exist in the db")
}
Handle.Close()
}