|
1 | 1 | package sqlite3 |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "encoding/json" |
4 | 5 | "math" |
| 6 | + "strconv" |
5 | 7 | "time" |
6 | 8 |
|
7 | 9 | "github.com/ncruces/go-sqlite3/internal/util" |
@@ -248,6 +250,23 @@ func (s *Stmt) bindRFC3339Nano(param int, value time.Time) error { |
248 | 250 | return s.c.error(r) |
249 | 251 | } |
250 | 252 |
|
| 253 | +// BindJSON binds the JSON encoding of value to the prepared statement. |
| 254 | +// The leftmost SQL parameter has an index of 1. |
| 255 | +// |
| 256 | +// https://www.sqlite.org/c3ref/bind_blob.html |
| 257 | +func (s *Stmt) BindJSON(param int, value any) error { |
| 258 | + data, err := json.Marshal(value) |
| 259 | + if err != nil { |
| 260 | + return err |
| 261 | + } |
| 262 | + ptr := s.c.newBytes(data) |
| 263 | + r := s.c.call(s.c.api.bindText, |
| 264 | + uint64(s.handle), uint64(param), |
| 265 | + uint64(ptr), uint64(len(data)), |
| 266 | + uint64(s.c.api.destructor)) |
| 267 | + return s.c.error(r) |
| 268 | +} |
| 269 | + |
251 | 270 | // ColumnCount returns the number of columns in a result set. |
252 | 271 | // |
253 | 272 | // https://www.sqlite.org/c3ref/column_count.html |
@@ -402,6 +421,28 @@ func (s *Stmt) columnRawBytes(col int, ptr uint32) []byte { |
402 | 421 | return util.View(s.c.mod, ptr, r) |
403 | 422 | } |
404 | 423 |
|
| 424 | +// ColumnJSON parses the JSON-encoded value of the result column |
| 425 | +// and stores it in the value pointed to by ptr. |
| 426 | +// The leftmost column of the result set has the index 0. |
| 427 | +// |
| 428 | +// https://www.sqlite.org/c3ref/column_blob.html |
| 429 | +func (s *Stmt) ColumnJSON(col int, ptr any) error { |
| 430 | + var data []byte |
| 431 | + switch s.ColumnType(col) { |
| 432 | + case NULL: |
| 433 | + data = []byte("null") |
| 434 | + case TEXT, BLOB: |
| 435 | + data = s.ColumnRawBlob(col) |
| 436 | + case INTEGER: |
| 437 | + data = strconv.AppendInt(nil, s.ColumnInt64(col), 10) |
| 438 | + case FLOAT: |
| 439 | + data = strconv.AppendFloat(nil, s.ColumnFloat(col), 'g', -1, 64) |
| 440 | + default: |
| 441 | + panic(util.AssertErr()) |
| 442 | + } |
| 443 | + return json.Unmarshal(data, ptr) |
| 444 | +} |
| 445 | + |
405 | 446 | // Return true if stmt is an empty SQL statement. |
406 | 447 | // This is used as an optimization. |
407 | 448 | // It's OK to always return false here. |
|
0 commit comments