80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import { pgTable, timestamp, integer, jsonb, uuid } from 'drizzle-orm/pg-core';
|
|
import { InferModel } from 'drizzle-orm';
|
|
import { sql } from 'drizzle-orm';
|
|
import { drizzle } from 'drizzle-orm/node-postgres';
|
|
import { Pool } from 'pg';
|
|
|
|
// Definiere den benutzerdefinierten Typ für das JSON-Objekt
|
|
type BusinessData = {
|
|
id?: string;
|
|
firstname: string;
|
|
lastname: string;
|
|
email: string;
|
|
phoneNumber: string;
|
|
companyLocation: string;
|
|
hasCompanyLogo: boolean;
|
|
hasProfile: boolean;
|
|
};
|
|
|
|
// Definiere die Tabelle "businesses"
|
|
const businesses = pgTable('businesses', {
|
|
id: uuid('id').primaryKey(),
|
|
created: timestamp('created'),
|
|
updated: timestamp('updated'),
|
|
visits: integer('visits'),
|
|
lastVisit: timestamp('last_visit'),
|
|
data: jsonb('data'),
|
|
});
|
|
|
|
// Definiere den Typ für das Modell
|
|
type Business = InferModel<typeof businesses, 'select'>;
|
|
|
|
// Erstelle eine Verbindung zur Datenbank
|
|
const pool = new Pool({
|
|
// Konfiguriere die Verbindungsoptionen
|
|
});
|
|
|
|
const db = drizzle(pool);
|
|
|
|
// Beispiel für das Einfügen eines neuen Datensatzes
|
|
const insertBusiness = async () => {
|
|
const businessData: BusinessData = {
|
|
firstname: 'Robert',
|
|
lastname: 'Jackson',
|
|
email: 'robert.jackson@texasbizbrokers.com',
|
|
phoneNumber: '(214) 555-7890',
|
|
companyLocation: 'Dallas - TX',
|
|
hasCompanyLogo: true,
|
|
hasProfile: true,
|
|
};
|
|
|
|
const [insertedBusiness] = await db
|
|
.with({
|
|
new_business: sql<{ generated_id: string; created: Date; updated: Date; visits: number; last_visit: Date; data: BusinessData }>`(${(qb) => {
|
|
return qb
|
|
.select({
|
|
generated_id: sql`uuid_generate_v4()`,
|
|
created: sql`NOW()`,
|
|
updated: sql`NOW()`,
|
|
visits: sql`0`,
|
|
last_visit: sql`NOW()`,
|
|
data: sql`jsonb_set(${JSON.stringify(businessData)}::jsonb, '{id}', to_jsonb(uuid_generate_v4()))`,
|
|
});
|
|
}})`
|
|
})
|
|
.insert(businesses)
|
|
.values((eb) => ({
|
|
id: eb.generated_id,
|
|
created: eb.created,
|
|
updated: eb.updated,
|
|
visits: eb.visits,
|
|
lastVisit: eb.last_visit,
|
|
data: sql`jsonb_set(${eb.data}::jsonb, '{id}', to_jsonb(${eb.generated_id}))`,
|
|
}))
|
|
.returning({ generatedId: businesses.id, jsonData: businesses.data });
|
|
|
|
console.log('Generated ID:', insertedBusiness.generatedId);
|
|
console.log('JSON Data:', insertedBusiness.jsonData);
|
|
};
|
|
|
|
insertBusiness(); |