development
HerrHase 3 months ago
parent d7a57f0ef1
commit 1eb378b055

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2024 Björn Hase, me@herr-hase.wtf
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

@ -1,2 +1,7 @@
# nano-sqlite # Nano Sqlite
Functions and Classes for handle sqlite in [Bun]().
## Function runMigrationSqlite(filePath: string, db: object)
## Function getOrCreateSqlite(options = {})
## Abstract Class Store

@ -0,0 +1,19 @@
{
"name": "@nano/sqlite",
"version": "0.1.0",
"description": "Function for using Sqlite in Bun",
"repository": {
"type": "git",
"url": "git@git.node001.net:HerrHase/nano-sqlite.git"
},
"author": "Björn Hase <me@herr-hase.wtf>",
"license": "MIT",
"type": "module",
"scripts": {
"test": "bun test"
},
"devDependencies": {
"chai": "^5.1.1",
"mocha": "^10.6.0"
}
}

@ -0,0 +1,26 @@
import Store from './../src/Store.ts'
/**
* store - abstract class
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://gitea.node001.net/HerrHase/urban-filehub.git
*
*/
class ItemStore extends Store {
/**
*
*
* @param {tableName}
*
*/
constructor(db) {
super(db, 'items')
}
}
export default ItemStore

@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY,
name TEXT,
description TEXT,
date_created_at TEXT,
date_upated_at TEXT
)

@ -0,0 +1,46 @@
import { readdir } from 'node:fs/promises'
import path from 'path'
/**
* runMigrationSqlite
*
* @param {string} path
* @param {object} db
*
*/
async function runMigrationSqlite(filePath: string, db: object): void {
const SQL_EXTENSION = '.sql'
// resolve path
filePath = path.resolve(__dirname, filePath)
// getting files
const files = await readdir(filePath)
for (const fileName of files) {
// skip if extension not sql
if (path.extname(fileName).toLowerCase() !== SQL_EXTENSION) {
continue
}
const file = Bun.file(filePath + '/' + fileName)
try {
const sql = await file.text()
if (!sql.trim()) {
throw new Error(fileName + ' is empty!')
}
db.query(sql.trim()).run()
console.log('migrated ' + path.basename(fileName, SQL_EXTENSION))
} catch(error) {
console.log(error)
}
}
}
export default runMigrationSqlite

@ -0,0 +1,33 @@
/**
* db
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://gitea.node001.net/HerrHase/urban-bucket.git
*
*/
import { Database } from 'bun:sqlite'
function getOrCreateSqlite(options = {}): Database {
// merge options
options = Object.assign({
name: process.env.NANO_SQLITE_STORAGE + '/' + process.env.NANO_SQLITE_NAME,
safeIntegers: true
}, options)
const name = options.name
delete options.name
if (Object.keys(options).length === 0) {
options = undefined
}
const db = new Database(name)
db.exec('PRAGMA journal_mode = WAL;')
return db
}
export default getOrCreateSqlite

@ -0,0 +1,122 @@
/**
* store - abstract class
*
* @author Björn Hase <me@herr-hase.wtf>
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://gitea.node001.net/HerrHase/urban-filehub.git
*
*/
abstract class Store {
protected db: string
protected tableName: string
/**
*
*
* @param {tableName}
*
*/
constructor(db: object, tableName?: string) {
this.db = db
this.tableName = tableName
}
/**
* create row
*
*/
findOneById(id: integer): object {
return this.db
.query('SELECT * FROM ' + this.tableName + ' WHERE id = $id')
.get({
'$id': id
})
}
/**
* create row
*
*/
create(data: object): integer {
this.db
.query('INSERT INTO ' + this.tableName + ' (' + Object.keys(data).join(', ') + ') VALUES (' + this.prepareInsertBinding(data) + ')')
.run(this.prepareData(data))
return this.db.query('SELECT last_insert_rowid()').get()['last_insert_rowid()']
}
/**
* update row
*
*/
update(id: integer, data: object): void {
this.db
.query('UPDATE ' + this.tableName + ' SET ' + this.prepareUpdateBinding(data) + ' WHERE id = $id')
.run(this.prepareData(Object.assign(data, {
'id': id
})))
}
/**
* create row
*
*/
remove(id: integer): remove {
this.db
.query('DELETE FROM ' + this.tableName + ' WHERE id = $id')
.run({
$id: id
})
}
/**
*
*/
prepareData(data: object) {
const results = {}
for (const key in data) {
results['$' + key] = data[key]
}
return results
}
/**
* run through object and add key to string for
* binding parameters for insert
*
* @param {object} data
* @return {string}
*/
prepareInsertBinding(data: array) {
let result = []
for (const key in data) {
result.push('$' + key)
}
return result.join(', ')
}
/**
* run through object and add key to string for
* binding parameters for update
*
* @param {object} data
* @return {string}
*/
prepareUpdateBinding(data: array) {
let result = []
for (const key in data) {
result.push(key + ' = $' + key)
}
return result.join(', ')
}
}
export default Store

@ -0,0 +1,16 @@
import { expect, test } from 'bun:test'
import path from 'path'
import runMigrationSqlite from './../src/migration.ts'
import getOrCreateSqlite from './../src/sqlite.ts'
import { Database } from 'bun:sqlite'
test('migration', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:', 'create': true, 'readwrite': true })
await runMigrationSqlite('./../resources', db)
// check for boxes
const results = db.query("SELECT name FROM sqlite_master WHERE type='table' AND name='items'").get()
expect(results).toEqual({ name: 'items' })
})

@ -0,0 +1,7 @@
import { expect, test } from 'bun:test'
import getOrCreateSqlite from './../src/sqlite.ts'
test('sqlite', () => {
const db = getOrCreateSqlite({ 'name': ':memory:' })
expect(typeof db === 'object').toBeTruthy();
})

@ -0,0 +1,53 @@
import { expect, test } from 'bun:test'
import ItemStore from './../resources/itemStore.ts'
import runMigrationSqlite from './../src/migration.ts'
import getOrCreateSqlite from './../src/sqlite.ts'
test('store', () => {
const db = getOrCreateSqlite({ 'name': ':memory:' })
const itemStore = new ItemStore(db)
expect(typeof itemStore === 'object').toBeTruthy();
})
test('store / insert', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:' })
await runMigrationSqlite('./../resources', db)
const itemStore = new ItemStore(db)
const id = itemStore.create({ 'name': 'Lorem ipsum dolor', 'description': 'lore' })
const result = itemStore.findOneById(id)
expect(result).toEqual({ 'id': 1, 'name': 'Lorem ipsum dolor', 'description': 'lore', 'date_created_at': null, 'date_upated_at': null })
})
test('store / remove', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:' })
await runMigrationSqlite('./../resources', db)
const itemStore = new ItemStore(db)
itemStore.create({ 'name': 'Lorem ipsum dolor', 'description': 'lore' })
const result = db.query("SELECT * FROM items").get()
itemStore.remove(result.id)
const emptyResult = db.query("SELECT * FROM items").get()
expect(emptyResult).toEqual(null)
})
test('store / update', async () => {
const db = getOrCreateSqlite({ 'name': ':memory:' })
await runMigrationSqlite('./../resources', db)
const itemStore = new ItemStore(db)
const id = itemStore.create({ 'name': 'Lorem ipsum dolor', 'description': 'lore' })
itemStore.update(id, { 'name': 'lore', 'description': 'Lorem ipsum dolor' })
const result = itemStore.findOneById(id)
expect(result).toEqual({ 'id': 1, 'name': 'lore', 'description': 'Lorem ipsum dolor', 'date_created_at': null, 'date_upated_at': null })
})
Loading…
Cancel
Save