Skip to content

Gel (precedentemente EdgeDB) è un database graph-relazionale basato su Postgres. Fornisce un linguaggio di schema dichiarativo, un sistema di migrazioni e un linguaggio di query orientato agli oggetti, oltre a supportare query SQL raw. Risolve il problema della mappatura oggetto-relazionale a livello di database, eliminando la necessità di una libreria ORM nel codice dell'applicazione.


Per prima cosa, installa Gel se non l'hai già fatto.

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 per creare un nuovo progetto.

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

Useremo la CLI di Gel per inizializzare un'istanza Gel per il nostro progetto. Questo crea un file gel.toml nella root del progetto.

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`

Per vedere se il database è in esecuzione, apriamo un REPL ed eseguiamo una semplice query.

sh
gel
gel> select 1 + 1;
txt
2

Poi esegui \quit per uscire dal REPL.

sh
gel> \quit

Con il progetto inizialito, possiamo definire uno schema. Il comando gel project init ha già creato un file dbschema/default.esdl per contenere il nostro schema.

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

Apri quel file e incolla il seguente contenuto.

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

Poi genera e applica una migrazione iniziale.

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 il nostro schema applicato, eseguiamo alcune query usando la libreria client JavaScript di Gel. Installeremo la libreria client e la CLI di codegen di Gel, e creeremo un file seed.ts.

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

Incolla il seguente codice in seed.ts.

Il client si connette automaticamente al database. Inseriamo un paio di film usando il metodo .execute(). Useremo l'espressione for di EdgeQL per trasformare questo inserimento bulk in una singola query ottimizzata.

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(`Seed completato.`);
process.exit();

Poi esegui questo file con Bun.

sh
bun run seed.ts
txt
Seed completato.

Gel implementa una serie di strumenti di generazione di codice per TypeScript. Per fare query al nostro database appena popolato in modo type-safe, useremo @gel/generate per generare il 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

In index.ts, possiamo importare il query builder generato da ./dbschema/edgeql-js e scrivere una semplice query select.

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

Eseguendo il file con Bun, possiamo vedere l'elenco dei film che abbiamo inserito.

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

Per la documentazione completa, consulta la documentazione Gel.

Bun a cura di www.bunjs.com.cn