Last active
December 16, 2022 18:44
-
-
Save husobee/cac9cddbaacc1d3a7ae1 to your computer and use it in GitHub Desktop.
scanner valuer example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"database/sql" | |
"database/sql/driver" | |
"errors" | |
"fmt" | |
_ "github.com/mattn/go-sqlite3" | |
) | |
type YesNoEnum bool | |
func (yne YesNoEnum) Value() (driver.Value, error) { | |
return bool(yne), nil | |
} | |
func (yne *YesNoEnum) Scan(value interface{}) error { | |
// if value is nil, false | |
if value == nil { | |
// set the value of the pointer yne to YesNoEnum(false) | |
*yne = YesNoEnum(false) | |
return nil | |
} | |
if bv, err := driver.Bool.ConvertValue(value); err == nil { | |
// if this is a bool type | |
if v, ok := bv.(bool); ok { | |
// set the value of the pointer yne to YesNoEnum(v) | |
*yne = YesNoEnum(v) | |
return nil | |
} | |
} | |
// otherwise, return an error | |
return errors.New("failed to scan YesNoEnum") | |
} | |
const ( | |
Yes YesNoEnum = true | |
No = false | |
) | |
type Customer struct { | |
CustomerID int64 | |
Active YesNoEnum | |
} | |
func main() { | |
// open a database | |
db, err := sql.Open("sqlite3", "./my.db") | |
if err != nil { | |
// fail! | |
fmt.Println(err.Error()) | |
fmt.Println("ouch, database open failed") | |
return | |
} | |
// close the database at the end of the function | |
defer db.Close() | |
//new Customer | |
c := &Customer{ | |
CustomerID: 1, | |
Active: Yes, | |
} | |
// insert customer! | |
_, err = db.Exec( | |
"insert into customer (id, active) values (?, ?);", | |
c.CustomerID, c.Active, | |
) | |
if err != nil { | |
// fail! | |
fmt.Println(err.Error()) | |
fmt.Println("I am sorry, your insert failed...better luck next time!") | |
return | |
} | |
// get the customer record | |
rows, err := db.Query("select id, active from customer") | |
if err != nil { | |
fmt.Println(err.Error()) | |
fmt.Println("I am sorry, your query failed...better luck next time!") | |
return | |
} | |
// close the rows at the end of the function | |
defer rows.Close() | |
for rows.Next() { | |
foundCustomer := new(Customer) | |
if err := rows.Scan( | |
&foundCustomer.CustomerID, &foundCustomer.Active, | |
); err != nil { | |
fmt.Println(err.Error()) | |
fmt.Println("I am sorry, your scanning failed...better luck next time!") | |
return | |
} | |
// time to print our customers!! | |
fmt.Println(foundCustomer) | |
} | |
if err := rows.Err(); err != nil { | |
fmt.Println(err.Error()) | |
fmt.Println("I am sorry, your rows failed...better luck next time!") | |
return | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks! This helped me write https://github.com/blaskovicz/go-cryptkeeper