ffi/sqlite-memory-query.protos

Repository
guillermomolina/protos
Commit
379c6fa63685c39a5954cfbd577bfda3b4df8e75
Tree
8cd4f4afe29ae4c3866381f38c1858108e9799f6
Blob
4bbfeabbe8d20706795d88c2eadcdac0196a3705
Source
View exact source on GitHub
// THE LICENSED WORK IS PROVIDED UNDER THE TERMS OF THE ADAPTIVE PUBLIC LICENSE
// ("LICENSE") AS FIRST COMPLETED BY: Guillermo Adrián Molina. ANY USE, PUBLIC
// DISPLAY, PUBLIC PERFORMANCE, REPRODUCTION OR DISTRIBUTION OF, OR PREPARATION OF
// DERIVATIVE WORKS BASED ON, THE LICENSED WORK CONSTITUTES RECIPIENT'S ACCEPTANCE
// OF THIS LICENSE AND ITS TERMS, WHETHER OR NOT SUCH RECIPIENT READS THE TERMS OF
// THE LICENSE. "LICENSED WORK" AND "RECIPIENT" ARE DEFINED IN THE LICENSE. A COPY
// OF THE LICENSE IS LOCATED IN THE TEXT FILE ENTITLED "LICENSE.TXT" ACCOMPANYING
// THE CONTENTS OF THIS FILE. IF A COPY OF THE LICENSE DOES NOT ACCOMPANY THIS
// FILE, A COPY OF THE LICENSE MAY ALSO BE OBTAINED AT THE FOLLOWING WEB SITE:
// https://github.com/guillermomolina/protos
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
// the specific language governing rights and limitations under the License.

// Query an in-memory SQLite database from Protos through the optional FFM
// provider (I144). Every C function is declared below in Protos; the provider
// contains no SQLite-specific Java.
//
// This remains a low-level private-provider exercise from I144, not a
// SQLite library. The public std:sqlite library (LIB029) is now implemented,
// and ordinary applications should use it instead (docs/guide/library/
// sqlite.md). This sample stays useful for studying FFM ABI declarations
// and borrowed-memory copying.
//
//   bin/protos --foreign-provider-path /path/to/protos-ffm-provider.jar --allow-library sqlite3=libsqlite3.so.0 \
//       protos/examples/ffi/sqlite-memory-query.protos
//
// Success: no standard output, exit status 0. `:memory:` keeps the example
// free of database files and of filesystem permissions.
// See protos/examples/ffi/README.md.

Assertions: import("std:test/assertions")
sqlite: import("ffi:sqlite3")

// Builds a C signature from an ordinary Protos Array of descriptors, one
// `param` at a time. The Array stays in Protos; it never crosses the SPI.
signature: (returns, parameters) => {
    composed: sqlite.signature(returns)
    parameters.each((parameter) => {
        composed = sqlite.param(composed, parameter)
    })
    composed
}

// Copies a borrowed region into ordinary Protos Bytes. Bytes has no prelude
// constructor: an empty Bytes comes from the standard encoder and grows
// through `add`. No UTF-8 is interpreted on the way.
copyBytes: (region, length) => {
    copied: sqlite.copy(region, length)
    bytes: Encoding.UTF8.encode("")
    index: 0
    while(index < copied.size) {
        bytes.add(copied[index])
        index = index + 1
    }
    bytes
}

SQLITE_OK: 0
SQLITE_ROW: 100
SQLITE_DONE: 101
SQLITE_OPEN_READWRITE_CREATE: 6

// ---- Types: a connection and a statement, each with its destructor

dbType: sqlite.opaque("sqlite3")
stmtType: sqlite.opaque("sqlite3_stmt")
db: sqlite.owned(dbType, "sqlite3_close_v2", sqlite.i32)
stmt: sqlite.owned(stmtType, "sqlite3_finalize", sqlite.i32)

// C NULL for `const char *zVfs` and `const char **pzTail`: nullable pointers
// of private types that no binding produces, so only `null` is admitted.
vfsName: sqlite.nullable(sqlite.opaque("sqlite3_vfs_name"))
sqlTail: sqlite.nullable(sqlite.opaque("sqlite3_sql_tail"))

// ---- C declarations

open: sqlite.bind("sqlite3_open_v2",
    signature(sqlite.i32, Array(sqlite.utf8z, sqlite.out(db), sqlite.i32, vfsName)))
prepare: sqlite.bind("sqlite3_prepare_v2",
    signature(sqlite.i32, Array(dbType, sqlite.utf8z, sqlite.i32, sqlite.out(stmt), sqlTail)))
step: sqlite.bind("sqlite3_step", signature(sqlite.i32, Array(stmtType)))

// Column readers that return scalars do not touch earlier borrowed regions:
// they are declared `preserving`, a trusted statement about SQLite's ABI.
columnInt64: sqlite.bind("sqlite3_column_int64",
    sqlite.preserving(signature(sqlite.i64, Array(stmtType, sqlite.i32))))
columnDouble: sqlite.bind("sqlite3_column_double",
    sqlite.preserving(signature(sqlite.f64, Array(stmtType, sqlite.i32))))
columnBytes: sqlite.bind("sqlite3_column_bytes",
    sqlite.preserving(signature(sqlite.i32, Array(stmtType, sqlite.i32))))
// Text and blob pointers are memory owned by SQLite: borrowed regions.
columnText: sqlite.bind("sqlite3_column_text",
    signature(sqlite.borrowed, Array(stmtType, sqlite.i32)))
columnBlob: sqlite.bind("sqlite3_column_blob",
    signature(sqlite.borrowed, Array(stmtType, sqlite.i32)))

// ---- Open the in-memory database

opened: open(":memory:", SQLITE_OPEN_READWRITE_CREATE, null)
// [status, connection]: the status is data; checking it is our job.
Assertions.require(opened[0] == SQLITE_OK)
connection: opened[1]

// ---- Prepare and run one query

prepared: prepare(connection, "SELECT 40 + 2, 1.5 * 2, 'caf\u{E9}', x'00ff10'", -1, null)
Assertions.require(prepared[0] == SQLITE_OK)
statement: prepared[1]

Assertions.require(step(statement) == SQLITE_ROW)

// Numeric columns arrive as ordinary Integer and Float values.
Assertions.require(columnInt64(statement, 0) == 42)
Assertions.require(columnDouble(statement, 1) == 3.0)

// Text: pointer, then length (preserving), then the bounded copy, in this
// order. The octets are the UTF-8 encoding SQLite stored: "caf" + C3 A9.
text: copyBytes(columnText(statement, 2), columnBytes(statement, 2))
Assertions.require(text.size() == 5)
Assertions.require((text[0] == 99) && (text[2] == 102) && (text[3] == 195) && (text[4] == 169))

// Blob: the same pattern; binary data, including a zero octet.
blob: copyBytes(columnBlob(statement, 3), columnBytes(statement, 3))
Assertions.require(blob.size() == 3)
Assertions.require((blob[0] == 0) && (blob[1] == 255) && (blob[2] == 16))

// One row only.
Assertions.require(step(statement) == SQLITE_DONE)

// ---- Release: statement first, then the connection

Assertions.require(sqlite.release(statement) == SQLITE_OK)   // sqlite3_finalize
Assertions.require(sqlite.release(connection) == SQLITE_OK)  // sqlite3_close_v2