Skip to content

Commit

Permalink
docs: add createCallbackFunction page
Browse files Browse the repository at this point in the history
  • Loading branch information
DallasHoff committed Aug 30, 2023
1 parent db3b8f0 commit da02d86
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
4 changes: 4 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export default defineConfig({
text: 'transaction',
link: '/api/transaction',
},
{
text: 'createCallbackFunction',
link: '/api/createcallbackfunction',
},
{
text: 'getDatabaseFile',
link: '/api/getdatabasefile',
Expand Down
48 changes: 48 additions & 0 deletions docs/api/createcallbackfunction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# createCallbackFunction

Create a SQL function that can be called from queries to trigger a JavaScript callback.

## Usage

Access or destructure `createCallbackFunction` from the `SQLocal` client.

```javascript
import { SQLocal } from 'sqlocal';

export const { createCallbackFunction } = new SQLocal('database.sqlite3');
```

<!-- @include: ../_partials/initialization-note.md -->

This method takes a string to name a custom SQL function as its first argument and a callback function as its second argument which the SQL function will call. After running `createCallbackFunction`, the function that you defined can be called from subsequent SQL queries. Arguments passed to the function in the SQL query will be passed to the JavaScript callback.

A good use-case for this is making SQL triggers that notify your application when certain mutations are made in the database. For example, let's create a `logInsert` callback function that takes a table name and a record name to log a message.

```javascript
await createCallbackFunction('logInsert', (tableName, recordName) => {
console.log(`New ${tableName} record created with name: ${recordName}`);
});
```

Then, we can create a temporary trigger that calls `logInsert` whenever we insert a row into our `groceries` table.

```javascript
await sql`
CREATE TEMP TRIGGER 'logGroceriesInsert' AFTER INSERT ON groceries
BEGIN
SELECT logInsert('groceries', new.name);
END
`;
```

Now, a message will be automatically logged whenever a query on the same connection inserts into the `groceries` table.

```javascript
await sql`INSERT INTO groceries (name) VALUES ('bread')`;
```

```log
New groceries record created with name: bread
```

Note that each callback function that you create will be connection-specific. If you create more than one connection using additional `SQLocal` instances but want to use the same function in queries sent over the other connections as well, you will need to call `createCallbackFunction` on each instance.

0 comments on commit da02d86

Please sign in to comment.