Android Room数据库Replace函数使用报错及路径替换需求解决
Hey, let's sort out that Room SQL issue you're dealing with! The "expression expected, got'replace'" error is probably because Room's SQL parser is tripping up on the tight spacing around your replace function parameters, or how it's interpreting the string concatenation. Plus, using replace directly has a hidden risk—it might swap out the old path prefix even if it shows up somewhere in the middle of the path, which isn't what you want for your use case.
The Corrected Query (Precise Prefix Replacement)
Here's a more reliable approach that only replaces the starting prefix of your paths, while fixing the syntax error:
@Query("UPDATE bookmarks SET bookmarks_path = :newPath || SUBSTR(bookmarks_path, LENGTH(:oldPath) + 1) WHERE bookmarks_path LIKE :oldPath || '%'") fun updateBookmarksPath(oldPath: String, newPath: String): Completable
How This Works:
WHERE bookmarks_path LIKE :oldPath || '%'ensures we only target rows where the path starts with your old prefix—exactly the rows you need to update.SUBSTR(bookmarks_path, LENGTH(:oldPath) + 1)snips off the old prefix from the start of the path. For example, ifoldPathis/root(length 5), it starts cutting from position 6, giving us/1/1or/name/1.- We then glue the new prefix (
/stack) to that cut-off section with||, resulting in the correct updated path.
If You Still Want to Use Replace (For Simple, Controlled Cases)
If you're 100% certain your paths will never have the old prefix anywhere except the very start, you can fix the original syntax error by adding spaces around the replace parameters and using uppercase for the function name (Room's parser tends to handle uppercase SQL keywords more smoothly):
@Query("UPDATE bookmarks SET bookmarks_path = REPLACE(bookmarks_path, :oldPath, :newPath) WHERE bookmarks_path LIKE :oldPath || '%'") fun updateBookmarksPath(oldPath: String, newPath: String): Completable
Testing It Out
When you call updateBookmarksPath("/root", "/stack"):
/root/1/1becomes/stack/1/1/root/name/1becomes/stack/name/1
Exactly the outcome you're aiming for!
内容的提问来源于stack exchange,提问作者limengxin

