asyncfunctioncreateUserTable() { await client.queryObject({ text: ` CREATE TABLE IF NOT EXISTS users ( id serial primary key, name text, created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ); `, }); }
asyncfunctioncreateUserFunction() { await client.queryObject({ text: ` DROP FUNCTION IF EXISTS set_update_time() CASCADE; CREATE FUNCTION set_update_time() RETURNS trigger AS ' begin new.updated_at := ''now''; return new; end; ' LANGUAGE plpgsql; CREATE TRIGGER update_trigger BEFORE UPDATE ON public.users FOR EACH ROW EXECUTE PROCEDURE set_update_time(); `, }); }
asyncfunctiongetUsers(): Promise<any[][]> { const users = await client.queryArray({ text: ` select id, name, created_at, updated_at from public.users order by id `, }); return users.rows; }
asyncfunctiongetUsersObject(): Promise<User[]> { const users = await client.queryObject<User>( { text: ` select id, name, created_at, updated_at from public.users order by id `, fields: ["id", "name", "created_at", "updated_at"], }); return users.rows; }
/** This is the final config object */ constconfig: NessieConfig = { client, migrationFolders: ["./db/migrations"], seedFolders: ["./db/seeds"], };
exportdefault config;
引き続き、マイグレーションファイルを作成。
1 2
$ deno run -A --unstable https://deno.land/x/nessie/cli.ts make:migration create_users $ deno run -A --unstable https://deno.land/x/nessie/cli.ts make:migration create_users_function
exportdefaultclassextendsAbstractMigration<ClientPostgreSQL> { /** Runs on migrate */ asyncup(info: Info): Promise<void> { awaitthis.client.queryArray(` CREATE FUNCTION set_update_time() RETURNS trigger AS ' begin new.updated_at := ''now''; return new; end; ' LANGUAGE plpgsql; CREATE TRIGGER update_trigger BEFORE UPDATE ON public.users FOR EACH ROW EXECUTE PROCEDURE set_update_time(); `); }
/** Runs on rollback */ asyncdown(info: Info): Promise<void> { awaitthis.client.queryArray( "DROP FUNCTION IF EXISTS set_update_time() CASCADE;", ); } }
1 2 3 4 5 6 7 8 9 10 11 12 13
$ deno run -A --unstable https://deno.land/x/nessie/cli.ts migrate Starting migration of 2 files ----
Migrating 20220916004331_create_users.ts Done in 0.04 seconds ----
Migrating 20220916004415_create_users_function.ts Done in 0.01 seconds ----