@duongital

WordPress works with Prisma

Step 1: Steup project

Start a new NodeJS project using Typescript:

{
  "name": "mysql_prisma",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^22.15.3",
    "prisma": "^6.7.0",
    "tsx": "^4.19.4",
    "typescript": "^5.8.3"
  },
  "dependencies": {
    "@prisma/client": "^6.7.0"
  }
}

Create .env file in the project to add a environment variable name: DATABASE_URL

// find this info in file explore: public_html/wpconfig.php
DATABASE_URL="mysql://user:password@host:3306/dbname

Create a new file prisma/schema.prisma in the root folder, then add initial content:

generator client {
  provider = "prisma-client-js"
  output   = "../generated/prisma"
}

datasource db {
  provider = "mysql"
  url      = env("DATABASE_URL")
}

Then turn on remote access from your IP address or any where:

Step 2: work with CLI tool

Pull the database from remote server: npx drizzle-kit pull

❯ npx prisma db pull
Prisma schema loaded from prisma/schema.prisma
Environment variables loaded from .env
Datasource "db": MySQL database "u690039970_ILJ5d" at "srv594.hstgr.io:3306"

✔ Introspected 14 models and wrote them into prisma/schema.prisma in 1.42s
      
*** WARNING ***

These objects have comments defined in the database, which is not yet fully supported. Read more: https://pris.ly/d/database-comments
  - Type: "field", name: "wp_litespeed_url_file.vary"
  - Type: "field", name: "wp_litespeed_url_file.filename"
  - Type: "field", name: "wp_litespeed_url_file.type"
  - Type: "field", name: "wp_litespeed_url_file.mobile"
  - Type: "field", name: "wp_litespeed_url_file.webp"

Run prisma generate to generate Prisma Client.

Optional to add or edit the current schema:

  • Add new schema or edit the file schema.ts
  • Push the database on remote server: npx drizzle-kit push

(there might be some errors and resolve that).

Generate and create a client from local: npx drizzle-kit generate.

Then we need to create a script.ts file:

import { PrismaClient } from "./generated/prisma";

const prisma = new PrismaClient();

async function main() {
  // ... you will write your Prisma Client queries here
  const user = await prisma.wp_posts.findMany({
    where: {
      ID: 1,
    },
  });
  console.log(user);
}

main()
  .then(async () => {
    await prisma.$disconnect();
  })
  .catch(async (e) => {
    console.error(e);
    await prisma.$disconnect();
    process.exit(1);
  });

Step 3: execute the application

Run your command with npx tsx script.ts