This blog post will be part of a series of blog posts where we show case an example of how we can use a third party dependency like SQLite in our Connect IoT code. In this last post we will go through the whole implementation, so as to give an overview on a possible implementation of SQLite in Connect IoT.
In this blog post we will show how you can store and retrieve data from sqlite and also do your own queries.
I will be using the vscode extension vscode-sqlite which allows me to have an extension in vscode where I can connect to the SQLite database and perform queries.
Ingesting Data
Let’s take a look at a specific use case. I have an assorted set of json files where I want to process and insert into my SQLite database.
We will use the File Raw Protocol and will process all new files.
Each json document will be inserted into my SQLite database. Right now I am not doing any kind of parsing I am just storing all the json files into a table called SMT.
Our Workflow is reacting to new files detected in a folder. For each of them it is reading the contents of the files and storing them using the Store SQLite task.
With this approach we can already perform queries but they tend to be very cumbersome as they will have to deal with schemaless json documents.
Looking at the Store SQLite Task
The store SQLite Task will receive json documents, extract information like the give time to live, the table name and the table id and finally store it in the SQLite database.
public override async onChanges(changes: Task.Changes): Promise {
if (changes["activate"]) {
// It is advised to reset the activate to allow being reactivated without the value being different
this.activate = undefined;
const stmtValues = new Map();
try {
this._logger.debug("Starting Execution of Store SQLite task");
for (const storeElement of this.inputs) {
// If there is an input with data to store
if (this[storeElement.name] != null) {
// Try to retrieve the id for the row if there is an id defined for this store element
const documentId = JSON.parse(this[storeElement.name] ?? {})?.[storeElement.idElement];
const data = this[storeElement.name];
// Resolve the table name for the row
const tableName = storeElement.tableName != null && storeElement.tableName !== "" ? storeElement.tableName : storeElement.name;
// Insert in SQLite database
const output = this._sqliteManager.insert(documentId, tableName, data, storeElement?.ttl);
// Collect values to provide feedback
stmtValues.set(output.id, output.result);
}
}
this.results.emit(stmtValues);
this.success.emit(true);
this._logger.info("Finished Executing Store SQLite task");
} catch (e) {
this.logAndEmitError(e.message);
}
}
}
As you can see the code is quite simple, we check if there’s any input with data to store and if it has we resolve some important metadata. In the SQLiteManager class is where we will handle the actual insert into the SQLite database.
As we saw in part II the SQLiteManager is being injected in the dependency injection container.
Looking at the Insert SQLiteManager
In SQLiteManager class, we will call the insert method. This method will be responsible for dealing with inserts.
public insert(id: string, documentType: string, data: object, ttlSeconds?: number) {
// Ensure that the SQLite has been instantiated
const tableName = this.guardClause(documentType);
// If needed generate an Id
if (id == null || id === "") {
id = this.newGuid();
}
// Check if data already exists
const checkStmt = this._db.prepare(`
SELECT id FROM ${tableName} WHERE json(data) = json(?)
`);
const existingRow = checkStmt.get(JSON.stringify(data));
// if the row already exists, we are going to keep the data and update the Time To Live
if (existingRow) {
// Update existing row with new TTL
const updateStmt = this._db.prepare(`
UPDATE ${tableName}
SET updated_at = CURRENT_TIMESTAMP,
expires_at = CASE
WHEN ? IS NOT NULL THEN datetime(CURRENT_TIMESTAMP, '+' || ? || ' seconds')
ELSE NULL
END
WHERE id = ?
`);
updateStmt.run(ttlSeconds, ttlSeconds, existingRow.id);
return { id: existingRow.id, result: { changes: 1 }, existed: true };
}
// Insert new row with calculated expires_at
const stmt = this._db.prepare(`
INSERT INTO ${tableName} (id, data, created_at, updated_at, expires_at)
VALUES (?, json(json_extract(?, '$')), CURRENT_TIMESTAMP, CURRENT_TIMESTAMP,
CASE
WHEN ? IS NOT NULL THEN datetime(CURRENT_TIMESTAMP, '+' || ? || ' seconds')
ELSE NULL
END)
`);
return {
id,
result: stmt.run(id, JSON.stringify(data), ttlSeconds, ttlSeconds),
existed: false
};
}
The insert will validate that we don’t try to store data with the same ids and will manage helpers like the time to live of our stored data. The controller is always running so it’s helpful to implement mechanisms to handle stale data and to stop our database from growing forever. Notice that we can already see some functions that we use in SQLite to manipulate JSON columns like the json_extract().
With this we can already see the big advantage of separating the SQLite Manager from the tasks. We have a complete separation of concerns, where the task does not need to know the SQLite language. In fact if we were to support other databases, the task store SQLite would remain the same, we could just import the DI Container for any other database. We also are managing the query logic only one location in the code, which is much easier to maintain, troubleshoot and improve.
A better approach is to provide at least a partial schema and storing each document type in different tables.
We will have the same approach of reading a set of json files. But now after reading we will provide some schema enforcement, each one will then be matched against an expected schema.
For example, for LineRecipeSetup we are expecting the schema:
When we now store we will store only json objects that obey the schema structure. We will store them in the table LineRecipeSetup. We can also specify meaningful indexes, for example for this json document the recipe full path will be a table index.
Now we are storing data into multiple tables based on schema. I am also storing all the read files in a Raw Data table.
Looking at the JSON Schema Validator Task
For the JSON schema task we will use ajv as our dependency for schema enforcement.
Ajv is a very simple but powerful tool, it allows us to provide it with a schema and then validate json objects.
public override async onChanges(changes: Task.Changes): Promise {
if (changes["activate"]) {
this.activate = undefined;
let hasErrors = false;
try {
// iterate defined schemas
for (const schema of this.schemas) {
// If there's data for this schema
const jsonData = this[schema.name];
if (jsonData != null) {
// Validate against defined schema
const validate = this.ajv.compile(schema.schema);
if (validate(JSON.parse(jsonData))) {
(this[Utilities.propertyToOutput(schema.name)] as Task.Output