//go:build go1.27

package sqlite3

import (
	
	

	
	
	
)

// JSON returns a value that can be used as an argument to
// [database/sql.DB.Exec], [database/sql.Row.Scan] and similar methods to
// store value as JSON, or decode JSON into value.
// JSON should NOT be used with [Stmt.BindJSON], [Stmt.ColumnJSON],
// [Value.JSON], or [Context.ResultJSON].
func ( any) any {
	return util.JSON{Value: }
}

// ResultJSON sets the result of the function to the JSON encoding of value.
//
// If you return JSON from application-defined functions,
// consider registering those functions with [RESULT_SUBTYPE]
// and calling [Context.ResultSubtype] with 'J'.
//
// https://sqlite.org/c3ref/result_blob.html
func ( Context) ( any) {
	 := bytesWriter{wrp: .c.wrp}
	if  := json.MarshalWrite(&, );  != nil {
		.c.wrp.Free(.ptr)
		.ResultError()
		return // notest
	}
	.c.wrp.Xsqlite3_result_text_go(
		int32(.handle), int32(.ptr), int64(len(.buf)))
}

// BindJSON binds the JSON encoding of value to the prepared statement.
// The leftmost SQL parameter has an index of 1.
//
// https://sqlite.org/c3ref/bind_blob.html
func ( *Stmt) ( int,  any) error {
	 := bytesWriter{wrp: .c.wrp}
	if  := json.MarshalWrite(&, );  != nil {
		.c.wrp.Free(.ptr)
		return  // notest
	}
	 := res_t(.c.wrp.Xsqlite3_bind_text_go(
		int32(.handle), int32(),
		int32(.ptr), int64(len(.buf))))
	return .c.error()
}

// ColumnJSON parses the JSON-encoded value of the result column
// and stores it in the value pointed to by ptr.
// The leftmost column of the result set has the index 0.
//
// https://sqlite.org/c3ref/column_blob.html
func ( *Stmt) ( int,  any) error {
	var  []byte
	switch .ColumnType() {
	case NULL:
		 = []byte("null")
	case TEXT:
		 = .ColumnRawText()
	case BLOB:
		 = .ColumnRawBlob()
	case INTEGER:
		 = strconv.AppendInt(nil, .ColumnInt64(), 10)
	case FLOAT:
		 = util.AppendFloat(nil, .ColumnFloat(), 64)
	default:
		panic(errutil.AssertErr())
	}
	return json.Unmarshal(, )
}

// JSON parses a JSON-encoded value
// and stores the result in the value pointed to by ptr.
func ( Value) ( any) error {
	var  []byte
	switch .Type() {
	case NULL:
		 = []byte("null")
	case TEXT:
		 = .RawText()
	case BLOB:
		 = .RawBlob()
	case INTEGER:
		 = strconv.AppendInt(nil, .Int64(), 10)
	case FLOAT:
		 = util.AppendFloat(nil, .Float(), 64)
	default:
		panic(errutil.AssertErr())
	}
	return json.Unmarshal(, )
}

type bytesWriter struct {
	wrp *sqlite3_wrap.Wrapper
	buf []byte
	ptr ptr_t
}

func ( *bytesWriter) ( []byte) ( int,  error) {
	if len() > cap(.buf)-len(.buf)-1 {
		 := int64(len(.buf)) + int64(len()) + 1
		 := int64(cap(.buf))
		 +=  >> 1
		 = max(, )
		.ptr = .wrp.Realloc(.ptr, )
		.buf = .wrp.Bytes(.ptr, )[:len(.buf)]
	}
	.buf = append(.buf, ...)
	_ = append(.buf, 0)
	return len(), nil
}