Gab RM SQLite

Gab RM SQLite
Version: 1.0.0
By: Gab!



Introduction

Allows you to create SQL databases locally, without server or Internet connection, of course, also will not allow others to see what's in this file unless you send it to them.

Features

Screenshots

Imperceptible by images

Demo

Not necessary, I think.

Script

Script Spoiler
  1.  
  2. #==============================================================================
  3. # ** SQLiteAPI
  4. #------------------------------------------------------------------------------
  5. #  Importa todas as funções usadas pelo script, a partir da DLL do SQLite3
  6. #==============================================================================
  7. module SQLiteAPI
  8.   FUNCTIONS = {}
  9.   DLL       = "System/SQLite3"
  10.  
  11.   # Prototypes
  12.   [
  13.     [:open,          "PP",   "L"], [:prepare,       "LPIPI", "I"],
  14.     [:sleep,         "L",    "I"], [:step,          "L",     "I"],
  15.     [:column_count,  "L",    "I"], [:column_name,   "LI",    "P"],
  16.     [:column_type,   "LI",   "I"], [:column_text,   "LI",    "P"],
  17.     [:column_int,    "LI",   "I"], [:column_double, "LI",    "D"],
  18.     [:finalize,      "L",    "I"], [:close,         "L",     "I"],
  19.     [:backup_init,   "LPLP", "L"], [:backup_step,   "LI",    "I"],
  20.     [:backup_finish, "L",    "I"], [:errmsg,        "L",     "P"]
  21.  
  22.   ].each{|func, arg1, arg2|
  23.     FUNCTIONS[func] = Win32API.new(DLL, "sqlite3_#{func.to_s}", arg1, arg2)
  24.     define_method(func){|*args| FUNCTIONS[func].call(*args) }
  25.     module_function(func)
  26.   }
  27.  
  28.   # Constantes
  29.   SQLITE_OK         =   0
  30.   SQLITE_ERROR      =   1
  31.   SQLITE_INTERNAL   =   2
  32.   SQLITE_PERM       =   3
  33.   SQLITE_ABORT      =   4
  34.   SQLITE_BUSY       =   5
  35.   SQLITE_LOCKED     =   6
  36.   SQLITE_NOMEM      =   7
  37.   SQLITE_READONLY   =   8
  38.   SQLITE_INTERRUPT  =   9
  39.   SQLITE_IOERR      =  10
  40.   SQLITE_CORRUPT    =  11
  41.   SQLITE_NOTFOUND   =  12
  42.   SQLITE_FULL       =  13
  43.   SQLITE_CANTOPEN   =  14
  44.   SQLITE_PROTOCOL   =  15
  45.   SQLITE_EMPTY      =  16
  46.   SQLITE_SCHEMA     =  17
  47.   SQLITE_TOOBIG     =  18
  48.   SQLITE_CONSTRAINT =  19
  49.   SQLITE_MISMATCH   =  20
  50.   SQLITE_MISUSE     =  21
  51.   SQLITE_NOLFS      =  22
  52.   SQLITE_AUTH       =  23
  53.   SQLITE_FORMAT     =  24
  54.   SQLITE_RANGE      =  25
  55.   SQLITE_NOTADB     =  26
  56.   SQLITE_NOTYPE     =  27
  57.   SQLITE_ROW        = 100
  58.   SQLITE_DONE       = 101
  59.  
  60.   SQLITE_INTEGER    = 1
  61.   SQLITE_FLOAT      = 2
  62.   SQLITE_TEXT       = 3
  63.   SQLITE_BLOB       = 4
  64.   SQLITE_NULL       = 5  
  65.  
  66.   # Função auxiliar
  67.   module_function
  68.   def errorStr(id)
  69.     case id
  70.     when SQLITE_OK;         "Sem erros"
  71.     when SQLITE_ERROR;      "Erro na consulta ou database não encontrada"
  72.     when SQLITE_INTERNAL;   "Erro interno no SQLite"
  73.     when SQLITE_PERM;       "Permissão de acesso negada"
  74.     when SQLITE_ABORT;      "Rotina de callback abortou"
  75.     when SQLITE_BUSY;       "Arquivo de database trancado"
  76.     when SQLITE_LOCKED;     "Uma tabela na database está trancada"
  77.     when SQLITE_NOMEM;      "Falha ao alocar memória"
  78.     when SQLITE_READONLY;   "Tentativa de escrever na database somente-leitura"
  79.     when SQLITE_INTERRUPT;  "Operação terminada pelo sqlite3_interrupt()"
  80.     when SQLITE_IOERR;      "Algum tipo de erro de I/O ocorreu"
  81.     when SQLITE_CORRUPT;    "A imagem da database está corrompida"
  82.     when SQLITE_NOTFOUNT;   "Código desconhecido para sqlite3_file_control()"
  83.     when SQLITE_FULL;       "Inserção falhou por que a database está cheia"
  84.     when SQLITE_CANTOPEN;   "Não foi possível abrir o arquivo da database"
  85.     when SQLITE_PROTOCOL;   "Protocolo para trancar a database falhou"
  86.     when SQLITE_EMPTY;      "A database está vazia"
  87.     when SQLITE_SCHEMA;     "A database mudou seu esquema"
  88.     when SQLITE_TOOBIG;     "A String ou BLOB excedeu o limite de tamanho"
  89.     when SQLITE_CONSTRAINT; "Abortar devido à violação de restrição"
  90.     when SQLITE_MISMATCH;   "Tipos de dados incompatíveis"
  91.     when SQLITE_MISUSE;     "Biblioteca usada incorretamente"
  92.     when SQLITE_NOLFS;      "Uso de recursos do sistema operacional não suportado no host"
  93.     when SQLITE_AUTH;       "Autorização negada"
  94.     when SQLITE_FORMAT;     "Erro de formato da database auxiliar"
  95.     when SQLITE_RANGE;      "2º parâmetro para o sqlite3_bind() fora da faixa"
  96.     when SQLITE_NOTABD;     "Arquivo aberto não é uma database"
  97.     when SQLITE_NOTYPE;     "Tipo de dado desconhecido"
  98.     when SQLITE_ROW;        "sqlite3_step() tem outra linha pronta"
  99.     when SQLITE_DONE;       "sqlite3_step() terminou a execução"
  100.     end
  101.   end
  102.  
  103.   # Classe de erros
  104.   class Error < Exception
  105.   end
  106. end
  107.  
  108.  
  109. #==============================================================================
  110. # ** SQLite
  111. #------------------------------------------------------------------------------
  112. #  Classe que gerencia as conexões com databases de modo orientado.
  113. #==============================================================================
  114. class SQLite
  115.   #-------------------------------------------------------------------------
  116.   # * Atributos
  117.   #-------------------------------------------------------------------------
  118.   attr_reader :closed
  119.   attr_reader :filename
  120.  
  121.   #-------------------------------------------------------------------------
  122.   # * Inicialização
  123.   #   + filename : Nome de criação da database
  124.   #-------------------------------------------------------------------------
  125.   def initialize(filename = "#{__FILE__}.db")
  126.     # Variáveis de instância
  127.     @filename     = filename
  128.     @closed       = false
  129.     @queryRunning = false
  130.    
  131.     # Abre a conexão
  132.     db = [0].pack("L*")
  133.     SQLiteAPI.open(filename, db);
  134.     @handle = db.unpack("L*").first
  135.    
  136.     # Define o finalizador para liberar o acesso à database
  137.     ObjectSpace.define_finalizer(self, method(:finalize))
  138.   end
  139.  
  140.   #-------------------------------------------------------------------------
  141.   # * Faz uma query recursiva para um bloco, retornando para ele cada linha
  142.   #   que foi recebida pela query.
  143.   #   + str    : Query SQL
  144.   #   + &block : Bloco que receberá as linhas (deve receber um argumento)
  145.   #-------------------------------------------------------------------------
  146.   def recursiveQuery(str, &block)
  147.     # Retorna se já estiver rodando uma query
  148.     return if @queryRunning
  149.    
  150.     # Checa se o arquivo está aberto
  151.     check_closed
  152.     @queryRunning = true
  153.  
  154.     # Prepara a query
  155.     buffer  = [0].pack("L*")
  156.     rc      = SQLiteAPI.prepare(@handle, str, -1, buffer, 0)
  157.     query   = buffer.unpack("L*").first
  158.    
  159.     # Se houver problemas, finaliza e imprime o erro (sintaxe, tabela inexistente, etc)
  160.     if (rc != SQLiteAPI::SQLITE_OK)
  161.       raise(SQLiteAPI::Error, SQLiteAPI.errorStr(rc).force_encoding("ASCII-8BIT") + ": " + SQLiteAPI.errmsg(@handle).to_s, caller)
  162.     end
  163.    
  164.     # Roda um passo da query (geralmente retornando uma linha)
  165.     rc = SQLiteAPI.step(query)
  166.     while (rc != SQLiteAPI::SQLITE_DONE)
  167.       case rc
  168.       when SQLiteAPI::SQLITE_BUSY # Se não estiver completa, espera 0.01s.
  169.         SQLiteAPI.sleep(10)
  170.        
  171.       when SQLiteAPI::SQLITE_ERROR # Se houver erro, imprime o erro e finaliza
  172.         raise(SQLiteAPI::Error, SQLiteAPI.errmsg(@handle).to_s, caller)
  173.         break;
  174.        
  175.       when SQLiteAPI::SQLITE_ROW # Se tiver recebido corretamente a linha, trata
  176.         rowdata = {}
  177.        
  178.         # Contagem de colunas
  179.         n = SQLiteAPI.column_count(query)
  180.        
  181.         # Recebimento da linha
  182.         n.times{|i|
  183.           # Nome e tipo da coluna
  184.           name = SQLiteAPI.column_name(query, i).to_s
  185.           type = SQLiteAPI.column_type(query, i).to_i
  186.          
  187.           case type
  188.           when SQLiteAPI::SQLITE_INTEGER # Inteiro
  189.             rowdata[name] = SQLiteAPI.column_int(query, i).to_i
  190.           when SQLiteAPI::SQLITE_FLOAT   # Float
  191.             rowdata[name] = SQLiteAPI.column_double(query, i).to_f
  192.           when SQLiteAPI::SQLITE_TEXT    # Texto
  193.             rowdata[name] = SQLiteAPI.column_text(query, i).to_s
  194.           when SQLiteAPI::SQLITE_BLOB    # Blob (não implementado)
  195.             warn("Leitura de BLOB não implementada")
  196.             rowdata[name] = ""
  197.           when SQLiteAPI::SQLITE_NULL    # Nulo
  198.             rowdata[name] = nil
  199.           else                           # Desconhecido
  200.             raise(SQLiteAPI::Error, SQLiteAPI.errorStr(SQLiteAPI::NOTYPE), caller)
  201.           end
  202.         }
  203.        
  204.         # Retorna a linha para o bloco
  205.         # Se o retorno for :breakRecursiveQuery, para a execução
  206.         break if block.call(rowdata) == :breakRecursiveQuery
  207.       end
  208.      
  209.       # Adquire informação sobre a próxima informação
  210.       rc = SQLiteAPI.step(query)
  211.     end
  212.    
  213.     # Habilita novamente a rodar queries
  214.     @queryRunning = false
  215.    
  216.     # Finaliza processo atual
  217.     SQLiteAPI.finalize(query)
  218.    
  219.     # Retorna o próprio objeto
  220.     return self
  221.   end
  222.  
  223.   #-------------------------------------------------------------------------
  224.   # * Faz uma query não recursiva e retorna todas as linhas recebidas
  225.   #   + str : Query a ser executada
  226.   #-------------------------------------------------------------------------
  227.   def query(str)
  228.     data = []
  229.     recursiveQuery(str){|rowdata| data << rowdata}
  230.     return data
  231.   end
  232.  
  233.   #-------------------------------------------------------------------------
  234.   # * Retorna todas as tabelas existentes na database
  235.   #-------------------------------------------------------------------------
  236.   def getTables
  237.     # Checa se a database está aberta
  238.     check_closed
  239.    
  240.     # Seleciona todas as tabelas
  241.     tabs = []
  242.     recursiveQuery("SELECT name FROM sqlite_master WHERE type = 'table'"){|data|
  243.       # Armazena seu nome
  244.       tabs << data['name']
  245.     }
  246.    
  247.     # Retorna nomes
  248.     return tabs
  249.   end
  250.  
  251.   #-------------------------------------------------------------------------
  252.   # * Retorna colunas existentes na tabela
  253.   #   + table : Tabela que será consultada
  254.   #-------------------------------------------------------------------------
  255.   def getColumns(table)
  256.     # Checa se a database está aberta
  257.     check_closed
  258.    
  259.     columns = []
  260.    
  261.     # Seleciona valores quaisquer
  262.     buffer  = [0].pack("L*")
  263.     rc      = SQLiteAPI.prepare(@handle, "SELECT * FROM `#{table}`", -1, buffer, 0)
  264.     query = buffer.unpack("L*").first
  265.    
  266.     # Faz a contagem de colunas
  267.     n = SQLiteAPI.column_count(query)
  268.    
  269.     # Adquire nome das colunas
  270.     n.times{|i| columns << SQLiteAPI.column_name(query, i).to_s }
  271.        
  272.     # Finaliza query
  273.     SQLiteAPI.finalize(query)
  274.    
  275.     # Retorna colunas compactadas (sem nil) e únicas.
  276.     return columns.compact.uniq
  277.   end
  278.  
  279.   #-------------------------------------------------------------------------
  280.   # * Realiza backup da database para um arquivo
  281.   #   + to : Arquivo de destino ou outra instância de database
  282.   #-------------------------------------------------------------------------
  283.   def backup(to = ("Backup#{__FILE__}#{Time.new.to_i}.db"))
  284.     # Checa se a database está aberta
  285.     check_closed
  286.    
  287.     if (to.is_a?(String))
  288.       # Abre uma handle para o arquivo de destino
  289.       db = [0].pack("L*")
  290.       SQLiteAPI.sqlite3_open(to, db);
  291.       toHandle = db.unpack("L*").first
  292.     elsif (to.is_a?(SQLite))
  293.       # Copia para outra database aberta
  294.       toHandle = to.instance_eval{@handle}
  295.     else
  296.       # Não suportado
  297.       raise(ArgumentError, "Tipo não suportado: #{to.class}")
  298.     end
  299.    
  300.     # Inicia backup
  301.     pBackup = SQLiteAPI.sqlite3_backup_init(toHandle, "main", @handle, "main")
  302.    
  303.     # Faz o backup, se houver permissão/necessidade
  304.     if (pBackup != SQLiteAPI::SQLITE_OK)
  305.       SQLiteAPI.sqlite3_backup_step(pBackup, -1);
  306.       SQLiteAPI.sqlite3_backup_finish(pBackup);
  307.     end
  308.    
  309.     # Fecha a handle da memória
  310.     SQLiteAPI.sqlite3_close(toHandle)
  311.    
  312.     # Retorna o próprio objeto
  313.     return self
  314.   end
  315.  
  316.   #-------------------------------------------------------------------------
  317.   # * Faz o contrário do backup: Copia de um arquivo para a database atual
  318.   #   + file : Arquivo lido para recuperar a database atual
  319.   #-------------------------------------------------------------------------
  320.   def restore(file)
  321.     # Checa se a database não foi fechada
  322.     check_closed
  323.    
  324.     # Restora
  325.     tmpClose{SQLite.new(file).backup(self).finalize}
  326.    
  327.     # Retorna a própria database
  328.     return self
  329.   end
  330.  
  331.   #-------------------------------------------------------------------------
  332.   # * Fecha temporáriamente a database para permitir acesso ao arquivo
  333.   #   + &block : Bloco que será rodado enquanto a database estiver fechada
  334.   #-------------------------------------------------------------------------
  335.   def tmpClose(&block)
  336.     # Checa se o arquivo já não está fechado
  337.     check_closed
  338.    
  339.     # Fecha a database
  340.     SQLiteAPI.sqlite3_close(@handle)
  341.    
  342.     # Determina que o arquivo já está fechado
  343.     @closed = true
  344.    
  345.     # Chama o bloco
  346.     block.call
  347.    
  348.     # Abre novamente a handle para a database
  349.     @closed = false
  350.     db = [0].pack("L*")
  351.     SQLiteAPI.sqlite3_open(@filename, db);
  352.     @handle = db.unpack("L*").first
  353.    
  354.     # Retorna a própria database
  355.     return self
  356.   end
  357.  
  358.   #-------------------------------------------------------------------------
  359.   # * Finaliza a database, fechando a conexão com o arquivo
  360.   #-------------------------------------------------------------------------
  361.   def finalize
  362.     SQLiteAPI.sqlite3_close(@handle)
  363.     @closed = true
  364.     @handle = 0
  365.   end
  366.  
  367.  
  368.   private
  369.   #-------------------------------------------------------------------------
  370.   # * Checa se o arquivo está fechado. Caso esteja, chama a excessão
  371.   #   SQLiteAPI::Error, para previnir acessos inválidos.
  372.   #-------------------------------------------------------------------------
  373.   def check_closed
  374.     return unless @closed
  375.     raise(SQLiteAPI::Error, "Database fechada!", caller)
  376.   end
  377. end
  378.  
  379. #==============================================================================
  380. # ** MemorySQLiteAPI
  381. #------------------------------------------------------------------------------
  382. #  Classe para iniciar database na memória. Suporta todos os métodos da SQLite
  383. #==============================================================================
  384. class MemorySQLite < SQLite
  385.   #-------------------------------------------------------------------------
  386.   # * Inicialização
  387.   #-------------------------------------------------------------------------
  388.   def initialize
  389.     super(':memory:')
  390.   end
  391.  
  392.   #-------------------------------------------------------------------------
  393.   # * Como é um bloco na memória, não são necessários processamentos adicio-
  394.   #   nais para permitir acesso ao arquivo.
  395.   #-------------------------------------------------------------------------
  396.   def tmpClose(&block)
  397.     # Checa se a conexão está ativa
  398.     check_closed
  399.    
  400.     # Chama o block
  401.     block.call
  402.    
  403.     # Retona a própria database
  404.     return self
  405.   end
  406.  
  407.   #-------------------------------------------------------------------------
  408.   # * Retira a definição do método filename, para que não ocorra uma tenta-
  409.   #   tiva de acesso à um arquivo inexistente.
  410.   #-------------------------------------------------------------------------
  411.   undef filename
  412. end
  413.  
Expand to see the code.

Sorry for Portuguese comments; anyway, I leave all you'll need to develop in "Instructions" section, look at "To Developers" topic.

Instructions

- Put SQLite3.dll (download here) on Project's "System" folder.
- Put script above "Main" script.
- To developers:
Content Hidden Spoiler
  1.  
  2. # Create new DB file. If already exists, open it.
  3. # To create a memory database (no file), use MemorySQLite instead SQLite with no arguments.
  4. sqlite = SQLite.new("File.db")
  5.  
  6. # Doing queries
  7. sqlite.query("CREATE TABLE `TestTable` (C1 INT(9), C2 TEXT)")
  8. sqlite.query("INSERT INTO `TestTable` VALUES (2012, 'ABCD')")
  9. sqlite.query("INSERT INTO `TestTable` VALUES (2013, 'EFGH')")
  10.  
  11. # Recursive Query
  12. sqlite.recursiveQuery("SELECT * FROM `TestTable`"){|line|
  13.   print line["C1"] # First loop: 2012 // Second loop: 2013
  14.   print line["C2"] # First loop: ABCD // Second loop: EFGH
  15. }
  16.  
  17. # Get database tables
  18. sqlite.getTables # => ["TestTable"]
  19.  
  20. # Get table's columns
  21. sqlite.getColumns("TestTable") # => ["C1", "C2"]
  22.  
  23. # Backup
  24. sqlite.backup("NewDBFile.db") # Save all on "NewDBFile.db"
  25.  
  26. # Backup to another instance
  27. tmpsql = SQLite.new("OtherDB.db")
  28. tmpsql.getTables # => []
  29. sqlite.backup(tmpsql)
  30. tmpsql.getTables # => ["TestTable"]
  31.  
  32. # Restore backup
  33. sqlite.restore("NewDBFile.db") # Copy all from "NewDBFile.db" to open instance
  34.  
  35. # Temporarily close
  36. sqlite.tmpClose{
  37.   print "Block running with db closed"
  38. }
  39.  
  40. # Finalize
  41. sqlite.finalize
Expand to see the code.


Compatibility

- RPG Maker VX Ace
I'll improve compatibility with VX n XP next days. It's because some Ruby 1.9 methods.

Credits and Thanks

SQLite.org - DLL & API

Author's Notes

Any problem with this script feel free to contact me by pm or email ([email hidden]).

Terms and Conditions

- Free for commercial use. It only apply to script, look at SQLite Copyright to see about it's license.
And what usage will you do of this in a game ?
High scores, user log information, achievement data...etc. Anything that requires a database to store information.
It's like using a sword to cut an apple.
I know..let them have their glory; it's not worth us talking about overkill, lol.

Original thread: https://www.hbgames.org/forums/viewtopic.php?t=76580