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.
curl https://www.geldata.com/sh --proto "=https" -sSf1 | shirm https://www.geldata.com/ps1 | iexbrew install geldata/tap/gel-cliUsa bun init per creare un nuovo progetto.
mkdir my-gel-app
cd my-gel-app
bun init -yUseremo la CLI di Gel per inizializzare un'istanza Gel per il nostro progetto. Questo crea un file gel.toml nella root del progetto.
gel project initNo `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.
gel
gel> select 1 + 1;2Poi esegui \quit per uscire dal REPL.
gel> \quitCon 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.
dbschema
├── default.esdl
└── migrationsApri quel file e incolla il seguente contenuto.
module default {
type Movie {
required title: str;
releaseYear: int64;
}
};Poi genera e applica una migrazione iniziale.
gel migration createCreated /Users/colinmcd94/Documents/bun/fun/examples/my-gel-app/dbschema/migrations/00001.edgeql, id: m1uwekrn4ni4qs7ul7hfar4xemm5kkxlpswolcoyqj3xdhweomwjrqgel migrateApplied 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.
bun add gel
bun add -D @gel/generate
touch seed.tsIncolla 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.
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.
bun run seed.tsSeed 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.
bunx @gel/generate edgeql-jsGenerating 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")
> yIn index.ts, possiamo importare il query builder generato da ./dbschema/edgeql-js e scrivere una semplice query select.
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.
bun run index.ts[
{
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.