ExistsTable

The ExistsTable method is used to check whether a table exists in the target database. ExistsTable accepts a single string argument containing the name of the table to be checked in the database. If the table is found, a ‘true’ value will be returned to the caller.

ExistsTable differs from the other *Tables methods in that it does not require the table’s go struct declaration to determine the table name. A string value is used, as this is the only information the method requires to carry out its task, and it is quite likely that the caller already knows the string name before the call is made.

The database name of a table related to a go struct containing ‘db:'/‘sqac:’ tags may be determined via package function sqac.GetTableName.

Errors encountered during the ExistsTable method are returned to the caller immediately as a ‘false’ response.

ExistsTable Example

The following structure ‘Depot’ has been used to create table “depot” in the target database. We will change the type of the Region field to an integer value, thereby necessitating a drop and recreation of the table in the database.

A complete sample program to perform the destructive reset of existing table “depot” is shown below:

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
  )

  //   Original Depot declaration - left for illustrative purposes
  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"`
    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()

  // Determine the table name in the database (optional)
  tn := sqac.GetTableName(Depot{})
  if tn == "" {
    log.Fatalf("Unable to determine table name for struct %v", Depot{})
  }

  if Handle.TableExists(tn) {
      log.Printf("Table %s exists in the database.\n", tn )
  } else {
      log.Printf("Table %s was not found in the database.\n", tn )
  }
}