mg.write("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\n\r\n") mg.write([[ Lua SQLite database test

This is Lua script example 1, served by the CivetWeb web server, version ]] .. mg.version .. [[.

The following features are available:

\r\n") mg.write("

Today is " .. os.date("%A") .. "

\r\n") mg.write("

URI is " .. mg.request_info.uri .. "

\r\n") mg.write("

\r\n

\r\n")

-- Open database
local db, errcode, errmsg = sqlite3.open('requests.db')

if db then

  -- Note that the data base is located in the current working directory
  -- of the process if no other path is given here.

  -- Setup a trace callback, to show SQL statements we'll be executing.
  -- db:trace(function(data, sql) mg.write('Executing: ', sql: '\n') end, nil)

  -- Create a table if it is not created already
  db:exec([[
    CREATE TABLE IF NOT EXISTS requests (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      timestamp NOT NULL,
      method NOT NULL,
      uri NOT NULL,
      addr,
      civetwebversion,
      luaversion,
      aux
    );
  ]])

  -- Add colums to table created with older version
  db:exec("ALTER TABLE requests ADD COLUMN civetwebversion;")
  db:exec("ALTER TABLE requests ADD COLUMN luaversion;")
  db:exec("ALTER TABLE requests ADD COLUMN aux;")

  -- Add entry about this request
  local stmt = db:prepare(
    'INSERT INTO requests VALUES(NULL, datetime("now"), ?, ?, ?, ?, ?, ?);');
  stmt:bind_values(mg.request_info.request_method,
                   mg.request_info.uri,
                   mg.request_info.remote_port,
                   mg.version,
                   _VERSION,
                   ""
                   )
  stmt:step()
  stmt:finalize()

  -- Show all previous records
  mg.write('\n')
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")
  mg.write("\n")

  stmt = db:prepare('SELECT * FROM requests ORDER BY id DESC;')
  while stmt:step() == sqlite3.ROW do
    local v = stmt:get_values()
    mg.write("\n")
    local i = 1
    while (v[i]) do
      mg.write("\n")
      i = i+1
    end
    mg.write("\n")
  end

  mg.write("
idtimestampmethoduriaddrcivetwebluaaux
" .. v[i] .. "
\n") -- Close database db:close() else mg.write("DB error:\n") mg.write("code = " .. tostring(errcode) .. "\n") mg.write("msg = " .. tostring(msg) .. "\n") end mg.write([[

]])