-
Notifications
You must be signed in to change notification settings - Fork 1
OSDatabase
Arthur Guiot edited this page Oct 11, 2020
·
2 revisions
class OSDatabase {
// Setup
constructor(cache = new Set()) {}
configure(main, secondary = null, lang = "en", completion=()=>{}) {}
// Interaction
select(contains = null, key="keywords", range=null) {}
add(records, main, secondary = null, lang="en") {}
setPlugin(select, add, keywords) {}
}OSDatabase is an object that enables OrionSearch to interact with any databases. It also contains a "keywords cache" that is used for rewriting the query. The cache will be auto-configured with the configure method, but if you already ran this function, you can just restore the cache by initiating the class with it:
const db1 = new OSDatabase()
db1.configure("title", "content")
const db2 = new OSDatabase(db1.keywordsCache) // same as db1. Use this when using the frontend package so that your visitors don't have to recompute the keywords cache every single time.
⚠️ Note about database structure:
Every database should have a column namedkeywordsthat will be used by OrionSearch to filter records.
In this section, we'll show you a detailed example with the SQLite 3 database.
const db = new OSDatabase() // Creates the object
/* Implementing methods */
db.setPlugin(
(key, contains, range) => { // Select method
const r = range == null ? [0, Number.MAX_SAFE_INTEGER] : range // Creates a range
let rows = []
if (contains == null) { // If OrionSearch needs to query everything. Used for the configure method.
const query = data.prepare(`SELECT rowid, * FROM main WHERE rowid BETWEEN ${r[0]} AND ${r[1]}`)
rows = query.all()
} else { // Otherwise
const query = data.prepare(`SELECT rowid, * FROM main WHERE ${key} LIKE "%${contains}%" AND rowid BETWEEN ${r[0]} AND ${r[1]}`)
rows = query.all()
}
let out = []
rows.forEach(row => { // Setting the main key.
const record = new OSRecord(row) // Creating a record based on the retrieved data.
record.main("headlines") // "headlines" is now the main column for this record.
out.push(record)
})
return out // Returning all the records
},
add => { // Add a record
const query = data.prepare(`INSERT INTO main VALUES (${add.values})`)
query.run()
},
(keywords, record) => { // Manage "keywords" column. It will insert an array of records in the desired row.
const keyQuery = data.prepare(`UPDATE main SET keywords = "${[...keywords].join(' ')}" WHERE rowid = ${record.data.rowid};`)
keyQuery.run()
}
)