import { pgTable, serial, text, timestamp, integer, jsonb, boolean, index } from 'drizzle-orm/pg-core'; import { relations } from 'drizzle-orm'; export const users = pgTable('users', { id: serial('id').primaryKey(), token: text('token').notNull().unique(), createdAt: timestamp('created_at').defaultNow().notNull(), }); export const habits = pgTable( 'habits', { id: serial('id').primaryKey(), userId: integer('user_id') .references(() => users.id) .notNull(), name: text('name').notNull(), type: text('type', { enum: ['positive', 'neutral', 'negative'] }) .notNull() .default('neutral'), targetFrequency: jsonb('target_frequency').$type<{ value: number; period: 'day' | 'week' | 'month'; }>(), color: text('color'), icon: text('icon'), isArchived: boolean('is_archived').default(false).notNull(), createdAt: timestamp('created_at').defaultNow().notNull(), archivedAt: timestamp('archived_at'), }, (table) => ({ userIdIdx: index('habits_user_id_idx').on(table.userId), }), ); export const habitLogs = pgTable( 'habit_logs', { id: serial('id').primaryKey(), habitId: integer('habit_id') .references(() => habits.id) .notNull(), loggedAt: timestamp('logged_at').defaultNow().notNull(), note: text('note'), }, (table) => ({ habitIdIdx: index('habit_logs_habit_id_idx').on(table.habitId), loggedAtIdx: index('habit_logs_logged_at_idx').on(table.loggedAt), }), ); // Relations export const usersRelations = relations(users, ({ many }) => ({ habits: many(habits), })); export const habitsRelations = relations(habits, ({ one, many }) => ({ user: one(users, { fields: [habits.userId], references: [users.id], }), logs: many(habitLogs), })); export const habitLogsRelations = relations(habitLogs, ({ one }) => ({ habit: one(habits, { fields: [habitLogs.habitId], references: [habits.id], }), })); // Types export type User = typeof users.$inferSelect; export type NewUser = typeof users.$inferInsert; export type Habit = typeof habits.$inferSelect; export type NewHabit = typeof habits.$inferInsert; export type HabitLog = typeof habitLogs.$inferSelect; export type NewHabitLog = typeof habitLogs.$inferInsert;