2021-05-10 15:37:34 +00:00
package main
import (
2022-02-23 09:23:26 +00:00
"context"
2021-05-10 15:37:34 +00:00
"database/sql"
2022-01-24 08:43:06 +00:00
"errors"
2021-05-10 15:37:34 +00:00
)
2021-06-06 12:39:42 +00:00
func ( db * database ) cachePersistently ( key string , data [ ] byte ) error {
2022-02-23 09:23:26 +00:00
return db . cachePersistentlyContext ( context . Background ( ) , key , data )
}
func ( db * database ) cachePersistentlyContext ( ctx context . Context , key string , data [ ] byte ) error {
2022-02-12 11:37:13 +00:00
if db == nil {
return errors . New ( "database is nil" )
}
2022-08-09 15:25:22 +00:00
_ , err := db . ExecContext ( ctx , "insert or replace into persistent_cache(key, data, date) values(@key, @data, @date)" , sql . Named ( "key" , key ) , sql . Named ( "data" , data ) , sql . Named ( "date" , utcNowString ( ) ) )
2021-05-10 15:37:34 +00:00
return err
}
2021-06-06 12:39:42 +00:00
func ( db * database ) retrievePersistentCache ( key string ) ( data [ ] byte , err error ) {
2022-02-23 09:23:26 +00:00
return db . retrievePersistentCacheContext ( context . Background ( ) , key )
}
func ( db * database ) retrievePersistentCacheContext ( c context . Context , key string ) ( data [ ] byte , err error ) {
2022-02-12 11:37:13 +00:00
if db == nil {
return nil , errors . New ( "database is nil" )
}
2022-03-16 07:28:03 +00:00
d , err , _ := db . pc . Do ( key , func ( ) ( any , error ) {
2022-08-09 15:25:22 +00:00
if row , err := db . QueryRowContext ( c , "select data from persistent_cache where key = @key" , sql . Named ( "key" , key ) ) ; err != nil {
2021-05-26 15:41:14 +00:00
return nil , err
} else {
err = row . Scan ( & data )
2022-01-24 08:43:06 +00:00
if errors . Is ( err , sql . ErrNoRows ) {
return nil , nil
}
2021-05-26 15:41:14 +00:00
return data , err
}
} )
if err != nil {
2021-05-10 15:37:34 +00:00
return nil , err
}
2022-01-24 08:43:06 +00:00
if d == nil {
return nil , nil
}
2021-05-26 15:41:14 +00:00
return d . ( [ ] byte ) , nil
2021-05-10 15:37:34 +00:00
}
2021-06-06 12:39:42 +00:00
func ( db * database ) clearPersistentCache ( pattern string ) error {
2022-02-23 09:23:26 +00:00
return db . clearPersistentCacheContext ( context . Background ( ) , pattern )
}
func ( db * database ) clearPersistentCacheContext ( c context . Context , pattern string ) error {
2022-08-09 15:25:22 +00:00
_ , err := db . ExecContext ( c , "delete from persistent_cache where key like @pattern" , sql . Named ( "pattern" , pattern ) )
2021-05-10 15:37:34 +00:00
return err
}