abstract_sql_store.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. package abstract_sql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "github.com/chrislusf/seaweedfs/weed/filer"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. "strings"
  11. "sync"
  12. )
  13. type SqlGenerator interface {
  14. GetSqlInsert(tableName string) string
  15. GetSqlUpdate(tableName string) string
  16. GetSqlFind(tableName string) string
  17. GetSqlDelete(tableName string) string
  18. GetSqlDeleteFolderChildren(tableName string) string
  19. GetSqlListExclusive(tableName string) string
  20. GetSqlListInclusive(tableName string) string
  21. GetSqlCreateTable(tableName string) string
  22. GetSqlDropTable(tableName string) string
  23. }
  24. type AbstractSqlStore struct {
  25. SqlGenerator
  26. DB *sql.DB
  27. SupportBucketTable bool
  28. dbs map[string]bool
  29. dbsLock sync.Mutex
  30. }
  31. func (store *AbstractSqlStore) CanDropWholeBucket() bool {
  32. return store.SupportBucketTable
  33. }
  34. func (store *AbstractSqlStore) OnBucketCreation(bucket string) {
  35. store.dbsLock.Lock()
  36. defer store.dbsLock.Unlock()
  37. store.CreateTable(context.Background(), bucket)
  38. if store.dbs == nil {
  39. return
  40. }
  41. store.dbs[bucket] = true
  42. }
  43. func (store *AbstractSqlStore) OnBucketDeletion(bucket string) {
  44. store.dbsLock.Lock()
  45. defer store.dbsLock.Unlock()
  46. store.deleteTable(context.Background(), bucket)
  47. if store.dbs == nil {
  48. return
  49. }
  50. delete(store.dbs, bucket)
  51. }
  52. const (
  53. DEFAULT_TABLE = "filemeta"
  54. )
  55. type TxOrDB interface {
  56. ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
  57. QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
  58. QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
  59. }
  60. func (store *AbstractSqlStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  61. tx, err := store.DB.BeginTx(ctx, &sql.TxOptions{
  62. Isolation: sql.LevelReadCommitted,
  63. ReadOnly: false,
  64. })
  65. if err != nil {
  66. return ctx, err
  67. }
  68. return context.WithValue(ctx, "tx", tx), nil
  69. }
  70. func (store *AbstractSqlStore) CommitTransaction(ctx context.Context) error {
  71. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  72. return tx.Commit()
  73. }
  74. return nil
  75. }
  76. func (store *AbstractSqlStore) RollbackTransaction(ctx context.Context) error {
  77. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  78. return tx.Rollback()
  79. }
  80. return nil
  81. }
  82. func (store *AbstractSqlStore) getTxOrDB(ctx context.Context, fullpath util.FullPath, isForChildren bool) (txOrDB TxOrDB, bucket string, shortPath util.FullPath, err error) {
  83. shortPath = fullpath
  84. bucket = DEFAULT_TABLE
  85. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  86. txOrDB = tx
  87. } else {
  88. txOrDB = store.DB
  89. }
  90. if !store.SupportBucketTable {
  91. return
  92. }
  93. if !strings.HasPrefix(string(fullpath), "/buckets/") {
  94. return
  95. }
  96. // detect bucket
  97. bucketAndObjectKey := string(fullpath)[len("/buckets/"):]
  98. t := strings.Index(bucketAndObjectKey, "/")
  99. if t < 0 && !isForChildren {
  100. return
  101. }
  102. bucket = bucketAndObjectKey
  103. shortPath = "/"
  104. if t > 0 {
  105. bucket = bucketAndObjectKey[:t]
  106. shortPath = util.FullPath(bucketAndObjectKey[t:])
  107. }
  108. if isValidBucket(bucket) {
  109. store.dbsLock.Lock()
  110. defer store.dbsLock.Unlock()
  111. if store.dbs == nil {
  112. store.dbs = make(map[string]bool)
  113. }
  114. if _, found := store.dbs[bucket]; !found {
  115. if err = store.CreateTable(ctx, bucket); err == nil {
  116. store.dbs[bucket] = true
  117. }
  118. }
  119. }
  120. return
  121. }
  122. func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  123. db, bucket, shortPath, err := store.getTxOrDB(ctx, entry.FullPath, false)
  124. if err != nil {
  125. return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
  126. }
  127. dir, name := shortPath.DirAndName()
  128. meta, err := entry.EncodeAttributesAndChunks()
  129. if err != nil {
  130. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  131. }
  132. if len(entry.Chunks) > 50 {
  133. meta = util.MaybeGzipData(meta)
  134. }
  135. res, err := db.ExecContext(ctx, store.GetSqlInsert(bucket), util.HashStringToLong(dir), name, dir, meta)
  136. if err == nil {
  137. return
  138. }
  139. if !strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  140. // return fmt.Errorf("insert: %s", err)
  141. // skip this since the error can be in a different language
  142. }
  143. // now the insert failed possibly due to duplication constraints
  144. glog.V(1).Infof("insert %s falls back to update: %v", entry.FullPath, err)
  145. res, err = db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
  146. if err != nil {
  147. return fmt.Errorf("upsert %s: %s", entry.FullPath, err)
  148. }
  149. _, err = res.RowsAffected()
  150. if err != nil {
  151. return fmt.Errorf("upsert %s but no rows affected: %s", entry.FullPath, err)
  152. }
  153. return nil
  154. }
  155. func (store *AbstractSqlStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  156. db, bucket, shortPath, err := store.getTxOrDB(ctx, entry.FullPath, false)
  157. if err != nil {
  158. return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
  159. }
  160. dir, name := shortPath.DirAndName()
  161. meta, err := entry.EncodeAttributesAndChunks()
  162. if err != nil {
  163. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  164. }
  165. res, err := db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
  166. if err != nil {
  167. return fmt.Errorf("update %s: %s", entry.FullPath, err)
  168. }
  169. _, err = res.RowsAffected()
  170. if err != nil {
  171. return fmt.Errorf("update %s but no rows affected: %s", entry.FullPath, err)
  172. }
  173. return nil
  174. }
  175. func (store *AbstractSqlStore) FindEntry(ctx context.Context, fullpath util.FullPath) (*filer.Entry, error) {
  176. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, false)
  177. if err != nil {
  178. return nil, fmt.Errorf("findDB %s : %v", fullpath, err)
  179. }
  180. dir, name := shortPath.DirAndName()
  181. row := db.QueryRowContext(ctx, store.GetSqlFind(bucket), util.HashStringToLong(dir), name, dir)
  182. var data []byte
  183. if err := row.Scan(&data); err != nil {
  184. if err == sql.ErrNoRows {
  185. return nil, filer_pb.ErrNotFound
  186. }
  187. return nil, fmt.Errorf("find %s: %v", fullpath, err)
  188. }
  189. entry := &filer.Entry{
  190. FullPath: fullpath,
  191. }
  192. if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  193. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  194. }
  195. return entry, nil
  196. }
  197. func (store *AbstractSqlStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  198. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, false)
  199. if err != nil {
  200. return fmt.Errorf("findDB %s : %v", fullpath, err)
  201. }
  202. dir, name := shortPath.DirAndName()
  203. res, err := db.ExecContext(ctx, store.GetSqlDelete(bucket), util.HashStringToLong(dir), name, dir)
  204. if err != nil {
  205. return fmt.Errorf("delete %s: %s", fullpath, err)
  206. }
  207. _, err = res.RowsAffected()
  208. if err != nil {
  209. return fmt.Errorf("delete %s but no rows affected: %s", fullpath, err)
  210. }
  211. return nil
  212. }
  213. func (store *AbstractSqlStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  214. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, true)
  215. if err != nil {
  216. return fmt.Errorf("findDB %s : %v", fullpath, err)
  217. }
  218. if isValidBucket(bucket) && shortPath == "/" {
  219. if err = store.deleteTable(ctx, bucket); err == nil {
  220. store.dbsLock.Lock()
  221. delete(store.dbs, bucket)
  222. store.dbsLock.Unlock()
  223. return nil
  224. } else {
  225. return err
  226. }
  227. }
  228. glog.V(4).Infof("delete %s SQL %s %d", string(shortPath), store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)))
  229. res, err := db.ExecContext(ctx, store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)), string(shortPath))
  230. if err != nil {
  231. return fmt.Errorf("deleteFolderChildren %s: %s", fullpath, err)
  232. }
  233. _, err = res.RowsAffected()
  234. if err != nil {
  235. return fmt.Errorf("deleteFolderChildren %s but no rows affected: %s", fullpath, err)
  236. }
  237. return nil
  238. }
  239. func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  240. db, bucket, shortPath, err := store.getTxOrDB(ctx, dirPath, true)
  241. if err != nil {
  242. return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
  243. }
  244. sqlText := store.GetSqlListExclusive(bucket)
  245. if includeStartFile {
  246. sqlText = store.GetSqlListInclusive(bucket)
  247. }
  248. rows, err := db.QueryContext(ctx, sqlText, util.HashStringToLong(string(shortPath)), startFileName, string(shortPath), prefix+"%", limit+1)
  249. if err != nil {
  250. return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
  251. }
  252. defer rows.Close()
  253. for rows.Next() {
  254. var name string
  255. var data []byte
  256. if err = rows.Scan(&name, &data); err != nil {
  257. glog.V(0).Infof("scan %s : %v", dirPath, err)
  258. return lastFileName, fmt.Errorf("scan %s: %v", dirPath, err)
  259. }
  260. lastFileName = name
  261. entry := &filer.Entry{
  262. FullPath: util.NewFullPath(string(dirPath), name),
  263. }
  264. if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  265. glog.V(0).Infof("scan decode %s : %v", entry.FullPath, err)
  266. return lastFileName, fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
  267. }
  268. if !eachEntryFunc(entry) {
  269. break
  270. }
  271. }
  272. return lastFileName, nil
  273. }
  274. func (store *AbstractSqlStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  275. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", nil)
  276. }
  277. func (store *AbstractSqlStore) Shutdown() {
  278. store.DB.Close()
  279. }
  280. func isValidBucket(bucket string) bool {
  281. return bucket != DEFAULT_TABLE && bucket != ""
  282. }
  283. func (store *AbstractSqlStore) CreateTable(ctx context.Context, bucket string) error {
  284. if !store.SupportBucketTable {
  285. return nil
  286. }
  287. _, err := store.DB.ExecContext(ctx, store.SqlGenerator.GetSqlCreateTable(bucket))
  288. return err
  289. }
  290. func (store *AbstractSqlStore) deleteTable(ctx context.Context, bucket string) error {
  291. if !store.SupportBucketTable {
  292. return nil
  293. }
  294. _, err := store.DB.ExecContext(ctx, store.SqlGenerator.GetSqlDropTable(bucket))
  295. return err
  296. }