implement SQL export in prisma api
This commit is contained in:
@ -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 });
|
||||
|
Reference in New Issue
Block a user