diff options
| author | Shulhan <ms@kilabit.info> | 2024-08-09 16:34:57 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2024-08-09 16:34:57 +0700 |
| commit | 437d1090ef8b94b8de784eb27f2cf85bcfc1fc6e (patch) | |
| tree | 767182fad89623fd3d719f839297f2ba88486ebc | |
| parent | 473738cfc9b33c18ee749112c7d248f4f626e7fb (diff) | |
| download | pakakeh.go-437d1090ef8b94b8de784eb27f2cf85bcfc1fc6e.tar.xz | |
lib/sql: replace [http.FileSystem] with [memfs.MemFS]
Accepting the [http.FileSystem] means that the parameter can receive an
instance of [embed.FS], but in most cases, it will fail.
Case example, when we embed SQL files for migration under
"db/migration" using the "go:embed" directive,
//go:embed db/migration/*.sql
var DBMigrationFS embed.FS
and then call the [Migrate] function, it will not found any ".sql" files
inside the "/" directory because the files is stored under
"db/migration/" prefix (also there is no "/" when using embed.FS).
| -rw-r--r-- | lib/sql/client.go | 19 |
1 files changed, 13 insertions, 6 deletions
diff --git a/lib/sql/client.go b/lib/sql/client.go index 344ed76b..53e8efc0 100644 --- a/lib/sql/client.go +++ b/lib/sql/client.go @@ -10,13 +10,13 @@ import ( "fmt" "io" "log" - "net/http" "os" "path" "path/filepath" "sort" "strings" + "git.sr.ht/~shulhan/pakakeh.go/lib/memfs" "git.sr.ht/~shulhan/pakakeh.go/lib/reflect" ) @@ -103,14 +103,23 @@ func (cl *Client) FetchTableNames() (tableNames []string, err error) { // If its empty default to "_migration". // The state including the SQL file name that has been executed and the // timestamp. -func (cl *Client) Migrate(tableMigration string, fs http.FileSystem) (err error) { +func (cl *Client) Migrate(tableMigration string, fs *memfs.MemFS) (err error) { logp := "Migrate" if reflect.IsNil(fs) { if len(cl.MigrationDir) == 0 { return nil } - fs = http.Dir(cl.MigrationDir) + var mfsopts = memfs.Options{ + Root: cl.MigrationDir, + Includes: []string{ + `.*\.(sql)$`, + }, + } + fs, err = memfs.New(&mfsopts) + if err != nil { + return fmt.Errorf(`%s: %w`, logp, err) + } } root, err := fs.Open("/") @@ -279,9 +288,7 @@ func (cl *Client) migrateFinished(tx *sql.Tx, tableMigration, file string) (err return nil } -func loadSQL(fs http.FileSystem, fi os.FileInfo, filename string) ( - sqlRaw []byte, err error, -) { +func loadSQL(fs *memfs.MemFS, fi os.FileInfo, filename string) (sqlRaw []byte, err error) { logp := "loadSQL" if strings.ToLower(filepath.Ext(filename)) != sqlExtension { |
