Last active
December 19, 2017 08:58
-
-
Save TomLous/a72b75d6999e8b7670c98909a3059024 to your computer and use it in GitHub Desktop.
Doobie list traverse and update within 1 transaction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import doobie.imports._ | |
import fs2.interop.cats._ | |
import cats.implicits._ | |
// Connection to localhost | |
val xa = DriverManagerTransactor[IOLite]("com.mysql.cj.jdbc.Driver", "jdbc:mysql://localhost:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC", "root", "") | |
// Equivalent of table structure | |
case class Item(id: String, name: String, fetced: Boolean) | |
// program | |
val prog = for { | |
// fetch 2 that aren't fetches yet | |
items <- sql"SELECT id, name, fetched FROM item WHERE fetched=0 LIMIT 0,2".query[Item].list | |
// traverse to update these | |
_ <- items.traverse(item => sql"UPDATE item SET fetched=1 WHERE id=${item.id}".update.run) | |
} yield items | |
// res is still original list of items | |
val res = prog.transact(xa).unsafePerformIO | |
res.foreach(println) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DROP TABLE IF EXISTS `item`; | |
CREATE TABLE `item` ( | |
`id` int(11) unsigned NOT NULL AUTO_INCREMENT, | |
`name` varchar(255) NOT NULL, | |
`fetched` tinyint(1) NOT NULL DEFAULT '0', | |
PRIMARY KEY (`id`) | |
) ENGINE=InnoDB DEFAULT CHARSET=latin1; | |
BEGIN; | |
INSERT INTO `item` VALUES ('1', 'Item 1', '1'), ('2', 'Item 2', '1'), ('3', 'Item 3', '0'), ('4', 'Item 4', '0'), ('5', 'Item 5', '0'); | |
COMMIT; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment