From ef90c4ee1ae4d691a6c3f370c3867a6917b0c290 Mon Sep 17 00:00:00 2001 From: thschleicher Date: Sat, 23 Dec 2023 12:28:00 +0100 Subject: [PATCH] changed useFetch to take a Query parameter so It is easy to work with across the whole app --- app/(tabs)/budget/index.tsx | 2 +- app/(tabs)/home/index.tsx | 16 +++++++++++----- app/(tabs)/stats/index.tsx | 31 +++++++++++++++++++++++++++---- hooks/useFetch.ts | 5 +++-- services/database.ts | 24 +++++++++--------------- 5 files changed, 51 insertions(+), 27 deletions(-) diff --git a/app/(tabs)/budget/index.tsx b/app/(tabs)/budget/index.tsx index aa527fb..bcc9580 100644 --- a/app/(tabs)/budget/index.tsx +++ b/app/(tabs)/budget/index.tsx @@ -18,7 +18,7 @@ export default function Page() { } }); - const {data, isLoading, reFetch} = useFetch(); + const {data, isLoading, reFetch} = useFetch({sql: "SELECT guid as category_guid, name as category_name, color as category_color FROM category", args: []}); return ( diff --git a/app/(tabs)/home/index.tsx b/app/(tabs)/home/index.tsx index 4a510a1..a679e46 100644 --- a/app/(tabs)/home/index.tsx +++ b/app/(tabs)/home/index.tsx @@ -5,7 +5,8 @@ import { FlatList } from 'react-native-gesture-handler'; import { SafeAreaView } from 'react-native-safe-area-context'; import { ExpenseItem, LoadingSymbol, Plus, SearchBar, Welcome } from '../../../components'; import useFetch from '../../../hooks/useFetch'; -import { addExpense } from "../../../services/database"; +import { useThemeColor } from "../../../hooks/useThemeColor"; +import { addExpense, executeQuery } from "../../../services/database"; import { useAuth } from '../../contexts/AuthContext'; import { useRouter } from "expo-router"; import { SimpleDate } from '../../../util/SimpleDate'; @@ -81,7 +82,7 @@ export default function Page() { } } - const {data, isLoading, reFetch} = useFetch(); + const {data, isLoading, reFetch} = useFetch({sql: "SELECT e.guid AS expense_guid, c.guid AS category_guid, e.name AS expense_name, c.name AS category_name, e.datetime AS expense_datetime, e.amount AS expense_amount, c.color AS category_color, c.type AS category_type FROM expense e JOIN category c ON e.category_guid = c.guid;", args: []}); const expenseDates = useMemo(()=> constructMarkedDates(data) @@ -93,9 +94,14 @@ export default function Page() { {plusShow && { // router.push("/(tabs)/home/addItem"); - newExpense("Test Title", "3b33b8ac-5fc1-43e5-81fc-cf61628861f7", "69.69.1234", 100).then(() => { - reFetch(); - }); + + executeQuery({sql: "SELECT guid FROM category", args: []}).then((result) => { + if("rows" in result[0]) { + newExpense("Test Title", result[0]["rows"][0]["guid"], "69.69.1234", 100).then(() => { + reFetch(); + }); + } + }) }}/>} {isLoading && } diff --git a/app/(tabs)/stats/index.tsx b/app/(tabs)/stats/index.tsx index 85c1636..6b0983b 100644 --- a/app/(tabs)/stats/index.tsx +++ b/app/(tabs)/stats/index.tsx @@ -1,17 +1,17 @@ +import { Query } from 'expo-sqlite'; import { StyleSheet, Text, View } from 'react-native'; -import { deleteExpenses } from '../../../services/database'; +import { addCategory, deleteDatabase, deleteExpenses, executeQuery, initDatabase } from '../../../services/database'; export default function Page() { const styles = StyleSheet.create({ container: { flex: 1, - justifyContent: 'center', + justifyContent: 'space-evenly', alignItems: 'center', }, text: { - textAlign: 'center', fontSize: 40, - color: "red", + color: "yellow", } }); @@ -24,5 +24,28 @@ export default function Page() { console.log("Expenses Deleted!"); }) }}>Reset Expenses + + { + deleteDatabase(); + console.log("Database Deleted!"); + }}>Reset Database + + { + initDatabase().then(() => { + console.log("Database Initialized!"); + }); + }}>Init Database + + { + addCategory("Test", "blue", "budget").then(() => { + const getCategoryQuery: Query = {sql: "SELECT guid FROM category", args: []}; + executeQuery(getCategoryQuery).then((result) => { + if("rows" in result[0]) { + console.log(result[0]["rows"]); + } + }) + console.log("Category added with success!"); + }) + }}>Add Category ); } diff --git a/hooks/useFetch.ts b/hooks/useFetch.ts index 790e4f2..cdb8ace 100644 --- a/hooks/useFetch.ts +++ b/hooks/useFetch.ts @@ -1,14 +1,15 @@ +import { Query } from "expo-sqlite"; import { useEffect, useState } from "react"; import { executeQuery } from "../services/database"; -const useFetch = () => { +const useFetch = (query: Query) => { const [isLoading, setIsLoading] = useState(false); const [data, setData] = useState<{[column: string]: any;}[]>([]); const reFetch = () => { setIsLoading(true); - executeQuery("SELECT e.guid AS expense_guid, c.guid AS category_guid, e.name AS expense_name, c.name AS category_name, e.datetime AS expense_datetime, e.amount AS expense_amount, c.color AS category_color, c.type AS category_type FROM expense e JOIN category c ON e.category_guid = c.guid;").then((result) => { + executeQuery(query).then((result) => { if("rows" in result[0]) { setData(result[0]["rows"]); } diff --git a/services/database.ts b/services/database.ts index ec1528b..404fa0f 100644 --- a/services/database.ts +++ b/services/database.ts @@ -1,4 +1,3 @@ -//created by thschleicher import * as SQLite from "expo-sqlite"; import uuid from "react-native-uuid"; @@ -6,22 +5,21 @@ import uuid from "react-native-uuid"; import { Query } from "expo-sqlite"; import { SimpleDate } from "../util/SimpleDate"; -const db = SQLite.openDatabase("interactive_systeme.db"); +let db: SQLite.SQLiteDatabase; export const initDatabase = async () => { + db = SQLite.openDatabase("interactive_systeme.db"); try { await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => { await tx.executeSqlAsync( - "CREATE TABLE IF NOT EXISTS category (guid VARCHAR(36) PRIMARY KEY, name TEXT, color TEXT, type TEXT);" + "CREATE TABLE IF NOT EXISTS category (guid VARCHAR(36) PRIMARY KEY, name TEXT, color TEXT, type TEXT, allocated_amount DOUBLE);" ); await tx.executeSqlAsync( "CREATE TABLE IF NOT EXISTS expense (guid VARCHAR(36) PRIMARY KEY, name TEXT, category_guid VARCHAR(36), datetime DATETIME, amount DOUBLE, FOREIGN KEY (category_guid) REFERENCES category(guid));" ); - console.log("Successfully initialized Tables!"); }); } catch (error) { - - console.log("Error initializing the Tables!"); + console.log("Error initializing the Database!"); throw (error); } }; @@ -38,7 +36,6 @@ export const addCategory = async (name: string, color: string, type: string) => [UUID.toString(), name, color, type] ); }); - console.log("Category added successfully!"); } catch (error) { console.log("Error adding category: ", error); throw error; @@ -56,7 +53,6 @@ export const addExpense = async (name: string, category_guid: string,datetime: s await tx.executeSqlAsync("INSERT INTO expense (guid, name, category_guid, datetime, amount) VALUES (?, ?, ?, ?, ?);", [expenseUUID.toString(), name, category_guid, datetime, amount] ); }); - console.log("Expense added successfully!"); } catch (error) { console.log("Error adding expense: ", error); throw error; @@ -85,15 +81,15 @@ export const deleteExpense = async (guid: string) => { } } -export const executeQuery = async (query: string) => { - const sqliteQuary: Query[] = [{sql: query, args: []}]; - const result = await db.execAsync(sqliteQuary, true); +export const executeQuery = async (query: Query) => { + const result = await db.execAsync([query], true); if("error" in result[0]){ throw result[0].error } - return result; + return result; } + export const deleteExpenses = async () => { try { await db.transactionAsync(async (tx: SQLite.SQLTransactionAsync) => { @@ -125,9 +121,7 @@ export const deleteDatabase = () => { console.log("Error deleting the Database: ", error); throw error; } - }); - console.log("Database Deleted!") } const closeDatabase = async () => { @@ -151,7 +145,7 @@ export const DEV_populateDatabase = async () => { let random = Math.floor(Math.random() * colors.length); await addCategory(`Category ${i}`, colors[random], "budget") } - const result = await executeQuery("SELECT * from category") + const result = await executeQuery({sql:"SELECT * from category", args:[]}) let categories: {[column: string]: any}[]; if("rows" in result[0]){ categories = result[0]["rows"]