Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add drizzle + examples #426

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@ web-build/
# The following patterns were generated by expo-cli

expo-env.d.ts
# @end expo-cli
# @end expo-cli

.env
12 changes: 12 additions & 0 deletions db/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { config } from "dotenv";
import { drizzle } from "drizzle-orm/libsql";
import { createClient } from "@libsql/client";

config({ path: ".env" }); // or .env.local

const client = createClient({
url: process.env.TURSO_CONNECTION_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!,
});

export const db = drizzle(client);
7 changes: 7 additions & 0 deletions db/queries/delete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { eq } from "drizzle-orm";
import { db } from "../index";
import { SelectUser, usersTable } from "../schema";

export async function deleteUser(id: SelectUser["id"]) {
await db.delete(usersTable).where(eq(usersTable.id, id));
}
10 changes: 10 additions & 0 deletions db/queries/insert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { db } from "../index";
import { InsertPost, InsertUser, postsTable, usersTable } from "../schema";

export async function createUser(data: InsertUser) {
await db.insert(usersTable).values(data);
}

export async function createPost(data: InsertPost) {
await db.insert(postsTable).values(data);
}
60 changes: 60 additions & 0 deletions db/queries/select.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { asc, count, eq, getTableColumns, gt, sql } from "drizzle-orm";
import { db } from "../index";
import { SelectUser, postsTable, usersTable } from "../schema";

export async function getUserById(id: SelectUser["id"]): Promise<
{
id: number;
name: string;
age: number;
email: string;
}[]
> {
return db.select().from(usersTable).where(eq(usersTable.id, id));
}

export async function getUsersWithPostsCount(
page = 1,
pageSize = 5,
): Promise<
{
postsCount: number;
id: number;
name: string;
age: number;
email: string;
}[]
> {
return db
.select({
...getTableColumns(usersTable),
postsCount: count(postsTable.id),
})
.from(usersTable)
.leftJoin(postsTable, eq(usersTable.id, postsTable.userId))
.groupBy(usersTable.id)
.orderBy(asc(usersTable.id))
.limit(pageSize)
.offset((page - 1) * pageSize);
}

export async function getPostsForLast24Hours(
page = 1,
pageSize = 5,
): Promise<
{
id: number;
title: string;
}[]
> {
return db
.select({
id: postsTable.id,
title: postsTable.title,
})
.from(postsTable)
.where(gt(postsTable.createdAt, sql`(datetime('now','-24 hour'))`))
.orderBy(asc(postsTable.title), asc(postsTable.id))
.limit(pageSize)
.offset((page - 1) * pageSize);
}
10 changes: 10 additions & 0 deletions db/queries/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { eq } from "drizzle-orm";
import { db } from "../index";
import { SelectPost, postsTable } from "../schema";

export async function updatePost(
id: SelectPost["id"],
data: Partial<Omit<SelectPost, "id">>,
) {
await db.update(postsTable).set(data).where(eq(postsTable.id, id));
}
29 changes: 29 additions & 0 deletions db/schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { sql } from "drizzle-orm";
import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core";

export const usersTable = sqliteTable("users", {
id: integer("id").primaryKey(),
name: text("name").notNull(),
age: integer("age").notNull(),
email: text("email").unique().notNull(),
});

export const postsTable = sqliteTable("posts", {
id: integer("id").primaryKey(),
title: text("title").notNull(),
content: text("content").notNull(),
userId: integer("user_id")
.notNull()
.references(() => usersTable.id, { onDelete: "cascade" }),
createdAt: text("created_at")
.default(sql`(CURRENT_TIMESTAMP)`)
.notNull(),
updateAt: integer("updated_at", { mode: "timestamp" }).$onUpdate(
() => new Date(),
),
});

export type InsertUser = typeof usersTable.$inferInsert;
export type SelectUser = typeof usersTable.$inferSelect;
export type InsertPost = typeof postsTable.$inferInsert;
export type SelectPost = typeof postsTable.$inferSelect;
15 changes: 15 additions & 0 deletions drizzle.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { config } from "dotenv";
import { defineConfig } from "drizzle-kit";

config({ path: ".env" });

export default defineConfig({
schema: "./db/schema.ts",
out: "./migrations",
dialect: "sqlite",
driver: "turso",
dbCredentials: {
url: process.env.TURSO_CONNECTION_URL!,
authToken: process.env.TURSO_AUTH_TOKEN!,
},
});
18 changes: 18 additions & 0 deletions migrations/0000_fast_proudstar.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
CREATE TABLE `posts` (
`id` integer PRIMARY KEY NOT NULL,
`title` text NOT NULL,
`content` text NOT NULL,
`user_id` integer NOT NULL,
`created_at` text DEFAULT (CURRENT_TIMESTAMP) NOT NULL,
`updated_at` integer,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `users` (
`id` integer PRIMARY KEY NOT NULL,
`name` text NOT NULL,
`age` integer NOT NULL,
`email` text NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `users_email_unique` ON `users` (`email`);
122 changes: 122 additions & 0 deletions migrations/meta/0000_snapshot.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
{
"version": "6",
"dialect": "sqlite",
"id": "780e74cb-d76b-4927-987f-47e4a3d120bf",
"prevId": "00000000-0000-0000-0000-000000000000",
"tables": {
"posts": {
"name": "posts",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"content": {
"name": "content",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "(CURRENT_TIMESTAMP)"
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"posts_user_id_users_id_fk": {
"name": "posts_user_id_users_id_fk",
"tableFrom": "posts",
"tableTo": "users",
"columnsFrom": ["user_id"],
"columnsTo": ["id"],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"age": {
"name": "age",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {
"users_email_unique": {
"name": "users_email_unique",
"columns": ["email"],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {}
}
},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
13 changes: 13 additions & 0 deletions migrations/meta/_journal.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "sqlite",
"entries": [
{
"idx": 0,
"version": "6",
"when": 1724127354467,
"tag": "0000_fast_proudstar",
"breakpoints": true
}
]
}
Loading