Skip to content

Gel (anteriormente EdgeDB) es una base de datos grafo-relacional impulsada por Postgres internamente. Proporciona un lenguaje de esquema declarativo, sistema de migraciones y lenguaje de consultas orientado a objetos, además de soportar consultas SQL sin procesar. Resuelve el problema de mapeo objeto-relacional en la capa de base de datos, eliminando la necesidad de una biblioteca ORM en tu código de aplicación.


Primero, instala Gel si aún no lo has hecho.

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

Usa bun init para crear un nuevo proyecto.

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

Usaremos la CLI de Gel para inicializar una instancia de Gel para nuestro proyecto. Esto crea un archivo gel.toml en la raíz de nuestro proyecto.

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 si la base de datos está funcionando, abramos un REPL y ejecutemos una consulta simple.

sh
gel
gel> select 1 + 1;
txt
2

Luego ejecuta \quit para salir del REPL.

sh
gel> \quit

Con el proyecto inicializado, podemos definir un esquema. El comando gel project init ya creó un archivo dbschema/default.esdl para contener nuestro esquema.

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

Abre ese archivo y pega el siguiente contenido.

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

Luego genera y aplica una migración 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)

Con nuestro esquema aplicado, ejecutemos algunas consultas usando la biblioteca cliente de JavaScript de Gel. Instalaremos la biblioteca cliente y la CLI de generación de código de Gel, y crearemos un archivo seed.ts.

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

Pega el siguiente código en seed.ts.

El cliente se conecta automáticamente a la base de datos. Insertamos un par de películas usando el método .execute(). Usaremos la expresión for de EdgeQL para convertir esta inserción masiva en una consulta optimizada única.

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(`Sembrado completo.`);
process.exit();

Luego ejecuta este archivo con Bun.

sh
bun run seed.ts
txt
Sembrado completo.

Gel implementa varias herramientas de generación de código para TypeScript. Para consultar nuestra base de datos recién sembrada de manera segura en cuanto a tipos, usaremos @gel/generate para generar el constructor de consultas 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

En index.ts, podemos importar el constructor de consultas generado desde ./dbschema/edgeql-js y escribir una consulta select simple.

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 }[]

Ejecutando el archivo con Bun, podemos ver la lista de películas que insertamos.

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

Para documentación completa, consulta la documentación de Gel.

Bun por www.bunjs.com.cn editar