SQLiteCRoutines.c Source File

Source Code


Source Code

/*
 *  SQLiteCRoutines.c
 *  Fortran/C interface to the SQLite C++ API (see www.sqlite.org)
 *
 *  Created by Building Synergies, LLC.  September, 2008.
 *  Copyright 2008 Building Synergies, LLC. All rights reserved.
 *
 */

#include "sqlite3.h"
#include <stdio.h>
#include "strings.h"
#include "SQLiteCRoutines.h"

enum {maxNumberOfPreparedStmts = 100};
static sqlite3 *db;
static sqlite3_stmt *stmt[maxNumberOfPreparedStmts];
static FILE *outputFile;

static int callback(void *NotUsed, int argc, char **argv, char **azColName){
    int i;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        for(i=0; i<argc; i++)
            fprintf(outputFile, "SQLite3 message, %s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }

    return 0;
}

int SQLiteOpenDatabase (char *dbNameBuffer)
{
    FILE *fopen();
    int rc = -1;
    char *zErrMsg = 0;

    FILE* testf = NULL;

    outputFile = fopen("sqlite.err", "w");
    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        fprintf(outputFile, "SQLite3 message, sqlite.err open for processing!\n");

        testf = fopen(dbNameBuffer, "r");
        if(testf != NULL)
        {
          fclose(testf);
          rc = sqlite3_open_v2(dbNameBuffer, &db, SQLITE_OPEN_READWRITE, NULL);
          // We test to see if we can write to the database
          // If we can't then there are probably locks on the database
          rc = sqlite3_exec(db, "CREATE TABLE Test(x INTEGER PRIMARY KEY)", NULL, 0, &zErrMsg);
          sqlite3_close(db);
          if( rc )
          {
            fprintf(outputFile, "SQLite3 message, can't get exclusive lock on existing database: %s\n", sqlite3_errmsg(db));
            return rc;
          }
          rc = remove( dbNameBuffer );
          if( rc )
          {
            fprintf(outputFile, "SQLite3 message, can't remove old database: %s\n", sqlite3_errmsg(db));
            return rc;
          }
        }

        rc = sqlite3_open_v2(dbNameBuffer, &db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, NULL);
        if( rc )
        {
            fprintf(outputFile, "SQLite3 message, can't open new database: %s\n", sqlite3_errmsg(db));
            sqlite3_close(db);
            return rc;
        }
    }


    return rc;
}

int SQLiteExecuteCommand (char *commandBuffer)
{
    char *zErrMsg = 0;
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        rc = sqlite3_exec(db, commandBuffer, callback, 0, &zErrMsg);
        if( rc != SQLITE_OK ){
            fprintf(outputFile, "SQLite3 message, error: %s\n", zErrMsg);
            sqlite3_free(zErrMsg);
        }
    }
    return rc;
}

int SQLiteCloseDatabase (char *dbNameBuffer, int dbNameLength)
{
    int rc = -1;

    dbNameBuffer[dbNameLength] = 0;

    sqlite3_close(db);
    return rc;
}

int SQLitePrepareStatement (int stmtType, char *stmtBuffer)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_prepare_v2(db, stmtBuffer, -1, &stmt[stmtType], 0);
            if( rc != SQLITE_OK ){
                fprintf(outputFile, "SQLite3 message, sqlite3_prepare_v2 message: %s\n", sqlite3_errmsg(db));
            }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_prepare_v2 error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteColumnInt (int stmtType, int iCol)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_column_int(stmt[stmtType], iCol);
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_column_int error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteBindText (int stmtType, int stmtInsertLocationIndex, char *textBuffer)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_bind_text(stmt[stmtType], stmtInsertLocationIndex, textBuffer, -1, SQLITE_TRANSIENT);
            if( rc != SQLITE_OK ){
                fprintf(outputFile, "SQLite3 message, sqlite3_bind_text message: %s\n", sqlite3_errmsg(db));
            }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_bind_text error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteBindInteger (int stmtType, int stmtInsertLocationIndex, int intToInsert)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_bind_int(stmt[stmtType], stmtInsertLocationIndex, intToInsert);
            if( rc != SQLITE_OK ){
                fprintf(outputFile, "SQLite3 message, sqlite3_bind_int message: %s\n", sqlite3_errmsg(db));
            }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_bind_int error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteBindDouble (int stmtType, int stmtInsertLocationIndex, double doubleToInsert)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_bind_double(stmt[stmtType], stmtInsertLocationIndex, doubleToInsert);
            if( rc != SQLITE_OK ){
                fprintf(outputFile, "SQLite3 message, sqlite3_bind_double message: %s\n", sqlite3_errmsg(db));
            }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_bind_double error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteBindNULL (int stmtType, int stmtInsertLocationIndex)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_bind_null(stmt[stmtType], stmtInsertLocationIndex);
            if( rc != SQLITE_OK ){
                fprintf(outputFile, "SQLite3 message, sqlite3_bind_null message: %s\n", sqlite3_errmsg(db));
            }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_bind_null error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteStepCommand (int stmtType)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_step(stmt[stmtType]);
            switch (rc)
                {
                case SQLITE_DONE:
                case SQLITE_OK:
                case SQLITE_ROW:
                    break;

                default:
                    fprintf(outputFile, "SQLite3 message, sqlite3_step message: %i %s, Stmt Type: %i\n", rc, sqlite3_errmsg(db), stmtType);
                    break;
                }
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_step error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteResetCommand (int stmtType)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_reset(stmt[stmtType]);
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_reset error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteClearBindings (int stmtType)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_clear_bindings(stmt[stmtType]);
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_clear_bindings error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteFinalizeCommand (int stmtType)
{
    int rc = -1;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
        if(stmtType < maxNumberOfPreparedStmts) {
            rc = sqlite3_finalize(stmt[stmtType]);
        } else {
            fprintf(outputFile, "SQLite3 message, sqlite3_finalize error: %i exceeds maximum allowed statement number\n", stmtType);
        }
    }
    return rc;
}

int SQLiteWriteMessage (char *message)
{
    int rc = 0;

    if (outputFile == NULL)
        fprintf(stderr, "SQLite3 message, can't open error file: sqlite.err\n");
    else
    {
      fprintf(outputFile, "SQLite3 message, %s\n", message);
    }
    return rc;
}

/*    NOTICE
 !
 !     Copyright © 1996-2008 The Board of Trustees of the University of Illinois
 !     and The Regents of the University of California through Ernest Orlando Lawrence
 !     Berkeley National Laboratory.  All rights reserved.
 !
 !     Portions of the EnergyPlus software package have been developed and copyrighted
 !     by other individuals, companies and institutions.  These portions have been
 !     incorporated into the EnergyPlus software package under license.   For a complete
 !     list of contributors, see "Notice" located in EnergyPlus.f90.
 !
 !     NOTICE: The U.S. Government is granted for itself and others acting on its
 !     behalf a paid-up, nonexclusive, irrevocable, worldwide license in this data to
 !     reproduce, prepare derivative works, and perform publicly and display publicly.
 !     Beginning five (5) years after permission to assert copyright is granted,
 !     subject to two possible five year renewals, the U.S. Government is granted for
 !     itself and others acting on its behalf a paid-up, non-exclusive, irrevocable
 !     worldwide license in this data to reproduce, prepare derivative works,
 !     distribute copies to the public, perform publicly and display publicly, and to
 !     permit others to do so.
 !
 !     TRADEMARKS: EnergyPlus is a trademark of the US Department of Energy.

 !     Copyright © 2008 Building Synergies, LLC.  All rights reserved.
 */

AirflowNetworkBalanceManager.f90 AirflowNetworkSolver.f90 BaseboardRadiator.f90 BaseboardRadiatorElectric.f90 BaseboardRadiatorSteam.f90 BaseboardRadiatorWater.f90 BranchInputManager.f90 BranchNodeConnections.f90 ConductionTransferFunctionCalc.f90 CoolTower.f90 CostEstimateManager.f90 CurveManager.f90 CVFOnlyRoutines.f90 DataAirflowNetwork.f90 DataAirLoop.f90 DataAirSystems.f90 DataBranchAirLoopPlant.f90 DataBranchNodeConnections.f90 DataBSDFWindow.f90 DataComplexFenestration.f90 DataContaminantBalance.f90 DataConvergParams.f90 DataConversions.f90 DataCostEstimate.f90 DataDaylighting.f90 DataDaylightingDevices.f90 Datadefineequip.f90 DataDElight.f90 DataEnvironment.f90 DataEquivalentLayerWindow.f90 DataErrorTracking.f90 DataGenerators.f90 DataGlobalConstants.f90 DataGlobals.f90 DataHeatBalance.f90 DataHeatBalFanSys.f90 DataHeatBalSurface.f90 DataHVACControllers.f90 DataHVACGlobals.f90 DataInterfaces.f90 DataIPShortCuts.f90 DataLoopNode.f90 DataMoistureBalance.f90 DataMoistureBalanceEMPD.f90 DataOutputs.f90 DataPhotovoltaics.f90 DataPlant.f90 DataPlantPipingSystems.f90 DataPrecisionGlobals.f90 DataReportingFlags.f90 DataRoomAir.f90 DataRootFinder.f90 DataRuntimeLanguage.f90 DataShadowingCombinations.f90 DataSizing.f90 DataStringGlobals.f90 DataSurfaceColors.f90 DataSurfaceLists.f90 DataSurfaces.f90 DataSystemVariables.f90 DataTimings.f90 DataUCSDSharedData.f90 DataVectorTypes.f90 DataViewFactorInformation.f90 DataWater.f90 DataZoneControls.f90 DataZoneEnergyDemands.f90 DataZoneEquipment.f90 DaylightingDevices.f90 DaylightingManager.f90 DElightManagerF.f90 DElightManagerF_NO.f90 DemandManager.f90 DesiccantDehumidifiers.f90 DirectAir.f90 DisplayRoutines.f90 DXCoil.f90 EarthTube.f90 EconomicLifeCycleCost.f90 EconomicTariff.f90 EcoRoof.f90 ElectricPowerGenerators.f90 ElectricPowerManager.f90 EMSManager.f90 EnergyPlus.f90 ExteriorEnergyUseManager.f90 ExternalInterface_NO.f90 FanCoilUnits.f90 FaultsManager.f90 FluidProperties.f90 General.f90 GeneralRoutines.f90 GlobalNames.f90 HeatBalanceAirManager.f90 HeatBalanceConvectionCoeffs.f90 HeatBalanceHAMTManager.f90 HeatBalanceInternalHeatGains.f90 HeatBalanceIntRadExchange.f90 HeatBalanceManager.f90 HeatBalanceMovableInsulation.f90 HeatBalanceSurfaceManager.f90 HeatBalFiniteDifferenceManager.f90 HeatRecovery.f90 Humidifiers.f90 HVACControllers.f90 HVACCooledBeam.f90 HVACDualDuctSystem.f90 HVACDuct.f90 HVACDXSystem.f90 HVACEvapComponent.f90 HVACFanComponent.f90 HVACFurnace.f90 HVACHeatingCoils.f90 HVACHXAssistedCoolingCoil.f90 HVACInterfaceManager.f90 HVACManager.f90 HVACMixerComponent.f90 HVACMultiSpeedHeatPump.f90 HVACSingleDuctInduc.f90 HVACSingleDuctSystem.f90 HVACSplitterComponent.f90 HVACStandAloneERV.f90 HVACSteamCoilComponent.f90 HVACTranspiredCollector.f90 HVACUnitaryBypassVAV.f90 HVACUnitarySystem.f90 HVACVariableRefrigerantFlow.f90 HVACWaterCoilComponent.f90 HVACWatertoAir.f90 HVACWatertoAirMultiSpeedHP.f90 InputProcessor.f90 MatrixDataManager.f90 MixedAir.f90 MoistureBalanceEMPDManager.f90 NodeInputManager.f90 NonZoneEquipmentManager.f90 OutAirNodeManager.f90 OutdoorAirUnit.f90 OutputProcessor.f90 OutputReportPredefined.f90 OutputReports.f90 OutputReportTabular.f90 PackagedTerminalHeatPump.f90 PackagedThermalStorageCoil.f90 Photovoltaics.f90 PhotovoltaicThermalCollectors.f90 PlantAbsorptionChillers.f90 PlantBoilers.f90 PlantBoilersSteam.f90 PlantCentralGSHP.f90 PlantChillers.f90 PlantCondLoopOperation.f90 PlantCondLoopTowers.f90 PlantEIRChillers.f90 PlantEvapFluidCoolers.f90 PlantExhaustAbsorptionChiller.f90 PlantFluidCoolers.f90 PlantGasAbsorptionChiller.f90 PlantGroundHeatExchangers.f90 PlantHeatExchanger.f90 PlantIceThermalStorage.f90 PlantLoadProfile.f90 PlantLoopEquipment.f90 PlantLoopSolver.f90 PlantManager.f90 PlantOutsideEnergySources.f90 PlantPipeHeatTransfer.f90 PlantPipes.f90 PlantPipingSystemManager.f90 PlantPondGroundHeatExchanger.f90 PlantPressureSystem.f90 PlantPumps.f90 PlantSolarCollectors.f90 PlantSurfaceGroundHeatExchanger.f90 PlantUtilities.f90 PlantValves.f90 PlantWaterSources.f90 PlantWaterThermalTank.f90 PlantWatertoWaterGSHP.f90 PlantWaterUse.f90 PollutionAnalysisModule.f90 PoweredInductionUnits.f90 PsychRoutines.f90 Purchasedairmanager.f90 RadiantSystemHighTemp.f90 RadiantSystemLowTemp.f90 RefrigeratedCase.f90 ReportSizingManager.f90 ReturnAirPath.f90 RoomAirManager.f90 RoomAirModelCrossVent.f90 RoomAirModelDisplacementVent.f90 RoomAirModelMundt.f90 RoomAirModelUFAD.f90 RoomAirModelUserTempPattern.f90 RootFinder.f90 RuntimeLanguageProcessor.f90 ScheduleManager.f90 SetPointManager.f90 SimAirServingZones.f90 SimulationManager.f90 SizingManager.f90 SolarReflectionManager.f90 SolarShading.f90 SortAndStringUtilities.f90 sqlite3.c SQLiteCRoutines.c SQLiteFortranRoutines.f90 SQLiteFortranRoutines_NO.f90 StandardRatings.f90 SurfaceGeometry.f90 SystemAvailabilityManager.f90 SystemReports.f90 TarcogComplexFenestration.f90 ThermalChimney.f90 ThermalComfort.f90 UnitHeater.f90 UnitVentilator.f90 UserDefinedComponents.f90 UtilityRoutines.f90 VectorUtilities.f90 VentilatedSlab.f90 WaterManager.f90 WeatherManager.f90 WindowAC.f90 WindowComplexManager.f90 WindowEquivalentLayer.f90 WindowManager.f90 WindTurbine.f90 Zoneairloopequipmentmanager.f90 ZoneContaminantPredictorCorrector.f90 ZoneDehumidifier.f90 Zoneequipmentmanager.f90 ZonePlenumComponent.f90 ZoneTempPredictorCorrector.f90