Fixed Database creation, The error was that there were 2 simultaenous Database connections, causing an error when both attempted to connect at once.

This commit is contained in:
Lynixenn
2025-03-30 22:59:19 +02:00
parent fb916e9e9f
commit 8f27246234
8 changed files with 52 additions and 73 deletions

1
.gitignore vendored
View File

@@ -12,6 +12,7 @@ dist
dist-ssr
.vite
*.local
*.sqlite
# Editor directories and files
.vscode/*

View File

@@ -1,20 +0,0 @@
# Use a Node.js base image with npm pre-installed
FROM node:alpine
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application code
COPY . .
# Expose the port your app will listen on
EXPOSE 3000
# Start the app
CMD ["node", "index.js"]

View File

@@ -10,19 +10,22 @@ ESP is a simple social media platform built with [Deno](https://deno.land/), [Vi
We're building ESP to avoid the clutter of other Social Media websites.
It's build to be simple, fast and easy to use, all while keeping a Minimal feeling to it.
It's built to be simple, fast and easy to use, all while keeping a Minimal feeling to it.
---
# How do I run it?
The only dependency is Deno! Nothing else is required, Deno will install all the Modules needed and start it.
## Running
Dev server:
API + Website:
```bash
$ deno task dev
```
API only:
```bash
$ deno task dev:api
@@ -59,12 +62,9 @@ $ deno task build
## Tools used
<ul>
<li><a href="https://www.jetbrains.com/webstorm/"><img src="https://upload.wikimedia.org/wikipedia/commons/c/c0/WebStorm_Icon.svg" width="20" height="20"> JetBrains WebStorm</a></li>
<li><a href="https://www.jetbrains.com/datagrip/"><img src="https://seeklogo.com/images/D/datagrip-logo-295CA63255-seeklogo.com.png" width="20" height="20"> JetBrains DataGrip</a></li>
<li><a href="https://neovim.io/"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/07/Neovim-mark-flat.svg/640px-Neovim-mark-flat.svg.png" width="20" height="20"> Neovim</a></li>
<li><a href="https://code.visualstudio.com/"><img src="https://code.visualstudio.com/assets/images/code-stable.png" width="20" height="20"> Visual Studio Code</a></li>
</ul>

View File

@@ -1,6 +0,0 @@
INSERT INTO posts (posts_uuid, user_id, created_at, post_text, likes, comments) VALUES
('1a2b3c4d', 1, '2024-11-01 10:00:00', 'Post1', 5, 2),
('2b3c4d5e', 1, '2024-11-02 11:30:00', 'Post2', 10, 3),
('3c4d5e6f', 2, '2024-11-03 12:45:00', 'Post3', 0, 0),
('4d5e6f7g', 2, '2024-11-04 14:20:00', 'Post4', 15, 5),
('5e6f7g8h', 3, '2024-11-05 09:15:00', 'Post5', 8, 1);

View File

@@ -55,7 +55,7 @@ type ApiResponse = {
};
// database creation if missing, runs here because this is the main file executed by the API.
db_utils.ensureDatabaseExists();
await db_utils.ensureDatabaseExists();
// +++ ROUTER ------------------------------------------------------- //
// Creates the routes for the API server.

View File

@@ -7,18 +7,10 @@
// +++ IMPORTS ------------------------------------------------------ //
import { DB } from "https://deno.land/x/sqlite@v3.9.1/mod.ts";
import {
dirname,
fromFileUrl,
join,
} from "https://deno.land/std@0.224.0/path/mod.ts";
// +++ VARIABLES ---------------------------------------------------- //
const _dirname: string = dirname(fromFileUrl(import.meta.url));
const dbPath: string = join(_dirname, "../database/esp-projekt.sqlite");
const db = new DB(dbPath);
export function createDatabase(): void {
export function createDatabase(db: DB): void {
db.execute(`
CREATE TABLE IF NOT EXISTS accounts (
user_id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -72,12 +64,17 @@ export function createDatabase(): void {
chat_name TEXT,
participants TEXT,
created_at TEXT
)
);
CREATE TABLE IF NOT EXISTS marker (
id INTEGER PRIMARY KEY AUTOINCREMENT
);
`);
}
// Sample data generated using AI, does not work yet and will be adjusted
export function insertSampleData(): void {
export function insertSampleData(db: DB): void {
db.query(
`INSERT INTO accounts (user_group, bio, displayname, username, user_email, password, password_salt, firstname, surname, account_created, blocked_users, followers, following, contacts) VALUES
('admin', 'Admin bio', 'Admin User', 'admin', 'admin@example.com', 'pw1', 'salt1', 'Admin', 'User', '2024-01-01', '[]', '[]', '[]', '[]'),

View File

@@ -77,48 +77,53 @@ export function queryDatabase<T>(
// +++ DATABASE INITIALIZATION -------------------------------------- //
export async function ensureDatabaseExists(): Promise<void> {
const dbDir = dirname(dbPath);
let dbInstance: DB | null = null; // Avoids hard to decode errors because it Throws one if it cant continue.
try {
// Check if the database directory exists, create it if not
const dbDir = dirname(dbPath);
try {
await Deno.stat(dbDir);
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
// Create the database directory
await Deno.mkdir(dbDir, { recursive: true });
if (error instanceof Deno.errors.NotFound) { // Deno.errors.NotFound is a type of error that is thrown when a file or directory is not found.
// In short, It's a type, and it makes sure that the "error" variable is of type Deno.errors.NotFound.
console.log(`Created database directory: ${dbDir}`);
} else {
throw error;
}
}
console.log(`Opening database connection: ${dbPath}`);
dbInstance = new DB(dbPath);
// Check if the database file exists
try {
await Deno.stat(dbPath);
console.log("Database file already exists");
dbInstance.query("SELECT 1 FROM marker LIMIT 1;");
console.log("Database already initialized (marker table found).");
} catch (error) {
if (error instanceof Deno.errors.NotFound) {
createDatabaseIfNotExist();
insertSamples();
// Nothing, file will be created below
if (error instanceof Error) {
console.log(
"Marker table not found or query failed. Initializing database tables.",
);
db_create.createDatabase(dbInstance);
db_create.insertSampleData(dbInstance);
console.log("Database initialization complete.");
} else {
throw error;
}
}
} catch (error) {
console.error("Error ensuring database exists:", error);
throw error;
console.error(
"Error during database existence check or initialization:",
error,
);
} finally {
if (dbInstance) {
dbInstance.close();
console.log("Database connection closed.");
} else {
console.log("Database connection was not opened.");
}
}
}
export function createDatabaseIfNotExist(): void {
db_create.createDatabase();
}
export function insertSamples(): void {
db_create.insertSampleData();
}
// +++ ACCOUNT FUNCTIONS -------------------------------------------- //
export const getAllUsersFromDB = () => getAllUsersFromDBInternal(db);
export const getUserByUsername = (username: string) =>

2
deno.lock generated
View File

@@ -6,6 +6,7 @@
"jsr:@std/bytes@1": "1.0.2",
"jsr:@std/bytes@^1.0.2": "1.0.2",
"jsr:@std/crypto@1": "1.0.3",
"jsr:@std/encoding@*": "1.0.5",
"jsr:@std/encoding@1": "1.0.5",
"jsr:@std/encoding@^1.0.5": "1.0.5",
"jsr:@std/http@1": "1.0.9",
@@ -1267,6 +1268,7 @@
"remote": {
"https://deno.land/std@0.224.0/assert/assert.ts": "09d30564c09de846855b7b071e62b5974b001bb72a4b797958fe0660e7849834",
"https://deno.land/std@0.224.0/assert/assertion_error.ts": "ba8752bd27ebc51f723702fac2f54d3e94447598f54264a6653d6413738a8917",
"https://deno.land/std@0.224.0/fs/exists.ts": "3d38cb7dcbca3cf313be343a7b8af18a87bddb4b5ca1bd2314be12d06533b50f",
"https://deno.land/std@0.224.0/path/_common/assert_path.ts": "dbdd757a465b690b2cc72fc5fb7698c51507dec6bfafce4ca500c46b76ff7bd8",
"https://deno.land/std@0.224.0/path/_common/basename.ts": "569744855bc8445f3a56087fd2aed56bdad39da971a8d92b138c9913aecc5fa2",
"https://deno.land/std@0.224.0/path/_common/common.ts": "ef73c2860694775fe8ffcbcdd387f9f97c7a656febf0daa8c73b56f4d8a7bd4c",