@@ -139,20 +139,25 @@ type connector struct {
139139 connInitFunc ConnInitFunc
140140}
141141
142+ func errWithMsg (db sqliteh.DB , err error , loc string ) error {
143+ if ec , ok := err .(sqliteh.ErrCode ); ok {
144+ e := & Error {
145+ Code : sqliteh .Code (ec ),
146+ Loc : loc ,
147+ }
148+ if db != nil {
149+ e .Msg = db .ErrMsg ()
150+ }
151+ return e
152+ }
153+ return err
154+ }
155+
142156func (p * connector ) Driver () driver.Driver { return drv {} }
143157func (p * connector ) Connect (ctx context.Context ) (driver.Conn , error ) {
144158 db , err := Open (p .name , sqliteh .OpenFlagsDefault , "" )
145159 if err != nil {
146- if ec , ok := err .(sqliteh.ErrCode ); ok {
147- e := & Error {
148- Code : sqliteh .Code (ec ),
149- Loc : "Open" ,
150- }
151- if db != nil {
152- e .Msg = db .ErrMsg ()
153- }
154- err = e
155- }
160+ err = errWithMsg (db , err , "Open" )
156161 if db != nil {
157162 db .Close ()
158163 }
@@ -781,3 +786,35 @@ func WithPersist(ctx context.Context) context.Context {
781786
782787// persistQuery is used as a context value.
783788type persistQuery struct {}
789+
790+ // DB executes fn with the sqliteh.DB underlying sqlconn.
791+ func DB (sqlconn SQLConn , fn func (sqliteh.DB ) error ) error {
792+ return sqlconn .Raw (func (driverConn interface {}) error {
793+ c , ok := driverConn .(* conn )
794+ if ! ok {
795+ return fmt .Errorf ("sqlite.Checkpoint: sql.Conn is not the sqlite driver: %T" , driverConn )
796+ }
797+ return fn (c .db )
798+ })
799+ }
800+
801+ // Backup backups the specified database from srcConn to dstConn.
802+ func Backup (dstConn SQLConn , dstSchema string , srcConn SQLConn , srcSchema string ) error {
803+ return DB (dstConn , func (dst sqliteh.DB ) error {
804+ return DB (srcConn , func (src sqliteh.DB ) error {
805+ b , err := dst .BackupInit (dstSchema , src , srcSchema )
806+ if err != nil {
807+ return errWithMsg (dst , err , "Backup" )
808+ }
809+ more := true
810+ for more {
811+ more , err = b .Step (1024 )
812+ if err != nil {
813+ b .Finish ()
814+ return errWithMsg (dst , err , "Step" )
815+ }
816+ }
817+ return errWithMsg (dst , b .Finish (), "Finish" )
818+ })
819+ })
820+ }
0 commit comments