Skip to content

Instantly share code, notes, and snippets.

@mingderwang
Created August 10, 2025 01:35
Show Gist options
  • Save mingderwang/80a4b7eec26d717500ea0812bc343aa9 to your computer and use it in GitHub Desktop.
Save mingderwang/80a4b7eec26d717500ea0812bc343aa9 to your computer and use it in GitHub Desktop.
.env -> DATABASE_URL='postgresql://neondb_owner:[email protected]/neondb?sslmode=require&channel_binding=require'
import { Kysely, Generated } from 'kysely';
import { NeonDialect } from 'kysely-neon';
import ws from 'ws';
import * as dotenv from 'dotenv';
dotenv.config();
// Define database interface
interface Database {
contacts: ContactTable;
}
interface ContactTable {
id: Generated<number>;
name: string;
email: string;
}
// Initialize Kysely with Neon dialect
const db = new Kysely<Database>({
dialect: new NeonDialect({
connectionString: process.env.DATABASE_URL!,
webSocketConstructor: ws,
}),
});
// Create contacts table
async function createTable() {
await db.schema
.createTable('contacts')
.ifNotExists()
.addColumn('id', 'serial', (col) => col.primaryKey())
.addColumn('name', 'text', (col) => col.notNull())
.addColumn('email', 'text', (col) => col.notNull())
.execute();
console.log('Table created');
}
// Insert a contact
async function insertContact() {
await db
.insertInto('contacts')
.values({ name: 'John Doe', email: '[email protected]' })
.execute();
console.log('Contact inserted');
}
// Read all contacts
async function getContacts() {
const contacts = await db.selectFrom('contacts').selectAll().execute();
console.log('Contacts:', contacts);
}
// Main function to run operations
async function main() {
await createTable();
await insertContact();
await getContacts();
}
main().catch((err) => {
console.error('Error:', err);
process.exit(1);
});%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment