Skip to content

Instantly share code, notes, and snippets.

@mightyguava
Last active January 24, 2020 17:08
Show Gist options
  • Save mightyguava/f2b7b0c3d1385df8eac509cc93f8d4f2 to your computer and use it in GitHub Desktop.
Save mightyguava/f2b7b0c3d1385df8eac509cc93f8d4f2 to your computer and use it in GitHub Desktop.
Example of sqlc generated code for the authors example
package com.example.testmodule
import java.sql.Connection
import java.sql.SQLException
data class Author(val id: Long, val name: String, val bio: String?);
const val createAuthor = """-- name: CreateAuthor :one
INSERT INTO authors (
name, bio
) VALUES (
\$1, \$2
)
RETURNING id, name, bio
"""
data class CreateAuthorParams(val id: Long, val name: String, val bio: String?)
const val deleteAuthor = """-- name: DeleteAuthor :exec
DELETE FROM authors
WHERE id = \$1
"""
const val getAuthor = """-- name: GetAuthor :one
SELECT id, name, bio FROM authors
WHERE id = \$1 LIMIT 1
"""
const val listAuthors = """-- name: ListAuthors :many
SELECT id, name, bio FROM authors
ORDER BY name"""
class Queries(private val conn: Connection) {
@Throws(SQLException::class)
fun createAuthor(arg: CreateAuthorParams): Author {
val stmt = conn.prepareStatement(createAuthor)
stmt.setString(1, arg.name)
stmt.setString(2, arg.bio)
val rs = stmt.executeQuery()
if (!rs.next()) {
throw SQLException("no rows in result set")
}
val author = Author(rs.getLong(1), rs.getString(2), rs.getString(3))
if (rs.next()) {
throw SQLException("expected one row in result set, but got many")
}
return author
}
@Throws(SQLException::class)
fun deleteAuthor(id: Long) {
val stmt = conn.prepareStatement(deleteAuthor)
stmt.setLong(1, id)
stmt.execute()
}
@Throws(SQLException::class)
fun getAuthor(id: Long): Author {
val stmt = conn.prepareStatement(getAuthor)
stmt.setLong(1, id)
val rs = stmt.executeQuery()
if (!rs.next()) {
throw SQLException("no rows in result set")
}
val author = Author(rs.getLong(1), rs.getString(2), rs.getString(3))
if (rs.next()) {
throw SQLException("expected one row in result set, but got many")
}
return author
}
@Throws(SQLException::class)
fun listAuthors(id: Long): List<Author> {
val stmt = conn.prepareStatement(listAuthors)
val rs = stmt.executeQuery()
val authors = mutableListOf<Author>()
while (rs.next()) {
authors.add(Author(rs.getLong(1), rs.getString(2), rs.getString(3)))
}
return authors
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment