To import data from CSV files into a PostgreSQL database using Prisma and TypeScript, you can follow these steps:
- Set up Prisma Client: Make sure you have Prisma set up in your project.
- Read the CSV files: Use a library like
csv-parser or fast-csv to read the CSV files.
- Map CSV data to Prisma models: Process the CSV data and map it to the related Prisma models.
- Insert data into the database: Use the Prisma Client to insert the mapped data into the database.
Below is a sample implementation using csv-parser for handling the CSV files:
import fs from 'fs';
import csv from 'csv-parser';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
interface EventCSV {
Name: string;
Year: string;
Drive: string;
}
interface CompanyCSV {
'Company Name': string;
Category: string;
Description: string;
'Contact Name': string;
'Contact Email': string;
'Contact Phone': string;
'Contact LinkedIn': string;
'Contact Facebook': string;
'Contact Role': string;
'Contact IsActive': string;
'Contact IsPrimary': string;
'Contact Notes': string;
}
interface ContractCSV {
'Company Name': string;
'Event Name': string;
'Event Year': string;
Status: string;
Notes: string;
}
async function importData(userId: string) {
const events: EventCSV[] = [];
const companies: CompanyCSV[] = [];
const contracts: ContractCSV[] = [];
// Read events.csv
const readEvents = new Promise<void>((resolve, reject) => {
fs.createReadStream('events.csv')
.pipe(csv())
.on('data', (data: EventCSV) => events.push(data))
.on('end', resolve)
.on('error', reject);
});
// Read companies.csv
const readCompanies = new Promise<void>((resolve, reject) => {
fs.createReadStream('companies.csv')
.pipe(csv())
.on('data', (data: CompanyCSV) => companies.push(data))
.on('end', resolve)
.on('error', reject);
});
// Read contracts.csv
const readContracts = new Promise<void>((resolve, reject) => {
fs.createReadStream('contracts.csv')
.pipe(csv())
.on('data', (data: ContractCSV) => contracts.push(data))
.on('end', resolve)
.on('error', reject);
});
await Promise.all([readEvents, readCompanies, readContracts]);
// Insert companies and networks
for (const companyData of companies) {
const createdCompany = await prisma.company.create({
data: {
name: companyData['Company Name'],
category: companyData.Category,
description: companyData.Description,
networks: {
create: {
name: companyData['Contact Name'],
email: companyData['Contact Email'],
phone: companyData['Contact Phone'],
linkedIn: companyData['Contact LinkedIn'],
facebook: companyData['Contact Facebook'],
role: companyData['Contact Role'],
isActive: companyData['Contact IsActive'] === 'true',
isPrimary: companyData['Contact IsPrimary'] === 'true',
notes: companyData['Contact Notes'],
},
},
},
});
}
// Insert events
for (const eventData of events) {
await prisma.event.create({
data: {
name: eventData.Name,
year: eventData.Year,
drive: eventData.Drive,
mdID: userId, // Assuming MD (Manager Director) is provided as userId
// Add any other necessary default or required fields
},
});
}
// Insert contracts
for (const contractData of contracts) {
const event = await prisma.event.findFirst({
where: {
name: contractData['Event Name'],
year: contractData['Event Year'],
},
});
const company = await prisma.company.findFirst({
where: {
name: contractData['Company Name'],
},
});
if (event && company) {
await prisma.contract.create({
data: {
eventID: event.id,
companyID: company.id,
userID: userId, // Assuming userID is provided
status: contractData.Status as any, // Type cast to Status enum
notes: contractData.Notes,
},
});
}
}
console.log('Data imported successfully');
}
// Usage
const userId = 'your-user-id-here'; // You should replace this with the real user ID
importData(userId)
.then(() => {
console.log('Import completed');
prisma.$disconnect();
})
.catch((err) => {
console.error('Error importing data:', err);
prisma.$disconnect();
});
Key Points:
- Reading CSV Files: Using the
csv-parser package to read and parse the CSV files.
- Mapping CSV Data: Creating interfaces to type the CSV data and then reading the data into arrays.
- Inserting Data with Prisma: Using the Prisma Client to create instances of
Company, Network, Event, and Contract and establish the relationships as per your schema.
Assumptions:
- You have Prisma set up and have the necessary models in your
schema.prisma file.
- Your database connection is correctly configured.
- User ID is provided and valid, as needed for certain entries in the database.
Make sure to handle potential errors and edge cases to make this script suitable for production. For example, checks for duplicates, validation of data, handling missing or incorrect fields, etc.