jodersky/simplesql
Tentang
A no-frills SQL library for Scala 3
Data dan analisisPertumbuhan bintang terukur
- dalam 24 jam
- 0
- dalam 7 hari
- 0
- dalam 15 hari
- 0
- dalam 1 bulan
- 0
Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.
README.md
AsliSimple SQL
A no-frills SQL library for Scala 3.
SimpleSQL is a very thin wrapper around JDBC, which allows you to take full advantage of full SQL and any database with a JDBC driver.
SimpleSQL is not a functional DSL to build SQL queries, but it does offer safe string interpolation and utilities to work with product types, which are the natural representation of relational data sets.
SimpleSQL has no dependencies. It is published to maven central, under
mvn"io.crashbox:simplesql:0.5.0".
Contents
Example
import simplesql as sq
// wrap any javax.sql.DataSource, this example uses a connection pool
// implemented by HikariCP
val hikari = com.zaxxer.hikari.HikariDataSource()
hikari.setJdbcUrl("jdbc:sqlite::memory:")
val ds = sq.DataSource(hikari)
// all queries must be run within the context of a connection, use either
// `<ds>.run` or `<ds>.transaction` blocks
ds.transaction:
sql"""
create table account (
id integer primary key,
name text not null,
email text not null
)
""".write()
// interpolated values are passed safely, as parameters of a prepared statement
val name = "admin"
sql"insert into account (id, name, email) values (${1}, $name, ${"[email protected]"})".write()
// 1 (the number of affected rows)
// read rows into tuples, by column position...
sql"select id, name, email from account".read[(Int, String, String)]
// List((1, "admin", "[email protected]"))
// ...or into case classes, by column name
case class Account(id: Int, name: String, email: String) derives sq.Reader
sql"select id, name, email from account".read[Account]
// List(Account(1, "admin", "[email protected]"))
// read exactly one row
sql"select name, id from account where id = ${1}".readOne[(String, Int)]
// ("admin", 1)
Explanation
Database connection
All queries must be run on a connection to a database. SimpleSQL models this
through a Connection class, which is just a simple wrapper around
java.sql.Connection.
A connection may be obtained as a context
function
through either <datasource>.run or <datasource>.transaction. Both functions
provide a connection, however the latter will automatically roll back any
changes, should an exception be thrown in its body.
An in-scope connection also gives access to the sql string interpolator. This
interpolator is a utility to build simplesql.Querys, which are builders for
java.sql.PreparedStatements. In other words, it can be used to build
injection-safe queries with interpolated parameters. Interpolated parameters
must be primitve types (supported by JDBC).
Read Queries
Read queries (e.g. selects) must be run in a read call. A read must have its
result type specified. The result type may be any primitive type supported by
JDBC ResultSets or a product thereof (including named products, i.e. case classes).
Fields of case classes are converted to snake_case in the database. You can
change this convention with a custom api (see below), or override it for a single
field by annotating it with simplesql.col("name").
Write Queries
Write queries (e.g. insertions, updates, deletes and table alterations) must be
run in a write call. It returns the number of affected rows.
To get values back from a write, such as generated keys, use a returning clause
(supported by PostgreSQL, SQLite 3.35+ and MariaDB 10.5+) and run the query in a
read call instead, since it produces a result set:
val id = sql"""insert into user (name) values ($name) returning id""".readOne[Int]
Custom configuration
Everything in the simplesql package (DataSource, Connection, Reader,
the readers and writers of column types, etc.) is exported from a default api
object, simplesql.default. Readers and writers are members of an api, so
different apis can support different types and conventions.
To customize the configuration, define your own api object by mixing in the
parts you need, and use it in place of the simplesql package:
object mydb extends simplesql.BaseApi
with simplesql.StandardColReaders
with simplesql.StandardColWriters:
// read case class fields from columns of the same name, instead of snake_case
override def columnName(fieldName: String) = fieldName
// support additional column types
given ColWriter[java.time.LocalDate] = (stat, index, value) => stat.setObject(index, value)
val ds = mydb.DataSource(hikari)
case class User(id: Int, name: String) derives mydb.Reader
Migrations
Simplesql also has an experimental module to manage database migrations, in the
simplesql.migrations package.
Essentially, the module works by looking for .sql files in a folder on the
classpath (typically packaged in your final application jar) and applying them
"in order" to reach a specific version (see below). The module also adds a
special table to your datasource to keep track of which migrations have been
already applied.
Defining a migration
A migration consists of:
- a unique name (its version)
- a reference to the version which precedes it (or "base" if nothing should precede it)
- upgrade sql statements
- optionally, downgrade sql statements
Each migration is made up of two files in the migrations folder:
<version>.up.sql(required), which contains the upgrade statements and declares the previous version in a-- prev:comment:-- prev: <prev version> -- upgrade statements<version>.down.sql(optional), which contains the downgrade statements.
For example, 0000_init.up.sql and 0000_init.down.sql define the migration
with version 0000_init. A subsequent migration would reference it with
-- prev: 0000_init.
A down file without a corresponding up file is an error, as is any other .sql
file in the migrations folder. If a migration has no down file, it cannot be
downgraded: attempting to migrate down past it fails before any statement is
run. Use an empty down file for migrations whose downgrade is a no-op.
See simplesql/test/resources/migrations/ for some example files.
Applying a migration
// reads migrations from the `migrations` folder on the classpath
val mdb = simplesql.migrations(ds)
mdb.applyUp("0001_data") // migrate upwards to explicit version
mdb.applyUp("head") // "head" means the "newest" version, it will fail if there are multiple newest versions
mdb.applyDown("base") // "base" is a special version which means the initial version before any migration was ever applied
simplesql.migrations optionally takes a different folder name (dir), a
logger (log) and a class loader (classLoader). To read migrations from
somewhere other than the classpath, create a MigrationTool with your own
Storage instead, e.g.
MigrationTool(MigrationGraph(InMemoryStorage(migrations)), ds, println).
Note: we recommend only ever downgrading for development purposes. In production, any mistakes should always be corrected with upgrading migrations.
Order of migrations
Each migration must have a pointer to a previous migration file. When applying a migration, the system will first do a topological sort from the target migration, and then apply migrations that are necessary.
Using explicit pointers instead of relying on filename order has a couple of benefits:
- It allows branching during development.
- Since and error will occur if attempting to migrate to the head version when there are multiple heads, it eliminates a source of data corruption if multiple migrations are devloped simultanously and merged together without rebasing them into a linear sequence.
Acknowledgements
The idea of branching in the migration library has been inspired from
Alembic. However, instead of
allowing migration merges, we explicitly require rebases to a linear history.
Also, migration versions correspond 1-1 with file names instead of synthetic
version identifiers that are part of the file names. We believe that this allows
developers to benefit from lexicographically sorted migrations (e.g. by calling
your migrations 0000-init.up.sql, 0001-foo.up.sql, 0002-bar.up.sql etc), but still
prevent accidental non-determinism when developing concurrently with others. It
also makes it easy to write migrations by hand without the need of a separate
too to manage them for us.
Changelog
0.5.0
Breaking changes
- Readers and writers are members of an api object, so that the configuration
can be customized (see "Custom configuration"). The
simplesqlpackage exports the default api,simplesql.default, so common usage is unchanged.SimpleReaderandSimpleWriterare renamed toColReaderandColWriter, and their methods are renamed. - Remove the dependency on HikariCP, and
DataSource.pooledwith it. Wrap anyjavax.sql.DataSourcewithDataSource(...)instead, e.g. aHikariDataSource. readOnethrows anUnexpectedRowCountExceptionunless the query produces exactly one row, andreadOptthrows one if the query produces more than one row. Previously, extra rows were silently ignored.runandtransactionblocks can no longer be nested (it is a compile error). A nested block used a separate connection, which did not see the uncommitted changes of the outer block.- Escape sequences in
sqlstrings are processed like insstrings, e.g.\nis a newline. Previously, they were passed to the database verbatim, so literal backslashes must now be escaped (\\). - Migrations are created with
simplesql.migrations(ds), instead of the more verbosesimplesql.migrations.MigrationTool.fromClasspath(ds).MigrationTool.fromClasspathandMigrationGraph.fromClasspathare removed. - Migrations are split into a
<version>.up.sqland an optional<version>.down.sqlfile, instead of a single file with a-- down:separator. Versions no longer include the.sqlextension. - Require Scala 3.9.0 (the current LTS) and JDK 25.
- Sources are split into one file per class; simplesql is no longer meant to be embedded by copying a single source file.
Non-breaking changes
- The case class column naming convention is configurable with
columnName. - Add a reader for
BigDecimal. ClasspathStorageaccepts a class loader.- Reading SQL NULL into an
Optionof a primitive type (e.g.Option[Int]) givesNoneinstead ofSome(0). - Read and write
InstantasOffsetDateTimein UTC, the JDBC mapping forTIMESTAMP WITH TIME ZONE. Previously,Instantfailed on PostgreSQL. write()no longer requests generated keys, which were never read but caused some drivers (e.g. PostgreSQL) to return all columns of all affected rows. Use areturningclause withreadinstead.- Migration scripts are split into statements on semicolons outside of string literals, quoted identifiers, comments and dollar-quoted strings (e.g. PostgreSQL function bodies). Previously, every semicolon ended a statement.
- Fix listing migrations from a jar when a file system for that jar is already open, e.g. when listing concurrently.
- Upgrade dependencies.
0.4.1
- fix
java.time.Instantrepresentation: delegate it to jdbc - upgrade scala LTS patch version to 3.3.8
- upgrade mill
0.4.0
- Rework migrations module to a graph-based system.
0.3.0
Make
runandtransactionmethods ofDataSourceinstead of top-level functions. Also makereadandwrite()methods on the type returned bysql. This removes an argument list in syntax. E.g. instead ofsq.transaction(ds): sq.read[A](sql"""...""")the syntax is now
ds.transaction: sql"""...""".read[A]Include HikariCP as a dependency for convenience
Separate the reader hierarchy in two:
- primitive "simple" readers read database columns and typically map to primitive database types
- normal readers user tuples of simple readers to read rows and map them to more complex scala types
Readers of case classes use column names instead of positions.
0.2.0
See git history
Jelajahi proyek terkait
Memuat…