From c2e368f211882d1924159b49db69bbf1182a1b96 Mon Sep 17 00:00:00 2001
From: Srikanth Raju <srikiraju@gmail.com>
Date: Wed, 16 Sep 2009 02:15:52 +0530
Subject: [PATCH] Sqlite Module

This is a sql module for VLC which connects the SQLite library to VLC.
---
 configure.ac            |   35 ++++
 modules/LIST            |    1 +
 modules/misc/Modules.am |    1 +
 modules/misc/sqlite.c   |  408 +++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 445 insertions(+), 0 deletions(-)
 create mode 100644 modules/misc/sqlite.c

diff --git a/configure.ac b/configure.ac
index 748bb21..73fe604 100644
--- a/configure.ac
+++ b/configure.ac
@@ -4664,6 +4664,41 @@ then
   AC_DEFINE([UPDATE_CHECK], 1, [Define if you want to use the VLC update mechanism])
 fi
 
+dnl
+dnl SQLite
+dnl
+if test "${SYS}" != "darwin"; then
+  PKG_ENABLE_MODULES_VLC([SQLITE], [], [sqlite3], [sqlite3], [auto])
+else
+  AC_ARG_ENABLE(sqlite,
+    [  --enable-sqlite   SQLite (default disabled)])
+  if test "${enable_sqlite}" = "yes"
+  then
+    AC_ARG_WITH(sqlite,
+      [    --with-sqlite=PATH sqlite path linking])
+    AC_CHECK_HEADERS(sqlite3.h, [
+        VLC_ADD_PLUGIN([sqlite])
+        if test "${with_sqlite}" != "no" -a -n "${with_sqlite}"; then
+          AC_MSG_CHECKING(existence of sqlite directory in ${with_sqlite})
+          real_sqlite="`cd ${with_sqlite} 2>/dev/null && pwd`"
+          if test -z "${real_sqlite}"
+          then
+            dnl  The given directory can't be found
+            AC_MSG_RESULT(no)
+            AC_MSG_ERROR([cannot cd to ${with_sqlite}])
+          fi
+          VLC_ADD_CFLAGS([sqlite],[-I${with_sqlite}/include])
+          VLC_ADD_LIBS([sqlite], [-L${with_sqlite}/lib -lsqlite3])
+          AC_MSG_RESULT(yes)
+        else
+          VLC_ADD_LIBS([sqlite], [-lsqlite3])
+        fi
+        AC_DEFINE([SQLITE_MODULE], 1, [Define if you want to use SQLite module]) ],
+        AC_MSG_ERROR([sqlite3 is required for sqlite module]) )
+  fi
+fi
+AM_CONDITIONAL([HAVE_SQLITE], [test "${enable_sqlite}" = "yes"])
+
 
 dnl
 dnl  Endianness check
diff --git a/modules/LIST b/modules/LIST
index 6159976..2039c08 100644
--- a/modules/LIST
+++ b/modules/LIST
@@ -294,6 +294,7 @@ $Id$
  * spdif_mixer: dummy audio mixer for the S/PDIF output
  * speex: a speex audio decoder/packetizer using the libspeex library
  * spudec: RLE DVD subtitles decoder
+ * sqlite: manage an SQLite database
  * stats: Stats encoder function
  * stream_filter_rar: Stream filter to read inside Rar files
  * stream_filter_record: record any stream instantly
diff --git a/modules/misc/Modules.am b/modules/misc/Modules.am
index 4756fa1..79d354c 100644
--- a/modules/misc/Modules.am
+++ b/modules/misc/Modules.am
@@ -23,6 +23,7 @@ SOURCES_gnutls = gnutls.c dhparams.h
 SOURCES_svg = svg.c
 SOURCES_audioscrobbler = audioscrobbler.c
 SOURCES_inhibit = inhibit.c
+SOURCES_sqlite = sqlite.c
 
 libvlc_LTLIBRARIES += \
 	liblogger_plugin.la
diff --git a/modules/misc/sqlite.c b/modules/misc/sqlite.c
new file mode 100644
index 0000000..a1943a9
--- /dev/null
+++ b/modules/misc/sqlite.c
@@ -0,0 +1,408 @@
+/*****************************************************************************
+ * sqlite.c: An SQLite3 wrapper for VLC
+ *****************************************************************************
+ * Copyright (C) 2008-2009 the VideoLAN team
+ * $Id$
+ *
+ * Authors: Antoine Lejeune <phytos@videolan.org>
+ *          Jean-Philippe André <jpeg@videolan.org>
+ *          Rémi Duraffort <ivoire@videolan.org>
+ *          Adrien Maglo <magsoft@videolan.org>
+ *          Srikanth Raju <srikiraju@gmail.com>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
+ *****************************************************************************/
+
+
+#ifdef HAVE_CONFIG_H
+# include "config.h"
+#endif
+
+#include <vlc_common.h>
+#include <vlc/vlc.h>
+#include <vlc_sql.h>
+#include <vlc_plugin.h>
+
+#include <sqlite3.h>
+#include <assert.h>
+
+#define SQLITE_DB_TEXT N_( "Filename of the SQLite database" )
+#define SQLITE_DB_LONGTEXT N_( "Path to the file containing the SQLite database" )
+
+
+/*****************************************************************************
+ * Private structures
+ *****************************************************************************/
+struct sql_sys_t
+{
+    char *psz_host;           /**< Database host: SQLite DB filename */
+    sqlite3 *db;              /**< Database connection. */
+    vlc_mutex_t lock;         /**< SQLite mutex. Threads are evil here. */
+    vlc_mutex_t trans_lock;   /**< Mutex for running transactions */
+};
+
+
+/*****************************************************************************
+ * Headers
+ *****************************************************************************/
+static int load ( vlc_object_t * );
+static void unload ( vlc_object_t * );
+
+static int OpenDatabase( sql_t * );
+static int CloseDatabase (sql_t * );
+static int QueryCallback( sql_t * p_sql,
+                          const char * query,
+                          sql_query_callback_t* callback,
+                          void *arg ); // 1st argument to callback
+static int Query( sql_t * p_sql,
+                  const char * query,
+                  char *** result,
+                  int * nrow,
+                  int * ncol );
+static int GetTables( sql_t * p_sql,
+                      char *** result );
+static void FreeResult( sql_t * p_sql, char **pp_result );
+static char* VMSprintf( const char* psz_fmt, va_list args );
+static int BeginTransaction( sql_t* p_sql );
+static void CommitTransaction( sql_t* p_sql );
+static void RollbackTransaction( sql_t* p_sql );
+
+/*****************************************************************************
+ * Module description
+ *****************************************************************************/
+vlc_module_begin()
+    set_shortname( "SQLite" )
+    set_description( _("SQLite database module") )
+    set_capability( "sql", 1 )
+    set_callbacks( load, unload )
+    set_category( CAT_ADVANCED )
+vlc_module_end()
+
+
+/**
+ * @brief Load module
+ * @param obj Parent object
+ * @return VLC_SUCCESS or VLC_ENOMEM
+ */
+static int load( vlc_object_t *p_this )
+{
+    sql_t *p_sql = (sql_t *) p_this;
+
+    p_sql->pf_query_callback = QueryCallback;
+    p_sql->pf_get_tables = GetTables;
+    p_sql->pf_query = Query;
+    p_sql->pf_free = FreeResult;
+    p_sql->pf_vmprintf = VMSprintf;
+    p_sql->pf_begin = BeginTransaction;
+    p_sql->pf_commit = CommitTransaction;
+    p_sql->pf_rollback = RollbackTransaction;
+
+    /* Initialize sys_t */
+    p_sql->p_sys = ( sql_sys_t* ) calloc( 1, sizeof( sql_sys_t ) );
+    if( !p_sql->p_sys )
+        return VLC_ENOMEM;
+
+    vlc_mutex_init( &p_sql->p_sys->lock );
+    vlc_mutex_init( &p_sql->p_sys->trans_lock );
+
+    /* Open Database */
+    if( OpenDatabase( p_sql ) == VLC_SUCCESS )
+        msg_Dbg( p_sql, "sqlite module loaded" );
+    else
+        return VLC_EGENERIC;
+
+    return VLC_SUCCESS;
+}
+
+/**
+ * @brief Unload module
+ * @param obj This sql_t object
+ * @return Nothing
+ */
+static void unload( vlc_object_t *p_this )
+{
+    sql_t *p_sql = (sql_t *)p_this;
+
+    CloseDatabase( p_sql );
+    vlc_mutex_destroy( &p_sql->p_sys->lock );
+    vlc_mutex_destroy( &p_sql->p_sys->trans_lock );
+    free( p_sql->p_sys->psz_host );
+    free( p_sql->p_sys );
+}
+
+/**
+ * @brief Open current database
+ * @param p_sql This sql_t object
+ * @return VLC_SUCCESS or VLC_EGENERIC
+ * @note p_sql->psz_host is required
+ */
+static int OpenDatabase( sql_t *p_sql )
+{
+    vlc_mutex_lock( &p_sql->p_sys->lock );
+
+    assert( !p_sql->p_sys->db );
+    assert( p_sql->psz_host && *p_sql->psz_host );
+
+    if( sqlite3_open( p_sql->psz_host, &p_sql->p_sys->db ) )
+    {
+        msg_Err( p_sql, "Can't open database : %s", p_sql->psz_host );
+        vlc_mutex_unlock( &p_sql->p_sys->lock );
+        return VLC_EGENERIC;
+    }
+
+    vlc_mutex_unlock( &p_sql->p_sys->lock );
+    return VLC_SUCCESS;
+}
+
+/**
+ * @brief Close current database
+ * @param p_sql This sql_t object
+ * @return VLC_SUCCESS
+ * You have to set and open current database first
+ */
+static int CloseDatabase( sql_t *p_sql )
+{
+    vlc_mutex_lock( &p_sql->p_sys->lock );
+    assert( p_sql->p_sys->db );
+
+    /* Close database */
+    int i_ret = sqlite3_close( p_sql->p_sys->db );
+    p_sql->p_sys->db = NULL;
+
+    vlc_mutex_unlock( &p_sql->p_sys->lock );
+    return ( i_ret == SQLITE_OK ) ? VLC_SUCCESS : VLC_EGENERIC;
+}
+
+/**
+ * @brief SQL Query with callback
+ * @param p_sql This sql_t object
+ * @param query SQL query
+ * @param callback Callback function to receive results row by row
+ * @param arg Argument to pass to callback
+ * @return VLC_SUCCESS or an error code
+ * You have to set and open current database first
+ */
+static int QueryCallback( sql_t * p_sql,
+                          const char * query,
+                          sql_query_callback_t* callback,
+                          void *arg )
+{
+    vlc_mutex_lock( &p_sql->p_sys->lock );
+
+    assert( p_sql->p_sys->db );
+
+#ifndef NDEBUG
+    msg_Dbg( p_sql, "QueryCallback: %s", query );
+#endif
+    sqlite3_exec( p_sql->p_sys->db, query, callback, arg, NULL );
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+        vlc_mutex_unlock( &p_sql->p_sys->lock );
+        return VLC_EGENERIC;
+    }
+
+    vlc_mutex_unlock( &p_sql->p_sys->lock );
+    return VLC_SUCCESS;
+}
+
+/**
+ * @brief Direct SQL Query
+ * @param p_sql This sql_t object
+ * @param query SQL query
+ * @param result Return value : Array of results
+ * @param nrow Return value : Row number
+ * @param ncol Return value : Column number
+ * @return VLC_SUCCESS or an error code
+ * You have to set and open current database first
+ * @todo Handle transaction closing due to errors in sql query
+ */
+static int Query( sql_t * p_sql,
+                  const char * query,
+                  char *** result,
+                  int * nrow,
+                  int * ncol )
+{
+    vlc_mutex_lock( &p_sql->p_sys->lock );
+
+    if( !p_sql->p_sys->db )
+    {
+        vlc_mutex_unlock( &p_sql->p_sys->lock );
+        return VLC_EGENERIC;
+    }
+
+#ifndef NDEBUG
+    msg_Dbg( p_sql, "Query: %s", query );
+#endif
+    sqlite3_get_table( p_sql->p_sys->db, query, result, nrow, ncol, NULL );
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+        vlc_mutex_unlock( &p_sql->p_sys->lock );
+        return VLC_EGENERIC;
+    }
+
+    vlc_mutex_unlock( &p_sql->p_sys->lock );
+    return VLC_SUCCESS;
+}
+
+/**
+ * @brief Get tables in database
+ * @param p_sql This sql_t object
+ * @param result SQL query result
+ * @return Number of elements
+ * You have to set and open current database first
+ */
+static int GetTables( sql_t * p_sql,
+                      char *** result )
+{
+    int nrow, i_num = false;
+    char ***pppsz_res;
+
+    vlc_mutex_lock( &p_sql->p_sys->lock );
+
+    if( !p_sql->p_sys->db )
+    {
+        vlc_mutex_unlock( &p_sql->p_sys->lock );
+        return VLC_EGENERIC;
+    }
+
+    if( result )
+        pppsz_res = result;
+    else
+        pppsz_res = (char ***) malloc( sizeof( char ** ) );
+
+    sqlite3_get_table( p_sql->p_sys->db, "SELECT * FROM sqlite_master;",
+                       pppsz_res, &nrow, &i_num, NULL );
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+    }
+    if( !result )
+    {
+        sqlite3_free_table( *pppsz_res );
+        free( pppsz_res );
+    }
+    vlc_mutex_unlock( &p_sql->p_sys->lock );
+    return i_num;
+}
+
+/**
+ * @brief Free SQL request's result
+ * @param p_sql This SQL object.
+ * @param ppsz_result SQL result to free
+ */
+static void FreeResult( sql_t * p_sql, char **ppsz_result )
+{
+    VLC_UNUSED( p_sql );
+    if( ppsz_result != NULL )
+        sqlite3_free_table( ppsz_result );
+}
+
+/**
+ * @brief vmprintf replacement for SQLite.
+ * @param psz_fmt Format string
+ * @param args va_list of arguments
+ * This function implements the formats %q, %Q and %z.
+ */
+static char* VMSprintf( const char* psz_fmt, va_list args )
+{
+    char *psz = sqlite3_vmprintf( psz_fmt, args );
+    char *ret = strdup( psz );
+    sqlite3_free( psz );
+    return ret;
+}
+
+/**
+ * @brief Starts a Transaction and waits if necessary
+ * @param p_sql The SQL object
+ * @note This function locks the transactions on the database.
+ * Within the period of the transaction, only the calling thread may
+ * execute sql statements provided all threads use these transaction fns.
+ */
+static int BeginTransaction( sql_t* p_sql )
+{
+    vlc_mutex_lock( &p_sql->p_sys->trans_lock );
+    if( !p_sql->p_sys->db )
+    {
+        vlc_mutex_unlock( &p_sql->p_sys->trans_lock );
+        return VLC_EGENERIC;
+    }
+    sqlite3_exec( p_sql->p_sys->db, "BEGIN;", NULL, NULL, NULL );
+#ifndef NDEBUG
+    msg_Dbg( p_sql, "Transaction Query: BEGIN;" );
+#endif
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        vlc_mutex_unlock( &p_sql->p_sys->trans_lock );
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+        return VLC_EGENERIC;
+    }
+    return VLC_SUCCESS;
+}
+
+/**
+ * @brief Commit a transaction
+ * @param p_sql The SQL object
+ * @note This function unlocks the transactions on the database
+ * Only the calling thread of "BeginTransaction" is allowed to call this method
+ * If the commit fails, the transaction lock is still held by the thread
+ * and this function may be retried or RollbackTransaction can be called
+ */
+static void CommitTransaction( sql_t* p_sql )
+{
+    /** This turns the auto commit on. */
+    sqlite3_exec( p_sql->p_sys->db, "COMMIT;", NULL, NULL, NULL );
+#ifndef NDEBUG
+    msg_Dbg( p_sql, "Transaction Query: COMMIT;" );
+#endif
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+    }
+    else
+        vlc_mutex_unlock( &p_sql->p_sys->trans_lock );
+}
+
+/**
+ * @brief Rollback a transaction, in case of failure
+ * @param p_sql The SQL object
+ * @note This function unlocks the transactions on the database
+ * Only the calling thread of "BeginTransaction" is allowed to call this method
+ */
+static void RollbackTransaction( sql_t* p_sql )
+{
+    sqlite3_exec( p_sql->p_sys->db, "ROLLBACK;", NULL, NULL, NULL );
+#ifndef NDEBUG
+    msg_Dbg( p_sql, "Transaction Query: ROLLBACK;" );
+#endif
+    if( sqlite3_errcode( p_sql->p_sys->db ) != SQLITE_OK )
+    {
+        msg_Warn( p_sql, "sqlite3 error: %d: %s",
+                  sqlite3_errcode( p_sql->p_sys->db ),
+                  sqlite3_errmsg( p_sql->p_sys->db ) );
+    }
+    vlc_mutex_unlock( &p_sql->p_sys->trans_lock );
+}
-- 
1.6.0.4

