/
QueriesImpl.kt
100 lines (82 loc) · 2.24 KB
/
QueriesImpl.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.13.0
package com.example.authors.mysql
import java.sql.Connection
import java.sql.SQLException
import java.sql.Statement
const val createAuthor = """-- name: createAuthor :execresult
INSERT INTO authors (
name, bio
) VALUES (
?, ?
)
"""
const val deleteAuthor = """-- name: deleteAuthor :exec
DELETE FROM authors
WHERE id = ?
"""
const val getAuthor = """-- name: getAuthor :one
SELECT id, name, bio FROM authors
WHERE id = ? LIMIT 1
"""
const val listAuthors = """-- name: listAuthors :many
SELECT id, name, bio FROM authors
ORDER BY name
"""
class QueriesImpl(private val conn: Connection) : Queries {
@Throws(SQLException::class)
override fun createAuthor(name: String, bio: String?): Long {
return conn.prepareStatement(createAuthor, Statement.RETURN_GENERATED_KEYS).use { stmt ->
stmt.setString(1, name)
stmt.setString(2, bio)
stmt.execute()
val results = stmt.generatedKeys
if (!results.next()) {
throw SQLException("no generated key returned")
}
results.getLong(1)
}
}
@Throws(SQLException::class)
override fun deleteAuthor(id: Long) {
conn.prepareStatement(deleteAuthor).use { stmt ->
stmt.setLong(1, id)
stmt.execute()
}
}
@Throws(SQLException::class)
override fun getAuthor(id: Long): Author? {
return conn.prepareStatement(getAuthor).use { stmt ->
stmt.setLong(1, id)
val results = stmt.executeQuery()
if (!results.next()) {
return null
}
val ret = Author(
results.getLong(1),
results.getString(2),
results.getString(3)
)
if (results.next()) {
throw SQLException("expected one row in result set, but got many")
}
ret
}
}
@Throws(SQLException::class)
override fun listAuthors(): List<Author> {
return conn.prepareStatement(listAuthors).use { stmt ->
val results = stmt.executeQuery()
val ret = mutableListOf<Author>()
while (results.next()) {
ret.add(Author(
results.getLong(1),
results.getString(2),
results.getString(3)
))
}
ret
}
}
}