Skip to main content

Reading and Writing Data

In this tutorial, we will use the JavaScript SDK to write and read data from a database. We will using the schema we created in the schema tutorial.

Full SDK documentation can be found here.

Install the SDK

First, install the Kwil SDK and the ethers library:

npm install @kwilteam/kwil-js ethers

Initialization

In order to read and write data, we first must initialize the SDK, and get the database ID for our deployed database.

Kwil has different initialization logic for Web and NodeJS.

Kwil Class

The Kwil class is the main class for interacting with Kwil. It is used to initialize the SDK, and to execute procedures.

import { WebKwil } from '@kwilteam/kwil-js';

const kwil = new WebKwil({
kwilProvider: "https://longhorn.kwil.com",
chainId: "longhorn-2",
});

Signer

The signer is used to sign transactions going to the Kwil network.

import { BrowserProvider } from 'ethers';
import { KwilSigner } from '@kwilteam/kwil-js';

async function getSigner() {
const provider = new BrowserProvider(window.ethereum);
const ethSigner = await provider.getSigner();
const ethAddress = await ethSigner.getAddress();
return new KwilSigner(ethSigner, ethAddress);
}

DBID

DBIDs are network-wide unique identifiers for databases. They are derived from the database owner's wallet address and the database name.

Make sure to replace your_wallet_here with your wallet address.

import { Utils } from '@kwilteam/kwil-js';

const dbid = Utils.generateDBID('your_wallet_here', 'social_media');

Write Data

To write data, we can use the execute() method to execute a procedure:

async function createUser(id, username, age) {
const kwilSigner = await getSigner();

const result = await kwil.execute({
dbid,
name: "create_user",
inputs: [
{
$id: id,
$username: username,
$age: age
}
]
}, kwilSigner);

return result.data;
}

Read Data

To read data, we will call a view procedure on the schema. This will return the data that was written to the database.

async function getUser(username) {
const result = await kwil.call({
dbid,
name: "get_user",
inputs: [
{
$username: username
}
]
});

return result.data;
}