ArangoDB

Responder
ramirezosvaldo
Mensajes: 127
Registered for: 3 years 5 months
Mexico

ArangoDB

Mensaje por ramirezosvaldo »

Hola,

Information basically

CRUD = Create,Read,Update,Delete; Concepto informático el cual es usado bajo protocolo http(s)
( Si hay mas dudas, pregunten!!! )

ArangoDB es un motor de base de datos tipo NoSQL, tipo MongoDB, anexo un link como compartivo.

https://www.arangodb.com/solutions/comp ... s-mongodb/

Al momento de instalar ArangoDB, este tiene de manera integral un WebServer para la administración de la DB y un WebService para el acceso via URL.

Toda la información necesaria para lograr esto, esta en :

https://www.arangodb.com/docs/stable/http/index.html

Y pongo un ejemplo simple el cual se conecta al servidor de ArangoDB y lo he corrido desde modharbour; Si todo va bien,
entonces nos regresa un JWT, y este dato lo usamos para todas las acciones posteriores

Como dato importante, esto es CRUD, por lo tanto, aceptar POST,GET,UPDATE,DELETE, etc, etc.

Código: Seleccionar todo

*********

#define HB_CURLOPT_POST                       47
#define HB_CURLOPT_URL                        2
#define HB_CURLOPT_DL_BUFF_SETUP              1008
#define HB_CURLOPT_HTTPHEADER                 23
#define HB_CURLOPT_USERPWD                    5
#define HB_CURLOPT_POSTFIELDS                 15
#define HB_CURLINFO_RESPONSE_CODE             2

function Main
AP_SetContentType( "application/json" )
?? curl( "http://127.0.0.1:8529/_open/auth","root","#ArangoDB#")
return nil

function curl( cUrl ,  cuser , cPassword )
    local nCode
    local cCode
    local uReturn
    local hCurl
    local hData := {=>}
    hData["username"] := cuser
    hData["password"] := cPassword
    curl_global_init()
    if ! empty( hCurl := curl_easy_init() )
        curl_easy_setopt( hCurl, HB_CURLOPT_POST, 1 )
        curl_easy_setopt( hCurl, HB_CURLOPT_URL, cUrl )
        curl_easy_setopt( hCurl, HB_CURLOPT_DL_BUFF_SETUP )
        curl_easy_setopt( hCurl, HB_CURLOPT_HTTPHEADER, {"Content-Type:application/json"} )
        curl_easy_setopt( hCurl, HB_CURLOPT_POSTFIELDS, hb_jsonencode(hData))
        if  curl_easy_perform( hCurl ) = 0
            nCode =curl_easy_getinfo(hCurl,HB_CURLINFO_RESPONSE_CODE)
                uReturn = curl_easy_dl_buff_get( hCurl )     // que regreso
        endif
    endif
    curl_global_cleanup()
RETU uReturn

*********
Pongo en otro msg otro ejemplo un poquito mas estructurado de como pudiera ser una clase, este esta operativo en Xbase++, pero debo decir que estoy a anos luz de que este completo, el camino apenas empieza. Esperando que se de una idea; Como ultimo comentario las bases de datos NoSQL no pretenden sustituir a las
bases de datos relaciónales, pero si pueden ser una super ayuda en los sistemas.

Saludos
Osvaldo Ramirez
Última edición por ramirezosvaldo el Sab Nov 06, 2021 8:54 pm, editado 1 vez en total.

ramirezosvaldo
Mensajes: 127
Registered for: 3 years 5 months
Mexico

Mensaje por ramirezosvaldo »

// Segundo ejemplo

Código: Seleccionar todo

#include "os.ch"
#include "xbp.ch"
#include "dll.ch"
#include "gra.ch"
#include "std.ch"
#include "ot4xb.ch"
#include "thread.ch"
#include "common.ch"
#include "activex.ch"
#include "Directry.ch"
#include "appevent.ch"

#define  OK        200


#include "xbp.ch"

PROCEDURE AppSys();return

PROCEDURE  main
* Begin

  local oArangoDB
  local cURL := "http://127.0.0.1"
  local nPort := 8529
  LOCAL cUser := "root"
  LOCAL cPassword := "1234"
  local cJson  , lError

  oArangoDB := ArangoDB():new( cURL , nPort )

  if oArangoDB:login( cUser , cPassword )

    msgbox("conetactado " + oArangoDB:jwt )
    

    // Para Crear una Tabla junto con usuarios de acceso
    TEXT INTO cJson WRAP
{
  "name" : "mydb3",
  "users" : [
    {
      "username" : "admin",
      "passwd" : "secret",
      "active" : true
    },
    {
      "username" : "tester",
      "passwd" : "test001",
      "active" : false
    }
  ]
}
   ENDTEXT

    if oArangoDB:execute( "POST" , "/_api/database" , cJson   ) = 200

       msgbox( "Tabla Creada" )

    else

       msgbox( "No se creo la tabla" )

    endif

  ELSE

    msgbox("Sin coneccion")

  ENDIF

RETURN


CLASS ArangoDB

   EXPORTED:

      VAR url        // string
      VAR port       // numeric
      VAR jwt        // string
      VAR http       // string
      VAR user       // string
      VAR password   // strgin
      VAR reponse    // response string of the last call
      VAR currentDB

      METHOD init()  // Create Objet

      METHOD login
        
//      METHOD dbf2Arango        // Export DBF to the current DB
//      METHOD CreateDB          // Create Database
//      METHOD DataSet           //
//      METHOD CurrentDatabase     // Current Database
//      METHOD CreateCollection  // Create Table
//      METHOD DeleteCollection  // Delete Table
//      METHOD ReadDocument      // Select
//      METHOD InsertDocument    // Insert Record
//      METHOD UpdateDocument    // Update Record
//      METHOD DeleteDocument    // Delete Record

      METHOD execute

ENDCLASS


// Inicializamos el objeto, este se ejecuta cuando se se llama :new() y nos sirve para inicializar variables.
// En caso de que cuando de que no se le pase parametros usa los default
METHOD ArangoDB:init(cURL ,nPort )

   DEFAULT cURL      TO "http://127.0.0.1"
   DEFAULT nPort     TO 8529

   ::url   := cURL
   ::Port  := nPort
   ::jwt   := ""

RETURN self

// Metodo Generico para hacer las llamadas al API
// Uso el pametro cfuncion para ver que API se va a llamar
//::Http:SetReQuestHeader( 'Content-lenght', 'text/pain')//application/json;charset=UTF-8')
// hay que hacer un encode64 el usuario + ":"+ password

METHOD ArangoDB:execute( cMetodo , cAPI , cJson )
* Begin

  if  valtype( cJson ) = 'O'
    cJson := json_serialize( cJson )
  endif

  // Pablo Botella Class for CURL on Xbase++
  ::Http := TServerXMLHTTPRequest():New()
  ::Http:Open( cMetodo , cAPI , .F. )
  ::Http:SetReQuestHeader( 'Content-Type', 'text/pain')//application/json;charset=UTF-8')
  ::Http:SetReQuestHeader( 'Connection', 'Keep-Alive')


  // Si el cAPI no es el login, entonce cada llamada debera tener cabezera 'Authorization' no importa si es POST o GET u otro
  if ! ( "_open/auth" $ cAPI )

    ::Http:SetReQuestHeader( 'Authorization','Basic ' + ::jwt )
  endif

  ::http:send( cJson )

RETURN ::Http:status


METHOD ArangoDB:login(cUser,cPassword)
* Begin

  local oAux
  local oJson
  local lError  := .f.
  local lReturn := .f.
  local cFuncion := "/_open/auth"

  DEFAULT cUser   TO "root"
  DEFAULT cPassword TO "1234"

  ::user := cUser
  ::password := cPassword

  /*
  {
  "username": "root",
  "password": ""
  }
  */

  oJson  := json_Container():New()    // Pablo Botella Wrapper to create a Json file
  oJson:username := ::user
  oJson:password := ::Password
  lReturn := ( ::execute( "POST" , ::url + ":" + alltrim(var2char(::Port)) + cFuncion , oJson ) ==  200 )

  if lReturn
      oAux :=  json_unserialize(  ::Http:responseText , @lError)
      ::jwt := oAux:jwt
   endif

RETURN  lReturn




// GET /_api/database/current
// Se graba un json en currentDB y solo regresa name del result
//{
//  "error" : false,
//  "code" : 200,
//  "result" : {
//    "id" : "1",
//    "name" : "_system",
//    "isSystem" : true,
//    "path" : "none"
//  }
//}
/*/
METHOD ArangoDB:CurrentDatabase(lReConnect)
* Begin
  local lError  := .f.
  local cReturn := ""
  local cAPI    := "/_api/database/current"
  local oJson   := nil

  default lReConnect  TO .f.

  if lReConnect .or. ::CurrentDB = NIL
    ::CurrentDB := NIL
    IF ::execute( "GET" , ::url + ":" + alltrim(var2char(::Port)) + cAPI  ) ==  200
      msgbox(  ::Http:responseText )

       oJson :=  json_unserialize(  ::Http:responseText , @lError)
       IF ! oJson:error
          ::CurrentDB := oJson:result
       endif
    ENDIF
  endif

  if ::currentDB != NIL
     cReturn := ::currentDB:name
  endif


RETURN cReturn

// POST "/_api/collection"
METHOD ArangoDB:CreateCollection( cCollectionName , lValidateIfExist )
* Begin
  local oAux
  local oJson
  local cFuncion := "/_api/collection"

  /*
   {
     "name" : "testCollectionUsers",
     "keyOptions" : {
       "type" : "autoincrement",
       "increment" : 5,
       "allowUserKeys" : true
     }
   }

  oAux  := json_Container():New()    // Pablo Botella Wrapper to create a Json file
  oAux:type := "autoincrement"
  oAux:increment := 5
  oAux:allowUserKeys := .t.

  oJson  := json_Container():New()    // Pablo Botella Wrapper to create a Json file
  oJson:name := cCollectionName
  oJson:keyOptions := oAux

  lReturn := ( ::execute( "POST" , ::url + ":" + alltrim(var2char(::Port)) + cFuncion , oJson ) ==  200 )

   msgbox(  ::Http:responseText )


  if lReturn
      oAux :=  json_unserialize(  ::Http:responseText , @lError)
   endif

RETURN  lReturn
*/

/*
METHOD ArangoDB:dbf2Arango( cFileDBF , cColectionName ,  )
* Begin
  local nReturn := NIL //
  DEFAULT cFileName TO ""
  DEFAULT cColection TO ""

  if ! empty( cFileDBF )
     if FExists( cFileDBF )

        select 0
        use ( cFileDBF ) shared
        if ! neterrr()
          go top
          if empty( cColection )
             cColection := alias()
          endif

          if ::CreateColeccion( cColectionName ,  )
            nReturn := 0
            do while ! eof()

               ArangoDB:insert( cColection , oJson )
               nReturn++
               skip 1

            enddo

          else

            nReturn := -1

          endif

        else
          nReturn := -2
        endif
     else
       nReturn := -3
     endif
  else
    nReturn := -4
  endif

RETUR nReturn
*/

Cristobal
Site Admin
Mensajes: 315
Registered for: 3 years 6 months
Spain

Mensaje por Cristobal »

Muchas gracias Osvaldo
Puedes poner el enlace a la versión que has instalado tú en tu ordenador ?
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces

ramirezosvaldo
Mensajes: 127
Registered for: 3 years 5 months
Mexico

Mensaje por ramirezosvaldo »

Cristobal, buen dia.

Este es el link

https://www.arangodb.com/download-major/windows/

Saludos
Osvaldo Ramirez

Cristobal
Site Admin
Mensajes: 315
Registered for: 3 years 6 months
Spain

Mensaje por Cristobal »

Gracias Osvaldo
Hay dos tipos de personas: las que te hacen perder el tiempo y las que te hacen perder la noción del tiempo
El secreto de la felicidad no está en hacer lo que te gusta, sino en que te guste lo que haces

Responder