diff --git a/cmd/main.go b/cmd/main.go new file mode 100644 index 0000000..9864979 --- /dev/null +++ b/cmd/main.go @@ -0,0 +1,73 @@ +package main + +import ( + "database/sql" + "fmt" + + "github.com/winebarrel/dbtyp" + _ "modernc.org/sqlite" +) + +type AliceDB struct{} +type BobDB struct{} + +type MyDB interface { + AliceDB | BobDB +} + +func main() { + aliceDB := openDB[AliceDB]() + bobDB := openDB[BobDB]() + + // bob = alice // COMPILE ERROR! + + createTable(aliceDB, "foo") + createTable(bobDB, "bar") + + procForAlice(aliceDB.ExecQueryer()) + // procForAlice(bob.ExecQueryer()) // COMPILE ERROR! + + procForBob(bobDB.Queryer()) + // procForBob(alice.Queryer()) // COMPILE ERROR! +} + +func openDB[T MyDB]() *dbtyp.DB[T] { + db, err := dbtyp.New2[T](sql.Open("sqlite", "file::memory:")) + + if err != nil { + panic(err) + } + + return db +} + +func createTable[T MyDB](db *dbtyp.DB[T], name string) { + _, err := db.Exec("create table " + name + " (id int)") + + if err != nil { + panic(err) + } +} + +func procForAlice(eq *dbtyp.ExecQueryer[AliceDB]) { + _, err := eq.Exec("insert into foo values (1)") + if err != nil { + panic(err) + } + + var n int + err = eq.QueryRow("select count(*) from foo").Scan(&n) + if err != nil { + panic(err) + } + fmt.Println("foo rows count:", n) +} + +func procForBob(q *dbtyp.Queryer[BobDB]) { + var n int + err := q.QueryRow("select count(*) from bar").Scan(&n) + if err != nil { + panic(err) + } + fmt.Println("bar rows count:", n) +} diff --git a/db.go b/db.go index 9d8db20..37fc665 100644 --- a/db.go +++ b/db.go @@ -7,10 +7,8 @@ import ( "github.com/winebarrel/dbtyp/iface" ) -var _ iface.DB = &DB[struct{}]{} - type DB[T any] struct { - *sql.DB + iface.DB } // Type converter diff --git a/stmt.go b/stmt.go index eefc4ef..f53205e 100644 --- a/stmt.go +++ b/stmt.go @@ -1,13 +1,9 @@ package dbtyp import ( - "database/sql" - "github.com/winebarrel/dbtyp/iface" ) -var _ iface.Stmt = &Stmt[struct{}]{} - type Stmt[T any] struct { - *sql.Stmt + iface.Stmt } diff --git a/tx.go b/tx.go index c68bf84..4e9a433 100644 --- a/tx.go +++ b/tx.go @@ -2,15 +2,12 @@ package dbtyp import ( "context" - "database/sql" "github.com/winebarrel/dbtyp/iface" ) -var _ iface.Tx = &Tx[struct{}]{} - type Tx[T any] struct { - *sql.Tx + iface.Tx } // Type converter