Dati e archiviazione
g.store.* — Archiviazione persistente
Sezione intitolata “g.store.* — Archiviazione persistente”Archiviazione documenti legata allo spazio di lavoro e basata su LiteDB. Richiede uno spazio di lavoro aperto.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
put | (collection, key, data) | No | Salva un documento |
get | (collection, key) → StoreDoc | null | No | Recupera un documento |
list | (collection, options?) → StoreDoc[] | No | Elenca documenti in una raccolta |
search | (collection, query, options?) → StoreDoc[] | No | Cerca testo dentro una raccolta |
delete | (collection, key) → boolean | No | Elimina un documento |
count | (collection) → number | No | Conta documenti |
clear | (collection) | No | Elimina tutti i documenti in una raccolta |
collections | () → string[] | No | Elenca tutti i nomi delle raccolte |
StoreDoc:
{ key: string data: any createdAt: string // ISO 8601 updatedAt: string // ISO 8601}StoreListOptions:
{ limit?: number // predefinito: 100 offset?: number // predefinito: 0 sort?: string // "key", "createdAt", "updatedAt" (predefinito) order?: string // "asc" o "desc" (predefinito)}Esempio
Sezione intitolata “Esempio”async function main() { // Salva dati g.store.put("products", "item-1", { name: "Widget", price: 9.99, inStock: true });
// Recuperali const doc = g.store.get("products", "item-1"); if (doc) g.log("Trovato: " + doc.data.name);
// Cerca const results = g.store.search("products", "Widget"); g.log("Corrispondenze: " + results.length);}g.queue.* — Coda di lavoro
Sezione intitolata “g.queue.* — Coda di lavoro”Coda persistente legata allo spazio di lavoro, con livelli di priorità e supporto per la coda degli scarti. Richiede uno spazio di lavoro aperto.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
enqueue | (name, data, options?) | No | Aggiunge un elemento a una coda |
dequeue | (name) → QueueItem | null | No | Estrae l’elemento successivo |
commit | (checkoutId) | No | Segna un elemento estratto come completato |
abort | (checkoutId, error?) → boolean | No | Riporta un elemento in coda (o nella coda degli scarti se supera il numero massimo di nuovi tentativi) |
peek | (name) → QueueItem | null | No | Visualizza l’elemento successivo senza estrarlo |
count | (name) → number | No | Conta gli elementi in attesa |
clear | (name) | No | Elimina tutti gli elementi in una coda |
list | (name, options?) → QueueItem[] | No | Elenca gli elementi in attesa |
queues | () → string[] | No | Elenca tutti i nomi delle code |
deadLetter | (name, options?) → DeadLetterItem[] | No | Elenca elementi nella coda degli scarti |
retry | (name, deadLetterId) | No | Rimette in coda un elemento scartato |
waitForItem | (name, options?) → Promise<QueueItem | null> | Sì | Attende finché un elemento diventa disponibile |
QueueEnqueueOptions:
{ priority?: number // 0=bassa, 1=normale (predefinito), 2=alta maxRetries?: number // predefinito: 3}QueueItem:
{ id: number data: any priority: number attempts: number maxRetries: number enqueuedAt: string lastAttemptAt?: string lastError?: string}Esempio
Sezione intitolata “Esempio”async function main() { // Metti in coda elementi di lavoro g.queue.enqueue("urls", { url: "https://example.com/page1" }); g.queue.enqueue("urls", { url: "https://example.com/page2" }, { priority: 2 });
// Elabora elementi const item = g.queue.dequeue("urls"); if (!item) return g.log("Coda vuota");
await g.nav.navigateToUrl(item.data.url); const html = await g.page.getDom();
// Segna come completato g.queue.commit(item.id);}g.search.* — Ricerca testuale
Sezione intitolata “g.search.* — Ricerca testuale”Indice di ricerca Lucene.NET legato allo spazio di lavoro. Supporta operatori booleani, caratteri jolly, ricerca di prossimità e ricerca basata su campi specifici. Richiede uno spazio di lavoro aperto.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
index | (fields) | No | Indicizza un documento (deve includere _key e _collection) |
query | (queryString, options?) → SearchResult[] | No | Cerca nell’indice con sintassi query Lucene |
delete | (collection, key) | No | Rimuove un documento dall’indice |
deleteByCollection | (collection) → number | No | Rimuove tutti i documenti in una raccolta |
count | (collection?) → number | No | Conta i documenti indicizzati |
clear | () | No | Svuota l’intero indice |
SearchResult:
{ key: string collection: string score: number // punteggio di rilevanza Lucene fields: Record<string, string>}Esempio
Sezione intitolata “Esempio”async function main() { // Indicizza documenti g.search.index({ _key: "article-1", _collection: "articles", title: "Introduzione a Guida", body: "Guida è un browser programmabile..." });
// Query con sintassi Lucene const results = g.search.query("browser programmabile", { collection: "articles" }); for (const r of results) { g.log(r.fields.title + " (punteggio: " + r.score + ")"); }}g.s3.* — Archiviazione di oggetti compatibile con S3
Sezione intitolata “g.s3.* — Archiviazione di oggetti compatibile con S3”Archiviazione compatibile con S3 tramite MinIO SDK. Funziona con AWS S3, MinIO e qualsiasi servizio compatibile con S3. Il parametro conn è il nome di una credenziale di accesso che contiene la stringa di connessione. Bloccato per gli script di origine MCP.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
listBuckets | (conn) → Promise<S3BucketInfo[]> | Sì | Elenca tutti i bucket accessibili |
bucketExists | (conn, bucket) → Promise<boolean> | Sì | Controlla se un bucket esiste |
listObjects | (conn, bucket, options?) → Promise<S3ObjectInfo[]> | Sì | Elenca oggetti in un bucket |
getObjectText | (conn, bucket, key) → Promise<string> | Sì | Scarica un oggetto come testo UTF-8 |
getObject | (conn, bucket, key, localPath) → Promise | Sì | Scarica un oggetto in un file locale |
putObjectText | (conn, bucket, key, content, contentType?) → Promise | Sì | Carica testo come oggetto |
putObject | (conn, bucket, key, localPath, contentType?) → Promise | Sì | Carica un file locale come oggetto |
deleteObject | (conn, bucket, key) → Promise | Sì | Elimina un oggetto |
objectExists | (conn, bucket, key) → Promise<boolean> | Sì | Controlla se un oggetto esiste |
createBucket | (conn, bucket, region?) → Promise | Sì | Crea un nuovo bucket |
copyObject | (conn, srcBucket, srcKey, dstBucket, dstKey) → Promise | Sì | Copia lato server (nessun dato passa dal client) |
getPresignedUrl | (conn, bucket, key, options?) → Promise<string> | Sì | Genera un URL prefirmato a durata limitata |
S3ListOptions:
{ prefix?: string // filtra oggetti per prefisso della chiave maxKeys?: number // numero massimo di oggetti da restituire (predefinito: 1000)}S3BucketInfo:
{ name: string creationDate: string // ISO 8601}S3ObjectInfo:
{ key: string // chiave oggetto (percorso) size: number // dimensione in byte lastModified: string // ISO 8601 etag: string // entity tag (hash)}S3PresignedUrlOptions:
{ method?: string // "GET" (download, predefinito) o "PUT" (upload) expiry?: number // scadenza URL in secondi (predefinito: 3600)}Esempio
Sezione intitolata “Esempio”async function main() { // Elenca file CSV in un bucket const files = await g.s3.listObjects("my-s3", "data-bucket", { prefix: "exports/" }); g.log("Trovati " + files.length + " oggetti");
// Carica dati estratti await g.s3.putObjectText( "my-s3", "data-bucket", "exports/results.json", JSON.stringify({ items: [1, 2, 3] }), "application/json" );
// Genera un link condivisibile const url = await g.s3.getPresignedUrl("my-s3", "data-bucket", "exports/results.json", { expiry: 86400 // 24 ore }); g.log("Link download: " + url);}g.mongodb.* — MongoDB
Sezione intitolata “g.mongodb.* — MongoDB”Operazioni MongoDB tramite MongoDB.Driver. Il parametro conn è il nome di una credenziale di accesso che contiene la stringa di connessione. Usa connection pooling automatico. Bloccato per gli script di origine MCP.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
find | (conn, db, collection, filter?, options?) → Promise<object[]> | Sì | Trova documenti che corrispondono a un filtro |
findOne | (conn, db, collection, filter?) → Promise<object | null> | Sì | Trova il primo documento corrispondente |
insertOne | (conn, db, collection, document) → Promise<MongoInsertResult> | Sì | Inserisce un singolo documento |
insertMany | (conn, db, collection, documents) → Promise<MongoInsertManyResult> | Sì | Inserisce più documenti |
updateOne | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Sì | Aggiorna il primo documento corrispondente |
updateMany | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Sì | Aggiorna tutti i documenti corrispondenti |
deleteOne | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Sì | Elimina il primo documento corrispondente |
deleteMany | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Sì | Elimina tutti i documenti corrispondenti |
replaceOne | (conn, db, collection, filter, replacement) → Promise<MongoUpdateResult> | Sì | Sostituisce il primo documento corrispondente |
countDocuments | (conn, db, collection, filter?) → Promise<number> | Sì | Conta i documenti corrispondenti |
listDatabases | (conn) → Promise<string[]> | Sì | Elenca tutti i nomi dei database |
listCollections | (conn, db) → Promise<string[]> | Sì | Elenca i nomi delle raccolte in un database |
aggregate | (conn, db, collection, pipeline) → Promise<object[]> | Sì | Esegue una pipeline di aggregazione |
createIndex | (conn, db, collection, keys, options?) → Promise<string> | Sì | Crea un indice, restituisce il nome dell’indice |
dropCollection | (conn, db, collection) → Promise | Sì | Elimina una raccolta |
distinct | (conn, db, collection, fieldName, filter?) → Promise<any[]> | Sì | Ottiene valori distinti per un campo |
bulkWrite | (conn, db, collection, operations) → Promise<MongoBulkWriteResult> | Sì | Esegue più operazioni di scrittura in blocco |
MongoFindOptions:
{ sort?: object // es. { name: 1, age: -1 } limit?: number skip?: number projection?: object // es. { name: 1, _id: 0 }}MongoInsertResult:
{ insertedId: string // _id del documento inserito}MongoInsertManyResult:
{ insertedCount: number insertedIds: string[]}MongoUpdateResult:
{ matchedCount: number modifiedCount: number}MongoDeleteResult:
{ deletedCount: number}MongoIndexOptions:
{ unique?: boolean // impone unicità name?: string // nome indice personalizzato}MongoBulkOperation:
{ type: string // "insertOne", "updateOne", "updateMany", // "deleteOne", "deleteMany", "replaceOne" filter?: object // per update/delete/replace document?: object // per insertOne update?: object // per updateOne/updateMany replacement?: object // per replaceOne}MongoBulkWriteResult:
{ insertedCount: number matchedCount: number modifiedCount: number deletedCount: number}Esempio
Sezione intitolata “Esempio”async function main() { const conn = "my-mongo"; // nome credenziale di accesso con stringa di connessione
// Inserisci un documento const result = await g.mongodb.insertOne(conn, "scraping", "products", { name: "Widget", price: 9.99, category: "tools" }); g.log("Inserito: " + result.insertedId);
// Trova con filtro e ordinamento const docs = await g.mongodb.find(conn, "scraping", "products", { price: { $lt: 20 } }, { sort: { price: 1 }, limit: 10 } ); g.log("Trovati " + docs.length + " prodotti economici");
// Pipeline di aggregazione const stats = await g.mongodb.aggregate(conn, "scraping", "products", [ { $group: { _id: "$category", avgPrice: { $avg: "$price" }, count: { $sum: 1 } } }, { $sort: { count: -1 } } ]); for (const s of stats) { g.log(s._id + ": " + s.count + " elementi, media $" + s.avgPrice.toFixed(2)); }}g.postgres.* — PostgreSQL
Sezione intitolata “g.postgres.* — PostgreSQL”Operazioni PostgreSQL tramite Npgsql. Usa parametri posizionali $1, $2, ...: non interpolare mai valori dentro stringhe SQL. Il parametro conn è il nome di una credenziale di accesso che contiene la stringa di connessione. Usa connection pooling automatico. Bloccato per gli script di origine MCP.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
query | (conn, sql, params?) → Promise<object[]> | Sì | SELECT che restituisce tutte le righe |
queryOne | (conn, sql, params?) → Promise<object | null> | Sì | SELECT che restituisce la prima riga |
execute | (conn, sql, params?) → Promise<PgExecuteResult> | Sì | INSERT/UPDATE/DELETE |
scalar | (conn, sql, params?) → Promise<any> | Sì | Restituisce la prima colonna della prima riga |
transaction | (conn, callback) → Promise<any> | Sì | Esegue una callback in una transazione (solo JS) |
executeBatch | (conn, statements) → Promise<PgBatchResult> | Sì | Più statement in una singola transazione |
copyFrom | (conn, table, rows, options?) → Promise<PgCopyResult> | Sì | Inserimento in blocco tramite protocollo COPY |
copyTo | (conn, query, options?) → Promise<string[][]> | Sì | Esportazione in blocco tramite protocollo COPY |
listDatabases | (conn) → Promise<string[]> | Sì | Elenca i nomi dei database non di modello |
listSchemas | (conn, options?) → Promise<string[]> | Sì | Elenca i nomi degli schemi |
listTables | (conn, schema?) → Promise<PgTableInfo[]> | Sì | Elenca tabelle e viste con conteggi righe |
describeTable | (conn, table, schema?) → Promise<PgColumnInfo[]> | Sì | Metadati colonne (tipi, nullability, default, PK) |
listIndexes | (conn, table, schema?) → Promise<PgIndexInfo[]> | Sì | Metadati indici con definizioni |
listConstraints | (conn, table, schema?) → Promise<PgConstraintInfo[]> | Sì | Metadati vincoli (PK, FK, UNIQUE, CHECK) |
PgExecuteResult:
{ rowsAffected: number}PgTableInfo:
{ name: string schema: string type: string // "table" o "view" estimatedRows: number // da pg_class.reltuples}PgColumnInfo:
{ name: string type: string // es. "integer", "character varying", "timestamp with time zone" nullable: boolean defaultValue: string | null isPrimaryKey: boolean maxLength: number | null // per tipi stringa}PgIndexInfo:
{ name: string columns: string[] isUnique: boolean isPrimary: boolean definition: string // statement CREATE INDEX completo}PgConstraintInfo:
{ name: string type: string // "PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK" columns: string // nomi colonne separati da virgole definition: string // definizione del vincolo}PgBatchStatement:
{ sql: string // SQL con parametri posizionali $1, $2, ... params?: any[] // valori dei parametri}PgBatchResult:
{ results: PgExecuteResult[] // conteggi rowsAffected per statement}PgTransactionProxy — passato al callback transaction:
{ query: (sql, params?) => Promise<object[]> queryOne: (sql, params?) => Promise<object | null> execute: (sql, params?) => Promise<PgExecuteResult> scalar: (sql, params?) => Promise<any>}PgCopyFromOptions:
{ columns?: string[] // nomi colonne a cui associare i valori riga (in ordine) schema?: string // predefinito: "public"}PgCopyToOptions:
{ schema?: string // predefinito: "public" (solo per nomi tabella, non query SQL)}PgCopyResult:
{ rowsCopied: number}PgSchemaOptions:
{ includeSystem?: boolean // include pg_* e information_schema (predefinito: false)}Esempio
Sezione intitolata “Esempio”async function main() { const conn = "my-postgres"; // nome credenziale di accesso con stringa di connessione
try { // Query con parametri const rows = await g.postgres.query(conn, "SELECT id, name, price FROM products WHERE price < $1 ORDER BY price", [20.00] ); g.log("Trovati " + rows.length + " prodotti");
// Transazione con callback const result = await g.postgres.transaction(conn, async (tx) => { await tx.execute("INSERT INTO orders (product_id, qty) VALUES ($1, $2)", [42, 3]); await tx.execute("UPDATE products SET stock = stock - $1 WHERE id = $2", [3, 42]); return await tx.scalar("SELECT count(*) FROM orders"); }); g.log("Ordini totali: " + result);
// Inserimento in blocco via COPY (molto più veloce di INSERT riga per riga) const copyResult = await g.postgres.copyFrom(conn, "products", [ ["Widget A", 9.99, 100], ["Widget B", 14.99, 50], ["Widget C", 24.99, 25] ], { columns: ["name", "price", "stock"] }); g.log("Importate " + copyResult.rowsCopied + " righe"); } catch (e) { g.log("Errore: " + e.message); }}g.elasticsearch.* — Elasticsearch
Sezione intitolata “g.elasticsearch.* — Elasticsearch”Supporto nativo per query e indicizzazione di dati in cluster Elasticsearch esterni tramite Elastic.Clients.Elasticsearch. Il parametro conn è il nome di una credenziale di accesso che contiene l’oggetto JSON di connessione (url e apiKey opzionale oppure username/password). Bloccato per gli script di origine MCP.
| Metodo | Firma | Async | Descrizione |
|---|---|---|---|
ping | (conn) → Promise<boolean> | Sì | Verifica la connessione al cluster. Restituisce true se riuscita. |
info | (conn) → Promise<ElasticsearchInfoResult> | Sì | Recupera metadati del cluster (nome, versione, tagline, ecc.). |
createIndex | (conn, indexName, mappingJson?) → Promise<boolean> | Sì | Crea un indice con una stringa JSON di mapping opzionale. |
deleteIndex | (conn, indexName) → Promise<boolean> | Sì | Elimina un indice esistente. |
index | (conn, indexName, id, document) → Promise<boolean> | Sì | Indicizza un singolo oggetto JS nel cluster. |
get | (conn, indexName, id) → Promise<any> | Sì | Recupera un singolo documento per ID. Restituisce l’oggetto _source parsato. |
bulk | (conn, indexName, documents, chunkSize?) → Promise<ElasticsearchBulkResult> | Sì | Ingestione ad alta velocità. Suddivide automaticamente array grandi per evitare limiti di contenuto. |
search | (conn, indexName, queryDsl) → Promise<any> | Sì | Esegue una query DSL JSON grezza o un oggetto JS e restituisce gli hit deserializzati. |
ElasticsearchInfoResult:
{ name: string clusterName: string clusterUuid: string version: string tagline: string}ElasticsearchBulkResult:
{ total: number successful: number failed: number}Esempio
Sezione intitolata “Esempio”async function main() { const conn = "my-elastic"; // nome credenziale di accesso
// Controlla la connessione const isUp = await g.elasticsearch.ping(conn); if (!isUp) return g.log("Connessione fallita");
// Indicizza documenti in blocco const docs = [{ id: 1, text: "A" }, { id: 2, text: "B" }]; const bulkRes = await g.elasticsearch.bulk(conn, "products", docs, 1000); g.log(`Indicizzati ${bulkRes.successful} su ${bulkRes.total}`);
// Ricerca con Query DSL const searchRes = await g.elasticsearch.search(conn, "products", { query: { match_all: {} } }); g.log(`Hit totali: ${searchRes.hits.total.value}`);}