Hive Devs Journal "HiveSQL" | Diario del desarrollador Hive

freepik__a-cyberpunkstyle-illustration-of-a-hacker-typing-c__48325.jpeg

Saludos Hivers, siempre es un placer saludarles y compartir lo que voy llevando a cabo. Quiera Dios que mis artículos sirvan para compartir el conocimiento y ahorrarles tiempo y esfuerzo mientras desarrollan en HIVE.

Otro dia otro reto

Ahora estoy en el diseño de una aplicacion especial para mi amigo @ecoinstant y no dire mucho pero les comento que sera relacionada con el HSBI @steembasicincome para ayudar a automatizar algunos procesos.

Nuevamente me encuentro con mas cosas que aunque nuevas para mi el dia de hoy, son fascinantes y valen la pena para dedicarles tiempo.

Hive SBI?

En las propias palabras de sus creadores cito:

Hive Stake Based Income (Hive SBI) es un experimento social para llevar una renta básica voluntaria financiada por crowdfunding al mayor número posible de Hivers. Los miembros se unen al programa patrocinando a otros. Hive SBI se entrega a través de proporcionar upvotes regulares a los contenidos de los miembros. Si usted no está activo en Steem, pero todavía tiene unidades allí, por favor lea los documentos para aprender a consolidar en una sola cadena. Mas info aca

En otras palabras:

  • Es una iniciativa fabulosa para usar el "human networking" o "social networking" para darnos apoyo mutuamente en la constante "batalla de los votos en HIVE".
  • Es una manera de ayudar a otros, al pagar un poco por su inclusion en el programa y recibir votos a cambio.
  • Y por eso y mucho mas, decido ayudar e ir aportando granitos de codigo para automatizar procesos.

Como puedo participar en Hive SBI?

  1. Contacta a otro miembro del HSBI para que te incluya ya que es la unica manera de participar. Puedes ir a conversar en el discord de Hive SBI y de seguro te daran patrocinio.
  2. Si quieres espiar un poco y ver quienes son miembros entra en la pagina oficial aca y ve a la seccion de "Famosos" y usando el nombre de usuario que ves en la lista puedes escribirles.
  3. Dejame un mensaje en comentarios y te incluyo en una rifa para tratar de incluir nuevas personas cada semana.
  4. Una vez dentro, puedes delegar HP(Hive Power) a la cuenta de @steembasicincome y con esto ganas unidades que se traducen en mayores probabilidades de voto y curacion.

Que beneficios tengo con eso del HSBI?

  • Contar con el apoyo de miembros de trayectoria en HIVE y con votos y curacion para tus publicaciones.
  • Hacer mas "red web3" para ir escalando en reputacion e incluso conectar con mas proyectos que de muchas maneras estan cambiando el mundo.

HiveSQL

Si eres nuevo en el mundo de la programacion de HIVE, te doy la bienvenida y te digo que si empiezas a hacer consultas a los nodos RPC te daras cuenta que como me dijo una vez @cedricguillas "alguna herramientas y librerias de HIVE son mejores para algunas cosas que otras".
Para entender lo que digo: intenta buscar las cuentas nuevas usando solo los nodos RPC. Una manera seria revisando la creacion de cuentas bloque por bloque. Si diariamente se crear alrededor de(1 bloque cada 3 segundos) = 28.800 bloques.

Es por eso que al buscar aca mismo en peakd encontre una solucion que ya tiene tiempo y fue hecha por otro gran programador llamado @arcange y se trata de HIVESQL que combina el poder de SQL o "Lenguaje de consulta estructurado" y la blockchain de HIVE.

Entendiendo en codigo:

Si intento hacer una consulta a los nodos RPC para buscar nuevas cuentas en la ultimas 24h, tendria un extracto de codigo como este, si ejecuto una busqueda en los ultimos 28.800 bloques:

async function findNewAccountsInBlock(blockNum: number): Promise<string[]> {
    try {
        const block = await client.database.getBlock(blockNum);

        if (!block) {
            // This might happen for very recent blocks or if the block number is invalid.
            // console.warn(`Block ${blockNum} not found or not available yet.`); // Optional: log warnings
            return [];
        }

        const newAccounts: string[] = [];
        // A block contains transactions
        for (const transaction of block.transactions) {
            // Each transaction contains operations
            for (const operation of transaction.operations) {
                // The operation is an array: [operation_name, operation_payload]
                const operationName = operation[0];
                const operationPayload = operation[1];

                // Check if the operation is for account creation
                if (operationName === 'account_create' || operationName === 'account_create_with_delegation') {
                    // The new account name is in the 'new_account_name' field of the payload
                    const newAccountName = operationPayload.new_account_name;
                    if (newAccountName) {
                        newAccounts.push(newAccountName);
                    }
                }
            }
        }
        return newAccounts;
    } catch (error) {
        // console.error(`Error fetching or processing block ${blockNum}:`, error); // Optional: log errors
        return []; // Return empty array in case of error
    }
}

Esto seria solamente una parte del modulo. Ya lo hice y lo probe. El resultado es que para este caso, de buscar nuevas cuentas, esta manera tarda y mucho. Mas de 10 segundos solo para recorrer un dia entero de bloques. Y eso no tiene sentido si va a usarse en un frontend solo para iniciar un proceso

Ahora como se ve el codigo usando HiveSQL con nodejs:

 try {
    await sql.connect(sqlConfig);
    const result = await sql.query`
      SELECT TOP 100 name, created -- Usamos TOP 100 para limitar los resultados en SQL Server
      FROM Accounts
      WHERE created >= DATEADD(day, -1, GETDATE()) -- Resta 1 día a la fecha y hora actual
      ORDER BY created DESC;
    `;
    console.dir(result);
  } catch (err) {
    console.error(err);
  }

Y el tiempo de ejecución no supera los 3 segundos y eso que estoy en la republica "aislada" de Venezuela.

Como usar HIVESQL

  • Transferir 1 HBD a @hivesql (no se requiere memo)
  • Tan pronto como @hivesql reciba su transferencia, se procesará su activación.
  • Unos segundos después, recibirás una microtransferencia de vuelta de @hivesql.

image.png

  • El memo de transferencia @hivesql contiene tus nuevas credenciales y, por tanto, está cifrado.
  • Para decifrar dicho memo, usando peakd, veras un candadito verde. Haces click en el y te abre la keychain wallet y listo. Guarda esos datos en un lugar seguro.
  • Ante dudas ve al discord de soporte de HiveSQL

Ahora que mas puedo hacer si soy desarrollador de nodejs o Javascript?

Primero empecemos por observar y analizar la base de datos directamente. Para esto instalemos(windows) "Azure Data Estudio".

Luego, ejecutamos la instalacion, todo por defecto y se deberia ejecutar. Veras algo asi:

image.png
He subrayado donde podemos ejecutar una conexion a la base de datos.

  • Hacemos clic y tenemos nuestros datos de usuario de HIVESQL a la mano.

image.png

  • Selecciona "SQL Login" y "Trust server.." como true. Agrega los demas datos y click en "Connect". Finalmente deberias ver la base de datos asi:

image.png

De que sirve visualizar la base de datos de HIVESQL?

Sirve de mucho porque podras:

  • Ejecutar consultas y verifica campos lo que te permitira construir consultas adecuadas para tu backend en nodejs por ejemplo.
  • Indagar las diversas opciones y saber mas o menos que permisos tienes como usuario regular.

Combinemos con nodejs, que herramientas usar para HIVESQL?

Tenemos muchas opciones, hasta el momento estoy probando una que me parece muy adecuada y es mssql y el repositorio por aca

Usando #mssql con nodejs para una API de consultas en HIVE

  • Suponemos que ya tienes configurada una app con express y al menos una primera ruta.
  • Instala el paquete de mssql desde la terminal de vscode

npm i mssql

  • Hagamos un modulo aparte, para mejor uso a futuro, mantenimiento y ampliacion. Llamemoslo db.ts y dentro hagamos una conexion de prueba:
import dotenv from "dotenv";
import sql from "mssql";

dotenv.config();

const sqlConfig = {
  user: process.env.USER!,
  password: process.env.PASSWORD!,
  database: process.env.DATABASE!,
  server: process.env.HOST!,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
  options: {
    trustServerCertificate: true,
  },
};

export const testConnection = async () => {
  try {
    await sql.connect(sqlConfig);
    const result = await sql.query`
      SELECT TOP 100 name, created 
      FROM Accounts
      WHERE created >= DATEADD(day, -1, GETDATE())
      ORDER BY created DESC;
    `;
     return result;
  } catch (err) {
    console.error(err);
    return null;
  }
};

Eso lo vamos a colocar en una ruta para probar HIVESQL y deberia devolver las 100 primeras cuentas creadas hace 24 horas. Y nos dara el campo name y el campo created

  • Ahora hagamos la ruta, supongamos que nos referimos al mismo archivo routes.ts:
router.get("/testCon", async (req, res) => {
  const tests = await testConnection();
  res.status(200).json({ tests });
});
  • Y en algun lugar del archivo principal del backend tendremos:
app.use("/api", accountsRouter);

En mi caso lo estoy usando en /api/testCon y pertenece a las rutas de cuentas. Pero puedes hacerlo como prefieras y/o necesites.
Y si todo marcha bien deberiamos ver nuestra primera consulta de la blockchain de HIVE usando HIVESQL:

image.png

Para que me tomo el tiempo de compartir lo que voy "descubriendo"?

  1. Creo que como dijo Morgan Freeman en la pelicula Lucy pues compartir el conocimiento es la base de que hoy seamos quienes somos y eso, define quienes podemos ser o no ser.
  2. Como desarrolladores de la web3 deberiamos tener el ideal de ayudar a otros y expandir nuestro circulo de desarrollo para que otros puedan venir y, quien sabe, inventar el proximo LEO token que en vez de 1 millon, llegue a capitalizar 1000 millones. Y no es solo dinero sino calidad de vida.
  3. Para que otros desarrolladores solo tengan que buscar articulos especificos en HIVE y puedan mejorar su codigo y su camino sea fluido.

Ultimo Tio y cierro

  • Para saber datos mas relevantes de una tabla y sus tipos de datos, usando Azure Data Studio y estando conectado a HIVESQL, ejecuta la siguiente consulta:
SELECT 
    COLUMN_NAME, 
    DATA_TYPE, 
    CHARACTER_MAXIMUM_LENGTH, 
    IS_NULLABLE
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_NAME = 'Comments';

Eso te dara lo siguiente:

image.png

Y eso vale oro para que sepas sobre el esquema de una tabla en particular. Asi podras estructurar mejor tus consultas :)


English

Greetings Hivers, it's always a pleasure to greet you and share what I'm working on. God willing, my articles will help share knowledge and save you time and effort as you develop on HIVE.

Another Day, Another Challenge

Right now, I'm designing a special application for my friend @ecoinstant. I won't say much, but I can tell you it will be related to HSBI @steembasicincome to help automate some processes.

Once again, I'm facing new things that, although unfamiliar to me today, are fascinating and worth spending time on.

Hive SBI?

In the creators’ own words:

Hive Stake Based Income (Hive SBI) is a social experiment to bring a voluntary crowdfunded basic income to as many Hivers as possible. Members join the program by sponsoring others. Hive SBI is delivered through providing regular upvotes to member content. If you are not active on Steem but still have units there, please read the documents to learn how to consolidate to a single chain. More info here

In other words:

  • It’s a fabulous initiative to use human or social networking to support each other in the constant “battle for votes” on HIVE.
  • It’s a way to help others by paying a bit for their inclusion in the program and receiving votes in return.
  • And for all that and more, I’ve decided to help and contribute little bits of code to automate processes.

How Can I Participate in Hive SBI?

  1. Contact another HSBI member to sponsor you, as that’s the only way to participate. You can join the Hive SBI Discord and they’ll likely sponsor you.
  2. If you want to snoop around and see who the members are, visit the official page here and go to the "Famous" section. Using the usernames on the list, you can reach out to them.
  3. Leave me a comment, and I’ll include you in a raffle to try to get new people in each week.
  4. Once you're in, you can delegate HP (Hive Power) to the @steembasicincome account, which earns you units that translate to higher voting and curation chances.

What Benefits Do I Get From HSBI?

  • Support from experienced HIVE members, along with votes and curation for your posts.
  • Building more web3 connections to grow in reputation and even connect with other projects that are changing the world in many ways.

HiveSQL

If you’re new to HIVE development, welcome! You’ll notice that if you start querying RPC nodes, you’ll realize—as @cedricguillas once told me—“some HIVE tools and libraries are better for some things than others.”
To understand what I mean: try searching for new accounts using only RPC nodes. One way would be to check account creation block by block. If approximately 1 block is created every 3 seconds, that’s about 28,800 blocks per day.

That’s why, while searching here on PeakD, I found a solution that’s been around for a while by another great programmer, @arcange. It’s called HIVESQL and it combines the power of SQL (Structured Query Language) with the HIVE blockchain.

Understanding With Code:

If I try to query RPC nodes to find new accounts in the last 24 hours, I’d use code like this to scan through 28,800 blocks:

async function findNewAccountsInBlock(blockNum: number): Promise<string[]> {
    try {
        const block = await client.database.getBlock(blockNum);

        if (!block) {
            return [];
        }

        const newAccounts: string[] = [];

        for (const transaction of block.transactions) {
            for (const operation of transaction.operations) {
                const operationName = operation[0];
                const operationPayload = operation[1];

                if (operationName === 'account_create' || operationName === 'account_create_with_delegation') {
                    const newAccountName = operationPayload.new_account_name;
                    if (newAccountName) {
                        newAccounts.push(newAccountName);
                    }
                }
            }
        }
        return newAccounts;
    } catch (error) {
        return [];
    }
}

This is only a small part of the module. I built and tested it. The result? For this task, scanning for new accounts takes too long—over 10 seconds just to process one day of blocks. That makes no sense for a frontend process just to trigger something.

Here’s what the code looks like using HiveSQL with Node.js:

try {
  await sql.connect(sqlConfig);
  const result = await sql.query`
    SELECT TOP 100 name, created
    FROM Accounts
    WHERE created >= DATEADD(day, -1, GETDATE())
    ORDER BY created DESC;
  `;
  console.dir(result);
} catch (err) {
  console.error(err);
}

The execution time is under 3 seconds—and I’m in the "isolated" Republic of Venezuela.

How to Use HIVESQL

  • Send 1 HBD to @hivesql (no memo required).

  • Once @hivesql receives your transfer, your activation will be processed.

  • A few seconds later, you’ll receive a micro-transfer back from @hivesql.

image.png

The memo in the transfer from @hivesql contains your new credentials and is encrypted.

To decrypt it in PeakD, click the little green lock. It’ll open your keychain wallet. Save those details securely.

For help, join the HiveSQL Support Discord


What Else Can I Do as a Node.js or JavaScript Developer?

Let’s start by exploring and analyzing the database directly. For this, install "Azure Data Studio" on Windows.

After installation, just run it. You’ll see something like this:

image.png
I’ve highlighted where you can set up the database connection.

  • Click it and use your HIVESQL credentials.

image.png

  • Select “SQL Login” and set “Trust server…” to true. Add the rest of the details and click “Connect.” You should then see the database like this:

image.png

Why Is Visualizing the HIVESQL Database Useful?

It’s incredibly helpful because you can:

  • Run queries and verify fields to build accurate queries for your Node.js backend.

  • Explore different options and understand what access you have as a regular user.

Combining With Node.js: What Tools to Use for HIVESQL?

There are many options. So far, I’m testing one I find very useful: mssql. Here’s the GitHub repo

Using #mssql With Node.js for a HIVE Query API
Assume you’ve already set up an Express app with at least one route.

Install the mssql package in VSCode terminal:

npm i mssql

  • Create a separate module for better reusability and maintenance. Call it db.ts and use it to test the connection:
import dotenv from "dotenv";
import sql from "mssql";

dotenv.config();

const sqlConfig = {
  user: process.env.USER!,
  password: process.env.PASSWORD!,
  database: process.env.DATABASE!,
  server: process.env.HOST!,
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000,
  },
  options: {
    trustServerCertificate: true,
  },
};

export const testConnection = async () => {
  try {
    await sql.connect(sqlConfig);
    const result = await sql.query`
      SELECT TOP 100 name, created 
      FROM Accounts
      WHERE created >= DATEADD(day, -1, GETDATE())
      ORDER BY created DESC;
    `;
    return result;
  } catch (err) {
    console.error(err);
    return null;
  }
};
  • We’ll now connect it to a route. Let’s say it’s in routes.ts:
router.get("/testCon", async (req, res) => {
  const tests = await testConnection();
  res.status(200).json({ tests });
});
  • Somewhere in your main backend file:
    app.use("/api", routerFile);

In my case, it’s under /api/testCon, part of the accounts routes. But feel free to set it up however fits your project. If all goes well, you’ll see your first query from the HIVE blockchain using HIVESQL:

image.png

Why Do I Take Time to Share What I’m Discovering?

Like Morgan Freeman said in the movie Lucy, sharing knowledge is the foundation of who we are—and who we might become.

As web3 developers, we should aim to help others and expand our dev circles, so future builders can come along and maybe invent the next LEO token—one worth billions, not just millions. And it’s not just money, but quality of life.

So other developers can easily find relevant HIVE articles and improve their code and development journey.

Final Tip

To know more about a table’s columns and data types using Azure Data Studio, run this:

SELECT 
    COLUMN_NAME, 
    DATA_TYPE, 
    CHARACTER_MAXIMUM_LENGTH, 
    IS_NULLABLE
FROM 
    INFORMATION_SCHEMA.COLUMNS
WHERE 
    TABLE_NAME = 'Comments';

You’ll get something like this:

image.png

And that’s gold when it comes to understanding a table’s structure. It’ll help you craft better queries. :)


discords:

documentaciones:


@theghost1980
Send me some love using the link in the image bellow:

Mándame algo de amor usando el enlace en la imagen de abajo:

support-apps-hive-tipjar-keychain.png

Sort:  

¡Qué bueno ver avances con HiveSQL! 🐴 Me intriga esa app para HSBI de @ecoinstant. ¡Seguro será genial! 😉

Saludos, gracias por su apoyo. Digamos que la app es para expandir aun mas las buenas acciones del HSBI. Apenas tenga avances importantes, con todo gusto publicare sobre eso.

@theghost1980 es un desarrollador increíble!

Gracias amigo! Intento hacer lo mejor que puedo y agradezco cada dia como una nueva oportunidad! Un abrazo!