Skip to content

Commit

Permalink
Formatted files
Browse files Browse the repository at this point in the history
  • Loading branch information
reynaldjoabet committed Jun 14, 2024
1 parent a0edbb7 commit eef7ecf
Show file tree
Hide file tree
Showing 20 changed files with 587 additions and 478 deletions.
108 changes: 92 additions & 16 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
@@ -1,21 +1,97 @@
version = "3.7.14"
#runner.dialect = scala213
version = "3.8.0"

# Scala 2 with -Xsource:3 compiler option
runner.dialect = scala213source3
maxColumn = 120
align.arrowEnumeratorGenerator = true
docstrings.style = Asterisk
docstrings.wrap = false
includeCurlyBraceInSelectChains = false
danglingParentheses.preset = true
#newlines.topLevelStatements = [before,after]
newlines.beforeCurlyLambdaParams = multilineWithCaseOnly
newlines.afterCurlyLambdaParams = never
newlines.avoidForSimpleOverflow = [tooLong, punct]
continuationIndent.callSite = 2
optIn.annotationNewlines = true
includeNoParensInSelectChains = true

# Number of maximum characters in a column
maxColumn = 100

# Indentation used historically in the project
indent.defnSite = 2

# Ensure breaks on each select (.method1.method2...) unless all fit on a single line
newlines.selectChains = unfold

# Ensure newlines are added around top level body definitions when there are more than one statement
newlines.topLevelBodyIfMinStatements = [before,after]
newlines.topLevelBodyMinStatements = 2

# Allow line-overflow for comments and lines that would overflow even with a newline.
newlines.avoidForSimpleOverflow=[slc, tooLong]

# Ensure newlines around every statement except `case object` definitions
newlines.topLevelStatementBlankLines = [
{
blanks = 1,
minBreaks = 1,
regex = "^(?!((Term\\.Apply)|(Defn\\.Object)))"
}
]

# Ensure lines starting with the margin character `|` are indented differently
assumeStandardLibraryStripMargin = true
rewrite.rules = [SortModifiers]

# Align everything that can be aligned
align.preset = most
align.multiline = false
align.tokens."+" = [
{
code = ":=", owner = "Term.ApplyInfix"
},
{
code = "+=", owner = "Term.ApplyInfix"
},
{
code = "++=", owner = "Term.ApplyInfix"
},
{
code = "--=", owner = "Term.ApplyInfix"
},
{
code = "-=", owner = "Term.ApplyInfix"
}
]

# Use ScalaDoc style and enable wrapping when reaching `maxColumn`
docstrings.style = "SpaceAsterisk"
docstrings.wrap = yes
docstrings.blankFirstLine = yes
docstrings.oneline = unfold

rewrite.rules = [
AvoidInfix, # Avoid infix calls (except for operators)
RedundantBraces,
RedundantParens, # Ensure redundant parentheses are removed
SortModifiers, # Ensure modifiers like `implicit` or `final` are sorted the same
PreferCurlyFors, # Replaces parentheses into curly braces in for comprehensions that contain multiple enumerator generators
Imports
]

# Ensure redundant braces are removed
rewrite.redundantBraces.maxLines = 1
rewrite.redundantBraces.stringInterpolation = true

# Ensure consistent ordering for imports
rewrite.imports.sort = original
rewrite.imports.groups = [
["java\\..*"],
["scala\\..*"],
["cats\\..*", "fs2\\..*"]
]

# Avoid ASCII tokens
rewriteTokens = {
"⇒": "=>"
"→": "->"
"←": "<-"
}

# Select followed by curly braces should not start a chain
includeCurlyBraceInSelectChains = false

# Ensure code blocks inside markdown files get formatted too
project.includePaths = ["glob:**.scala", "glob:**.sbt", "glob:**.sc", "glob:**.md"]
project.excludePaths = ["glob:**metals.sbt"]
fileOverride {
"glob:**/scala3-examples/src/main/scala/**" {
runner.dialect = scala3
Expand Down
29 changes: 13 additions & 16 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,28 @@ version := "1.0"

val skunk = "org.tpolecat" %% "skunk-core" % "0.6.2"

lazy val `scala2-examples` = (project in file("scala2-examples"))
.settings(
scalaVersion := "2.13.12",
libraryDependencies ++= Seq(skunk)
)

lazy val `scala3-examples` = (project in file("scala3-examples"))
.settings(
scalaVersion := "3.3.1",
libraryDependencies ++= Seq(skunk),
scalacOptions ++= Seq(
"-no-indent"
)
lazy val `scala2-examples` = (project in file("scala2-examples")).settings(
scalaVersion := "2.13.12",
libraryDependencies ++= Seq(skunk)
)

lazy val `scala3-examples` = (project in file("scala3-examples")).settings(
scalaVersion := "3.3.1",
libraryDependencies ++= Seq(skunk),
scalacOptions ++= Seq(
"-no-indent"
)
)
// by default sbt run runs the program in the same JVM as sbt
//in order to run the program in a different JVM, we add the following
//fork in run := true


scalacOptions +="-target:17"// ensures the Scala compiler generates bytecode optimized for the Java 17 virtual machine
scalacOptions += "-target:17" // ensures the Scala compiler generates bytecode optimized for the Java 17 virtual machine

//We can also set the soruce and target compatibility for the Java compiler by configuring the JavaOptions in build.sbt

// javaOptions ++= Seq(
// "-soruce","17","target","17"
// )

ThisBuild / semanticdbEnabled := true
ThisBuild / semanticdbEnabled := true
42 changes: 23 additions & 19 deletions scala2-examples/src/main/scala/CommandExample.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import cats.Monad
import cats.effect._
import cats.syntax.all._
import cats.Monad

import natchez.Trace.Implicits.noop
import skunk._
import skunk.codec.all._
Expand All @@ -11,19 +12,19 @@ case class Pet(name: String, age: Short)

// a service interface
trait PetService[F[_]] {

def insert(pet: Pet): F[Unit]
def insert(ps: List[Pet]): F[Unit]
def selectAll: F[List[Pet]]

}

// a companion with a constructor
object PetService {

// command to insert a pet
private val insertOne: Command[Pet] =
sql"INSERT INTO pets VALUES ($varchar, $int2)"
.command
.to[Pet]
sql"INSERT INTO pets VALUES ($varchar, $int2)".command.to[Pet]

// command to insert a specific list of pets
private def insertMany(ps: List[Pet]): Command[ps.type] = {
Expand All @@ -33,16 +34,16 @@ object PetService {

// query to select all pets
private val all: Query[Void, Pet] =
sql"SELECT name, age FROM pets"
.query(varchar *: int2)
.to[Pet]
sql"SELECT name, age FROM pets".query(varchar *: int2).to[Pet]

// construct a PetService
def fromSession[F[_]: Monad](s: Session[F]): PetService[F] =
new PetService[F] {
def insert(pet: Pet): F[Unit] = s.prepare(insertOne).flatMap(_.execute(pet)).void

def insert(pet: Pet): F[Unit] = s.prepare(insertOne).flatMap(_.execute(pet)).void
def insert(ps: List[Pet]): F[Unit] = s.prepare(insertMany(ps)).flatMap(_.execute(ps)).void
def selectAll: F[List[Pet]] = s.execute(all)
def selectAll: F[List[Pet]] = s.execute(all)

}

}
Expand All @@ -61,23 +62,26 @@ object CommandExample extends IOApp {
// a resource that creates and drops a temporary table
def withPetsTable(s: Session[IO]): Resource[IO, Unit] = {
val alloc = s.execute(sql"CREATE TEMP TABLE pets (name varchar, age int2)".command).void
val free = s.execute(sql"DROP TABLE pets".command).void
val free = s.execute(sql"DROP TABLE pets".command).void
Resource.make(alloc)(_ => free)
}

// some sample data
val bob = Pet("Bob", 12)
val bob = Pet("Bob", 12)
val beagles = List(Pet("John", 2), Pet("George", 3), Pet("Paul", 6), Pet("Ringo", 3))

// our entry point
def run(args: List[String]): IO[ExitCode] =
session.flatTap(withPetsTable).map(PetService.fromSession(_)).use { s =>
for {
_ <- s.insert(bob)
_ <- s.insert(beagles)
ps <- s.selectAll
_ <- ps.traverse(p => IO.println(p))
} yield ExitCode.Success
}
session
.flatTap(withPetsTable)
.map(PetService.fromSession(_))
.use { s =>
for {
_ <- s.insert(bob)
_ <- s.insert(beagles)
ps <- s.selectAll
_ <- ps.traverse(p => IO.println(p))
} yield ExitCode.Success
}

}
21 changes: 11 additions & 10 deletions scala2-examples/src/main/scala/ConnectionPoolSkunk.scala
Original file line number Diff line number Diff line change
@@ -1,18 +1,19 @@
import cats.effect.IO
import cats.effect.kernel.Resource
import cats.effect.IO

import natchez.Trace.Implicits.noop
import skunk.Session

object ConnectionPoolSkunk {

val kunkConnectionPool: Resource[IO, Resource[IO, Session[IO]]] = Session.pooled[IO](
host = "localhost",
port = 5432,
user = "jimmy",
database = "world",
password = Some("banana"),
max = 10,
debug = false
)
val kunkConnectionPool: Resource[IO, Resource[IO, Session[IO]]] = Session.pooled[IO](
host = "localhost",
port = 5432,
user = "jimmy",
database = "world",
password = Some("banana"),
max = 10,
debug = false
)

}
6 changes: 5 additions & 1 deletion scala2-examples/src/main/scala/EntityGateway.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
trait EntityGateway[F[_], TodoId] {

def writeMany(todos: Vector[Todo[TodoId]]): F[Vector[Todo.Existing[TodoId]]]

def readManyById(ids: Vector[TodoId]): F[Vector[Todo.Existing[TodoId]]]

def readManyByPartialDescription(
partialDescription: String
partialDescription: String
): F[Vector[Todo.Existing[TodoId]]]

def readAll: F[Vector[Todo.Existing[TodoId]]]

def deleteMany(todos: Vector[Todo.Existing[TodoId]]): F[Unit]
def deleteAll: F[Unit]

}
20 changes: 11 additions & 9 deletions scala2-examples/src/main/scala/Hello.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import cats.effect._

import natchez.Trace.Implicits.noop // (1) // (1)
import skunk._
import skunk.implicits._
import skunk.codec.all._
import natchez.Trace.Implicits.noop // (1) // (1)
import skunk.implicits._

object Hello extends IOApp {

// Command->SQL and parameter encoder for a statement that returns no rows
val commad: Command[Short *: String *: EmptyTuple] =
sql"INSERT INTO foo VALUES ($int2, $varchar)".command // Command[(Short, String)]
Expand All @@ -21,15 +23,15 @@ object Hello extends IOApp {
//s.execute(a) // IO[List[String]]

/**
* In the above example note that query parameters are specified by interpolated `Encoder`s and
* column types are specified by a `Decoder` passed to `.query`. The `~` syntax constructs
* left-associated HLists of types and values via nested pairs. These are all described in more
* detail a bit further down.
* Commands are constructed in a similar way but have no output columns and thus no `Decoder` is
* needed.
*/
* In the above example note that query parameters are specified by interpolated `Encoder`s and
* column types are specified by a `Decoder` passed to `.query`. The `~` syntax constructs
* left-associated HLists of types and values via nested pairs. These are all described in more
* detail a bit further down. Commands are constructed in a similar way but have no output
* columns and thus no `Decoder` is needed.
*/

val c = sql"""UPDATE employee SET salary = salary * 1.05 WHERE id = $int8""".command // Command[Long]

val session: Resource[IO, Session[IO]] =
Session.single( // (2)
host = "localhost",
Expand Down
Loading

0 comments on commit eef7ecf

Please sign in to comment.