Skip to content

Instantly share code, notes, and snippets.

@TomLous
Last active December 19, 2017 08:58
Show Gist options
  • Save TomLous/a72b75d6999e8b7670c98909a3059024 to your computer and use it in GitHub Desktop.
Save TomLous/a72b75d6999e8b7670c98909a3059024 to your computer and use it in GitHub Desktop.
Doobie list traverse and update within 1 transaction
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)
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