Last active
February 5, 2022 15:13
-
-
Save exlnt/f9d59b60406d80b71565e9e90a52ce67 to your computer and use it in GitHub Desktop.
SQL Lite DB helper class used in React-Native EXPO app.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import * as Constants from "../constants/constants"; | |
import * as SQLite from "expo-sqlite"; | |
const db = SQLite.openDatabase(Constants.SQLLITE_Database_Name); | |
export default class BudgetCategoryDB { | |
// Init DB and create table | |
initDB() { | |
return new Promise((resolve) => { | |
db.transaction((tx) => { | |
tx.executeSql( | |
"CREATE TABLE IF NOT EXISTS BudgetCategory(CategoryId INTEGER PRIMARY KEY AUTOINCREMENT, CategoryName VARCHAR(20), CategoryType varchar(10), CategoryColor VARCHAR(10))", | |
[], | |
() => resolve(db), | |
() => console.log("Init DB failed!") | |
); | |
}); | |
}); | |
} | |
// Get all budget categories | |
listBudgetCategories() { | |
return new Promise((resolve) => { | |
this.initDB().then((db) => { | |
db.transaction((tx) => { | |
tx.executeSql( | |
"select * from BudgetCategory Order By CategoryType, CategoryName", | |
[], | |
(tx, { rows }) => { | |
resolve(rows._array); | |
}, | |
() => console.log("listBudgetCategories failed!") | |
); | |
}); | |
}); | |
}); | |
} | |
createBudgetCategory(newCategory) { | |
let sqlOK = false; | |
return new Promise((resolve) => { | |
this.initDB().then((db) => { | |
db.transaction((tx) => { | |
tx.executeSql( | |
"INSERT INTO BudgetCategory (CategoryName, CategoryType, CategoryColor) VALUES (?,?,?)", | |
[newCategory.categoryName, newCategory.type, newCategory.color], | |
(trans, results) => { | |
if (results.rowsAffected > 0) { | |
sqlOK = true; | |
} | |
}, | |
() => resolve(false) | |
); | |
tx.executeSql( | |
"select * from BudgetCategory Where CategoryName=?", | |
[newCategory.categoryName], | |
(trans, results) => { | |
if (!sqlOK && results.rows.length == 0) { | |
resolve(false); | |
} else { | |
resolve(true); | |
} | |
} | |
); | |
}); | |
}); | |
}); | |
} | |
changeBudgetCategory(Category) { | |
let sqlOK = false; | |
return new Promise((resolve) => { | |
this.initDB().then((db) => { | |
db.transaction((tx) => { | |
tx.executeSql( | |
"Update BudgetCategory Set CategoryName=?, CategoryType=?, CategoryColor=? Where CategoryId=?", | |
[ | |
Category.categoryName, | |
Category.type, | |
Category.color, | |
Category.categoryId, | |
], | |
(trans, results) => { | |
if (results.rowsAffected == 0) { | |
resolve(false); | |
} else { | |
resolve(true); | |
} | |
}, | |
() => resolve(false) | |
); | |
}); | |
}); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment