hopesix
hopesix
Explore posts from servers
TTCTheo's Typesafe Cult
Created by hopesix on 4/3/2024 in #questions
Can't set env variables in package.json scripts?
So essentially I'm trying to run some test scripts (playwright for example) and I want to assign an env var like APP_ENV=test or something like that when I do, this way I can swap the database to a local testing db src/server/db/index.ts 1:
import * as schema from "./schema";
import { sql } from "@vercel/postgres";
import postgres from "postgres";
import {
drizzle as VercelDrizzle,
type VercelPgClient,
type VercelPgDatabase,
} from "drizzle-orm/vercel-postgres";
import {
drizzle as LocalDrizzle,
type PostgresJsDatabase,
} from "drizzle-orm/postgres-js";
import { env } from "@/env";

// https://www.thisdot.co/blog/configure-your-project-with-drizzle-for-local-and-deployed-databases
// Reconfigured for test (local) and production (vercel+supabase) databases following this guide as a baseline

// Define a type that represents the structure of the database schema.
type MySchema = typeof schema;

// Define a variable 'db' that can be either a VercelPgDatabase or a PostgresJsDatabase,
// both typed with the schema structure.
let db: VercelPgDatabase<MySchema> | PostgresJsDatabase<MySchema>;

console.log("NODE_ENV: ", process.env.NODE_ENV);
// This shows that playwright tests are coming through as NODE_ENV=development
console.log("APP_ENV: ", process.env.APP_ENV);
console.log("ENVIRONMENT: ", process.env.ENVIRONMENT);

// Check custom APP_ENV variable to determine which database to use
// This can be refactored later to separate production and development if necessary
if (process.env.APP_ENV === "test") {
// In the test environment, use a local Postgres database.
// The TEST_DATABASE_URL environment variable should contain the connection string.
const migrationClient = postgres(process.env.TEST_DATABASE_URL!); // removed 'as string' from end
// Initialize the database with the local Postgres client and the defined schema.
db = LocalDrizzle(migrationClient, { schema });
//db = LocalDrizzle(migrationClient);
console.log("Using Local Postgres for Testing");
} else {
// In production or development, use Vercel Postgres with the defined schema.
db = VercelDrizzle(sql as VercelPgClient, { schema });
//db = VercelDrizzle(sql);
console.log("Using Vercel Postgres (supabase)");
}
import * as schema from "./schema";
import { sql } from "@vercel/postgres";
import postgres from "postgres";
import {
drizzle as VercelDrizzle,
type VercelPgClient,
type VercelPgDatabase,
} from "drizzle-orm/vercel-postgres";
import {
drizzle as LocalDrizzle,
type PostgresJsDatabase,
} from "drizzle-orm/postgres-js";
import { env } from "@/env";

// https://www.thisdot.co/blog/configure-your-project-with-drizzle-for-local-and-deployed-databases
// Reconfigured for test (local) and production (vercel+supabase) databases following this guide as a baseline

// Define a type that represents the structure of the database schema.
type MySchema = typeof schema;

// Define a variable 'db' that can be either a VercelPgDatabase or a PostgresJsDatabase,
// both typed with the schema structure.
let db: VercelPgDatabase<MySchema> | PostgresJsDatabase<MySchema>;

console.log("NODE_ENV: ", process.env.NODE_ENV);
// This shows that playwright tests are coming through as NODE_ENV=development
console.log("APP_ENV: ", process.env.APP_ENV);
console.log("ENVIRONMENT: ", process.env.ENVIRONMENT);

// Check custom APP_ENV variable to determine which database to use
// This can be refactored later to separate production and development if necessary
if (process.env.APP_ENV === "test") {
// In the test environment, use a local Postgres database.
// The TEST_DATABASE_URL environment variable should contain the connection string.
const migrationClient = postgres(process.env.TEST_DATABASE_URL!); // removed 'as string' from end
// Initialize the database with the local Postgres client and the defined schema.
db = LocalDrizzle(migrationClient, { schema });
//db = LocalDrizzle(migrationClient);
console.log("Using Local Postgres for Testing");
} else {
// In production or development, use Vercel Postgres with the defined schema.
db = VercelDrizzle(sql as VercelPgClient, { schema });
//db = VercelDrizzle(sql);
console.log("Using Vercel Postgres (supabase)");
}
I've seen several instances as I've been googling of people simply adding things to scripts like:
"scripts": {
"test": "APP_ENV=test ENVIRONMENT=test playwright test",
}
"scripts": {
"test": "APP_ENV=test ENVIRONMENT=test playwright test",
}
Example: https://stackoverflow.com/a/77810676/630988 But for some reason when I try and do this it doesn't work, my log results always show undefined as well if I don't have something pre-set in .env, and when something is pre set it never changes to test. Note: I should mention I'm using Mac OSX, and I've also tried using cross-env and that also didn't work. So I'm not sure if the src/env.js file has something to do with this, but I've tried adding stuff in there as well and had no difference in results. I'm also not entirely sure how I could use that SKIP_ENV_VALIDATION or if it would even help. https://github.com/t3-oss/t3-env
3 replies
DTDrizzle Team
Created by hopesix on 2/7/2024 in #help
Can't edit datetime column in drizzle studio "Error: value.toISOString is not a function"
So I'm seeing my database with some data, and for the two datetime fields I've had a strange issue where I can ONLY submit as a javascript date object, even though in the schema it shows multiple options. And then when I save as a JS Date and go into Drizzle Studio and try to edit it (even changing a single hour or minute) I get this error when I try and save:
Error
value.toISOString is not a function
Error
value.toISOString is not a function
And here's an example value of what is saved in the column 2024-02-07T08:17:36.000Z Using PlanetScale as a DB, project started with create-t3-app 2 weeks ago from my package.json "drizzle-orm": "^0.29.3", "drizzle-kit": "^0.20.9", schema file (excerpt of bookings table)
export const bookings = createTable(
"bookings",
{
id: varchar("id", { length: 36 }).primaryKey(),
locationId: varchar("location_id", { length: 36 }).notNull(),
customerName: varchar("customer_name", { length: 256 }).notNull(),
customerEmail: varchar("customer_email", { length: 256 }).notNull(),
customerPhone: varchar("customer_phone", { length: 50 }).notNull(),
startTime: datetime("start_time").notNull(),
endTime: datetime("end_time").notNull(),
totalCost: decimal("total_cost", { precision: 10, scale: 2 }),
taxAmount: decimal("tax_amount", { precision: 10, scale: 2 }),
status: varchar("status", { length: 50 }),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at").onUpdateNow(),
},
(table) => ({
locationIdIdx: index("location_id_idx").on(table.locationId),
}),
);
export const bookings = createTable(
"bookings",
{
id: varchar("id", { length: 36 }).primaryKey(),
locationId: varchar("location_id", { length: 36 }).notNull(),
customerName: varchar("customer_name", { length: 256 }).notNull(),
customerEmail: varchar("customer_email", { length: 256 }).notNull(),
customerPhone: varchar("customer_phone", { length: 50 }).notNull(),
startTime: datetime("start_time").notNull(),
endTime: datetime("end_time").notNull(),
totalCost: decimal("total_cost", { precision: 10, scale: 2 }),
taxAmount: decimal("tax_amount", { precision: 10, scale: 2 }),
status: varchar("status", { length: 50 }),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updated_at").onUpdateNow(),
},
(table) => ({
locationIdIdx: index("location_id_idx").on(table.locationId),
}),
);
When I hover over datetime I see
(alias) datetime<"start_time", "string" | "date">(name: "start_time", config?: MySqlDatetimeConfig<"string" | "date"> | undefined): MySqlDateTimeBuilderInitial<"start_time">
import datetime
(alias) datetime<"start_time", "string" | "date">(name: "start_time", config?: MySqlDatetimeConfig<"string" | "date"> | undefined): MySqlDateTimeBuilderInitial<"start_time">
import datetime
However, when I try and save this in any way other than a javascript date (either new Date() or using luxon .toJSDate()) I get an error in my db insert values, here's where I've tried to return them as .toISO with luxon for example. For some reason the error shows under the id key and it took me a long time to debug that it was related to the startTime and endTime values.
No overload matches this call.
Overload 2 of 2, '(values: { id: string | SQL<unknown> | Placeholder<string, any>; locationId: string | SQL<unknown> | Placeholder<string, any>; customerName: string | SQL<unknown> | Placeholder<...>; ... 8 more ...; status?: string | ... 3 more ... | undefined; }[]): MySqlInsertBase<...>', gave the following error.
Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; locationId: string | SQL<unknown> | Placeholder<string, any>; customerName: string | SQL<unknown> | Placeholder<...>; ... 8 more ...; status?: string | ... 3 more ... | undefined; }[]'.ts(2769)
Codeium: Explain Problem

(property) id: string | SQL<unknown> | Placeholder<string, any>
No overload matches this call.
Overload 2 of 2, '(values: { id: string | SQL<unknown> | Placeholder<string, any>; locationId: string | SQL<unknown> | Placeholder<string, any>; customerName: string | SQL<unknown> | Placeholder<...>; ... 8 more ...; status?: string | ... 3 more ... | undefined; }[]): MySqlInsertBase<...>', gave the following error.
Object literal may only specify known properties, and 'id' does not exist in type '{ id: string | SQL<unknown> | Placeholder<string, any>; locationId: string | SQL<unknown> | Placeholder<string, any>; customerName: string | SQL<unknown> | Placeholder<...>; ... 8 more ...; status?: string | ... 3 more ... | undefined; }[]'.ts(2769)
Codeium: Explain Problem

(property) id: string | SQL<unknown> | Placeholder<string, any>
I'm very confused here, from what I've read online I should be able to store ISO inside of datetime?
6 replies
DTDrizzle Team
Created by hopesix on 1/30/2024 in #help
Trying to rename empty table from "user" to "users" w/ push
Building an app using T3 stack w/ Drizzle and PlanetScale(MySQL) Here's my current schema (at the bottom), I'm trying to rename "user" to "users" and my table is completely empty. When I run "db:push": "drizzle-kit push:mysql" I get
Is beesly_users table created or renamed from another table?
+ beesly_users create table
~ beesly_user › beesly_users rename table
Is beesly_users table created or renamed from another table?
+ beesly_users create table
~ beesly_user › beesly_users rename table
I've tried the second option to rename it and I get this back
~ beesly_user › beesly_users table will be renamed
--- all table conflicts resolved ---

TypeError: Cannot read properties of undefined (reading 'compositePrimaryKeys')
at /Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17175:51
at Array.map (<anonymous>)
at prepareDeleteCompositePrimaryKeyMySql (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17170:33)
at /Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17560:33
at Array.forEach (<anonymous>)
at applySnapshotsDiff (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17488:26)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async prepareSQL (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:15055:14)
at async prepareMySQLPush (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:14863:47)
at async Command.<anonymous> (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:63069:22)
[i] No changes detected
~ beesly_user › beesly_users table will be renamed
--- all table conflicts resolved ---

TypeError: Cannot read properties of undefined (reading 'compositePrimaryKeys')
at /Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17175:51
at Array.map (<anonymous>)
at prepareDeleteCompositePrimaryKeyMySql (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17170:33)
at /Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17560:33
at Array.forEach (<anonymous>)
at applySnapshotsDiff (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:17488:26)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async prepareSQL (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:15055:14)
at async prepareMySQLPush (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:14863:47)
at async Command.<anonymous> (/Users/jassi/Documents/Dev/booking-app/beesly/node_modules/.pnpm/[email protected]/node_modules/drizzle-kit/bin.cjs:63069:22)
[i] No changes detected
No idea what is happening, since I'm working in development I don't mind deleting tables completely or wiping data from them frequently right now, so just curious, should I be handling this a different way? I generally thought if I did push that it was going to rebuild the entire db based off my current schema ? Full schema so far
export const createTable = mysqlTableCreator((name) => `beesly_${name}`);

export const users = createTable(
"user", // Tried to rename this to "users"
{
id: varchar("id", { length: 256 }).primaryKey(),
email: varchar("email", { length: 256 }).unique(),
username: varchar("username", { length: 256 }).unique(),
displayName: varchar("display_name", { length: 256 }),
userImage: varchar("user_image", { length: 2048 }),
onboarded: boolean("onboarded").default(false).notNull(),
stripeCustomerId: varchar("stripe_customer_id", { length: 256 }).unique(),
stripeSubscriptionId: varchar("stripe_subscription_id", {
length: 256,
}).unique(),
stripePriceId: varchar("stripe_price_id", { length: 256 }),
stripeCurrentPeriodEnd: timestamp("stripe_current_period_end"),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updatedAt").onUpdateNow(),
},
(table) => ({
emailIndex: index("email_idx").on(table.email),
}),
);
export const createTable = mysqlTableCreator((name) => `beesly_${name}`);

export const users = createTable(
"user", // Tried to rename this to "users"
{
id: varchar("id", { length: 256 }).primaryKey(),
email: varchar("email", { length: 256 }).unique(),
username: varchar("username", { length: 256 }).unique(),
displayName: varchar("display_name", { length: 256 }),
userImage: varchar("user_image", { length: 2048 }),
onboarded: boolean("onboarded").default(false).notNull(),
stripeCustomerId: varchar("stripe_customer_id", { length: 256 }).unique(),
stripeSubscriptionId: varchar("stripe_subscription_id", {
length: 256,
}).unique(),
stripePriceId: varchar("stripe_price_id", { length: 256 }),
stripeCurrentPeriodEnd: timestamp("stripe_current_period_end"),
createdAt: timestamp("created_at")
.default(sql`CURRENT_TIMESTAMP`)
.notNull(),
updatedAt: timestamp("updatedAt").onUpdateNow(),
},
(table) => ({
emailIndex: index("email_idx").on(table.email),
}),
);
2 replies
TTCTheo's Typesafe Cult
Created by hopesix on 1/24/2024 in #questions
T3 Drizzle Questions: Push, Migrate, Etc
Apologies I'm still pretty new to using ORM's, I've only worked with Prisma a few times in the past as well. When I say, add a new table, or add a new column to a table, I simply need to call pnpm db:push afterwards and it'll push that up to PlanetScale for me. So when exactly would I need to deal with Migrations with Drizzle Kit..?
3 replies
TTCTheo's Typesafe Cult
Created by hopesix on 1/18/2024 in #questions
T3 tRPC tutorials/videos show useQuery / useMutation, but I only see query / mutate?
No description
6 replies