Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: moved the client ui db to sqlite (#84)

Aman Agarwal55caa297378d
diff --git a/src/client/.gitignore b/src/client/.gitignore
index b9f8d23e..35ef117a 100644
--- a/src/client/.gitignore
+++ b/src/client/.gitignore
@@ -35,4 +35,7 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
-.env
\ No newline at end of file
+.env
+
+#data
+/db-data
\ No newline at end of file
diff --git a/src/client/README.md b/src/client/README.md
index aa548dec..884cd776 100644
--- a/src/client/README.md
+++ b/src/client/README.md
@@ -14,7 +14,7 @@ Doku Client frontend uses Nextjs, Typescript and Tailwind. The application uses
### Pre-requisites:
- `node` : version >=20
-- `postgres` : db for the doku client's storage (this comes under docker compose but if you setup without docker, then you need postgres db url to be set in env variable)
+- `sqlite` : db for the doku client's storage (this will come under docker compose with persistent volumne but if you setup without docker, then you need provide file url as env variable like `file:/path/to/file`)
### The first step : Setup server without docker
1. Clone the doku repository
@@ -29,11 +29,11 @@ Doku Client frontend uses Nextjs, Typescript and Tailwind. The application uses
```sh
npm install
````
-4. Run command below to create an env file and then update the .env file for the `DATABASE_URL` to point to the postgres db
+4. Run command below to create an env file and then update the .env file for the `DATABASE_URL` to point to the sqlite db
```sh
cp .env.example .env
````
-5. Apply the migrations to the postgres db using the below commands. First command applies the migrations to the db and the second command generates assets like Prisma Client based on the generator and data model blocks defined in your prisma/schema.prisma file.
+5. Apply the migrations to the sqlite db using the below commands. First command applies the migrations to the db and the second command generates assets like Prisma Client based on the generator and data model blocks defined in your prisma/schema.prisma file.
```sh
npx prisma migrate deploy
npx prisma generate
diff --git a/src/client/prisma/migrations/0_init/migration.sql b/src/client/prisma/migrations/0_init/migration.sql
index 4895924b..92afe40a 100644
--- a/src/client/prisma/migrations/0_init/migration.sql
+++ b/src/client/prisma/migrations/0_init/migration.sql
@@ -1,6 +1,6 @@
-- CreateTable
CREATE TABLE "accounts" (
- "id" TEXT NOT NULL,
+ "id" TEXT NOT NULL PRIMARY KEY,
"user_id" TEXT NOT NULL,
"type" TEXT,
"provider" TEXT NOT NULL,
@@ -11,49 +11,43 @@ CREATE TABLE "accounts" (
"expires_at" INTEGER,
"scope" TEXT,
"id_token" TEXT,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "accounts_pkey" PRIMARY KEY ("id")
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "sessions" (
- "id" TEXT NOT NULL,
+ "id" TEXT NOT NULL PRIMARY KEY,
"user_id" TEXT,
"session_token" TEXT NOT NULL,
"access_token" TEXT,
- "expires" TIMESTAMP(3) NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "sessions_pkey" PRIMARY KEY ("id")
+ "expires" DATETIME NOT NULL,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE
);
-- CreateTable
CREATE TABLE "users" (
- "id" TEXT NOT NULL,
+ "id" TEXT NOT NULL PRIMARY KEY,
"name" TEXT,
"email" TEXT NOT NULL,
- "email_verified" TIMESTAMP(3),
+ "email_verified" DATETIME,
"password" TEXT,
"image" TEXT,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "users_pkey" PRIMARY KEY ("id")
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL
);
-- CreateTable
-CREATE TABLE "VerificationRequest" (
- "id" TEXT NOT NULL,
+CREATE TABLE "verificationrequest" (
+ "id" TEXT NOT NULL PRIMARY KEY,
"identifier" TEXT NOT NULL,
"token" TEXT NOT NULL,
- "expires" TIMESTAMP(3) NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "VerificationRequest_pkey" PRIMARY KEY ("id")
+ "expires" DATETIME NOT NULL,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL
);
-- CreateIndex
@@ -66,14 +60,7 @@ CREATE UNIQUE INDEX "sessions_session_token_key" ON "sessions"("session_token");
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
-- CreateIndex
-CREATE UNIQUE INDEX "VerificationRequest_token_key" ON "VerificationRequest"("token");
+CREATE UNIQUE INDEX "verificationrequest_token_key" ON "verificationrequest"("token");
-- CreateIndex
-CREATE UNIQUE INDEX "VerificationRequest_identifier_token_key" ON "VerificationRequest"("identifier", "token");
-
--- AddForeignKey
-ALTER TABLE "accounts" ADD CONSTRAINT "accounts_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
-
+CREATE UNIQUE INDEX "verificationrequest_identifier_token_key" ON "verificationrequest"("identifier", "token");
diff --git a/src/client/prisma/migrations/20240227112228_database_config/migration.sql b/src/client/prisma/migrations/20240227112228_database_config/migration.sql
deleted file mode 100644
index 5e6b48b1..00000000
--- a/src/client/prisma/migrations/20240227112228_database_config/migration.sql
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- Warnings:
-
- - You are about to drop the `VerificationRequest` table. If the table is not empty, all the data it contains will be lost.
-
-*/
--- DropTable
-DROP TABLE "VerificationRequest";
-
--- CreateTable
-CREATE TABLE "verificationrequest" (
- "id" TEXT NOT NULL,
- "identifier" TEXT NOT NULL,
- "token" TEXT NOT NULL,
- "expires" TIMESTAMP(3) NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
-
- CONSTRAINT "verificationrequest_pkey" PRIMARY KEY ("id")
-);
-
--- CreateTable
-CREATE TABLE "databaseconfig" (
- "id" TEXT NOT NULL,
- "name" TEXT NOT NULL,
- "environment" TEXT NOT NULL DEFAULT 'production',
- "meta" JSONB NOT NULL,
- "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
- "updatedAt" TIMESTAMP(3) NOT NULL,
- "user_id" TEXT NOT NULL,
-
- CONSTRAINT "databaseconfig_pkey" PRIMARY KEY ("id")
-);
-
--- CreateTable
-CREATE TABLE "databaseconfiguser" (
- "databaseConfigId" TEXT NOT NULL,
- "user_id" TEXT NOT NULL,
- "isCurrent" BOOLEAN NOT NULL DEFAULT false
-);
-
--- CreateIndex
-CREATE UNIQUE INDEX "verificationrequest_token_key" ON "verificationrequest"("token");
-
--- CreateIndex
-CREATE UNIQUE INDEX "verificationrequest_identifier_token_key" ON "verificationrequest"("identifier", "token");
-
--- CreateIndex
-CREATE UNIQUE INDEX "databaseconfig_name_key" ON "databaseconfig"("name");
-
--- CreateIndex
-CREATE UNIQUE INDEX "databaseconfiguser_databaseConfigId_user_id_key" ON "databaseconfiguser"("databaseConfigId", "user_id");
-
--- AddForeignKey
-ALTER TABLE "databaseconfig" ADD CONSTRAINT "databaseconfig_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "databaseconfiguser" ADD CONSTRAINT "databaseconfiguser_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-
--- AddForeignKey
-ALTER TABLE "databaseconfiguser" ADD CONSTRAINT "databaseconfiguser_databaseConfigId_fkey" FOREIGN KEY ("databaseConfigId") REFERENCES "databaseconfig"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
diff --git a/src/client/prisma/migrations/20240303191212_database_config/migration.sql b/src/client/prisma/migrations/20240303191212_database_config/migration.sql
new file mode 100644
index 00000000..9c9eb2cf
--- /dev/null
+++ b/src/client/prisma/migrations/20240303191212_database_config/migration.sql
@@ -0,0 +1,31 @@
+-- CreateTable
+CREATE TABLE "databaseconfig" (
+ "id" TEXT NOT NULL PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "environment" TEXT NOT NULL DEFAULT 'production',
+ "username" TEXT NOT NULL DEFAULT 'admin',
+ "password" TEXT,
+ "host" TEXT NOT NULL DEFAULT '127.0.0.1',
+ "port" TEXT NOT NULL DEFAULT '8123',
+ "database" TEXT NOT NULL DEFAULT 'doku',
+ "query" TEXT,
+ "createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" DATETIME NOT NULL,
+ "user_id" TEXT NOT NULL,
+ CONSTRAINT "databaseconfig_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateTable
+CREATE TABLE "databaseconfiguser" (
+ "databaseConfigId" TEXT NOT NULL,
+ "user_id" TEXT NOT NULL,
+ "isCurrent" BOOLEAN NOT NULL DEFAULT false,
+ CONSTRAINT "databaseconfiguser_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "databaseconfiguser_databaseConfigId_fkey" FOREIGN KEY ("databaseConfigId") REFERENCES "databaseconfig" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+-- CreateIndex
+CREATE UNIQUE INDEX "databaseconfig_name_key" ON "databaseconfig"("name");
+
+-- CreateIndex
+CREATE UNIQUE INDEX "databaseconfiguser_databaseConfigId_user_id_key" ON "databaseconfiguser"("databaseConfigId", "user_id");
diff --git a/src/client/prisma/migrations/migration_lock.toml b/src/client/prisma/migrations/migration_lock.toml
index fbffa92c..e5e5c470 100644
--- a/src/client/prisma/migrations/migration_lock.toml
+++ b/src/client/prisma/migrations/migration_lock.toml
@@ -1,3 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
-provider = "postgresql"
\ No newline at end of file
+provider = "sqlite"
\ No newline at end of file
diff --git a/src/client/prisma/schema.prisma b/src/client/prisma/schema.prisma
index 93722325..342ca128 100644
--- a/src/client/prisma/schema.prisma
+++ b/src/client/prisma/schema.prisma
@@ -4,7 +4,7 @@ generator client {
}
datasource db {
- provider = "postgresql"
+ provider = "sqlite"
url = env("DATABASE_URL")
}
@@ -15,11 +15,11 @@ model Account {
provider String
providerAccountId String @map("provider_account_id")
token_type String?
- refresh_token String? @db.Text
- access_token String? @db.Text
+ refresh_token String?
+ access_token String?
expires_at Int?
scope String?
- id_token String? @db.Text
+ id_token String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
@@ -31,8 +31,8 @@ model Account {
model Session {
id String @id @default(cuid())
userId String? @map("user_id")
- sessionToken String @unique @map("session_token") @db.Text
- accessToken String? @map("access_token") @db.Text
+ sessionToken String @unique @map("session_token")
+ accessToken String? @map("access_token")
expires DateTime
user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
createdAt DateTime @default(now())
@@ -75,7 +75,12 @@ model DatabaseConfig {
id String @id @default(cuid())
name String
environment String @default("production")
- meta Json
+ username String @default("admin")
+ password String?
+ host String @default("127.0.0.1")
+ port String @default("8123")
+ database String @default("doku")
+ query String?
dbUsers DatabaseConfigUser[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
diff --git a/src/client/src/app/(playground)/settings/database.tsx b/src/client/src/app/(playground)/settings/database.tsx
index aec97bc9..9e6e1953 100644
--- a/src/client/src/app/(playground)/settings/database.tsx
+++ b/src/client/src/app/(playground)/settings/database.tsx
@@ -1,8 +1,7 @@
+import FormBuilder from "@/components/common/form-builder";
import SideTabs, { SideTabItemProps } from "@/components/common/side-tabs";
-import { DB_META_KEYS } from "@/constants/dbConfig";
+import { DatabaseConfig } from "@/constants/dbConfig";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
-import { noop } from "@/utils/noop";
-import { CheckIcon, TrashIcon } from "@heroicons/react/24/outline";
import { keyBy } from "lodash";
import {
FormEventHandler,
@@ -13,11 +12,7 @@ import {
} from "react";
import toast from "react-hot-toast";
-type DBConfig = {
- id: string;
- name: string;
- environment: string;
- meta: Record<string, any>;
+type DBConfig = DatabaseConfig & {
isCurrent?: boolean;
};
@@ -42,11 +37,14 @@ function ModifyDatabaseConfig({
fireRequest({
body: JSON.stringify({
id: dbConfig?.id,
- name: (formElement.name as any)?.value,
- environment: (formElement.environment as any)?.value,
- meta: {
- [DB_META_KEYS.url]: (formElement[DB_META_KEYS.url] as any)?.value,
- },
+ name: (formElement.name as any).value,
+ environment: formElement.environment.value,
+ username: formElement.username.value,
+ password: formElement.username.password || "",
+ host: formElement.host.value,
+ port: formElement.port.value,
+ database: formElement.database.value,
+ query: formElement.query.value,
}),
requestType: "POST",
url: "/api/db-config",
@@ -69,93 +67,77 @@ function ModifyDatabaseConfig({
);
return (
- <form
- className="flex flex-col w-full"
- onSubmit={isLoading ? noop : modifyDetails}
- >
- <div className="flex flex-col relative flex-1 overflow-y-auto px-5 py-3">
- <h2 className="text-base font-semibold text-tertiary sticky top-0 bg-white">
- {dbConfig?.id ? "Update" : "Add"} database config
- </h2>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="name"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Config Name
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key={`${dbConfig?.id}-name`}
- type="text"
- name="name"
- id="name"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="db-config"
- defaultValue={dbConfig?.name}
- />
- </div>
- </div>
- </div>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="environment"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Environment
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key={`${dbConfig?.id}-environment`}
- type="text"
- name="environment"
- id="environment"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="production"
- defaultValue={dbConfig?.environment}
- />
- </div>
- </div>
- </div>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor={DB_META_KEYS.url}
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Clickhouse Database url
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key={`${dbConfig?.id}-${DB_META_KEYS.url}`}
- type="text"
- name={DB_META_KEYS.url}
- id={DB_META_KEYS.url}
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="clickhouse://<user>:<password>@<host>:<port>/<database>[? key=value..]"
- defaultValue={dbConfig?.meta[DB_META_KEYS.url]}
- />
- </div>
- </div>
- </div>
- </div>
-
- <div className="mt-6 flex items-center justify-end border-t border-secondary w-full py-2 gap-3">
- <button
- type="submit"
- className={`rounded-sm bg-primary/[0.9] px-5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-primary focus-visible:outline ${
- isLoading ? "animate-pulse" : ""
- }`}
- >
- {dbConfig?.id ? "Update" : "Save"}
- </button>
- </div>
- </form>
+ <FormBuilder
+ fields={[
+ {
+ label: "Config Name",
+ type: "text",
+ name: "name",
+ placeholder: "db-config",
+ defaultValue: dbConfig?.name,
+ inputKey: `${dbConfig?.id}-name`,
+ },
+ {
+ label: "Environment",
+ type: "text",
+ name: "environment",
+ placeholder: "production",
+ defaultValue: dbConfig?.environment,
+ inputKey: `${dbConfig?.id}-environment`,
+ },
+ {
+ label: "Username",
+ type: "text",
+ name: "username",
+ placeholder: "username",
+ defaultValue: dbConfig?.username,
+ inputKey: `${dbConfig?.id}-username`,
+ },
+ {
+ label: "Password",
+ type: "password",
+ name: "password",
+ placeholder: "*******",
+ inputKey: `${dbConfig?.id}-password`,
+ },
+ {
+ label: "Host",
+ type: "text",
+ name: "host",
+ placeholder: "127.0.0.1",
+ defaultValue: dbConfig?.host,
+ inputKey: `${dbConfig?.id}-host`,
+ },
+ {
+ label: "Port",
+ type: "number",
+ name: "port",
+ placeholder: "8123",
+ defaultValue: dbConfig?.port,
+ inputKey: `${dbConfig?.id}-port`,
+ },
+ {
+ label: "Database",
+ type: "text",
+ name: "database",
+ placeholder: "doku",
+ defaultValue: dbConfig?.database,
+ inputKey: `${dbConfig?.id}-database`,
+ },
+ {
+ label: "Query params",
+ type: "text",
+ name: "query",
+ placeholder: "a=b&c=d",
+ defaultValue: dbConfig?.query,
+ inputKey: `${dbConfig?.id}-query`,
+ },
+ ]}
+ heading={`${dbConfig?.id ? "Update" : "Add"} database config`}
+ isLoading={isLoading}
+ onSubmit={modifyDetails}
+ submitButtonText={dbConfig?.id ? "Update" : "Save"}
+ />
);
}
diff --git a/src/client/src/app/(playground)/settings/profile.tsx b/src/client/src/app/(playground)/settings/profile.tsx
index db25b3e6..92cde209 100644
--- a/src/client/src/app/(playground)/settings/profile.tsx
+++ b/src/client/src/app/(playground)/settings/profile.tsx
@@ -1,13 +1,37 @@
+import FormBuilder from "@/components/common/form-builder";
import SideTabs, { SideTabItemProps } from "@/components/common/side-tabs";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
-import { noop } from "@/utils/noop";
-import { FormEventHandler, MouseEventHandler, useState } from "react";
+import { User } from "@prisma/client";
+import {
+ FormEventHandler,
+ MouseEventHandler,
+ useEffect,
+ useState,
+} from "react";
import toast from "react-hot-toast";
const PROFILE_TOAST_ID = "profile-details";
function ModifyProfileDetails() {
- const { error, fireRequest, isLoading } = useFetchWrapper();
+ const { data: user, fireRequest: getUser } = useFetchWrapper();
+ const { fireRequest, isLoading } = useFetchWrapper();
+
+ const fetchUser = () => {
+ getUser({
+ requestType: "GET",
+ url: "/api/user/profile",
+ responseDataKey: "data",
+ failureCb: (err?: string) => {
+ toast.error(err || "Unauthorized access!", {
+ id: PROFILE_TOAST_ID,
+ });
+ },
+ });
+ };
+
+ useEffect(() => {
+ fetchUser();
+ }, []);
const modifyDetails: FormEventHandler<HTMLFormElement> = (event) => {
event.preventDefault();
@@ -42,6 +66,7 @@ function ModifyProfileDetails() {
id: PROFILE_TOAST_ID,
});
formElement.reset();
+ fetchUser();
},
failureCb: (err?: string) => {
toast.error(err || "Profile details updation failed!", {
@@ -51,113 +76,46 @@ function ModifyProfileDetails() {
});
};
- return (
- <form
- className="flex flex-col w-full"
- onSubmit={isLoading ? noop : modifyDetails}
- >
- <div className="flex flex-col relative flex-1 overflow-y-auto px-5 py-3">
- <h2 className="text-base font-semibold text-tertiary sticky top-0 bg-white">
- Update profile details
- </h2>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="name"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Profile Name
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key="name"
- type="text"
- name="name"
- id="name"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="profile name"
- defaultValue=""
- />
- </div>
- </div>
- </div>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="currentPassword"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Current Password
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key="currentPassword"
- type="password"
- name="currentPassword"
- id="currentPassword"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="********"
- />
- </div>
- </div>
- </div>
-
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="newPassword"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- New Password
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key="newPassword"
- type="password"
- name="newPassword"
- id="newPassword"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="********"
- />
- </div>
- </div>
- </div>
+ const updatedUser = user as User;
- <div className="flex flex-col mt-6 w-full">
- <div className="flex flex-1 items-center">
- <label
- htmlFor="confirmNewPassword"
- className="text-tertiary/[0.8] text-sm font-normal w-1/5"
- >
- Confirm New Password
- </label>
- <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
- <input
- key="confirmNewPassword"
- type="password"
- name="confirmNewPassword"
- id="confirmNewPassword"
- className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
- placeholder="********"
- />
- </div>
- </div>
- </div>
- </div>
-
- <div className="mt-6 flex items-center justify-end border-t border-secondary w-full py-2 gap-3">
- <button
- type="submit"
- className={`rounded-sm bg-primary/[0.9] px-5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-primary focus-visible:outline ${
- isLoading ? "animate-pulse" : ""
- }`}
- >
- Update
- </button>
- </div>
- </form>
+ return (
+ <FormBuilder
+ fields={[
+ {
+ label: "Profile Name",
+ type: "text",
+ name: "name",
+ placeholder: "db-config",
+ defaultValue: updatedUser?.name || "",
+ inputKey: `${updatedUser?.id}-name`,
+ },
+ {
+ label: "Current Password",
+ type: "password",
+ name: "currentPassword",
+ placeholder: "*******",
+ inputKey: `${updatedUser?.id}-currentPassword`,
+ },
+ {
+ label: "New Password",
+ type: "password",
+ name: "newPassword",
+ placeholder: "*******",
+ inputKey: `${updatedUser?.id}-newPassword`,
+ },
+ {
+ label: "Confirm New Password",
+ type: "password",
+ name: "confirmNewPassword",
+ placeholder: "*******",
+ inputKey: `${updatedUser?.id}-confirmNewPassword`,
+ },
+ ]}
+ heading={`Update profile details`}
+ isLoading={isLoading}
+ onSubmit={modifyDetails}
+ submitButtonText={"Update"}
+ />
);
}
diff --git a/src/client/src/app/api/db-config/route.ts b/src/client/src/app/api/db-config/route.ts
index 61c0f143..0a389c83 100644
--- a/src/client/src/app/api/db-config/route.ts
+++ b/src/client/src/app/api/db-config/route.ts
@@ -1,5 +1,6 @@
import { getDBConfigByUser, upsertDBConfig } from "@/lib/db-config";
import asaw from "@/utils/asaw";
+import { DatabaseConfig } from "@prisma/client";
export async function GET() {
const [err, res]: any = await asaw(getDBConfigByUser());
@@ -14,13 +15,18 @@ export async function GET() {
export async function POST(request: Request) {
const formData = await request.json();
const id = formData.id;
- const name = formData.name;
- const environment = formData.environment;
- const meta = formData.meta;
- const [err, res]: any = await asaw(
- upsertDBConfig({ name, environment, meta }, id)
- );
+ const dbConfig: Partial<DatabaseConfig> = {
+ name: formData.name,
+ environment: formData.environment,
+ username: formData.username,
+ host: formData.host,
+ port: formData.port,
+ database: formData.database,
+ query: formData.query,
+ };
+
+ const [err, res]: any = await asaw(upsertDBConfig(dbConfig, id));
if (err)
return Response.json(err, {
diff --git a/src/client/src/app/api/user/profile/route.ts b/src/client/src/app/api/user/profile/route.ts
index 6035771d..71c7a654 100644
--- a/src/client/src/app/api/user/profile/route.ts
+++ b/src/client/src/app/api/user/profile/route.ts
@@ -1,6 +1,18 @@
+import { getCurrentUser } from "@/lib/session";
import { updateUserProfile } from "@/lib/user";
import asaw from "@/utils/asaw";
+export async function GET() {
+ const user: any = await getCurrentUser();
+
+ if (!user)
+ return Response.json("No user loggedin!", {
+ status: 401,
+ });
+
+ return Response.json(user);
+}
+
export async function POST(request: Request) {
const formData = await request.json();
const formObject = {
diff --git a/src/client/src/components/common/form-builder.tsx b/src/client/src/components/common/form-builder.tsx
new file mode 100644
index 00000000..d1961046
--- /dev/null
+++ b/src/client/src/components/common/form-builder.tsx
@@ -0,0 +1,89 @@
+import { noop } from "@/utils/noop";
+import React, { FormEventHandler, HTMLInputTypeAttribute } from "react";
+
+type FieldProps = {
+ label: string;
+ type: HTMLInputTypeAttribute;
+ name: string;
+ placeholder?: string;
+ defaultValue?: string;
+ inputKey?: string;
+};
+
+const FormField = ({
+ label,
+ type,
+ name,
+ placeholder,
+ defaultValue,
+ inputKey,
+}: FieldProps) => {
+ return (
+ <div className="flex flex-col mt-6 w-full">
+ <div className="flex flex-1 items-center">
+ <label
+ htmlFor={name}
+ className="text-tertiary/[0.8] text-sm font-normal w-1/5"
+ >
+ {label}
+ </label>
+ <div className="flex w-2/3 shadow-sm ring-1 ring-inset ring-gray-300">
+ <input
+ key={inputKey || `${name}-${defaultValue}`}
+ type={type}
+ name={name}
+ id={name}
+ className="flex-1 border border-tertiary/[0.2] py-1.5 px-2 text-tertiary placeholder:text-tertiary/[0.4] outline-none focus:ring-0 text-sm"
+ placeholder={placeholder}
+ defaultValue={defaultValue}
+ />
+ </div>
+ </div>
+ </div>
+ );
+};
+
+const FormBuilder = ({
+ fields,
+ heading,
+ isLoading = false,
+ onSubmit,
+ submitButtonText,
+}: {
+ fields: FieldProps[];
+ heading: string;
+ isLoading?: boolean;
+ onSubmit: FormEventHandler<HTMLFormElement>;
+ submitButtonText: string;
+}) => {
+ return (
+ <form
+ className="flex flex-col w-full"
+ onSubmit={isLoading ? noop : onSubmit}
+ >
+ <div className="flex flex-col relative flex-1 overflow-y-auto">
+ <h2 className="text-base font-semibold px-5 pt-3 text-tertiary sticky top-0 bg-white">
+ {heading}
+ </h2>
+
+ <div className="flex flex-col relative flex-1 overflow-y-auto px-5 pb-3">
+ {fields.map((field, index) => (
+ <FormField key={index} {...field} />
+ ))}
+ </div>
+ <div className="mt-6 flex items-center justify-end border-t border-secondary w-full py-2 gap-3">
+ <button
+ type="submit"
+ className={`rounded-sm bg-primary/[0.9] px-5 py-1.5 text-sm font-semibold text-white shadow-sm hover:bg-primary focus-visible:outline ${
+ isLoading ? "animate-pulse" : ""
+ }`}
+ >
+ {submitButtonText}
+ </button>
+ </div>
+ </div>
+ </form>
+ );
+};
+
+export default FormBuilder;
diff --git a/src/client/src/constants/dbConfig.ts b/src/client/src/constants/dbConfig.ts
index 0fd8a116..757de522 100644
--- a/src/client/src/constants/dbConfig.ts
+++ b/src/client/src/constants/dbConfig.ts
@@ -1,3 +1,11 @@
-export const DB_META_KEYS = {
- url: "databaseURL",
+export type DatabaseConfig = {
+ id: string;
+ name: string;
+ environment: string;
+ username: string;
+ password?: string;
+ host: string;
+ port: string;
+ database: string;
+ query?: string;
};
diff --git a/src/client/src/lib/db-config.ts b/src/client/src/lib/db-config.ts
index 6db1df8a..6967add8 100644
--- a/src/client/src/lib/db-config.ts
+++ b/src/client/src/lib/db-config.ts
@@ -53,19 +53,15 @@ export const getDBConfigById = async ({ id }: { id: string }) => {
};
export const upsertDBConfig = async (
- {
- environment,
- name,
- meta,
- }: {
- environment: string;
- name: string;
- meta: string;
- },
+ dbConfig: Partial<DatabaseConfig>,
id?: string
) => {
- if (!name) throw new Error("No name provided");
- if (!meta) throw new Error("No meta details provided");
+ if (!dbConfig.name) throw new Error("No name provided");
+ if (!dbConfig.username) throw new Error("No username provided");
+ if (!dbConfig.host) throw new Error("No host provided");
+ if (!dbConfig.port) throw new Error("No port provided");
+ if (!dbConfig.database) throw new Error("No database provided");
+ if (!dbConfig.database) throw new Error("No database provided");
const user = await getCurrentUser();
@@ -73,7 +69,7 @@ export const upsertDBConfig = async (
const existingDBName = await prisma.databaseConfig.findUnique({
where: {
- name,
+ name: dbConfig.name,
NOT: {
id,
},
@@ -84,20 +80,16 @@ export const upsertDBConfig = async (
const whereObject: any = {};
if (id) whereObject.id = id;
- else whereObject.name = name;
+ else whereObject.name = dbConfig.name;
- const dbConfig = await prisma.databaseConfig.upsert({
+ const createddbConfig = await prisma.databaseConfig.upsert({
where: whereObject,
create: {
- environment,
- name,
- meta,
+ ...(dbConfig as any),
createdByUserId: user.id,
},
update: {
- environment,
- name,
- meta,
+ ...dbConfig,
},
});
@@ -110,7 +102,7 @@ export const upsertDBConfig = async (
await prisma.databaseConfigUser.create({
data: {
userId: user.id,
- databaseConfigId: dbConfig.id,
+ databaseConfigId: createddbConfig.id,
isCurrent: !ifFirstDBConfigCreated,
},
});
diff --git a/src/client/src/lib/doku/clickhouse-client.ts b/src/client/src/lib/doku/clickhouse-client.ts
index f0a13edf..58f3d1c3 100644
--- a/src/client/src/lib/doku/clickhouse-client.ts
+++ b/src/client/src/lib/doku/clickhouse-client.ts
@@ -1,21 +1,38 @@
-// clickhouseService.js
-import { parseClickHouseConnectionString } from "@/utils/parser";
+import { parseQueryStringToObject } from "@/utils/parser";
import { ClickHouseClient, createClient } from "@clickhouse/client";
+import { DatabaseConfig } from "@prisma/client";
import { createPool, Pool } from "generic-pool";
+interface ClickHouseConnectionInfo {
+ username: string;
+ password: string;
+ host: string;
+ port: string;
+ database: string;
+ additional_headers: Record<string, string>;
+}
+
export default function createClickhousePool(
- connectionString: string
+ dbConfig: DatabaseConfig
): Pool<ClickHouseClient> {
- const connectionObject = parseClickHouseConnectionString(connectionString);
+ const connectionObject: ClickHouseConnectionInfo = {
+ username: dbConfig.username,
+ password: dbConfig.password || "",
+ host: dbConfig.host,
+ port: dbConfig.port,
+ database: dbConfig.database,
+ additional_headers: parseQueryStringToObject(dbConfig.query || ""),
+ };
+
return createPool(
{
create: async () => createClient(connectionObject),
destroy: (client: ClickHouseClient) => client.close(),
},
{
- max: 10, // Adjust based on your server capacity and requirements
- min: 2, // Start with a minimum number of connections
- idleTimeoutMillis: 30000, // Adjust based on your workload and server characteristics
+ max: 10,
+ min: 2,
+ idleTimeoutMillis: 30000,
}
);
}
diff --git a/src/client/src/lib/doku/common.ts b/src/client/src/lib/doku/common.ts
index 7f6309d1..91fb4944 100644
--- a/src/client/src/lib/doku/common.ts
+++ b/src/client/src/lib/doku/common.ts
@@ -1,7 +1,5 @@
-import { DatabaseConfig } from "@prisma/client";
import { getDBConfigByUser } from "../db-config";
import createClickhousePool from "./clickhouse-client";
-import { DB_META_KEYS } from "@/constants/dbConfig";
import asaw from "@/utils/asaw";
export const DATA_TABLE_NAME = "DOKU_LLM_DATA";
@@ -31,11 +29,7 @@ export type DataCollectorType = { err?: unknown; data?: unknown };
export async function dataCollector(query: string): Promise<DataCollectorType> {
const [err, dbConfig] = await asaw(getDBConfigByUser(true));
if (err) return { err, data: [] };
- const clickhousePool = createClickhousePool(
- ((dbConfig as DatabaseConfig)?.meta as Record<string, any>)?.[
- DB_META_KEYS.url
- ] || ""
- );
+ const clickhousePool = createClickhousePool(dbConfig);
const client = await clickhousePool.acquire();
try {
diff --git a/src/client/src/utils/parser.ts b/src/client/src/utils/parser.ts
index 9dc6e1dd..531de1f8 100644
--- a/src/client/src/utils/parser.ts
+++ b/src/client/src/utils/parser.ts
@@ -1,45 +1,13 @@
-interface ClickHouseConnectionInfo {
- username: string;
- password: string;
- host: string;
- database: string;
- additional_headers: Record<string, string>;
-}
-
-export const parseClickHouseConnectionString = (
- connectionString: string
-): ClickHouseConnectionInfo => {
- const regex =
- /clickhouse(?:\+(\w+))?:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/([^?]+)(?:\?([^*]+))?/;
-
- const match = connectionString.match(regex);
-
- if (!match) {
- throw new Error("Invalid ClickHouse connection string format");
- }
-
- const [, , username, password, hostStr, portStr, database, queryParamsStr] =
- match;
-
- const port = parseInt(portStr, 10);
-
- const additional_headers: Record<string, string> = {};
+export const parseQueryStringToObject = (
+ queryParamsStr: string
+): Record<string, string> => {
+ const queryObject: Record<string, string> = {};
if (queryParamsStr) {
queryParamsStr.split("&").forEach((param) => {
const [key, value] = param.split("=");
- additional_headers[key] = value;
+ queryObject[key] = value;
});
}
- const host = `${
- additional_headers["protocol"] || "http"
- }://${hostStr}:${port}`;
-
- return {
- username,
- password,
- host,
- database,
- additional_headers,
- };
+ return queryObject;
};