Skip to content

Gel (anteriormente EdgeDB) é um banco de dados grafo-relacional alimentado por Postgres. Ele fornece uma linguagem de schema declarativa, sistema de migrações e linguagem de query orientada a objetos, além de suportar queries SQL brutas. Ele resolve o problema de mapeamento objeto-relacional na camada do banco de dados, eliminando a necessidade de uma biblioteca ORM no código da sua aplicação.


Primeiro, instale o Gel se ainda não o fez.

sh
curl https://www.geldata.com/sh --proto "=https" -sSf1 | sh
sh
irm https://www.geldata.com/ps1 | iex
sh
brew install geldata/tap/gel-cli

Use bun init para criar um novo projeto.

sh
mkdir my-edgedb-app
cd my-edgedb-app
bun init -y

Usaremos a CLI do Gel para inicializar uma instância do Gel para nosso projeto. Isso cria um arquivo gel.toml na raiz do projeto.

sh
gel project init
txt
No `gel.toml` found in `/Users/colinmcd94/Documents/bun/fun/examples/my-gel-app` or above
Do you want to initialize a new project? [Y/n]
> Y
Specify the name of Gel instance to use with this project [default: my_gel_app]:
> my_gel_app
Checking Gel versions...
Specify the version of Gel to use with this project [default: x.y]:
> x.y
┌─────────────────────┬──────────────────────────────────────────────────────────────────┐
│ Project directory   │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app         │
│ Project config      │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/gel.toml│
│ Schema dir (empty)  │ /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema│
│ Installation method │ portable package                                                 │
│ Version             │ x.y+6d5921b                                                      │
│ Instance name       │ my_gel_app                                                       │
└─────────────────────┴──────────────────────────────────────────────────────────────────┘
Version x.y+6d5921b is already downloaded
Initializing Gel instance...
Applying migrations...
Everything is up to date. Revision initial
Project initialized.
To connect to my_gel_app, run `gel`

Para ver se o banco de dados está funcionando, vamos abrir um REPL e executar uma query simples.

sh
gel
gel> select 1 + 1;
txt
2

Em seguida, execute \quit para sair do REPL.

sh
gel> \quit

Com o projeto inicializado, podemos definir um schema. O comando gel project init já criou um arquivo dbschema/default.esdl para conter nosso schema.

txt
dbschema
├── default.esdl
└── migrations

Abra esse arquivo e cole o seguinte conteúdo.

ts
module default {
  type Movie {
    required title: str;
    releaseYear: int64;
  }
};

Em seguida, gere e aplique uma migração inicial.

sh
gel migration create
txt
Created /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema/migrations/00001.edgeql, id: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq
sh
gel migrate
txt
Applied m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrq (00001.edgeql)

Com nosso schema aplicado, vamos executar algumas queries usando a biblioteca cliente JavaScript do Gel. Instalaremos a biblioteca cliente e a CLI de geração de código do Gel e criaremos um arquivo seed.ts.

sh
bun add gel
bun add -D @gel/generate
touch seed.ts

Cole o seguinte código em seed.ts.

O cliente conecta automaticamente ao banco de dados. Inserimos alguns filmes usando o método .execute(). Usaremos a expressão for do EdgeQL para transformar esta inserção em massa em uma única query otimizada.

ts
import { createClient } from "gel";

const client = createClient();

const INSERT_MOVIE = `
  with movies := <array<tuple<title: str, year: int64>>>$movies
  for movie in array_unpack(movies) union (
    insert Movie {
      title := movie.title,
      releaseYear := movie.year,
    }
  )
`;

const movies = [
  { title: "The Matrix", year: 1999 },
  { title: "The Matrix Reloaded", year: 2003 },
  { title: "The Matrix Revolutions", year: 2003 },
];

await client.execute(INSERT_MOVIE, { movies });

console.log(`Seeding completo.`);
process.exit();

Em seguida, execute este arquivo com Bun.

sh
bun run seed.ts
txt
Seeding completo.

O Gel implementa várias ferramentas de geração de código para TypeScript. Para consultar nosso banco de dados recém-populado de forma tipada, usaremos @gel/generate para gerar o query builder EdgeQL.

sh
bunx @gel/generate edgeql-js
txt
Generating query builder...
Detected tsconfig.json, generating TypeScript files.
   To override this, use the --target flag.
   Run `npx @edgedb/generate --help` for full options.
Introspecting database schema...
Writing files to ./dbschema/edgeql-js
Generation complete! 🤘
Checking the generated query builder into version control
is not recommended. Would you like to update .gitignore to ignore
the query builder directory? The following line will be added:

   dbschema/edgeql-js

[y/n] (leave blank for "y")
> y

Em index.ts, podemos importar o query builder gerado de ./dbschema/edgeql-js e escrever uma query select simples.

ts
import { createClient } from "gel";
import e from "./dbschema/edgeql-js";

const client = createClient();

const query = e.select(e.Movie, () => ({
  title: true,
  releaseYear: true,
}));

const results = await query.run(client);
console.log(results);

results; // { title: string, releaseYear: number | null }[]

Executando o arquivo com Bun, podemos ver a lista de filmes que inserimos.

sh
bun run index.ts
txt
[
  {
    title: "The Matrix",
    releaseYear: 1999
  }, {
    title: "The Matrix Reloaded",
    releaseYear: 2003
  }, {
    title: "The Matrix Revolutions",
    releaseYear: 2003
  }
]

Para documentação completa, consulte a documentação do Gel.

Bun by www.bunjs.com.cn edit