diff --git a/pages/api/data/prisma/[...model].ts b/pages/api/data/prisma/[...model].ts index 97c1687..ba5ba99 100644 --- a/pages/api/data/prisma/[...model].ts +++ b/pages/api/data/prisma/[...model].ts @@ -17,6 +17,37 @@ const parseQueryParams = (query: any) => { }; }; + +// Helper function to escape and quote strings, handle nulls and other types +const serializeValue = (value) => { + if (value === null || value === undefined) { + return 'NULL'; + } + if (typeof value === 'string') { + return `'${value.replace(/'/g, "''")}'`; // escape single quotes in SQL string + } + if (typeof value === 'boolean') { + return value ? 'true' : 'false'; + } + if (typeof value === 'number') { + return value; + } + if (Array.isArray(value) || typeof value === 'object') { + // Convert arrays and objects to JSON strings and escape them + return `'${JSON.stringify(value).replace(/'/g, "''")}'`; + } + return value; +}; + +// Function to generate SQL INSERT statements from data +const generateSQL = (data, tableName) => { + return data.map(item => { + const columns = Object.keys(item).join(", "); + const values = Object.values(item).map(serializeValue).join(", "); + return `INSERT INTO ${tableName} (${columns}) VALUES (${values});`; + }).join("\n"); +}; + export default async function handler(req: NextApiRequest, res: NextApiResponse) { const prisma: PrismaClient = common.getPrismaClient(); const modelArray = (req.query.model || (req.body && req.body.model)) as string[]; @@ -39,7 +70,15 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse) throw new Error(`Model ${modelName} not found in Prisma client.`); } const result = await prisma[modelName].findMany(queryOptions); - res.status(200).json(result); + if (req.query.format === 'sql') { + // Generate SQL if requested via query parameter + const sql = generateSQL(result, modelName); + res.setHeader('Content-Type', 'application/sql'); + res.send(sql); + } else { + // Normal JSON response + res.status(200).json(result); + } } catch (error) { console.error(error); res.status(500).json({ error: error.message });