update mariadb

This commit is contained in:
2026-03-01 14:42:49 +09:00
parent aa6667235a
commit c0b3598f88
4 changed files with 152 additions and 51 deletions

100
server.js
View File

@@ -1,10 +1,7 @@
import express from 'express';
import sqlite3 from 'sqlite3';
import mysql from 'mysql2/promise';
import cors from 'cors';
import { open } from 'sqlite';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
@@ -19,54 +16,56 @@ app.use(cors());
app.use(express.json());
// Database setup
let db;
let pool;
async function initializeDB() {
const dbDir = path.join(__dirname, 'db');
if (!fs.existsSync(dbDir)) {
fs.mkdirSync(dbDir, { recursive: true });
const dbConfig = {
host: process.env.DB_HOST || 'truenas.site',
user: process.env.DB_USER || 'wifi',
password: process.env.DB_PASSWORD || 'wifi12345',
database: process.env.DB_NAME || 'wifishare',
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
};
try {
pool = mysql.createPool(dbConfig);
// Create table (MariaDB/MySQL syntax)
await pool.query(`
CREATE TABLE IF NOT EXISTS markers (
id VARCHAR(50) PRIMARY KEY,
name VARCHAR(255) NOT NULL,
ssid VARCHAR(255) NOT NULL,
password VARCHAR(255),
lat DOUBLE NOT NULL,
lng DOUBLE NOT NULL,
securityType VARCHAR(50) NOT NULL,
iconType VARCHAR(50) NOT NULL,
description TEXT,
addedBy VARCHAR(100),
createdAt BIGINT,
isPublic TINYINT DEFAULT 1
)
`);
console.log(`[DB] MariaDB connected to ${dbConfig.host}/${dbConfig.database}`);
const [rows] = await pool.query('SELECT COUNT(*) as count FROM markers');
console.log(`[DB] Current Status: ${rows[0].count} markers stored in database.`);
} catch (error) {
console.error('[DB] MariaDB connection failed:', error.message);
process.exit(1);
}
const dbPath = path.join(dbDir, 'wifi_markers.db');
db = await open({
filename: dbPath,
driver: sqlite3.Database
});
// Enable WAL mode for concurrency
await db.exec('PRAGMA journal_mode = WAL;');
// Create table
await db.exec(`
CREATE TABLE IF NOT EXISTS markers (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
ssid TEXT NOT NULL,
password TEXT,
lat REAL NOT NULL,
lng REAL NOT NULL,
securityType TEXT NOT NULL,
iconType TEXT NOT NULL,
description TEXT,
addedBy TEXT,
createdAt INTEGER,
isPublic INTEGER DEFAULT 1
)
`);
console.log(`[DB] Database initialized at: ${dbPath}`);
console.log('[DB] WAL mode enabled for concurrent writes.');
const count = await db.get('SELECT COUNT(*) as count FROM markers');
console.log(`[DB] Current Status: ${count.count} markers stored in database.`);
}
// Routes
app.get('/api/markers', async (req, res) => {
const host = req.headers.host;
if (isDebug) console.log(`[API] GET /api/markers - Host: ${host} - Fetching from SQLite`);
if (isDebug) console.log(`[API] GET /api/markers - Host: ${host} - Fetching from MariaDB`);
try {
const markers = await db.all('SELECT * FROM markers');
const [markers] = await pool.query('SELECT * FROM markers');
if (isDebug) console.log(`[API] Found ${markers.length} markers`);
// Convert isPublic from 0/1 to boolean
const formattedMarkers = markers.map(m => ({
@@ -82,12 +81,17 @@ app.get('/api/markers', async (req, res) => {
app.post('/api/markers', async (req, res) => {
const { id, name, ssid, password, lat, lng, securityType, iconType, description, addedBy, createdAt, isPublic } = req.body;
if (isDebug) console.log(`[API] POST /api/markers - Saving marker: ${name} (${ssid}) to SQLite`);
if (isDebug) console.log(`[API] POST /api/markers - Saving marker: ${name} (${ssid}) to MariaDB`);
try {
await db.run(`
INSERT OR REPLACE INTO markers (id, name, ssid, password, lat, lng, securityType, iconType, description, addedBy, createdAt, isPublic)
await pool.query(`
INSERT INTO markers (id, name, ssid, password, lat, lng, securityType, iconType, description, addedBy, createdAt, isPublic)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
name=VALUES(name), ssid=VALUES(ssid), password=VALUES(password),
lat=VALUES(lat), lng=VALUES(lng), securityType=VALUES(securityType),
iconType=VALUES(iconType), description=VALUES(description),
addedBy=VALUES(addedBy), createdAt=VALUES(createdAt), isPublic=VALUES(isPublic)
`, [id, name, ssid, password, lat, lng, securityType, iconType, description || '', addedBy, createdAt, isPublic ? 1 : 0]);
if (isDebug) console.log(`[API] Successfully saved marker: ${id}`);
@@ -100,9 +104,9 @@ app.post('/api/markers', async (req, res) => {
app.delete('/api/markers/:id', async (req, res) => {
const { id } = req.params;
if (isDebug) console.log(`[API] DELETE /api/markers/${id} - Deleting marker from SQLite`);
if (isDebug) console.log(`[API] DELETE /api/markers/${id} - Deleting marker from MariaDB`);
try {
await db.run('DELETE FROM markers WHERE id = ?', [id]);
await pool.query('DELETE FROM markers WHERE id = ?', [id]);
if (isDebug) console.log(`[API] Successfully deleted marker: ${id}`);
res.json({ success: true });
} catch (error) {