diff --git a/.github/workflows/develop.yml b/.github/workflows/develop.yml index 709da13a5..79d1a2a99 100644 --- a/.github/workflows/develop.yml +++ b/.github/workflows/develop.yml @@ -8,28 +8,34 @@ on: jobs: build: + runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - - name: Setup system - run: sudo ./setup.sh --local - - - name: Build gridlabd - run: sudo ./build.sh --system --parallel - - - name: Install openfido - run: curl -sL https://raw.githubusercontent.com/openfido/cli/main/install.sh | sudo sh - - - name: Validate system - run: sudo gridlabd -D keep_progress=TRUE -T 0 --validate -D github_actions=yes || ( sudo utilities/save_validation_errors ; false ) - - - name: Upload artifacts on failure - uses: actions/upload-artifact@v4 - if: failure() - with: - name: validate-result - path: | - validate.txt - validate.tar.gz + - uses: actions/checkout@v4 + + - name: Setup system + run: sudo ./setup.sh --local + + - name: Build gridlabd + run: sudo ./build.sh --system --parallel + + - name: Install openfido + run: | + test -x /usr/local/bin/python3 || sudo ln -sf $(which python3) /usr/local/bin/python3 + sudo /usr/local/bin/python3 -m venv /usr/local/opt/openfido + source /usr/local/opt/openfido/bin/activate + sudo /usr/local/bin/python3 -m pip install requests pandas docker + curl -sL https://raw.githubusercontent.com/openfido/cli/main/install.sh | sudo sh + + - name: Validate system + run: sudo gridlabd -D keep_progress=TRUE -T 0 --validate -D github_actions=yes || ( sudo utilities/save_validation_errors ; false ) + + - name: Upload artifacts on failure + uses: actions/upload-artifact@v4 + if: failure() + with: + name: validate-result + path: | + validate.txt + validate.tar.gz diff --git a/.github/workflows/master.yml b/.github/workflows/master.yml index 01777c241..468cd5798 100644 --- a/.github/workflows/master.yml +++ b/.github/workflows/master.yml @@ -21,7 +21,12 @@ jobs: run: sudo ./build.sh --system --parallel - name: Install openfido - run: curl -sL https://raw.githubusercontent.com/openfido/cli/main/install.sh | sudo sh + run: | + test -x /usr/local/bin/python3 || sudo ln -sf $(which python3) /usr/local/bin/python3 + sudo /usr/local/bin/python3 -m venv /usr/local/opt/openfido + source /usr/local/opt/openfido/bin/activate + sudo /usr/local/bin/python3 -m pip install requests pandas docker + curl -sL https://raw.githubusercontent.com/openfido/cli/main/install.sh | sudo sh - name: Validate system run: sudo gridlabd -D keep_progress=TRUE -T 0 --validate -D github_actions=yes || ( sudo utilities/save_validation_errors ; false ) diff --git a/COPYRIGHT b/COPYRIGHT index 55d866a6f..d097681ba 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -7,16 +7,3 @@ Copyright (C) 2020-2022, Regents of the Leland Stanford Junior University GridLAB-D Version 1.0-4.0 Copyright (C) 2004-2019, Battelle Memorial Institute All Rights Reserved - -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 3 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, see . \ No newline at end of file diff --git a/LICENSE b/LICENSE index c429bcecd..a4ec19603 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,14 @@ BSD 3-Clause License -Copyright (c) 2018, Regents of the Leland Stanford Junior University -All rights reserved. +Arras Energy Version 4.3 +Copyright (C) 2023-, LF Energy + +HiPAS GridLAB-D 4.1-4.2 +Copyright (C) 2020-2022, Regents of the Leland Stanford Junior University + +GridLAB-D Version 1.0-4.0 +Copyright (C) 2004-2019, Battelle Memorial Institute +All Rights Reserved Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: diff --git a/converters/mdb-cyme2omd.py b/converters/mdb-cyme2omd.py deleted file mode 100644 index d4ac5d877..000000000 --- a/converters/mdb-cyme2omd.py +++ /dev/null @@ -1,3239 +0,0 @@ -# mdb2glm-cyme.py -# Copyright (C) 2020 Regents of the Leland Stanford Junior University -# Adapted by dchassin@slac.stanford.edu from NRECA OMF CYME-GLM converter -# See https://github.com/dpinney/omf/blob/master/omf/cymeToGridlab.py -# The original CYME-GLM converter was written by A Fisher @ PNNL in 2013 (no copyright) -# Current license: GPL-3 - -"""Convert CYME MDB to GridLAB-D GLM - -Python API: - convert(ifile,ofile,options=[]) - -CLI: - python3 mdb2glm-cyme.py -i|--input -o|--output [options...] - -Options: - -v enable verbose output - -d enable debug output - -q disable warning output -""" - -import csv, random, math, copy, subprocess, locale, tempfile, traceback -from os.path import join as pJoin -from io import StringIO -import sys, os, json, traceback, shutil -from pathlib import Path -import matplotlib -#matplotlib.pyplot.switch_backend("Agg") -from matplotlib import pyplot as plt -import numpy as np -from numpy.linalg import inv -import platform -# from feeder import * - -import importlib, copy -importlib.util.spec_from_file_location("feeder", sys.argv[0].replace("converters/mdb-cyme2glm","rt/feeder")); -feeder = importlib.import_module("feeder"); - -m2ft = 1.0 / 0.3048 # Conversion factor for meters to feet - -def convert(ifile,ofile,options=[]): - """Convert CYME MDB to GLM - Parameters: - input_name (str) [REQUIRED] input MDB filename - output_name (str) [REQUIRED] output GLM filename - options (list) [OPTIONAL] converter options - Options - -v enable verbose output - -d enable debugging output - -q disable warning output - """ - verbose=False - debug=False - quiet=False - if "-v" in options: - verbose = True - options.remove("-v") - if "-d" in options: - debug = True - options.remove("-d") - if "-q" in options: - quiet = True - options.remove("-q") - set_context(ifile,verbose,debug,quiet) - if len(options) > 0: - print_error(f"{options[0]} is not valid") - return - glmCirc = convertCymeModel(ifile) - with open(ofile,'w') as f: - glmString = feeder.sortedWrite(glmCirc) - f.write(glmString) - -verbose_output = False -debug_output = False -quiet_output = False -context_info = "mdb2glm.py" -def set_context(info,verbose,debug,quiet): - global context_info - global verbose_output - global debug_output - global quiet_output - context_info = info - verbose_output = verbose - debug_output = debug - quiet_output = quiet - -def print_verbose(msg): - global context_info - global verbose_output - if verbose_output: - print(f" ... [{context_info}] {msg}") - -def print_warning(msg): - global context_info - global quiet_output - if not quiet_output: - print(f"WARNING [{context_info}]: {msg}") - -def print_error(msg): - global context_info - print(f"ERROR [{context_info}]: {msg}") - -def print_debug(msg): - global context_info - global debug_output - if debug_output: - print(f"DEBUG [{context_info}]: {msg}") - -def flatten(*args, **kwargs): - dicty = dict(*args, **kwargs) - for arg in args: - if isinstance(arg, dict): - for k, v in arg.items(): - dicty[k] = v - if kwargs: - for k, v in kwargs.items(): - dicty[k] = v - return dicty - -def _csvDump(database_file): - # Get the list of table names with "mdb-tables" - table_names = subprocess.Popen( - ["mdb-tables", "-1", database_file], stdout=subprocess.PIPE - ).communicate()[0] - tables = table_names.decode("utf-8").split("\n") - csvdata = {} - for table in tables: - if table != "": - filename = table.replace(" ", "_") + ".csv" - csvdata[table] = subprocess.Popen( - ["mdb-export", database_file, table], - stdout=subprocess.PIPE - ).communicate()[0].decode("utf-8") - return csvdata - -def _findNetworkId(csvData): - csvDict = csv.DictReader(StringIO(csvData)) - networks = [] - for row in csvDict: - networks.append(row["NetworkId"]) - # HACK: For multi-source networks (Titanium), select the second source - # Need to find a way to do this better - if len(networks) > 1: - return networks[1] - else: - # If single source network, select the only source - return networks[0] - - -def _isfloat(value): - "Helper function for _fixName." - try: - float(value) - return True - except: - return False - - -def _fixName(name): - "Function that replaces characters not allowed in name with _" - badChar = [" ", "-", "\\", "//", "/", ":", ".", "''", "&"] - for char in badChar: - name = name.replace(char, "_") - # JOHN FITZGERALD KENNEDY. Don't allow names that start with a number - if _isfloat(name[0]): - name = "x" + name - return name - - -phases = ["AN", "BN", "CN", "ABN", "ACN", "BCN", "ABCN"] - - -def _convertPhase(int_phase): - "Function that converts a number to a phase" - - try: - return phases[int_phase - 1] - except IndexError: - return None - - -def _convertRegulatorPhase(int_phase): - ret = _convertPhase(int_phase) - return ret[:-1] if ret else None - - -classes = { - "Residential1": 0, - "Residential2": 1, - "Residential3": 2, - "Residential4": 3, - "Residential5": 4, - "Residential6": 5, - "Commercial1": 6, - "Commercial2": 7, - "Commercial3": 8, -} - - -def _convertLoadClass(class_from_db): - """# Function the converts a load classification string to a number""" - return classes.get(class_from_db) - - -def _csvToArray(csvFileName): - """ Simple .csv data ingester. """ - with open(csvFileName, "r") as csvFile: - csvReader = csv.reader(csvFile) - outArray = [] - for row in csvReader: - outArray += [row] - return outArray - - -def _csvToDictList(csvData, feederId): - included_columns = [] - header = [] - mapped = [] - deleteRows = [] - content = [] - csvDict = csv.DictReader(StringIO(csvData)) - for row in csvDict: - # Equipment files, all equipment gets added - if "NetworkId" not in header: - mapped.append(flatten(row)) - elif row["NetworkId"] == feederId: - mapped.append(flatten(row)) - return mapped - - -def checkMissingNodes( - nodes, sectionDevices, objectList, feederId, cymsection -): - dbNodes = [] - MISSINGNO = {"name": None} - nodesNotMake = {} - missingNodes = [] - glmObjs = [] - objNotMiss = [] - toNodesMissing = [] - sectionObjects = [] - otherObjects = [] - nonMissNodes = [] - nodesLen = len(nodes) - # Make missingNodesReport.txt - missingNodesReport = pJoin(modelDir, "missingNodesReport.txt") - with open(missingNodesReport, "w") as inFile: - inFile.write( - "Missing nodes report for " + feederId + "\nList of missing nodes:\n" - ) - node_db = _csvToDictList(pJoin(modelDir, "cymeCsvDump", "CYMNODE.csv"), feederId) - # Nodes in mdb are compared with nodes in glm and missing nodes is populated with those missing - for row in node_db: - dbNodes.append(_fixName(row["NodeId"])) - if _fixName(row["NodeId"]) not in nodes: - nodesNotMake[_fixName(row["NodeId"])] = copy.deepcopy(MISSINGNO) - nodesNotMake[_fixName(row["NodeId"])]["name"] = _fixName(row["NodeId"]) - missingNodes.append(_fixName(row["NodeId"])) - with open(missingNodesReport, "a") as inFile: - inFile.write(_fixName(row["NodeId"]) + "\n") - # All objects in glm are put in a list - for row in objectList: - for key in row.keys(): - glmObjs.append(key) - # Comparing missing nodes names to names of other glm objects to see if they are not nodes but other objects - # For Titanium these are batteries, diesel dg - with open(missingNodesReport, "a") as inFile: - inFile.write( - "Comparing the names of the missing nodes to the names of other objects in the .glm:\n" - ) - for row in missingNodes: - if row in glmObjs: - with open(missingNodesReport, "a") as inFile: - inFile.write( - row - + " was found as an existing object in the .glm. Removing it from the list of missing nodes...\n" - ) - objNotMiss.append(row) - # remove above objects from missing nodes list - for row in objNotMiss: - missingNodes.remove(row) - with open(missingNodesReport, "a") as inFile: - inFile.write("Updated list of missing nodes:\n") - for row in missingNodes: - with open(missingNodesReport, "a") as inFile: - inFile.write(row + "\n") - # check cymsection for the missing device and its corresponding device - with open(missingNodesReport, "a") as inFile: - inFile.write( - "Some nodes get absorbed into the objects that they lead to, checking for this situation now...\n" - ) - for row in cymsection: - for missNode in missingNodes: - if cymsection[row]["to"] == missNode: - sectionId = cymsection[row]["name"] - with open(missingNodesReport, "a") as inFile: - inFile.write( - "The missing node " - + missNode - + " is a part of the section " - + sectionId - + "\n" - ) - for dev in sectionDevices: - if sectionDevices[dev]["section_name"] == sectionId: - sectionObjects.append(sectionDevices[dev]["name"]) - with open(missingNodesReport, "a") as inFile: - inFile.write( - "This section corresponds to the device " - + sectionDevices[dev]["name"] - + "\n" - ) - # check to see if that device is in the glm - with open(missingNodesReport, "a") as inFile: - inFile.write( - "Comparing those devices to objects that already exist in the .glm:\n" - ) - for row in sectionObjects: - for obj in glmObjs: - if row in obj and "config" not in obj and "_" not in obj: - if row not in otherObjects: - otherObjects.append(row) - with open(missingNodesReport, "a") as inFile: - inFile.write( - row - + " was found as the existing object " - + obj - + " in the .glm. Removing its parent node from the list of missing nodes...\n" - ) - # Removing nodes with devices in the glm from this missing nodes list - for row in otherObjects: - nonMissNodes.append(cymsection[sectionDevices[row]["section_name"]]["to"]) - for row in nonMissNodes: - missingNodes.remove(row) - with open(missingNodesReport, "a") as inFile: - inFile.write("Updated list of missing nodes:\n") - for row in missingNodes: - with open(missingNodesReport, "a") as inFile: - inFile.write(row + "\n") - - -def _readSource(csvdata, feederId, _type): - """store information for the swing bus""" - # Stores information found in CYMSOURCE or CYMEQUIVALENTSOURCE in the network database - cymsource = {} - struct = { - "name": None, # information structure for each object found in struct - "bustype": "SWING", - "nominal_voltage": None, - "phases": None, - } - - if _type == 1: - # Check to see if the network database contains models for more than one database and if we chose a valid feeder_id to convert - feeder_db = _csvToDictList(csvdata["CYMSOURCE"], feederId - ) - elif _type == 2: - # Check to see if the network database contains models for more than one database and if we chose a valid feeder_id to convert - feeder_db = _csvToDictList(csvdata["CYMEQUIVALENTSOURCE"], feederId - ) - # feeder_db_net = networkDatabase.execute("SELECT NetworkId FROM CYMNETWORK").fetchall() - feeder_db_net = _csvToDictList(csvdata["CYMNETWORK"], feederId - ) - if feeder_db_net == None: - raise RuntimeError( - "No source node was found in struct: {:s}.\n".format(feederId) - ) - - if feeder_db == None: - raise RuntimeError( - "No source node was found in CYMSOURCE: {:s}.\n".format(feederId) - ) - else: - try: - print_verbose(f"NetworkId {feeder_db_net}") - except: - pass - """MICHAEL JACKSON debug""" - # if feederId arg is none (from findNetworkId call on CYMNETWORK.csv) - if feederId == None: - print_warning("no feeder id") - if len(feeder_db) == 1: - try: - row = feeder_db[0] - feederId = row["NetworkId"] - node_id = _fixName(row["NodeId"]) - cymsource[node_id] = copy.deepcopy(struct) - cymsource[node_id]["name"] = node_id - cymsource[node_id]["nominal_voltage"] = str( - float(row["DesiredVoltage"]) * 1000.0 / math.sqrt(3) - ) - except: - for row in feeder_db_net: - feederId = row["NetworkId"] - node_id = _fixName(row["NodeId"]) - cymsource[node_id] = copy.deepcopy(struct) - cymsource[node_id]["name"] = node_id - cymsource[node_id]["nominal_voltage"] = str( - float(row["OperatingVoltage1"]) * 1000.0 / math.sqrt(3) - ) - elif len(feeder_db) > 1: - raise RuntimeError( - "The was no feeder id given and the network database contians more than one feeder. Please specify a feeder id to extract." - ) - else: - print_verbose(f"feeder_id = {feederId}") - try: - feeder_index = [ - row["NetworkId"] for row in (feeder_db if _type == 1 else feeder_db_net) - ].index(feederId) - except ValueError: - raise RuntimeError( - "The feeder id provided is not in the network database. Please specify a valid feeder id to extract." - ) - - if _type == 1: - row = feeder_db[feeder_index] - feeder_id = feederId - node_id = _fixName(row["NodeId"]) - cymsource[node_id] = copy.deepcopy(struct) - cymsource[node_id]["name"] = node_id - cymsource[node_id]["nominal_voltage"] = str( - float(row["DesiredVoltage"]) * 1000.0 / math.sqrt(3) - ) - swingBus = node_id - elif _type == 2: - feederId_equivalent = "SOURCE_" + feederId - for row in feeder_db: - if row["NodeId"] in feederId_equivalent: - # JOHN FITZGERALD KENNEDY. logic was backwards. - feeder_id = feederId - node_id = _fixName(row["NodeId"]) - cymsource[node_id] = copy.deepcopy(struct) - cymsource[node_id]["name"] = node_id - # JOHN FITZGERALD KENNEDY. Differentiating between nominal voltage and voltage setpoint at the source. Otherwise, per unit calcs get messy later. Also, more accurate for capacitors. - cymsource[node_id]["nominal_voltage"] = str( - float(row["KVLL"]) * 1000.0 / math.sqrt(3) - ) # JOHN FITZGERALD KENNEDY. - cymsource[node_id]["source_voltage"] = str( - float(row["OperatingVoltage1"]) * 1000.0 - ) # JOHN FITZGERALD KENNEDY - swingBus = node_id - return cymsource, feeder_id, swingBus - - -def _readNode(csvdata, feederId): - """store lat/lon information on nodes""" - # Helper for lat/lon conversion. - x_pixel_range = 1200 - y_pixel_range = 800 - cymnode = {} - struct = {"name": None, "latitude": None, "longitude": None} - - node_db = _csvToDictList(csvdata["CYMNODE"], feederId) - if len(node_db) == 0: - print_verbose(f"no node locations were found for feeder id {feederId}") - else: - x = [float(row["X"]) for row in node_db] - y = [float(row["Y"]) for row in node_db] - try: - x_scale = x_pixel_range / (max(x) - min(x)) - x_b = -x_scale * min(x) - y_scale = y_pixel_range / (max(x) - min(y)) - y_b = -y_scale * min(y) - except: - x_scale, x_b, y_scale, y_b = (0, 0, 0, 0) - for row in node_db: - row["NodeId"] = _fixName(row["NodeId"]) - if row["NodeId"] not in cymnode: - cymnode[row["NodeId"]] = copy.deepcopy(struct) - cymnode[row["NodeId"]]["name"] = row["NodeId"] - cymnode[row["NodeId"]]["latitude"] = str( - x_scale * float(row["X"]) + x_b - ) - cymnode[row["NodeId"]]["longitude"] = str( - y_pixel_range - (y_scale * float(row["Y"]) + y_b) - ) - return cymnode, x_scale, y_scale - - -def _readOverheadByPhase(csvdata, feederId): - """store information from CYMOVERHEADBYPHASE""" - data_dict = {} - # Stores information found in CYMOVERHEADBYPHASE in the network database - olc = {} - uniqueSpacing = [] - overheadConductors = [] # Stores the unique conductor equipment Ids - struct = { - "name": None, # Information structure for each object found in CYMOVERHEADBYPHASE - "length": None, - "configuration": None, - } - - overheadbyphase_db = _csvToDictList(csvdata["CYMOVERHEADBYPHASE"], feederId - ) - if len(overheadbyphase_db) == 0: - print_verbose(f"no phase conductors, spacing, and lengths were found for feeder_id {feederId}") - else: - # Add all phase conductors to the line configuration dictionary. - for row in overheadbyphase_db: - device_no = _fixName(row["DeviceNumber"]) - if row["DeviceNumber"] not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - overheadLineConfiguration = {} - - for P in "ABC": - if row["PhaseConductorId" + P] != "NONE": - c_name = _fixName(row["PhaseConductorId" + P]) - overheadLineConfiguration["conductor_" + P] = c_name - if c_name not in overheadConductors: - overheadConductors.append(c_name) - - if row["NeutralConductorId"] != "NONE": - c_name = _fixName(row["NeutralConductorId"]) - overheadLineConfiguration["conductor_N"] = c_name - if c_name not in overheadConductors: - overheadConductors.append(c_name) - - tmp = _fixName(row["ConductorSpacingId"]) - overheadLineConfiguration["spacing"] = tmp - if tmp not in uniqueSpacing: - uniqueSpacing.append(tmp) - - tmp = float(row["Length"]) * m2ft - data_dict[device_no]["length"] = tmp if tmp != 0 else 1.0 - - for key, config in olc.items(): - if overheadLineConfiguration == config: - data_dict[device_no]["configuration"] = key - if data_dict[device_no]["configuration"] is None: - key = "olc" + str(len(olc)) - olc[key] = copy.deepcopy(overheadLineConfiguration) - data_dict[device_no]["configuration"] = key - return overheadConductors, data_dict, olc, uniqueSpacing - - -def _readGenericLine(csvdata, csvName, feederId, underground=False): - """store information from csvName""" - data_dict = {} - # Stores information found in CYMOVERHEADLINEUNBALANCED in the network database - conductors = [] # Stores the unique underground conductor equipment Ids - struct = { - "name": None, # Information structure for each object found in CYMOVERHEADLINEUNBALANCED - "length": None, - } - - struct["cable_id" if underground else "configuration"] = None - - db = _csvToDictList(csvdata[csvName], feederId) - if len(db) == 0: - print_verbose(f"no lines were found in {csvName} for feeder_id: {feederId}") - else: - for row in db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - - if underground: - tmp = _fixName(row["CableId"]) - data_dict[device_no]["cable_id"] = tmp - else: - tmp = _fixName(row["LineId"]) - data_dict[device_no]["configuration"] = tmp - - if tmp not in conductors: - conductors.append(tmp) - - tmp = float(row["Length"]) * m2ft - data_dict[device_no]["length"] = tmp if tmp != 0 else 1.0 - return conductors, data_dict - - -def _readOverheadLineUnbalanced(csvdata, feederId): - """store information from CYMOVERHEADLINEUNBALANCED""" - return _readGenericLine(csvdata,"CYMOVERHEADLINEUNBALANCED", feederId) - - -def _readOverheadLine(csvdata, feederId): - return _readGenericLine(csvdata,"CYMOVERHEADLINE", feederId) - - -def _readUndergroundLine(csvdata, feederId): - return _readGenericLine(csvdata, - "CYMUNDERGROUNDLINE", feederId, underground=True - ) - - -def _readQOverheadLine(csvdata, feederId): - data_dict = {} - struct = { - "name": None, # Information structure for each object found in CYMOVERHEADBYPHASE - "configuration": None, - } - spacingIds = [] - db = _csvToDictList(csvdata["CYMEQOVERHEADLINE"], feederId - ) - if len(db) == 0: - print_verbose("no overhead lines found for feeder_id {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - spacingIds.append(_fixName(row["ConductorSpacingId"])) - if eq_id not in data_dict: - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["configuration"] = _fixName(row["PhaseConductorId"]) - data_dict[eq_id]["spacing"] = _fixName(row["ConductorSpacingId"]) - data_dict[eq_id]["conductor_N"] = _fixName(row["NeutralConductorId"]) - return data_dict, spacingIds - - -def _readReactors(csvdata,feederId): - data_dict = {} - struct = {"name": None, "configuration": None} - reactorIds = [] - seriesreactor_db = _csvToDictList(csvdata["CYMSERIESREACTOR"], feederId - ) - if len(seriesreactor_db) == 0: - print_verbose(f"no series reactors were found for feeder_id {feederId}") - else: - for row in seriesreactor_db: - device_no = _fixName(row["DeviceNumber"]) - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in reactorIds: - reactorIds.append(eq_id) - if device_no not in data_dict: - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["configuration"] = eq_id - return data_dict, reactorIds - - -def _readEqReactors(csvdata, feederId): - data_dict = {} - struct = {"name": None, "reactance": None} - db = _csvToDictList(csvdata["CYMEQSERIESREACTOR"], feederId - ) - if len(db) == 0: - print_verbose(f"no reactor equipment was found for feeder_id {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict: - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["reactance"] = row["ReactanceOhms"] - return data_dict - - -def _readSection(csvdata, feederId): - """store information from CYMSECTION""" - data_dict = {} # Stores information found in CYMSECTION in the network database - struct = { - "name": None, # Information structure for each object found in CYMSECTION - "from": None, - "to": None, - "phases": None, - } - # section_db = networkDatabase.execute("SELECT SectionId, FromNodeId, ToNodeId, Phase FROM CYMSECTION WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - section_db = _csvToDictList(csvdata["CYMSECTION"], feederId - ) - if len(section_db) == 0: - print_verbose(f"no section information was found for feeder_id: {feederId}") - else: - for row in section_db: - sect_id = _fixName(row["SectionId"]) - if sect_id not in data_dict.keys(): - data_dict[sect_id] = copy.deepcopy(struct) - data_dict[sect_id]["name"] = sect_id - data_dict[sect_id]["from"] = _fixName(row["FromNodeId"]) - data_dict[sect_id]["to"] = _fixName(row["ToNodeId"]) - data_dict[sect_id]["phases"] = _convertPhase(int(row["Phase"])) - return data_dict - - -def _readSectionDevice(csvdata, feederId): - """store information from CYMSECTIONDEVICE""" - data_dict = ( - {} - ) # Stores information found in CYMSECTIONDEVICE in the network database - struct = { - "name": None, # Information structure for each object found in CYMSECTIONDEVICE - "device_type": None, - "section_name": None, - "location": None, - } - # section_device_db = networkDatabase.execute("SELECT DeviceNumber, DeviceType, SectionId, Location FROM CYMSECTIONDEVICE WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - section_device_db = _csvToDictList(csvdata["CYMSECTIONDEVICE"], feederId - ) - if len(section_device_db) == 0: - print_verbose(f"no section device found for feeder_id {feederId}") - else: - for row in section_device_db: - sect_id = _fixName(row["SectionId"]) - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["device_type"] = int(row["DeviceType"]) - data_dict[device_no]["section_name"] = sect_id - data_dict[device_no]["location"] = int(row["Location"]) - else: - # JOHN FITZGERALD KENNEDY. A better fix is needed. - print_warning(f"duplicate device ID {device_no} must be renamed Cyme to not be overwritten") - return data_dict - - -def _splitLinkObjects(sectionDict, deviceDict, linkDict, overheadDict, undergroundDict): - """Split multiple link objects from the line that they are folded into""" - # JOHN FITZGERALD KENNEDY. Several changes in here related to the following problem. Old code assume that each section (linkDict) would - # only have one device or link object per section. I found that this wasn't true for solar PV and switches. - # Later in the code, linkDicts for these objects have lists as their values. - # This code now reflects this possiblity. But it makes it kind of inconsistent and hacky. - for link in linkDict: - if link in overheadDict or link in undergroundDict: - # if true the link is embedded in a line object and must be separated - lineId = link - - tmp = linkDict[link] - newLinkIds = tmp if type(tmp) == list else [tmp] - - for newLinkId in newLinkIds: # JOHN FITZGERALD KENNEDY - at_from = deviceDict[newLinkId]["location"] == 1 - to_of = newLinkId if at_from else lineId - from_of = lineId if at_from else newLinkId - - sectionDict[newLinkId] = copy.deepcopy(sectionDict[lineId]) - sectionDict[newLinkId]["name"] = newLinkId - - sectionDict[to_of]["to"] = "node" + newLinkId - sectionDict[from_of]["from"] = "node" + newLinkId - - a = "to" if at_from else "from" - b = "from" if at_from else "to" - - sectionDict[newLinkId][a + "X"] = str( - float(sectionDict[lineId][b + "X"]) + random.uniform(-10, 10) - ) - sectionDict[newLinkId][a + "Y"] = str( - float(sectionDict[lineId][b + "Y"]) + random.uniform(-10, 10) - ) - sectionDict[lineId][b + "X"] = sectionDict[newLinkId][a + "X"] - sectionDict[lineId][b + "Y"] = sectionDict[newLinkId][a + "Y"] - - for phase in ["N", "D"]: - sectionDict[newLinkId]["phases"] = sectionDict[newLinkId][ - "phases" - ].replace(phase, "") - deviceDict[newLinkId]["section_name"] = newLinkId - deviceDict[newLinkId]["location"] = 0 - - -def _findParents(sectionDict, deviceDict, loadDict): - """store parent information for load type objects""" - for lineId, loaddevices in loadDict.items(): - # if it's not a list, put it into a list on len 1 - loaddevices = loaddevices if type(loaddevices) == list else [loaddevices] - for loaddevice in loaddevices: - tmp = "to" if deviceDict[loaddevice]["location"] == 2 else "from" - deviceDict[loaddevice]["parent"] = sectionDict[lineId][tmp] - deviceDict[loaddevice]["phases"] = sectionDict[lineId]["phases"] - - -def _readSwitch(csvdata, feederId): - data_dict = {} # Stores information found in CYMSWITCH in the network database - struct = { - "name": None, # Information structure for each object found in CYMSWITCH - "equipment_name": None, - "status": None, - } - # switch_db = networkDatabase.execute("SELECT DeviceNumber, EquipmentId, ClosedPhase FROM CYMSWITCH WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - switch_db = _csvToDictList(csvdata["CYMSWITCH"], feederId - ) - if len(switch_db) == 0: - print_verbose(f"No switches were found in CYMSWITCH for feeder_id {feederId}") - else: - for row in switch_db: - device_no = _fixName(row["DeviceNumber"]) - eq_id = _fixName(row["EquipmentId"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_name"] = eq_id - data_dict[device_no]["status"] = ( - 0 if float(row["ClosedPhase"]) == 0 else 1 - ) - return data_dict - - -def _readSectionalizer(csvdata, feederId): - data_dict = ( - {} - ) # Stores information found in CYMSECTIONALIZER in the network database - struct = { - "name": None, # Information structure for each object found in CYMSECTIONALIZER - "status": None, - } - # sectionalizer_db = networkDatabase.execute("SELECT DeviceNumber, NormalStatus FROM CYMSECTIONALIZER WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - sectionalizer_db = _csvToDictList(csvdata["CYMSECTIONALIZER"], feederId - ) - if len(sectionalizer_db) == 0: - print_verbose(f"no sectionalizers were found for feeder_id {feederId}") - else: - for row in sectionalizer_db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["status"] = ( - 0 if float(row["NormalStatus"]) == 0 else 1 - ) - return data_dict - - -def _readFuse(csvdata, feederId): - data_dict = {} # Stores information found in CYMFUSE in the network database - struct = { - "name": None, # Information structure for each object found in CYMFUSE - "status": None, - "equipment_id": None, - } - # fuse_db = networkDatabase.execute("SELECT DeviceNumber, EquipmentId, NormalStatus FROM CYMFUSE WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - fuse_db = _csvToDictList(csvdata["CYMFUSE"], feederId) - if len(fuse_db) == 0: - print_verbose(f"no fuses were found for feeder_id {feederId}") - else: - for row in fuse_db: - device_no = _fixName(row["DeviceNumber"]) - eq_id = _fixName(row["EquipmentId"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_id"] = eq_id - data_dict[device_no]["status"] = ( - 0 if float(row["NormalStatus"]) == 0 else 1 - ) - return data_dict - - -def _readRecloser(csvdata, feederId): - data_dict = {} - struct = {"name": None, "status": None} - recloser_db = _csvToDictList(csvdata["CYMRECLOSER"], feederId - ) - if len(recloser_db) == 0: - print_verbose(f"no reclosers were found for feeder_id {feederId}") - else: - for row in recloser_db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["status"] = ( - 0 if float(row["NormalStatus"]) == 0 else 1 - ) - return data_dict - - -def _readRegulator(csvdata, feederId): - data_dict = {} - # Stores information found in CYMREGULATOR in the network database - struct = { - "name": None, # Information structure for each object found in CYMREGULATOR - "equipment_name": None, - "regulation": None, - "band_width": None, - "tap_pos_A": None, - "tap_pos_B": None, - "tap_pos_C": None, - } - # regulator_db = networkDatabase.execute("SELECT DeviceNumber, EquipmentId, BandWidth, BoostPercent, TapPositionA, TapPositionB, TapPositionC FROM CYMREGULATOR WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - regulator_db = _csvToDictList(csvdata["CYMREGULATOR"], feederId - ) - if len(regulator_db) == 0: - print_verbose(f"no regulators were found for feeder_id: {feederId}") - else: - for row in regulator_db: - device_no = _fixName(row["DeviceNumber"]) - eq_id = _fixName(row["EquipmentId"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_name"] = eq_id - # data_dict[device_no]['band_width'] = float(row["BandWidth"])/120.0 #does not exist in database. now forwardbandwidth in regulator equipment - data_dict[device_no]["regulation"] = float(row["BoostPercent"]) / 100.0 - for p in "ABC": - data_dict[device_no]["tap_pos_" + p] = row["TapPosition" + p] - return data_dict - - -def _readShuntCapacitor(csvdata, feederId): - data_dict = {} - # Stores information found in CYMSHUNTCAPACITOR in the network database - struct = { - "name": None, # Information structure for each object found in CYMSHUNTCAPACITOR - "equipment_name": None, - "status": None, - "phases": None, - "capacitor_A": None, - "capacitor_B": None, - "capacitor_C": None, - "capacitor_ABC": None, - "kV_line_neutral": None, # kV. for consistency - "control": None, - "voltage_set_high": None, - "voltage_set_low": None, - "VAr_set_high": None, - "VAr_set_low": None, - "current_set_high": None, - "current_set_low": None, - "pt_phase": None, - "remote_sense": None, - "control_level": None, - } - - shuntcapacitor_db = _csvToDictList(csvdata["CYMSHUNTCAPACITOR"], feederId - ) - if len(shuntcapacitor_db) == 0: - print_verbose(f"no shunt capacitors were found for feeder_id {feederId}") - else: - # if shunt capacitor table has KVARBC as a column use this block: - for row in shuntcapacitor_db: - device_no = _fixName(row["DeviceNumber"]) - if not "EquipmentId" in row.keys(): - row["EquipmentId"] = "DEFAULT" - eq_id = _fixName(row["EquipmentId"]) - - if device_no not in data_dict: - data_dict[device_no] = struct.copy() - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_name"] = eq_id - data_dict[device_no]["status"] = row["Status"] - - if float(row["KVLN"]) > 0.0: - data_dict[device_no]["kV_line_neutral"] = float(row["KVLN"]) * 1000 - - # if CCT is 2 or 3, we make set the phase and offvalue under the if below - if int(row["CapacitorControlType"]) == 2: - data_dict[device_no]["control"] = "VAR" - data_dict[device_no]["VAr_set_high"] = float(row["OnValue"]) * 1000 - elif int(row["CapacitorControlType"]) == 3: - data_dict[device_no]["control"] = "CURRENT" - data_dict[device_no]["current_set_high"] = row["OnValue"] - # NOTE: should the above be cast to float? - elif int(row["CapacitorControlType"]) == 7: - data_dict[device_no]["control"] = "VOLT" - controlledphase = _convertPhase( - int(row["ControlledPhase"]) - ).replace("N", "") - data_dict[device_no]["voltage_set_low"] = float( - row.get("OnValue" + controlledphase, 0) - ) - data_dict[device_no]["voltage_set_high"] = float( - row.get("OffValue" + controlledphase, 0) - ) - data_dict[device_no]["pt_phase"] = controlledphase - data_dict[device_no]["remote_sense"] = _fixName( - row["ControlledNodeId"] - ) - else: - data_dict[device_no]["control"] = "MANUAL" - data_dict[device_no]["pt_phase"] = "ABCN" - data_dict[device_no]["voltage_set_high"] = float(row["KVLN"]) * 1000 - data_dict[device_no]["voltage_set_low"] = float(row["KVLN"]) * 1000 - - if float(row.get("SwitchedKVARA", 0)) == 0: - data_dict[device_no]["phases"] = "ABC" - # _convertPhase(int(row["Phase"])) - # JOHN FITZGERALD KENNEDY. Painful change. Phase doesn't exist in my capacitor tables. - - for p in ("A", "B", "C", "ABC"): - row["KVAR" + p] = float(row["KVAR" + p]) - - if all([row["KVAR" + p] == 0 for p in "ABC"]): - for p in "ABC": - data_dict[device_no]["capacitor_" + p] = ( - row["KVARABC"] * 1000 / 3 - ) - else: - for p in "ABC": - if row["KVAR" + p] > 0: - data_dict[device_no]["capacitor_" + p] = ( - row["KVAR" + p] * 1000 - ) - - if int(row["CapacitorControlType"]) == 2: - data_dict[device_no]["VAr_set_low"] = ( - float(row["OffValue"]) * 1000 - ) - data_dict[device_no]["pt_phase"] = _convertPhase( - int(row["Phase"]) - ) - elif int(row["CapacitorControlType"]) == 3: - data_dict[device_no]["current_set_low"] = row["OffValue"] - data_dict[device_no]["pt_phase"] = _convertPhase( - int(row["Phase"]) - ) - else: - if row["SwitchingMode"] == "2": - data_dict[device_no]["control_level"] = "BANK" - elif row["SwitchingMode"] == "1": - data_dict[device_no]["control_level"] = "INDIVIDUAL" - else: - print_warning("could not find capacitor switching mode, using 'INDIVIDUAL' by default") - data_dict[device_no]["control_level"] = "INDIVIDUAL" - for p in "ABC": - if float(row["SwictchedKVAR" + p]) > 0: - data_dict[device_no]["capacitor_" + p] = ( - float(row["SwitchedKVAR" + p]) * 1000 - ) - - if int(row["CapacitorControlType"]) == 2: - data_dict[device_no]["VAr_set_low"] = ( - float(row["OffValueA"]) * 1000 - ) - data_dict[device_no]["pt_phase"] = "ABCN" - elif int(row["CapacitorControlType"]) == 3: - data_dict[device_no]["current_set_low"] = row["OffValueA"] - data_dict[device_no]["pt_phase"] = "ABCN" - return data_dict - - -def _determineLoad(l_type, l_v1, l_v2, conKVA): - l_real = 0 - l_imag = 0 - conKVA = float(conKVA) - if l_type == 0: # information was stored as kW & kVAR - l_real = l_v1 * 1000.0 - l_imag = abs(l_v2) * 1000.0 - elif l_type == 1: # information was stored as kVA & power factor - l_real = l_v1 * abs(l_v2) / 100.0 * 1000.0 - l_imag = l_v1 * math.sqrt(1 - (abs(l_v2) / 100.0) ** 2) * 1000.0 - else: # information was stored as kW and power factor - l_real = l_v1 * 1000.0 - if l_v2 != 0.0: - l_imag = ( - l_real / (abs(l_v2) / 100.0) * math.sqrt(1 - (abs(l_v2) / 100.0) ** 2) - ) - if l_real == 0.0 and l_imag == 0.0: - l_real = conKVA * abs(l_v2) / 100.0 * 1000.0 - l_imag = conKVA * math.sqrt(1 - (abs(l_v2) / 100.0) ** 2) * 1000.0 - if l_v2 < 0.0: - l_imag *= -1.0 - return l_real, l_imag - - -def _setConstantPower(l_v2, l_real, l_imag): - if l_v2 >= 0.0: - cp_string = "{:0.3f}+{:0.3f}j".format(l_real, l_imag) - else: - cp_string = "{:0.3f}-{:0.3f}j".format(l_real, abs(l_imag)) - return cp_string - - -def _cleanPhases(phases): - p = "" - if "A" in phases: - p = p + "A" - if "B" in phases: - p = p + "B" - if "C" in phases: - p = p + "C" - return p - - -def _readCustomerLoad(csvdata, feederId): - data_dict = ( - {} - ) # Stores information found in CYMCUSTOMERLOAD in the network database - struct = { - "name": None, # Information structure for each object found in CYMCUSTERLOAD - "phases": None, - "constant_power_A": None, - "constant_power_B": None, - "constant_power_C": None, - "load_realA": 0.0, - "load_imagA": 0.0, - "load_realB": 0.0, - "load_imagB": 0.0, - "load_realC": 0.0, - "load_imagC": 0.0, - "load_class": None, - } - load_real = 0 - load_imag = 0 - # customerload_db = networkDatabase.execute("SELECT DeviceNumber, DeviceType, ConsumerClassId, Phase, LoadValueType, Phase, LoadValue1, LoadValue2, ConnectedKVA FROM CYMCUSTOMERLOAD WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - customerload_db = _csvToDictList(csvdata["CYMCUSTOMERLOAD"], feederId - ) - if len(customerload_db) == 0: - print_verbose("no loads were found for feeder_id {feederId}.") - else: - for row in customerload_db: - device_no = _fixName(row["DeviceNumber"]) - load_real, load_imag = _determineLoad( - int(row["LoadValueType"]), - float(row["LoadValue1"]), - float(row["LoadValue2"]), - row["ConnectedKVA"], - ) - row_phases = _cleanPhases(_convertPhase(int(row["Phase"]))) - if device_no not in data_dict.keys(): - # check for 0 load - if ( - row["Status"] == "1" - ): # JOHN FITZGERALD KENNEDY. Set disconnected loads to zero. - load_real = 0 - load_imag = 0 - - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - # _cleanPhases essentially removes N in this case - data_dict[device_no]["phases"] = row_phases - - # prior code only allowed 'A', 'B', 'C', or 'ABC' - for p in row_phases: - # temp vars - lr = float(load_real / len(row_phases)) - li = float(load_imag / len(row_phases)) - data_dict[device_no]["load_real" + p] = lr - data_dict[device_no]["load_imag" + p] = li - data_dict[device_no]["constant_power_" + p] = _setConstantPower( - float(row["LoadValue2"]), lr, li - ) - - # Determine the load classification (default is residential) - if "commercial" in (row["ConsumerClassId"]).lower(): - data_dict[device_no]["load_class"] = "C" - else: - data_dict[device_no]["load_class"] = "R" - convert_class = _convertLoadClass(row["ConsumerClassId"]) - if convert_class is not None: - data_dict[device_no]["load_class"] = convert_class - - else: - # device_no alr exists in data_dict - device_ps = data_dict[device_no]["phases"] + row_phases - data_dict[device_no]["phases"] = _cleanPhases(device_ps) - - # again, prior code only allowed 'A', 'B', 'C', or 'ABC' - for p in row_phases: - data_dict[device_no]["load_real" + p] += float( - load_real / len(row_phases) - ) - data_dict[device_no]["load_imag" + p] += float( - load_imag / len(row_phases) - ) - data_dict[device_no]["constant_power_" + p] = _setConstantPower( - float(row["LoadValue2"]), - data_dict[device_no]["load_real" + p], - data_dict[device_no]["load_imag" + p], - ) - return data_dict - - -def _readThreeWindingTransformer(csvdata, feederId): - data_dict = {} # Stores information found in CYMREGULATOR in the network database - struct = { - "name": None, # Information structure for each object found in CYMREGULATOR - "equipment_name": None, - } - # threewxfmr_db = networkDatabase.execute("SELECT DeviceNumber, EquipmentId FROM CYMTHREEWINDINGTRANSFORMER WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - threewxfmr_db = _csvToDictList(csvdata["CYMTHREEWINDINGTRANSFORMER"], feederId - ) - if len(threewxfmr_db) == 0: - print_verbose(f"no three-winding transformers were found for feeder_id {feederId}") - else: - for row in threewxfmr_db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_name"] = _fixName(row["EquipmentId"]) - return data_dict - - -def _readTransformer(csvdata, feederId): - data_dict = {} - struct = {"name": None, "equipment_name": None} - # xfmrDb = networkDatabase.execute("SELECT DeviceNumber, EquipmentId FROM CYMTRANSFORMER WHERE NetworkId = '{:s}'".format(feederId)).fetchall() - xfmrDb = _csvToDictList(csvdata["CYMTRANSFORMER"], feederId - ) - if len(xfmrDb) == 0: - print_verbose(f"no transformers were found for feeder id {feederId}") - else: - for row in xfmrDb: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["equipment_name"] = _fixName(row["EquipmentId"]) - return data_dict - - -def _readEqConductor(csvdata, feederId): - data_dict = ( - {} - ) # Stores information found in CYMEQCONDUCTOR in the equipment database - struct = { - "name": None, # Information structure for each object found in CYMEQCONDUCTOR - "rating.summer_continuous": None, - "geometric_mean_radius": None, - "resistance": None, - } - db = _csvToDictList(csvdata["CYMEQCONDUCTOR"], feederId) - if len(db) == 0: - print_warning(f"no conductors were found for feeder_id {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["rating.summer_continuous"] = row["FirstRating"] - data_dict[eq_id]["geometric_mean_radius"] = ( - float(row["GMR"]) * m2ft / 100 - ) - # GMR is stored in cm. Must convert to ft. - data_dict[eq_id]["resistance"] = ( - float(row["R50"]) * 5280 / (m2ft * 1000) - ) - # R50 is stored in Ohm/km. Must convert to Ohm/mile - return data_dict - - -def _readEqOverheadLineUnbalanced(csvdata, feederId): - """store information from CYMEQOVERHEADLINEUNBALANCED""" - data_dict = ( - {} - ) # Stores information found in CYMEQOVERHEADLINEUNBALANCED in the network database - struct = { - "object": "line_configuration", - "name": None, - "z11": None, - "z12": None, - "z13": None, - "z21": None, - "z22": None, - "z23": None, - "z31": None, - "z32": None, - "z33": None, - } - # ug_line_db = networkDatabase.execute("SELECT EquipmentId, SelfResistanceA, SelfResistanceB, SelfResistanceC, SelfReactanceA, SelfReactanceB, SelfReactanceC, MutualResistanceAB, MutualResistanceBC, MutualResistanceCA, MutualReactanceAB, MutualReactanceBC, MutualReactanceCA FROM CYMEQOVERHEADLINEUNBALANCED WHERE EquipmentId = '{:s}'".format("LINE606")).fetchall() - oh_line_db = _csvToDictList(csvdata["CYMEQOVERHEADLINEUNBALANCED"], feederId - ) - if len(oh_line_db) == 0: - print_verbose(f"no underground line configurations were found for feeder_id {feederId}.") - else: - for row in oh_line_db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = _fixName(eq_id) - - # in source, split between two entries: Resistance and Reactance - source = [ - "Self%sA", - "Self%sB", - "Self%sC", - "Mutual%sAB", - "Mutual%sBC", - "Mutual%sCA", - ] - target = ["z11", "z22", "z33", "z12", "z23", "z13"] - for s, t in zip(source, target): - data_dict[eq_id][t] = "{:0.6f}{:+0.6}j".format( - float(row[s % "Resistance"]) * 5280 / (m2ft * 1000), - float(row[s % "Reactance"]) * 5280 / (m2ft * 1000), - ) - - # glm has entries with the phase order swapped. cym doesn't, so we duplicate. - reverses = [("z12", "z21"), ("z23", "z32"), ("z13", "z31")] - for v1, v2 in reverses: - data_dict[eq_id][v2] = data_dict[eq_id][v1] - return data_dict - - -def _readEqGeometricalArrangement(csvdata, feederId): - data_dict = {} - # Stores information found in CYMEQGEOMETRICALARRANGEMENT in the equipment database - struct = { - "name": None, # Information structure for each object found in CYMEQGEOMETRICALARRANGEMENT - "distance_AB": None, - "distance_AC": None, - "distance_AN": None, - "distance_BC": None, - "distance_BN": None, - "distance_CN": None, - } - # db = equipmentDatabase.execute("SELECT EquipmentId, ConductorA_Horizontal, ConductorA_Vertical, ConductorB_Horizontal, ConductorB_Vertical, ConductorC_Horizontal, ConductorC_Vertical, NeutralConductor_Horizontal, NeutralConductor_Vertical FROM CYMEQGEOMETRICALARRANGEMENT").fetchall() - db = _csvToDictList(csvdata["CYMEQGEOMETRICALARRANGEMENT"], feederId - ) - if len(db) == 0: - print_verfbose(f"no geometric spacing information found for feeder_id {feederId}") - else: - - def _dist(phase_pair): - first, second = phase_pair[0], phase_pair[1] - first = "Conductor" + first - second = "Conductor" + second if second != "N" else "NeutralConductor" - H1, H2 = row[first + "_Horizontal"], row[second + "_Horizontal"] - V1, V2 = row[first + "_Vertical"], row[second + "_Vertical"] - return math.sqrt( - (float(H1) - float(H2)) ** 2 + (float(V1) - float(V2)) ** 2 - ) - - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - for phase_pair in ("AB", "AC", "AN", "BC", "BN", "CN"): - data_dict[eq_id]["distance_" + phase_pair] = _dist(phase_pair) - return data_dict - - -def _readUgConfiguration(csvdata, feederId): - from itertools import product - - data_dict = {} - # Defaults, need defaults for all values - struct = { - "name": None, - "rating.summer_continuous": None, - "outer_diameter": 0.0640837, - "conductor_resistance": 14.87200, - "conductor_gmr": 0.020800, - "conductor_diameter": 0.0640837, - "neutral_resistance": 14.87200, - "neutral_gmr": 0.020800, - "neutral_diameter": 0.0640837, - "neutral_strands": 10, - "distance_AB": 0.05, - "distance_AC": 1.0, - "distance_AN": 0.0, - "distance_BC": 0.5, - "distance_BN": 0.0, - "distance_CN": 0.0, - "z11": 0 + 1j, - "z12": 0 + 1j, - "z13": 0 + 1j, - "z21": 0 + 1j, - "z22": 0 + 1j, - "z23": 0 + 1j, - "z31": 0 + 1j, - "z32": 0 + 1j, - "z33": 0 + 1j, - } - try: - undergroundcable = _csvToDictList(csvdata["CYMEQCABLE"], feederId - ) - undergroundcableconductor = _csvToDictList(csvdata["CYMEQCABLECONDUCTOR"], feederId - ) - except: - undergroundcableconductor = {} - print_verbose(f"no underground line configurations found for feeder_id {feederId}") - if len(undergroundcable) == 0: - print_verbose(f"no underground_line configurations found for feeder_id: {feederId}") - else: - # declare some conversion matrices for impedance conversion later - a_s = 1 * np.exp(1j * np.deg2rad(120)) - As = np.array([[1, 1, 1], [1, a_s ** 2, a_s], [1, a_s, a_s ** 2]]) - for row in undergroundcable: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["rating.summer_continuous"] = row["FirstRating"] - data_dict[eq_id]["outer_diameter"] = row.get( - "OverallDiameter", 0.0640837 - ) - data_dict[eq_id]["conductor_resistance"] = row[ - "PositiveSequenceResistance" - ] - # leaving as is since z matrix overwrites - - # potential bad values: None, "", "0" - tmp = row.get("ArmorOuterDiameter") - tmp = float(tmp) if tmp else 0 - if tmp != 0: - data_dict[eq_id]["conductor_diameter"] = row["ArmorOuterDiameter"] - data_dict[eq_id]["conductor_gmr"] = tmp / 3 - - # conversion from cyme's ZeroSequenceResistance/Reactance -> Gridlabd's self/mutual impedances - z00 = complex( - float(row["ZeroSequenceResistance"]), - float(row["ZeroSequenceReactance"]), - ) - z11 = complex( - float(row["PositiveSequenceResistance"]), - float(row["PositiveSequenceReactance"]), - ) - Z012 = ( - np.array([[z00, 0, 0], [0, z11, 0], [0, 0, z11]]) - * 5280 - / (m2ft * 1000) - ) - Zabc = As.dot(Z012).dot(inv(As)) - for p1, p2 in product([1, 2, 3], [1, 2, 3]): - data_dict[eq_id]["z%d%d" % (p1, p2)] = ( - "{:0.6f}".format(Zabc[p1 - 1][p2 - 1].real) - + "{:+0.6f}".format(Zabc[p1 - 1][p2 - 1].imag) - + "j" - ) - - # Still missing these properties, will have default values for all objects - # data_dict[eq_id]]['neutral_resistance'] = row["ZeroSequenceResistance"] - # data_dict[eq_id]]['distance_AB'] = row["OverallDiameter"] - # data_dict[eq_id]]['distance_AC'] = row["OverallDiameter"] - # data_dict[eq_id]]['distance_AN'] = row["OverallDiameter"] - # data_dict[eq_id]]['distance_BC'] = row["OverallDiameter"] - # data_dict[eq_id]]['distance_BC'] = row["OverallDiameter"] - # data_dict[eq_id]]['distance_CN'] = row["OverallDiameter"] - for row in undergroundcableconductor: - eq_id = _fixName(row["EquipmentId"]) - if eq_id in data_dict.keys(): - data_dict[eq_id]["neutral_diameter"] = row["Diameter"] - data_dict[eq_id]["neutral_strands"] = row["NumberOfStrands"] - data_dict[eq_id]["neutral_gmr"] = float(row["Diameter"]) / 3 - return data_dict - - -def _readEqAvgGeometricalArrangement(csvdata, feederId): - data_dict = {} - struct = { - "name": None, - "distance_AB": None, - "distance_AC": None, - "distance_AN": None, - "distance_BC": None, - "distance_BN": None, - "distance_CN": None, - } - # cymeqaveragegeoarrangement_db = equipmentDatabase.execute("SELECT EquipmentId, GMDPhaseToPhase, GMDPhaseToNeutral FROM CYMEQAVERAGEGEOARRANGEMENT").fetchall() - cymeqaveragegeoarrangement_db = _csvToDictList(csvdata["CYMEQAVERAGEGEOARRANGEMENT"], feederId - ) - if len(cymeqaveragegeoarrangement_db) == 0: - print_verbose(f"no average spacing information found for feeder_id {feederId}") - else: - for row in cymeqaveragegeoarrangement_db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - - phase_to_phase = ("AB", "AC", "BC") - phase_to_neutral = ("AN", "BN", "CN") - for pp in phase_to_phase: - data_dict[eq_id]["distance_" + pp] = ( - float(row["GMDPhaseToPhase"]) * m2ft - ) # information is stored in meters. must convert to feet. - for pn in phase_to_neutral: - data_dict[eq_id]["distance_" + pn] = ( - float(row["GMDPhaseToNeutral"]) * m2ft - ) - return data_dict - - -def _readEqRegulator(csvdata, feederId): - data_dict = ( - {} - ) # Stores information found in CYMEQREGULATOR in the equipment database - struct = { - "name": None, # Information structure for each object found in CYMEQREGULATOR - "raise_taps": None, - "lower_taps": None, - "nominal_voltage": None, - "bandwidth": None, - } - # db = equipmentDatabase.execute("SELECT EquipmentId, NumberOfTaps FROM CYMEQREGULATOR").fetchall() - db = _csvToDictList(csvdata["CYMEQREGULATOR"], feederId - ) - - if len(db) == 0: - print_verbose(f"no regulator equipment found for feeder_id {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["raise_taps"] = str( - int(float(row["NumberOfTaps"]) * 0.5) - ) - data_dict[eq_id]["lower_taps"] = str( - int(float(row["NumberOfTaps"]) * 0.5) - ) - data_dict[eq_id]["nominal_voltage"] = row["RatedKVLN"] - data_dict[eq_id]["bandwidth"] = row.get("ForwardBandwidth") - # TODO: figure out how to determine bandwidth. this should be there, but isn't - return data_dict - - -def _readEqThreeWAutoXfmr(csvdata, feederId): - data_dict = {} - # Stores information found in CYMEQOVERHEADLINE in the equipment database - struct = { - "name": None, # Information structure for each object found in CYMEQOVERHEADLINE - "PrimaryRatedCapacity": None, - "PrimaryVoltage": None, - "SecondaryVoltage": None, - "impedance": None, - } - - db = _csvToDictList(csvdata["CYMEQTHREEWINDAUTOTRANSFORMER"], feederId - ) - if len(db) == 0: - print_verbose(f"no three-winding autotransformer information found for feeder_id {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["PrimaryRatedCapacity"] = float( - row["PrimaryRatedCapacity"] - ) - data_dict[eq_id]["PrimaryVoltage"] = ( - float(row["PrimaryVoltage"]) * 1000.0 / math.sqrt(3.0) - ) - data_dict[eq_id]["SecondaryVoltage"] = ( - float(row["SecondaryVoltage"]) * 1000.0 / math.sqrt(3.0) - ) - if ( - data_dict[eq_id]["PrimaryVoltage"] - == data_dict[eq_id]["SecondaryVoltage"] - ): - data_dict[eq_id]["SecondaryVoltage"] += 0.1 - z1mag = float(row["PrimarySecondaryZ1"]) / 100.0 - if z1mag == 0: - r = 0.000333 - x = 0.00222 - else: - xr1_ratio = float(row["PrimarySecondaryXR1Ratio"]) - r = z1mag / math.sqrt(1 + xr1_ratio ** 2) - x = r * xr1_ratio - data_dict[eq_id]["impedance"] = "{:0.6f}{:+0.6f}j".format(r, x) - return data_dict - - -def _readEqAutoXfmr(csvdata, feederId): - return _readEqXfmr(csvdata, feederId, _auto=True) - - -def _readEqXfmr(csvdata, feederId, _auto=False): - transformer_text = "AUTOTRANSFORMER" if _auto else "TRANSFORMER" - data_dict = {} - struct = { - "name": None, - "PrimaryRatedCapacity": None, - "PrimaryVoltage": None, - "SecondaryVoltage": None, - "impedance": None, - } - db = _csvToDictList(csvdata[f"CYMEQ{transformer_text}"], feederId - ) - if len(db) == 0: - print_verbose(f"no average {transformer_text.lower()} equipment information found for feeder id: {feederId}") - else: - for row in db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["PrimaryRatedCapacity"] = float( - row["NominalRatingKVA"] - ) - data_dict[eq_id]["PrimaryVoltage"] = ( - float(row["PrimaryVoltageKVLL"]) * 1000.0 / math.sqrt(3.0) - ) - data_dict[eq_id]["SecondaryVoltage"] = ( - float(row["SecondaryVoltageKVLL"]) * 1000.0 / math.sqrt(3.0) - ) - if ( - data_dict[eq_id]["PrimaryVoltage"] - == data_dict[eq_id]["SecondaryVoltage"] - ): - data_dict[eq_id]["SecondaryVoltage"] += 0.001 - z1mag = float(row["PosSeqImpedancePercent"]) / 100.0 - r = z1mag / math.sqrt(1 + (float(row["XRRatio"])) ** 2) - if r == 0.0: - r = 0.000333 - x = 0.00222 - else: - x = r * float(row["XRRatio"]) - data_dict[eq_id]["impedance"] = "{:0.6f}{:+0.6f}j".format(r, x) - return data_dict - - -def _readPhotovoltaic(csvdata, feederId): - data_dict = {} - struct = {"name": None, "configuration": None} - cymphotovoltaic_db = _csvToDictList(csvdata["CYMPHOTOVOLTAIC"], feederId - ) - if len(cymphotovoltaic_db) == 0: - print_verbose(f"no photovoltaics was found for feeder id {feederId}") - else: - for row in cymphotovoltaic_db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["configuration"] = _fixName(row["EquipmentId"]) - return data_dict - - -def _readEqPhotovoltaic(csvdata, feederId): - data_dict = {} - struct = {"name": None, "current": 4.59, "voltage": 17.30, "efficiency": 0.155} - cymeqphotovoltaic_db = _csvToDictList(csvdata["CYMEQPHOTOVOLTAIC"], feederId - ) - if len(cymeqphotovoltaic_db) == 0: - print_verbose(f"no photovoltaic information found for feeder id {feederId}") - else: - for row in cymeqphotovoltaic_db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["current"] = row["MPPCurrent"] - data_dict[eq_id]["voltage"] = row["MPPVoltage"] - return data_dict - - -def _readEqBattery(csvdata, feederId): - data_dict = {} - struct = { - "name": None, - "rated_storage_energy": None, - "max_charging_power": None, - "max_discharging_power": None, - "charge_efficiency": None, - "discharge_efficiency": None, - } - cymeqbattery_db = _csvToDictList(csvdata["CYMEQBESS"], feederId - ) - if len(cymeqbattery_db) == 0: - print_verbose(f"no battery information found for feeder id {feederId}") - else: - for row in cymeqbattery_db: - eq_id = _fixName(row["EquipmentId"]) - if eq_id not in data_dict.keys(): - data_dict[eq_id] = copy.deepcopy(struct) - data_dict[eq_id]["name"] = eq_id - data_dict[eq_id]["rated_storage_energy"] = float( - row["RatedStorageEnergy"] - ) - data_dict[eq_id]["max_charging_power"] = row["MaxChargingPower"] - data_dict[eq_id]["max_discharging_power"] = row["MaxDischargingPower"] - data_dict[eq_id]["round_trip_efficiency"] = ( - float(row["ChargeEfficiency"]) - / 1000 - * float(row["DischargeEfficiency"]) - / 1000 - ) - return data_dict - - -def _readBattery(csvdata, feederId): - data_dict = {} - struct = {"name": None, "configuration": None, "phase": None} - cymbattery_db = _csvToDictList(csvdata["CYMBESS"], feederId - ) - if len(cymbattery_db) == 0: - print_verbose(f"no battery information found for feeder id {feederId}") - else: - for row in cymbattery_db: - device_no = _fixName(row["DeviceNumber"]) - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["configuration"] = row["EquipmentId"] - data_dict[device_no]["phase"] = row["Phase"] - return data_dict - - -def _readGenerator(csvdata, feederId): - data_dict = {} - struct = {"name": None, "generation": None, "power_factor": None} - cymgenerator_db = _csvToDictList(csvdata["CYMDGGENERATIONMODEL"], feederId - ) - if len(cymgenerator_db) == 0: - print_verbose(f"no generator information found for feeder id {feederId}") - else: - for row in cymgenerator_db: - device_no = _fixName(row["DeviceNumber"]) - if row["DeviceType"] == "37": - if device_no not in data_dict.keys(): - data_dict[device_no] = copy.deepcopy(struct) - data_dict[device_no]["name"] = device_no - data_dict[device_no]["generation"] = row["ActiveGeneration"] - data_dict[device_no]["power_factor"] = row["PowerFactor"] - return data_dict - - -def _find_SPCT_rating(load_str): - spot_load = ( - abs(complex(load_str)) / 1000.0 - ) # JOHN FITZGERALD KENNEDY. needs to be in kVA for transformer rating estimation - spct_rating = [ - 5, - 10, - 15, - 25, - 30, - 37.5, - 50, - 75, - 87.5, - 100, - 112.5, - 125, - 137.5, - 150, - 162.5, - 175, - 187.5, - 200, - 225, - 250, - 262.5, - 300, - 337.5, - 400, - 412.5, - 450, - 500, - 750, - 1000, - 1250, - 1500, - 2000, - 2500, - 3000, - 4000, - 5000, - ] - past_rating = max(spct_rating) - for rating in spct_rating: - if spot_load <= rating < past_rating: - past_rating = rating - return str(past_rating) - - -def convertCymeModel(network_db, test=False, _type=1, feeder_id=None): - - # HACK: manual network ID detection. - dbflag = 1 if "OakPass" in str(network_db) else 0 - - # Dictionary that will hold the feeder model for conversion to .glm format - glmTree = {} - - # Initialize our other section dicts - regulator_sections = {} - recloser_sections = {} - sectionalizer_sections = {} - switch_sections = {} - fuse_sections = {} - capacitor_sections = {} - vsc_sections = {} - threewautoxfmr_sections = {} - transformer_sections = {} - overheadline_sections = {} - undergroundline_sections = {} - sx_section = [] - reactor_sections = {} - pv_sections = {} - load_sections = {} - threewxfmr_sections = {} - battery_sections = {} - syncgen_sections = {} - - # Open the network database file - # net_db = _openDatabase(network_db) - - # Dumping csv's to folder - csvdata = _csvDump(network_db) - - # import pdb - # pdb.set_trace() - # feeder_id =_csvToDictList(pJoin(modelDir,'cymeCsvDump',"CYMNETWORK.csv"),columns=['NetworkId']) - feeder_id = _findNetworkId(csvdata["CYMNETWORK"]) - - # -1-CYME CYMSOURCE *** - cymsource, feeder_id, swingBus = _readSource(csvdata, feeder_id, _type) - - # -2-CYME CYMNODE *** - cymnode, x_scale, y_scale = _readNode(csvdata, feeder_id) - - # -3-CYME OVERHEADBYPHASE *** - OH_conductors, cymoverheadbyphase, ohConfigurations, uniqueOhSpacing = _readOverheadByPhase( - csvdata, feeder_id) - - # -4-CYME UNDERGROUNDLINE *** - UG_conductors, cymundergroundline = _readUndergroundLine(csvdata, feeder_id) - - # -5-CYME CYMOVERHEADLINEBALANCED *** - UOLConfigNames, cymUnbalancedOverheadLine = _readOverheadLineUnbalanced( - csvdata, feeder_id) - - # -5-CYME CYMSWITCH*** - cymswitch = _readSwitch(csvdata, feeder_id) - - # -6-CYME CYMSECTIONALIZER*** - cymsectionalizer = _readSectionalizer(csvdata, feeder_id) - - # -7-CYME CYMFUSE*** - cymfuse = _readFuse(csvdata, feeder_id) - - # -8-CYME CYMRECLOSER*** - cymrecloser = _readRecloser(csvdata, feeder_id) - - # -9-CYME CYMREGULATOR*** - cymregulator = _readRegulator(csvdata, feeder_id) - - # -10-CYME CYMSHUNTCAPACITOR*** - cymshuntcapacitor = _readShuntCapacitor(csvdata, feeder_id) - - # -11-CYME CYMCUSTOMERLOAD*** - cymcustomerload = _readCustomerLoad(csvdata, feeder_id) - - # -12-CYME CYMSECTION *** - cymsection = _readSection(csvdata, feeder_id) - for section in cymsection.keys(): - fromNode = cymsection[section]["from"] - toNode = cymsection[section]["to"] - cymsection[section]["fromX"] = ( - cymnode[fromNode]["latitude"] if fromNode in cymnode.keys() else 0 - ) - cymsection[section]["fromY"] = ( - cymnode[fromNode]["longitude"] if fromNode in cymnode.keys() else 800 - ) - cymsection[section]["toX"] = ( - cymnode[toNode]["latitude"] if toNode in cymnode.keys() else 0 - ) - cymsection[section]["toY"] = ( - cymnode[toNode]["longitude"] if toNode in cymnode.keys() else 800 - ) - - # -13-CYME CYMSECTIONDEVICE *** - cymsectiondevice = _readSectionDevice(csvdata, feeder_id) - - # OVERHEAD LINES - cymoverheadline, lineIds = _readOverheadLine(csvdata, feeder_id) - - # OVERHEAD LINE CONFIGS - cymeqoverheadline, spacingIds = _readQOverheadLine(csvdata, feeder_id) - - # PV - cymphotovoltaic = _readPhotovoltaic(csvdata, feeder_id) - - # PV CONFIGS - cymeqphotovoltaic = _readEqPhotovoltaic(csvdata, feeder_id) - - try: - # BATTERY - cymbattery = _readBattery(csvdata, feeder_id) - - # BATTERY CONFIGS - cymeqbattery = _readEqBattery(csvdata, feeder_id) - except: - pass # TODO: better way to handle generator failure. - try: - # GENERATOR - cymgenerator = _readGenerator(csvdata, feeder_id) - except: - pass # TODO: give this a more detailed way to handle generator failure. - # Check that the section actually is a device. - - for link in cymsection.keys(): - link_exists = False - for device in cymsectiondevice.keys(): - if cymsectiondevice[device]["section_name"] == link: - link_exists = True - break - - if not link_exists: - cymsection[link]["connector"] = "" - print_warning(f"missing device associated with section:{link} in {network_db} will be modeled as a switch") - - if "connector" in cymsection[link].keys(): - cymsectiondevice[link] = { - "name": link, - "device_type": 13, - "section_name": link, - "location": 0, - } - cymswitch[link] = { - "name": link, # Information structure for each object found in CYMSWITCH - "equipment_name": None, - "status": 1, - } - del cymsection[link]["connector"] - - # Remove islands from the network database - fromNodes = [] - toNodes = [] - cleanToNodes = [] - for link, section in cymsection.items(): - if "from" in section: - if section["from"] not in fromNodes: - fromNodes.append(section["from"]) - if section["to"] not in toNodes: - toNodes.append(section["to"]) - cleanToNodes.append(section["to"]) - # print(f"\n>>> checking phases for link '{link}'...") - # print(f">>>> section data: {section}") - # print(f">>>> from data: {cymnode[section['from']]}") - # print(f">>>> to data: {cymnode[section['to']]}") - - islandNodes = set() - for node in fromNodes: - if node not in toNodes and node != swingBus: - islandNodes.add(node) - islands = 0 - nislands = len(islandNodes) - while nislands != islands: - islands = len(islandNodes) - for link, section in cymsection.items(): - if "from" in section.keys(): - if section["from"] in islandNodes and section["to"] not in islandNodes: - islandNodes.add(section["to"]) - nislands = len(islandNodes) - - deleteSections = set() - for node in islandNodes: - for link, section in cymsection.items(): - if ( node == section["from"] or node == section["to"] - ) and link not in deleteSections: - deleteSections.add(link) - - # TODO: uncomment this and actually delete orphaned nodes - # for section in deleteSections: - # del cymsection[section] - # for device in cymsectiondevice.keys(): - # if cymsectiondevice[device]['section_name'] in deleteSections: - # del cymsectiondevice[device] - - # Group each type of device. - # unconnected = [] - for device, value in cymsectiondevice.items(): - - value["islink"] = ( "from" in value.keys() and "to" in value.keys() ) - - if value['device_type'] not in [1,2,3] and not device in fromNodes and not device in toNodes: - print_warning(f"device {device} (type {device}) is not properly linked to network, device ignored") - # print(f"{device}: {value}") - # unconnected.append(device) - continue - - dType = value["device_type"] - sName = value["section_name"] - - if dType == 1: - undergroundline_sections[sName] = device - elif dType == 3 or dType == 2: - overheadline_sections[sName] = device - elif dType == 4: - regulator_sections[sName] = device - elif dType == 10: - recloser_sections[sName] = device - elif dType == 12: - sectionalizer_sections[sName] = device - elif dType == 13: - if sName not in switch_sections.keys(): - switch_sections[sName] = [ - device - ] # JOHN FITZGERALD KENNEDY. could use default dict to make this cleaner - else: - switch_sections[sName].append(device) - # switch_sections[value['section_name']] = key #sometimes have two switches on a section! this overwrite the first! - elif dType == 14: - fuse_sections[sName] = device - elif dType == 16: - # sx_section.append(value['section_name']) #this was not needed for PECO files - reactor_sections[sName] = device - elif dType == 17: - capacitor_sections[sName] = device - elif dType == 20: - load_sections[sName] = device - elif dType == 37: - syncgen_sections[sName] = device - elif dType == 45: - if sName not in pv_sections.devices(): - pv_sections[sName] = [device] # JOHN FITZGERALD KENNEDY - else: - pv_sections[sName].append(device) - elif ( - dType == 47 or dType == 5 - ): # JOHN FITZGERALD KENNEDY. added check for 5, another transformer device - transformer_sections[sName] = device - elif dType == 48: - if dbflag == 0: - threewautoxfmr_sections[sName] = device - elif dbflag == 1: - threewxfmr_sections[sName] = device - elif dType == 80: - battery_sections[sName] = device - else: - print_warning(f"device {dtype} is ignored") - - # find the parent of capacitors, loads, and pv - for x in [ capacitor_sections, - load_sections, - pv_sections, - syncgen_sections, - battery_sections, - ]: - if len(x) > 0: - _findParents(cymsection, cymsectiondevice, x) - - # split out fuses, regulators, transformers, switches, reclosers, and sectionalizers from the lines. - # MICHAEL JACKSON debug: check these phases - for x in [ fuse_sections, - regulator_sections, - threewxfmr_sections, - threewautoxfmr_sections, - transformer_sections, - switch_sections, - recloser_sections, - sectionalizer_sections, - reactor_sections, - ]: - if len(x) > 0: - _splitLinkObjects( - cymsection, - cymsectiondevice, - x, - overheadline_sections, - undergroundline_sections, - ) - - # -14-CYME CYMTRANSFORMER*** - cymxfmr = _readTransformer(csvdata, feeder_id) - - # -15-CYME CYMTHREEWINDINGTRANSFORMER*** - cym3wxfmr = _readThreeWindingTransformer(csvdata, feeder_id) - - # -16-CYME CYMEQCONDUCTOR*** - cymeqconductor = _readEqConductor(csvdata, feeder_id) - - # -17-CYME CYMEQCONDUCTOR*** - cymeqoverheadlineunbalanced = _readEqOverheadLineUnbalanced(csvdata, feeder_id) - - # -17-CYME CYMEQGEOMETRICALARRANGEMENT*** - if dbflag == 0: - cymeqgeometricalarrangement = _readEqGeometricalArrangement(csvdata, feeder_id) - elif dbflag == 1: - cymeqgeometricalarrangement = _readEqAvgGeometricalArrangement( - csvdata, feeder_id - ) - - # -18-CYME convertCymeModelXLSX Sheet*** - cymcsvundergroundcable = _readUgConfiguration(csvdata, feeder_id) - - # -19-CYME CYMEQREGULATOR*** - cymeqregulator = _readEqRegulator(csvdata, feeder_id) - - # -20-CYME CYMEQTHREEWINDAUTOTRANSFORMER*** - cymeq3wautoxfmr = _readEqThreeWAutoXfmr(csvdata, feeder_id) - - # -21-CYME CYMEQAUTOTRANSFORMER*** - cymeqautoxfmr = _readEqAutoXfmr(csvdata, feeder_id) - - # -22-CYME CYME REACTORS*** - cymreactor, reactorIds = _readReactors(csvdata, feeder_id) - - # -23-CYME CYMEQREACTORS*** - cymeqreactor = _readEqReactors(csvdata, feeder_id) - - # -24-CYME CYMEQTRANSFORMER*** - cymeqxfmr = _readEqXfmr(csvdata, feeder_id) - - # Check number of sources - meters = {} - if len(cymsource) > 1: - print_warning(f"more than one swing bus for feeder_id {feeder_id}") - for x in cymsource.keys(): - meters[x] = { - "object": "meter", - "name": "{:s}".format(cymsource[x]["name"]), - # 'bustype' : 'SWING', - "nominal_voltage": cymsource[x]["nominal_voltage"], - "latitude": cymnode[x]["latitude"], - "longitude": cymnode[x]["longitude"], - } - feeder_VLN = cymsource[x]["nominal_voltage"] - - # Check for parallel links and islands - fromTo = [] - fromNodes = [] - toNodes = [] - parallelLinks = [] - for link in cymsection.keys(): - if "from" in cymsection[link].keys() and "to" in cymsection[link].keys(): - if {cymsection[link]["from"], cymsection[link]["to"]} in fromTo: - for key, value in cymsectiondevice.items(): - if value["section_name"] == link: - parallelLinks.append(key) - break - else: - fromTo.append({cymsection[link]["from"], cymsection[link]["to"]}) - if cymsection[link]["from"] not in fromNodes: - fromNodes.append(cymsection[link]["from"]) - if cymsection[link]["to"] not in toNodes: - toNodes.append(cymsection[link]["to"]) - # islandNodes = [] - # for node in fromNodes: - # if node not in toNodes and node != swingBus and node not in islandNodes: - # islandNodes.append(node) - # for node in islandNodes: - # if node != swingBus: - # print "Feeder islanded\n" - # Pass from, to, and phase information from cymsection to cymsectiondevice - nodes = {} - for key, value in cymsectiondevice.items(): - sName = value["section_name"] - - value["fromLatitude"] = cymsection[sName]["fromX"] - value["fromLongitude"] = cymsection[sName]["fromY"] - value["toLatitude"] = cymsection[sName]["toX"] - value["toLongitude"] = cymsection[sName]["toY"] - - if "parent" not in value.keys(): - value["from"] = cymsection[sName]["from"] - value["to"] = cymsection[sName]["to"] - value["phases"] = cymsection[sName]["phases"] - - # Create all the node dictionaries - for a in ("from", "to"): - if value[a] not in nodes.keys() and value[a] != swingBus: - nodes[value[a]] = { - "object": "node", - "name": value[a], - "phases": value["phases"], - "nominal_voltage": str(feeder_VLN), - "latitude": value[a + "Latitude"], - "longitude": value[a + "Longitude"], - } - else: - if value["parent"] not in nodes.keys() and value["parent"] != swingBus: - nodes[value["parent"]] = { - "object": "node", - "name": value["parent"], - "phases": value["phases"], - "nominal_voltage": str(feeder_VLN), - } - if value["location"] == 2: - nodes[value["parent"]]["latitude"] = value["toLatitude"] - nodes[value["parent"]]["longitude"] = value["toLongitude"] - else: - nodes[value["parent"]]["latitude"] = value["fromLatitude"] - nodes[value["parent"]]["longitude"] = value["fromLongitude"] - - # Create overhead line conductor dictionaries - ohl_conds = {} - for src in (OH_conductors, cymeqconductor): - for olc in src: - if olc in cymeqconductor: - if olc in ohl_conds: - continue - ohl_conds[olc] = { - "object": "overhead_line_conductor", - "name": olc, - "resistance": "{:0.6f}".format(cymeqconductor[olc]["resistance"]), - "geometric_mean_radius": "{:0.6f}".format( - cymeqconductor[olc]["geometric_mean_radius"] - ), - } - else: - print_warning(f"no conductor spec for {olc} in the equipment database provided") - - ohl_configs = {} - for ohlc in cymeqoverheadline: - if ohlc in lineIds: - if ohlc not in ohl_configs.keys(): - ohl_configs[ohlc] = { - "object": "line_configuration", - "name": ohlc + "conf", - "spacing": cymeqoverheadline[ohlc]["spacing"] - + "ohsps", # uhhh? is this meant to be like this - "conductor_A": cymeqoverheadline[ohlc]["configuration"], - "conductor_B": cymeqoverheadline[ohlc]["configuration"], - "conductor_C": cymeqoverheadline[ohlc]["configuration"], - "conductor_N": cymeqoverheadline[ohlc]["conductor_N"], - } - - ohl_spcs = {} - - # Create overhead line spacing dictionaries - for src in (uniqueOhSpacing, spacingIds): - for ols in uniqueOhSpacing: - if ols in cymeqgeometricalarrangement.keys(): - if ols in ohl_spcs: - continue - - ohl_spcs[ols] = {"object": "line_spacing", "name": ols} - - # if we are iterating over spacingIds, we add "ohsps" - if src is spacingIds: - ohl_spcs[ols]["name"] += "ohsps" - - for pp in ("AB", "AC", "AN", "BC", "BN", "CN"): - ohl_spcs[ols]["distance_" + pp] = "{:0.6f}".format( - cymeqgeometricalarrangement[ols]["distance_" + pp] - ) - else: - print_warning(f"no line spacing spec for {ols} in the equipment database provided") - - # Create overhead line configuration dictionaries - ohl_cfgs = {} - ohl_neutral = [] - for ohl_cfg in ohConfigurations: - if ohl_cfg not in ohl_cfgs.keys(): - ohl_cfgs[ohl_cfg] = copy.deepcopy(ohConfigurations[ohl_cfg]) - ohl_cfgs[ohl_cfg]["name"] = ohl_cfg - ohl_cfgs[ohl_cfg]["object"] = "line_configuration" - if "conductor_N" in ohl_cfgs[ohl_cfg].keys(): - ohl_neutral.append(ohl_cfg) - - for ohl_cfg in UOLConfigNames: - if ohl_cfg in cymeqoverheadlineunbalanced.keys(): - if ohl_cfg not in ohl_cfgs.keys(): - ohl_cfgs[ohl_cfg] = copy.deepcopy(cymeqoverheadlineunbalanced[ohl_cfg]) - else: - print_warning(f"no overhead line configuration for {ohl_cfg} in the equipment database provided") - - def split_parallel(target_dict, line_key, struct, nodes): - # if a line is a parallel link, split it in two and add a parNode - # struct contains all of the parameters of the line prior to being split - if line_key not in parallelLinks: - target_dict[line_key] = struct - else: - target_dict[line_key + "par1"] = struct.copy() - target_dict[line_key + "par1"]["name"] += "par1" - target_dict[line_key + "par1"]["to"] = line_key + "parNode" - target_dict[line_key + "par1"]["length"] = "{:0.6f}".format( - float(struct["length"]) / 2 - ) - - target_dict[line_key + "par2"] = struct.copy() - target_dict[line_key + "par2"]["name"] += "par2" - target_dict[line_key + "par2"]["from"] = line_key + "parNode" - target_dict[line_key + "par2"]["length"] = "{:0.6f}".format( - float(struct["length"]) / 2 - ) - nodes[line_key + "parNode"] = { - "object": "node", - "name": line_key + "parNode", - "phases": cymsectiondevice[line_key]["phases"], - "nominal_voltage": str(feeder_VLN), - "latitude": str( - ( - float(cymsectiondevice[line_key]["fromLatitude"]) - + float(cymsectiondevice[line_key]["toLatitude"]) - ) - / 2.0 - ), - "longitude": str( - ( - float(cymsectiondevice[line_key]["fromLongitude"]) - + float(cymsectiondevice[line_key]["toLongitude"]) - ) - / 2.0 - ), - } - - # Create underground line conductor, and spacing dictionaries - ugl_conds = {} - ugl_sps = {} - for ulc in UG_conductors: - if ( - ulc in cymcsvundergroundcable.keys() - and ulc + "cond" not in ugl_conds.keys() - ): - cable_dict = cymcsvundergroundcable[ulc] - - ugl_conds[ulc + "cond"] = { - "object": "underground_line_conductor", - "name": ulc + "cond", - } - - to_copy = [ - "conductor_resistance", - "neutral_gmr", - "outer_diameter", - "neutral_strands", - "neutral_resistance", - "neutral_diameter", - "conductor_diameter", - "conductor_gmr", - ] - for field in to_copy: - ugl_conds[ulc + "cond"][field] = cable_dict[field] - - if ulc + "sps" not in ugl_sps.keys(): - ugl_sps[ulc + "sps"] = { - "object": "line_spacing", - "name": ulc + "sps", - "distance_AB": cable_dict["distance_AB"], - "distance_AC": cable_dict["distance_AC"], - "distance_BC": cable_dict["distance_BC"], - } - else: - print_warning(f"missing configuration spec for {ulc} in the underground csv file") - - # We are going to loop over cymsectiondevice and populate these dictionaries with their respective devices - # Names were not changed, but maybe they should be? - ohls = {} - ugl_cfgs = {} - ugls = {} - swObjs = {} - rcls = {} - sxnlrs = {} - fuses = {} - reactors = {} - caps = {} - loads = {} - spct_cfgs = {} - spcts = {} - tpns = {} - tpms = {} - loadNames = [] - reg_cfgs = {} - regs = {} - pv_sec = {} - bat_sec = {} - gen_secs = {} - xfmr_cfgs = {} - xfmrs = {} - - # print(f"sections: {cymsection.keys()}") - # print(f"devices: {cymsectiondevice.keys()}") - - for dev_key, dev_dict in cymsectiondevice.items(): - - # if "from" in dev_dict.keys(): - # from_ok = dev_dict["from"] in cymsection.keys() - # if "to" in dev_dict.keys(): - # to_ok = dev_dict["to"] in cymsection.keys() - # connected_ok = from_ok and to_ok - # print(f"====================\ndev_key = {dev_key}, from_ok = {from_ok}, to_ok = {to_ok}, connected_ok = {connected_ok}") - # print(json.dumps(dev_dict,indent=4)) - - if dev_dict["device_type"] == 3: - if dev_key not in cymoverheadbyphase.keys(): - print_warning(f"no line spec for {dev_key} in the network database provided") - elif dev_key not in ohls.keys(): - struct = { - "object": "overhead_line", - "name": dev_key, - "phases": dev_dict["phases"], - "from": dev_dict["from"], - "to": dev_dict["to"], - "length": "{:0.6f}".format(cymoverheadbyphase[dev_key]["length"]), - "configuration": cymoverheadbyphase[dev_key]["configuration"], - } - split_parallel(ohls, dev_key, struct, nodes) - - elif dev_dict["device_type"] == 2: - if dev_key not in cymoverheadline.keys(): - print_warning(f"no line spec for {dev_key} in the network database provided") - elif dev_key not in ohls.keys(): - if dev_key not in parallelLinks: - ohls[dev_key] = { - "object": "overhead_line", - "name": dev_key, - "phases": dev_dict["phases"], - "from": dev_dict["from"], - "to": dev_dict["to"], - "length": "{:0.6f}".format(cymoverheadline[dev_key]["length"]), - "configuration": cymoverheadline[dev_key]["configuration"] - + "conf", - } - - elif dev_dict["device_type"] == 23: - # very similar to device 3 - if dev_key not in cymUnbalancedOverheadLine.keys(): - print_warning(f"no line spec for {oh1} in the network database provided") - elif dev_key not in ohls.keys(): - struct = { - "object": "overhead_line", - "name": dev_key, - "phases": dev_dict["phases"], - "from": dev_dict["from"], - "to": dev_dict["to"], - "length": "{:0.6f}".format( - cymUnbalancedOverheadLine[dev_key]["length"] - ), - "configuration": cymUnbalancedOverheadLine[dev_key][ - "configuration" - ], - } - split_parallel(ohls, dev_key, struct, nodes) - - # Creat Underground line configuration, and link objects. - elif dev_dict["device_type"] == 1: - ph = dev_dict["phases"] - if dev_key not in cymundergroundline.keys(): - print_warning(f"no line spec for {dev_key} in the network database provided") - else: - ph = _cleanPhases(ph) - config_name = cymundergroundline[dev_key]["cable_id"] + "ph" + ph - if config_name not in ugl_cfgs.keys(): - ref_dict = cymundergroundline[dev_key] - cable_dict = cymcsvundergroundcable[ref_dict["cable_id"]] - - ugl_cfgs[config_name] = { - "object": "line_configuration", - "name": config_name, - "spacing": ref_dict["cable_id"] + "sps", - "z11": cable_dict["z11"], - "z12": cable_dict["z12"], - "z13": cable_dict["z13"], - "z21": cable_dict["z21"], - "z22": cable_dict["z22"], - "z23": cable_dict["z23"], - "z31": cable_dict["z31"], - "z32": cable_dict["z32"], - "z33": cable_dict["z33"], - } - for p in ph: - ugl_cfgs[config_name]["conductor_" + p] = ( - ref_dict["cable_id"] + "cond" - ) - - if dev_key not in ugls.keys(): - struct = { - "object": "underground_line", - "name": dev_key, - "phases": dev_dict["phases"], - "from": dev_dict["from"], - "to": dev_dict["to"], - "length": "{:0.6f}".format(ref_dict["length"]), - "configuration": config_name, - } - split_parallel(ugls, dev_key, struct, node) - - # Create switch dictionaries - gableid = ref_dict["cable_id"] - elif dev_dict["device_type"] == 13: - if dev_key not in cymswitch.keys(): - print_warning(f"no switch spec for {dev_key} in the network database provided") - elif dev_key not in swObjs.keys(): - swObjs[dev_key] = { - "object": "switch", - "name": dev_key, - "phases": dev_dict["phases"].replace("N", ""), - "from": dev_dict["from"], - "to": dev_dict["to"], - "operating_mode": "BANKED", - } - if cymswitch[dev_key]["status"] == 0: - status = "OPEN" - # JOHN FITZGERALD KENNEDY. This was CLOSED. Must have been a typo? - else: - status = "CLOSED" - for phase in swObjs[dev_key]["phases"]: - swObjs[dev_key]["phase_{:s}_state".format(phase)] = status - - # Create recloser dictionaries - elif dev_dict["device_type"] == 10: - if dev_key not in cymrecloser.keys(): - print_warning(f"no recloster spec for {rc1} in the network database provided.") - elif dev_key not in rcls.keys(): - rcls[dev_key] = { - "object": "recloser", - "name": dev_key, - "phases": dev_dict["phases"].replace("N", ""), - "from": dev_dict["from"], - "to": dev_dict["to"], - "operating_mode": "BANKED", - } - if cymrecloser[dev_key]["status"] == 0: - status = "OPEN" - # was 'CLOSED' #JOHN FITZGERALD KENNEDY. Mistake seemed intentional. Maybe it was just a typo? - else: - status = "CLOSED" - for phase in rcls[dev_key]["phases"]: - rcls[dev_key]["phase_{:s}_state".format(phase)] = status - - # Create sectionalizer dictionaries - elif dev_dict["device_type"] == 12: - if dev_key not in cymsectionalizer.keys(): - print_warning(f"no sectionalizer spec for {dev_key} in the network database provided") - elif dev_key not in sxnlrs.keys(): - sxnlrs[dev_key] = { - "object": "sectionalizer", - "name": dev_key, - "phases": dev_dict["phases"].replace("N", ""), - "from": dev_dict["from"], - "to": dev_dict["to"], - "operating_mode": "BANKED", - } - if cymsectionalizer[dev_key]["status"] == 0: - status = "OPEN" # 'CLOSED' #JOHN FITZGERALD KENNEDY - else: - status = "CLOSED" - for phase in sxnlrs[dev_key]["phases"]: - sxnlrs[dev_key]["phase_{:s}_state".format(phase)] = status - - # Create fuse dictionaries - elif dev_dict["device_type"] == 14: - if dev_key not in cymfuse.keys(): - print_warning(f"no fuse spec for {dev_key} in the network database provided") - elif dev_key not in fuses.keys(): - fuses[dev_key] = { - "object": "fuse", - "name": dev_key, - "phases": dev_dict["phases"].replace("N", ""), - "from": dev_dict["from"], - "to": dev_dict["to"], - "repair_dist_type": "EXPONENTIAL", - "mean_replacement_time": "3600", - "current_limit": "9999", - } - if cymfuse[dev_key]["status"] == 0: - status = "BLOWN" - else: - status = "GOOD" - for phase in fuses[dev_key]["phases"]: - fuses[dev_key]["phase_{:s}_status".format(phase)] = status - - # JOHN FITZGERALD KENNEDY. added all this reactor code - elif dev_dict["device_type"] == 16: - if dev_key not in cymreactor.keys(): - print_warning(f"no reactor spec for {dev_key} in the network database provice") - elif dev_key not in reactors.keys(): - reactors[dev_key] = { - "object": "series_reactor", - "name": dev_key, - "phases": dev_dict["phases"].replace("N", ""), - "from": dev_dict["from"], - "to": dev_dict["to"], - } - equipmentId = cymreactor[dev_key]["configuration"] - Zohms = float(cymeqdev_key[equipmentId]["reactance"]) - for ph in reactors[dev_key]["phases"]: - reactors[dev_key]["phase_" + ph + "_reactance"] = "{:0.6f}".format( - Zohms - ) - - # Create capacitor dictionaries - elif dev_dict["device_type"] == 17: - if dev_key not in cymshuntcapacitor.keys(): - print_warning(f"no capacitor spec for {dev_key} in the network database provided") - elif dev_key not in caps.keys(): - # a temporary variable to shorten some of these long lookups - ref_dict = cymshuntcapacitor[dev_key] - caps[dev_key] = { - "object": "capacitor", - "name": dev_key, - "phases": dev_dict["phases"], - "phases_connected": dev_dict["phases"], # JOHN FITZGERALD KENNEDY - "parent": dev_dict["parent"], - # 'control_level' : 'INDIVIDUAL', #JOHN FITZGERALD KENNEDY - "control": ref_dict["control"], #'MANUAL', - # 'cap_nominal_voltage' : str(feeder_VLN), - "nominal_voltage": ref_dict["kV_line_neutral"], - "time_delay": "2", - "dwell_time": "3", - "latitude": str( - float(nodes[dev_dict["parent"]]["latitude"]) - + random.uniform(-5, 5) - ), - "longitude": str( - float(nodes[dev_dict["parent"]]["longitude"]) - + random.uniform(-5, 5) - ), - } - - # This needs to be expanded for other control types too. - if caps[dev_key]["control"] == "VOLT": - caps[dev_key]["remote_sense"] = "n" + str(ref_dict["remote_sense"]) - # JOHN FITZGERALD KENNEDY. hacky. have to add 'n' because it's added later to nodes. - caps[dev_key]["voltage_set_high"] = str( - ref_dict["voltage_set_high"] * (1 / 120.0) * float(feeder_VLN) - ) - caps[dev_key]["voltage_set_low"] = str( - ref_dict["voltage_set_low"] * (1 / 120.0) * float(feeder_VLN) - ) - caps[dev_key]["pt_phase"] = ref_dict["pt_phase"] - caps[dev_key]["control_level"] = ref_dict["control_level"] - for phase in caps[dev_key]["phases"]: - if phase not in ["N", "D"]: - caps[dev_key]["capacitor_" + phase] = str( - ref_dict["capacitor_" + phase] - ) - - if ref_dict["status"] == "1": - status = "OPEN" - else: - status = "CLOSED" - for phase in caps[dev_key]["phases"]: - if phase not in ["N", "D"]: - caps[dev_key]["switch" + phase] = status - caps[dev_key]["capacitor_" + phase] = str( - ref_dict["capacitor_" + phase] - ) - - # Create load dictionaries - elif dev_dict["device_type"] == 20: - if dev_key not in cymcustomerload.keys(): - print_warning(f"no load spec for {dev_key} in the network database provided") - continue - - ref_dict = cymcustomerload[dev_key] - if dev_key not in loads.keys() and ref_dict["load_class"] == "commercial": - loads[dev_key] = { - "object": "load", - "name": dev_key, - "phases": dev_dict["phases"], - "parent": dev_dict["parent"], - "nominal_votlage": str(feeder_VLN), - "load_class": "C", - } - for phase in loads[dev_key]["phases"]: - if phase not in ["N", "D"]: - loads[dev_key]["constant_power_" + phase] = ref_dict[ - "constant_power_" + phase - ] - elif dev_key not in tpns.keys() and dev_dict["name"] not in loadNames: - loadNames.append(dev_dict["name"]) - - for phase in ref_dict["phases"]: # JOHN FITZGERALD KENNEDY - if phase in ["N", "D"]: - continue - - if "constant_power_" + phase not in ref_dict.keys(): - ref_dict["constant_power_" + phase] = ref_dict[ - "constant_power_A" - ] - spctRating = _find_SPCT_rating( - str(ref_dict["constant_power_" + phase]) - ) - - spct_cfg_name = "SPCTconfig{:s}{:s}".format(dev_key, phase) - spct_name = "SPCT{:s}{:s}".format(dev_key, phase) - tpm_name = "tpm{:s}{:s}".format(dev_key, phase) - tpn_name = "tpn{:s}{:s}".format(dev_key, phase) - - spct_cfgs[spct_cfg_name] = { - "object": "transformer_configuration", - "name": spct_cfg_name, - "connect_type": "SINGLE_PHASE_CENTER_TAPPED", - "install_type": "POLETOP", - "primary_voltage": str(feeder_VLN), - "secondary_voltage": "120", - "power_rating": spctRating, - "power{:s}_rating".format(phase): spctRating, - "impedance": "0.00033+0.0022j", - } - - spcts[spct_name] = { - "object": "transformer", - "name": spct_name, - "phases": "{:s}S".format(phase), - "from": dev_dict["parent"], - "to": tpm_name, - "configuration": spct_cfg_name, - } - - tpms[tpm_name] = { - "object": "triplex_meter", - "name": tpm_name, - "phases": "{:s}S".format(phase), - "nominal_voltage": "120", - "latitude": str( - float(nodes[dev_dict["parent"]]["latitude"]) - + random.uniform(-5, 5) - ), - "longitude": str( - float(nodes[dev_dict["parent"]]["longitude"]) - + random.uniform(-5, 5) - ), - } - - tpns[tpn_name] = { - "object": "triplex_node", - "name": tpn_name, - "phases": "{:s}S".format(phase), - "nominal_voltage": "120", - "parent": tpm_name, - "power_12": ref_dict["constant_power_" + phase], - "latitude": str( - float(tpms[tpm_name]["latitude"]) + random.uniform(-5, 5) - ), - "longitude": str( - float(tpms[tpm_name]["longitude"]) + random.uniform(-5, 5) - ), - } - - # Create regulator dictionaries - elif dev_dict["device_type"] == 4: - if dev_key not in cymregulator.keys(): - print_warning(f"no regulator spec for {dev_key} in the network database provided") - else: - # NOTE: by the way we construct cymregulator, this should be the same as dev_key (the equipmentId) - regEq = cymregulator[dev_key]["equipment_name"] - ref_dict = cymeqregulator[regEq] - - raiseTaps = ref_dict.get("raise_taps", "16") - lowerTaps = ref_dict.get("lower_taps", "16") - reg_nominalvoltage = float(ref_dict["nominal_voltage"]) * 1000.0 - - # HACK: bandwidth sometimes set to none (likely bc it is not being read properly in _readCymRegulator) - # HACK: just choose 10% of nominal. Good idea? TBD. - safeRegBand = float( - ref_dict["bandwidth"] - if ref_dict["bandwidth"] - else 0.10 * reg_nominalvoltage - ) - reg_bandwidth = str(safeRegBand * reg_nominalvoltage / 120.0) - - # JOHN FITZGERALD KENNEDY. Need to have separate regulator configurations for each regulator - # Cyme holds tap position in regulator, but Gridlabd holds tap position in configuration - # NOTE: this seems incorrect. as the above note mentions, regEq seems to be the same as dev_key - regEq = regEq + "_" + dev_key - - print_warning(f"missing bandcenter info is set to 1.05.") - band_center120 = 126.0 - - print_warning("regulators set to OUTPUT_VOLTAGE") - - ph = dev_dict["phases"].replace("N", "") - if regEq not in reg_cfgs.keys(): - reg_cfgs[regEq] = { - "object": "regulator_configuration", - "name": regEq, # JOHN FITZGERALD KENNEDY - "connect_type": "WYE_WYE", - "band_center": str( - float(reg_nominalvoltage) * (band_center120 / 120.0) - ), - "band_width": reg_bandwidth, - "regulation": str(cymregulator[dev_key]["regulation"]), - "time_delay": "30.0", - "dwell_time": "5", - "Control": "OUTPUT_VOLTAGE", #'MANUAL' # - "control_level": "INDIVIDUAL", - "raise_taps": raiseTaps, - "lower_taps": lowerTaps, - } - for phase in ph: - reg_cfgs[regEq]["tap_pos_" + phase] = str( - cymregulator[dev_key]["tap_pos_" + phase] - ) - if dev_key not in reg_cfgs.keys(): - regs[dev_key] = { - "object": "regulator", - "name": dev_key, - "phases": ph, - "from": dev_dict["from"], - "to": dev_dict["to"], - "configuration": regEq, - } # JOHN FITZGERALD KENNEDY - - # Create photovoltaic, inverter, and meter dictionaries - elif dev_dict["device_type"] == 45: - if dev_key not in cymphotovoltaic.keys(): - print_warning(f"no PV spec for {dev_key} in the network database provided") - else: - config = cymeqphotovoltaic[cymphotovoltaic[dev_key]["configuration"]] - pv_sec[dev_key + "meter"] = { - "object": "meter", - "name": dev_key + "meter", - "parent": dev_dict["parent"], - "latitude": dev_dict["toLatitude"], - "longitude": dev_dict["toLongitude"], - } - pv_sec[dev_key + "inv"] = { - "object": "inverter", - "name": "n" + dev_key + "inv", - "parent": dev_key + "meter", - "latitude": dev_dict["toLatitude"], - "longitude": dev_dict["toLongitude"], - } - pv_sec[dev_key] = { - "object": "solar", - "name": dev_key, - "efficiency": config["efficiency"], - "area": 1000 - * 0.075 - * float(config["voltage"]) - * float(config["current"]), - "parent": dev_key + "inv", - "latitude": dev_dict["toLatitude"], - "longitude": dev_dict["toLongitude"], - } - - # Create battery dictionaries - elif dev_dict["device_type"] == 80: - if dev_key not in cymbattery.keys(): - print_warning(f"no battery spec for {dev_key} in the network database provided") - else: - config = cymeqbattery[cymbattery[dev_key]["configuration"]] - bat_sec[dev_dict["section_name"]] = { - "object": "meter", - "name": dev_dict["section_name"], - "parent": dev_dict["parent"], - } - bat_sec[dev_key + "inv"] = { - "object": "inverter", - "name": "n" + dev_key + "inv", - "generator_mode": "CONSTANT_PQ", - "parent": dev_dict["section_name"], - "phases": "BS", - "four_quadrant_control_mode": "LOAD_FOLLOWING", - "generator_status": "ONLINE", - "inverter_type": "FOUR_QUADRANT", - "discharge_off_threshold": 7454, - "rated_power": config["rated_storage_energy"], - "charge_off_threshold": 6148, - "max_charge_rate": config["max_charging_power"], - "max_discharge_rate": config["max_discharging_power"], - "discharge_lockout_time": 60, - "charge_lockout_time": 60, - "inverter_efficiency": config["round_trip_efficiency"], - } - bat_sec[dev_key] = { - "object": "battery", - "name": dev_key, - "state_of_charge": 1.0, - "parent": dev_key + "inv", - "latitude": dev_dict["toLatitude"], - "longitude": dev_dict["toLongitude"], - "round_trip_efficiency": config["round_trip_efficiency"], - "generator_mode": "SUPPLY_DRIVEN", - "generator_status": "ONLINE", - "battery_state": 1.0, - "battery_capacity": config["rated_storage_energy"], - "battery_type": "LI_ION", - "use_internal_battery_model": "TRUE", - } - - # Create generator dictionaries - elif dev_dict["device_type"] == 37: - if dev_key not in cymgenerator.keys(): - print_warning(f"no generator spec for {dev_key} in the network database provided") - else: - gen_secs[dev_key] = { - "object": "diesel_dg", - "name": dev_key, - "parent": dev_dict["parent"], - "Gen_type": 2, - "Gen_mode": 1, - "TotalRealPow": cymgenerator[dev_key]["generation"], - "pf": cymgenerator[dev_key]["power_factor"], - } - - # Create transformer and transformer configuration dictionaries - elif dev_dict["device_type"] in [47, 5, 48]: - # Selecting which cymeq dict and cym dict to get data from - if dev_dict["device_type"] == 47: - cymeq_dict = cymeqautoxfmr - threeway = False - elif dev_dict["device_type"] == 5: - cymeq_dict = cymeqxfmr - threeway = False - elif dev_dict["device_type"] == 48: - cymeq_dict = cymeq3wautoxfmr - threeway = True - - cym_dict = cym3wxfmr if threeway else cymxfmr - - if dev_key not in cym_dict.keys(): - print_warning(f"no xmfr spec for {dev_key} in the network database provided") - else: - xfmrEq = cym_dict[dev_key]["equipment_name"] - if xfmrEq == dev_key: - suffix = "cfg" - else: - suffix = "" - - ph = dev_dict["phases"] - phNum = len(_cleanPhases(ph)) - - if xfmrEq not in cymeq_dict.keys(): - print_warning(f"no xmfr spec for ", xfmrEq, " in the network database provided") - else: - if xfmrEq not in xfmr_cfgs.keys(): - xfmr_cfgs[xfmrEq] = { - "object": "transformer_configuration", - "name": xfmrEq + suffix, - "connect_type": "WYE_WYE", - "primary_voltage": (cymeq_dict[xfmrEq]["PrimaryVoltage"]), - "secondary_voltage": ( - cymeq_dict[xfmrEq]["SecondaryVoltage"] - ), - "impedance": cymeq_dict[xfmrEq]["impedance"], - "power_rating": "{:0.0f}".format( - cymeq_dict[xfmrEq]["PrimaryRatedCapacity"] - ), - } - - if threeway: - xfmr_cfgs[xfmrEq]["primary_voltage"] = "{:0.6f}".format( - cymeq_dict[xfmrEq]["PrimaryVoltage"] - ) - xfmr_cfgs[xfmrEq]["secondary_voltage"] = "{:0.6f}".format( - cymeq_dict[xfmrEq]["SecondaryVoltage"] - ) - else: - xfmr_cfgs[xfmrEq]["primary_voltage"] = "{:0.6f}".format( - cymeq_dict[xfmrEq]["PrimaryVoltage"] * math.sqrt(3) - ) - xfmr_cfgs[xfmrEq]["secondary_voltage"] = "{:0.6f}".format( - cymeq_dict[xfmrEq]["SecondaryVoltage"] * math.sqrt(3) - ) - - for phase in ph: - xfmr_cfgs[xfmrEq][ - "power{:s}_rating".format(phase) - ] = "{:0.6f}".format( - cymeq_dict[xfmrEq]["PrimaryRatedCapacity"] / phNum - ) - - if dev_key not in xfmrs.keys(): - xfmrs[dev_key] = { - "object": "transformer", - "name": dev_key, - "phases": ph, - "from": dev_dict["from"], - "to": dev_dict["to"], - "configuration": xfmrEq + suffix, - } - - # Add dictionaries to feeder tree object - # JOHN FITZGERALD KENNEDY. giving an hour for everything to settle down. needed for regulators and verification - genericHeaders = [ - {"omftype": "#set", "argument": "relax_naming_rules=TRUE"}, - {"omftype": "module", "argument": "generators"}, - {"solver_method": "NR", "module": "powerflow"}, - ] - for headId in range(len(genericHeaders)): - glmTree[headId] = genericHeaders[headId] - key = len(glmTree) - objectList = [ - ohl_conds, - ugl_conds, - ohl_spcs, - ohl_configs, - ugl_sps, - ohl_cfgs, - ugl_cfgs, - xfmr_cfgs, - spct_cfgs, - reg_cfgs, - meters, - nodes, - loads, - tpms, - tpns, - ohls, - ugls, - xfmrs, - spcts, - regs, - swObjs, - rcls, - sxnlrs, - fuses, - caps, - bat_sec, - pv_sec, - gen_secs, - reactors, - ] - for objDict in objectList: - if len(objDict) > 0: - for obj in objDict.keys(): - glmTree[key] = copy.deepcopy(objDict[obj]) - key = len(glmTree) - - # Find and fix duplicate names between nodes and links - for x in glmTree.keys(): - if "object" in glmTree[x].keys() and glmTree[x]["object"] in [ - "node", - "meter", - "triplex_meter", - "triplex_node", - ]: - glmTree[x]["name"] = "n" + glmTree[x]["name"] - if "from" in glmTree[x].keys(): - glmTree[x]["from"] = "n" + glmTree[x]["from"] - glmTree[x]["to"] = "n" + glmTree[x]["to"] - if "parent" in glmTree[x].keys(): - glmTree[x]["parent"] = "n" + glmTree[x]["parent"] - # FINISHED CONVERSION FROM THE DATABASES**************************************************************************************************************************************************** - # Deletign malformed lniks - for key in glmTree.keys(): - if ( - "object" in glmTree[key].keys() - and glmTree[key]["object"] - in [ - "overhead_line", - "underground_line", - "regulator", - "transformer", - "switch", - "fuse", - "series_reactor", - ] - and ("to" not in glmTree[key].keys() or "from" not in glmTree[key].keys()) - ): - del glmTree[key] - - # Create list of all from and to node names - LinkedNodes = {} - toNodes = [] - fromNodes = [] - for key in glmTree.keys(): - # JOHN FITZGERALD KENNEDY. dont want phase information to be passed on by open switches - # I have scenarios like: phaseC -/ - phaseB - if glmTree[key].get("object", "") == "switch": - if "OPEN" in glmTree[key].values(): - continue - - if "to" in glmTree[key].keys(): - ph = LinkedNodes.get(glmTree[key]["from"], "") - LinkedNodes[glmTree[key]["from"]] = ph + glmTree[key]["phases"] - ph = LinkedNodes.get(glmTree[key]["to"], "") - LinkedNodes[glmTree[key]["to"]] = ph + glmTree[key]["phases"] - if glmTree[key]["to"] not in toNodes: - toNodes.append(glmTree[key]["to"]) - if glmTree[key]["from"] not in fromNodes: - fromNodes.append(glmTree[key]["from"]) - # for node in fromNodes: - # if node not in toNodes and node != "n" + swingBus: - # print (node) - - # Find the unique phase information and place them in the node like object dictionaries - for node in LinkedNodes.keys(): - phase = "" - ABCphases = 0 - if "A" in LinkedNodes[node]: - phase = phase + "A" - ABCphases = ABCphases + 1 - if "B" in LinkedNodes[node]: - phase = phase + "B" - ABCphases = ABCphases + 1 - if "C" in LinkedNodes[node]: - phase = phase + "C" - ABCphases = ABCphases + 1 - if "S" in LinkedNodes[node] and ABCphases == 1 and node not in fromNodes: - phase = phase + "S" - else: - phase = phase + "N" - - for x in glmTree.keys(): - if "name" in glmTree[x].keys() and glmTree[x]["name"] == node: - glmTree[x]["phases"] = phase - - # Take care of open switches - swFromNodes = {} - swToNodes = {} - for x in glmTree.keys(): - if "from" in glmTree[x].keys(): - if glmTree[x]["from"] not in swFromNodes.keys(): - swFromNodes[glmTree[x]["from"]] = 1 - else: - swFromNodes[glmTree[x]["from"]] += 1 - if glmTree[x]["to"] not in swToNodes.keys(): - swToNodes[glmTree[x]["to"]] = 1 - else: - swToNodes[glmTree[x]["to"]] += 1 - - deleteKeys = [] - for x in glmTree.keys(): - if ( - glmTree[x].get("phase_A_state", "") == "OPEN" - or glmTree[x].get("phase_B_state", "") == "OPEN" - or glmTree[x].get("phase_C_state", "") == "OPEN" - ): - if swToNodes[glmTree[x]["to"]] > 1: - deleteKeys.append(x) - elif swFromNodes.get(glmTree[x]["to"], 0) > 0: - for phase in glmTree[x]["phases"]: - if phase not in ["N", "D"]: - glmTree[x]["phase_{:s}_state".format(phase)] = "CLOSED" - else: - deleteKeys.append(x) - for y in glmTree.keys(): - if glmTree[y].get("name", "") == glmTree[x]["to"]: - deleteKeys.append(y) - - for key in deleteKeys: - del glmTree[key] - - def _fixNominalVoltage(glm_dict, volt_dict): - for x in glm_dict.keys(): - if ( - "from" in glm_dict[x].keys() - and glm_dict[x]["from"] in volt_dict.keys() - and glm_dict[x]["to"] not in volt_dict.keys() - ): - if glm_dict[x]["object"] == "transformer": - # get secondary voltage from transformer configuration - if "SPCT" in glm_dict[x]["name"]: - nv = "120.0" - else: - cnfg = glm_dict[x]["configuration"] - for y in glm_dict.keys(): - if ( - "name" in glm_dict[y].keys() - and glm_dict[y]["name"] == cnfg - ): - nv = glm_dict[y]["secondary_voltage"] - volt_dict[glm_dict[x]["to"]] = nv - elif glm_dict[x]["object"] == "regulator": - volt_dict[glm_dict[x]["to"]] = volt_dict[glm_dict[x]["from"]] - cnfg = glm_dict[x]["configuration"] - nv = volt_dict[glm_dict[x]["from"]] - for y in glm_dict.keys(): - if glm_dict[y].get("name", "") == cnfg: - pass - # glmTree[y]['band_center'] = nv - # glmTree[y]['band_width'] = str(float(glmTree[y]['band_width'])*float(glmTree[y]['band_center'])) - else: - volt_dict[glm_dict[x]["to"]] = volt_dict[glm_dict[x]["from"]] - elif ( - "parent" in glm_dict[x].keys() - and glm_dict[x]["parent"] in volt_dict.keys() - and glm_dict[x]["name"] not in volt_dict.keys() - ): - volt_dict[glm_dict[x]["name"]] = volt_dict[glm_dict[x]["parent"]] - - parent_voltage = {} - current_parents = len(parent_voltage) - previous_parents = 0 - - for obj in glmTree: - if "bustype" in glmTree[obj] and glmTree[obj]["bustype"] == "SWING": - parent_voltage[glmTree[obj]["name"]] = glmTree[obj]["nominal_voltage"] - current_parents = len(parent_voltage) - - while current_parents > previous_parents: - _fixNominalVoltage(glmTree, parent_voltage) - previous_parents = current_parents - current_parents = len(parent_voltage) - - for x in glmTree.keys(): - if glmTree[x].get("name", "") in parent_voltage.keys(): - glmTree[x]["nominal_voltage"] = parent_voltage[glmTree[x].get("name", "")] - - # Delete nominal_voltage from link objects - del_nom_volt_list = [ - "overhead_line", - "underground_line", - "regulator", - "transformer", - "switch", - "fuse", - "ZIPload", - "diesel_dg", - "solar", - "inverter", - ] - for x in glmTree: - if ( - "object" in glmTree[x].keys() - and glmTree[x]["object"] in del_nom_volt_list - and "nominal_voltage" in glmTree[x].keys() - ): - del glmTree[x]["nominal_voltage"] - - # Delete neutrals from links with no neutrals - for x in glmTree.keys(): - if "object" in glmTree[x].keys() and glmTree[x]["object"] in [ - "underground_line", - "regulator", - "transformer", - "switch", - "fuse", - "capacitor", - "series_reactor", - ]: - glmTree[x]["phases"] = glmTree[x]["phases"].replace("N", "") - elif ( - "object" in glmTree[x].keys() - and glmTree[x]["object"] == "overhead_line" - and glmTree[x]["configuration"] not in ohl_neutral - ): - glmTree[x]["phases"] = glmTree[x]["phases"].replace("N", "") - if "object" in glmTree[x].keys() and glmTree[x]["object"] in ["node", "meter"]: - try: - glmTree[x]["phases"] = glmTree[x]["phases"].replace("S", "") - if "N" not in glmTree[x]["phases"]: - glmTree[x]["phases"] = glmTree[x]["phases"] + "N" - except Exception as e: - print_error(e) - pass - # TODO: have this missing nodes report not put files all over the place. - # checkMissingNodes(nodes, cymsectiondevice, objectList, feeder_id, cymsection) - - # JOHN FITZGERALD KENNEDY. add regulator to source - biggestkey = max(glmTree.keys()) - glmTree[biggestkey + 1] = { - "object": "node", - "name": "sourcenode", - "phases": "ABC", - "nominal_voltage": cymsource[_fixName(swingBus)]["nominal_voltage"], - "bustype": "SWING", - } - glmTree[biggestkey + 2] = { - "object": "regulator", - "name": "sourceregulator", - "phases": "ABC", - "from": "sourcenode", - "to": "n" + swingBus, - "configuration": "ss_regconfiguration", - } - glmTree[biggestkey + 3] = { - "object": "regulator_configuration", - "name": "ss_regconfiguration", - "band_center": cymsource[_fixName(swingBus)][ - "nominal_voltage" - ], # HACK: source_voltage set to nominal. - "Control": "OUTPUT_VOLTAGE", - "connect_type": "WYE_WYE", - "raise_taps": "50", # want to be very close to desired voltage for agreement with cyme - "lower_taps": "50", - "band_width": "2.0", # bandwidth should be very small for all voltage levels - "regulation": "0.1", - "dwell_time": "5", - "tap_pos_A": "0", - "tap_pos_B": "0", - "tap_pos_C": "0", - "time_delay": "30.0", - "control_level": "INDIVIDUAL", - } - return glmTree - -def main(argv): - raise Exception("mdb2glm.py CLI not implemented yet") - -if __name__ == "__main__": - main(sys.argv) diff --git a/docs/Module/Mysql/Database.md b/docs/Module/Mysql/Database.md index 4957f434e..99c5b7981 100644 --- a/docs/Module/Mysql/Database.md +++ b/docs/Module/Mysql/Database.md @@ -117,7 +117,7 @@ Do not permit `db_name.tbl_name.col_name` syntax. This is for ODBC. It causes th ### `ODBC` -Unused. +Deprecated ### `SSL` diff --git a/docs/User manual/0 - Cover/2 - Preface.md b/docs/User manual/0 - Cover/2 - Preface.md index bf8591780..ba6f42029 100644 --- a/docs/User manual/0 - Cover/2 - Preface.md +++ b/docs/User manual/0 - Cover/2 - Preface.md @@ -44,7 +44,7 @@ The appendices contain the following - A thorough GLM language reference - - References for Java, Matlab®, ODBC, gnutools, Microsoft® Visual Studio® and methods for interface GridLAB-D with other systems + - References for Java, Matlab®, gnutools, Microsoft® Visual Studio® and methods for interface GridLAB-D with other systems ## What not to expect from this manual diff --git a/module/mysql/database.cpp b/module/mysql/database.cpp index de1d2df8e..d08034592 100644 --- a/module/mysql/database.cpp +++ b/module/mysql/database.cpp @@ -51,7 +51,6 @@ database::database(MODULE *module) PT_KEYWORD,"MULTI_RESULTS",(int64)CLIENT_MULTI_RESULTS, PT_KEYWORD,"MULTI_STATEMENTS",(int64)CLIENT_MULTI_STATEMENTS, PT_KEYWORD,"NO_SCHEMA",(int64)CLIENT_NO_SCHEMA, - PT_KEYWORD,"ODBC",(int64)CLIENT_ODBC, PT_KEYWORD,"SSL",(int64)CLIENT_SSL, PT_KEYWORD,"REMEMBER_OPTIONS",(int64)CLIENT_REMEMBER_OPTIONS, PT_set,"options",get_options_offset(),PT_ACCESS,PA_PUBLIC,PT_DESCRIPTION,"database connection options", diff --git a/module/mysql/init.cpp b/module/mysql/init.cpp index 8a4f73401..5951862da 100644 --- a/module/mysql/init.cpp +++ b/module/mysql/init.cpp @@ -36,7 +36,6 @@ EXPORT CLASS *init(CALLBACKS *fntable, MODULE *module, int argc, char *argv[]) PT_KEYWORD,"MULTI_RESULTS",(int64)CLIENT_MULTI_RESULTS, PT_KEYWORD,"MULTI_STATEMENTS",(int64)CLIENT_MULTI_STATEMENTS, PT_KEYWORD,"NO_SCHEMA",(int64)CLIENT_NO_SCHEMA, - PT_KEYWORD,"ODBC",(int64)CLIENT_ODBC, PT_KEYWORD,"SSL",(int64)CLIENT_SSL, PT_KEYWORD,"REMEMBER_OPTIONS",(int64)CLIENT_REMEMBER_OPTIONS, NULL); diff --git a/module/tape/Makefile.mk b/module/tape/Makefile.mk index 466a4e601..621803f33 100644 --- a/module/tape/Makefile.mk +++ b/module/tape/Makefile.mk @@ -23,7 +23,6 @@ module_tape_tape_la_SOURCES += module/tape/histogram.cpp module/tape/histogram.h module_tape_tape_la_SOURCES += module/tape/loadshape.cpp module/tape/loadshape.h module_tape_tape_la_SOURCES += module/tape/tape.cpp module/tape/tape.h module_tape_tape_la_SOURCES += module/tape/memory.cpp module/tape/memory.h -module_tape_tape_la_SOURCES += module/tape/odbc.cpp module/tape/odbc.h module_tape_tape_la_SOURCES += module/tape/multi_recorder.cpp module_tape_tape_la_SOURCES += module/tape/collector.cpp diff --git a/module/tape/collector.cpp b/module/tape/collector.cpp index d29ce20f1..03d1340a6 100644 --- a/module/tape/collector.cpp +++ b/module/tape/collector.cpp @@ -32,7 +32,6 @@ #include "tape.h" #include "file.h" -#include "odbc.h" CLASS *collector_class = NULL; static OBJECT *last_collector = NULL; diff --git a/module/tape/multi_recorder.cpp b/module/tape/multi_recorder.cpp index 4a6b9dc9e..9c23c104d 100644 --- a/module/tape/multi_recorder.cpp +++ b/module/tape/multi_recorder.cpp @@ -37,7 +37,6 @@ #include "tape.h" #include "file.h" -#include "odbc.h" #if defined WIN32 && defined __MINGW32__ inline char* strtok_t(char *str, const char *delim, char **nextp) diff --git a/module/tape/odbc.cpp b/module/tape/odbc.cpp deleted file mode 100644 index 78a18e988..000000000 --- a/module/tape/odbc.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* $Id: odbc.c 4738 2014-07-03 00:55:39Z dchassin $ - * Copyright (C) 2008 Battelle Memorial Institute - */ - -#include -#include -#include -#include -#include - -#include "tape.h" -#include "odbc.h" - -/******************************************************************* - * players - */ -int odbc_open_player(struct player *my, char *fname, char *flags) -{ - return 0; -} - -char *odbc_read_player(struct player *my,char *buffer,unsigned int size) -{ - return NULL; -} - -int odbc_rewind_player(struct player *my) -{ - return 0; -} - -void odbc_close_player(struct player *my) -{ -} - -/******************************************************************* - * shaper generators - */ -int odbc_open_shaper(struct shaper *my, char *fname, char *flags) -{ - return 0; -} - -char *odbc_read_shaper(struct shaper *my,char *buffer,unsigned int size) -{ - return NULL; -} - -int odbc_rewind_shaper(struct shaper *my) -{ - return 0; -} - -void odbc_close_shaper(struct shaper *my) -{ -} - -/******************************************************************* - * recorders - */ -int odbc_open_recorder(struct recorder *my, char *fname, char *flags) -{ - return 0; -} - -int odbc_write_recorder(struct recorder *my, char *timestamp, char *value) -{ - return 0; -} - -void odbc_close_recorder(struct recorder *my) -{ -} - -/******************************************************************* - * collectors - */ -int odbc_open_collector(struct collector *my, char *fname, char *flags) -{ - return 0; -} - -int odbc_write_collector(struct collector *my, char *timestamp, char *value) -{ - return 0; -} - -void odbc_close_collector(struct collector *my) -{ -} diff --git a/module/tape/odbc.h b/module/tape/odbc.h deleted file mode 100644 index e362385d7..000000000 --- a/module/tape/odbc.h +++ /dev/null @@ -1,26 +0,0 @@ -/* $Id: odbc.h 4738 2014-07-03 00:55:39Z dchassin $ - * Copyright (C) 2008 Battelle Memorial Institute - */ - -#ifndef _ODBC_H -#define _ODBC_H - -int odbc_open_player(struct player *my, char *fname, char *flags); -char *odbc_read_player(struct player *my,char *buffer,unsigned int size); -int odbc_rewind_player(struct player *my); -void odbc_close_player(struct player *my); - -int odbc_open_shaper(struct shaper *my, char *fname, char *flags); -char *odbc_read_shaper(struct shaper *my,char *buffer,unsigned int size); -int odbc_rewind_shaper(struct shaper *my); -void odbc_close_shaper(struct shaper *my); - -int odbc_open_recorder(struct recorder *my, char *fname, char *flags); -int odbc_write_recorder(struct recorder *my, char *timestamp, char *value); -void odbc_close_recorder(struct recorder *my); - -int odbc_open_collector(struct collector *my, char *fname, char *flags); -int odbc_write_collector(struct collector *my, char *timestamp, char *value); -void odbc_close_collector(struct collector *my); - -#endif diff --git a/module/tape/player.cpp b/module/tape/player.cpp index ed7be3c54..782596319 100644 --- a/module/tape/player.cpp +++ b/module/tape/player.cpp @@ -10,7 +10,7 @@ The default \p type is \p file The default \p name is the target (parent) objects \p classname-\p id The default \p flags is \p "r" - - \p filetype specifies the source file extension, default is \p "txt". Valid types are \p txt, \p odbc, and \p memory. + - \p filetype specifies the source file extension, default is \p "txt". Valid types are \p txt, and \p memory. - \p property is the target (parent) that is written to - \p loop is the number of times the tape is to be repeated @@ -42,7 +42,6 @@ #include "tape.h" #include "file.h" -#include "odbc.h" CLASS *player_class = NULL; static OBJECT *last_player = NULL; diff --git a/module/tape/recorder.cpp b/module/tape/recorder.cpp index d84629ebe..c621c53fe 100644 --- a/module/tape/recorder.cpp +++ b/module/tape/recorder.cpp @@ -27,7 +27,6 @@ #include "tape.h" #include "file.h" -#include "odbc.h" #if defined WIN32 && defined __MINGW32__ inline char* strtok_t(char *str, const char *delim, char **nextp) diff --git a/module/tape/shaper.cpp b/module/tape/shaper.cpp index 8131ee512..169413a1b 100644 --- a/module/tape/shaper.cpp +++ b/module/tape/shaper.cpp @@ -43,7 +43,6 @@ #include "tape.h" #include "file.h" -#include "odbc.h" CLASS *shaper_class = NULL; diff --git a/module/tape/tape.cpp b/module/tape/tape.cpp index a02058736..09775db36 100644 --- a/module/tape/tape.cpp +++ b/module/tape/tape.cpp @@ -36,7 +36,6 @@ void new_metrics_collector_writer(MODULE *); #include "tape.h" #include "file.h" -#include "odbc.h" #define MAP_DOUBLE(X,LO,HI) {#X,VT_DOUBLE,&X,LO,HI} #define MAP_INTEGER(X,LO,HI) {#X,VT_INTEGER,&X,LO,HI} diff --git a/module/tape/tape.h b/module/tape/tape.h index 2dc41c01e..6d464332a 100644 --- a/module/tape/tape.h +++ b/module/tape/tape.h @@ -15,7 +15,7 @@ extern char timestamp_format[32]; typedef enum {VT_INTEGER, VT_DOUBLE, VT_STRING} VARIABLETYPE; typedef enum {TS_INIT, TS_OPEN, TS_DONE, TS_ERROR} TAPESTATUS; -typedef enum {FT_FILE, FT_ODBC, FT_MEMORY} FILETYPE; +typedef enum {FT_FILE, FT_MEMORY} FILETYPE; typedef enum {SCR, EPS, GIF, JPG, PDF, PNG, SVG} PLOTFILE; typedef enum e_complex_part {CP_NONE = 0, REAL, IMAG, MAG, ANG, ANG_RAD} CPLPT; typedef enum {UNKNOWN=0, PLAYER=1, RECORDER=2, GROUPRECORDER=3} DELTATAPEOBJ; diff --git a/runtime/gridlabd.h b/runtime/gridlabd.h index 2efff8237..a43be1559 100644 --- a/runtime/gridlabd.h +++ b/runtime/gridlabd.h @@ -101,7 +101,6 @@ class complex { { r *= m/old; i *= m/old; - return m; } else { @@ -109,6 +108,7 @@ class complex { r = m; i = 0; } + return m; }; inline double Arg(void) const /**< compute angle */ { @@ -1450,15 +1450,20 @@ typedef FUNCTIONADDR function; /// @return a pointer to a static buffer containing the object's name inline char* gl_name(OBJECT *my, char *buffer, size_t size) { - char temp[256]; if(my == NULL || buffer == NULL) return NULL; + int len = 0; if (my->name==NULL) - sprintf(temp,"%s:%d", my->oclass->name, my->id); + { + len = snprintf(buffer,size,"%s:%d", my->oclass->name, my->id); + } else - sprintf(temp,"%s", my->name); - if(size < strlen(temp)) + { + len = snprintf(buffer,size,"%s", my->name); + } + if ( len == size ) + { return NULL; - strcpy(buffer, temp); + } return buffer; } diff --git a/source/convert.cpp b/source/convert.cpp index 02dbd0be2..7f86ad5db 100644 --- a/source/convert.cpp +++ b/source/convert.cpp @@ -230,7 +230,7 @@ int convert_from_complex(char *buffer, /**< pointer to the string buffer */ PROPERTY *prop) /**< a pointer to keywords that are supported */ { int count = 0; - char temp[1025] = ""; + char temp[2048] = ""; complex *v = (complex*)data; CNOTATION cplex_output_type = J; @@ -278,27 +278,23 @@ int convert_from_complex(char *buffer, /**< pointer to the string buffer */ double m = v->Mag()*scale; double a = v->Arg(); if (a>PI) a-=(2*PI); - snprintf(temp,sizeof(temp)-1,global_complex_format,m,a*180/PI,A); - count = strlen(temp); + count += snprintf(temp,sizeof(temp)-1,global_complex_format,m,a*180/PI,A); } else if ( v->Notation() == R ) { double m = v->Mag()*scale; double a = v->Arg(); if (a>PI) a-=(2*PI); - snprintf(temp,sizeof(temp)-1,global_complex_format,m,a,R); - count = strlen(temp); + count += snprintf(temp,sizeof(temp)-1,global_complex_format,m,a,R); } else { - snprintf(temp,sizeof(temp)-1,global_complex_format,v->Re()*scale,v->Im()*scale,v->Notation()?v->Notation():'i'); - count = strlen(temp); + count += snprintf(temp,sizeof(temp)-1,global_complex_format,v->Re()*scale,v->Im()*scale,v->Notation()?v->Notation():'i'); } if ( prop->unit ) { - snprintf(temp+count,sizeof(temp)-1+count," %s",prop->unit->name); - count += strlen(temp); + count += snprintf(temp+count,sizeof(temp)-1-count," %s",prop->unit->name); } if ( size == 0 ) diff --git a/source/curl.cpp b/source/curl.cpp index f9597e99e..e23ebde57 100644 --- a/source/curl.cpp +++ b/source/curl.cpp @@ -11,7 +11,7 @@ GldCurl::GldCurl(const char *remote, const char *local) { // initialize libcurl curl = curl_easy_init(); - if ( ! curl ) + if ( curl == NULL ) throw "GldCurl: curl_easy_init() failed"; IN_MYCONTEXT output_debug("GldCurl(remote='%s', local='%s'): curl init ok", remote, local); @@ -26,7 +26,7 @@ GldCurl::GldCurl(const char *remote, const char *local) // access local file fp = fopen(local,"w"); - if ( ! fp ) + if ( fp == NULL ) throw "GldCurl: local fopen failed"; if ( curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)fp) != CURLE_OK ) { @@ -69,8 +69,8 @@ GldCurl::GldCurl(const char *remote, const char *local) GldCurl::~GldCurl(void) { - if ( ! curl ) curl_easy_cleanup(curl); - if ( ! fp ) fclose(fp); + if ( curl != NULL ) curl_easy_cleanup(curl); + if ( fp != NULL ) fclose(fp); } bool GldCurl::get_option(const char *name, long long &llval) @@ -84,7 +84,7 @@ bool GldCurl::get_option(const char *name, long long &llval) { char token[256]; long long value; - if ( sscanf(tag,"%s:%lld",token,&value) == 2 && strcmp(token,name)==0 ) + if ( sscanf(tag,"%255s:%lld",token,&value) == 2 && strcmp(token,name)==0 ) { llval = value; return true; diff --git a/source/globals.cpp b/source/globals.cpp index ef948e981..bd976486b 100644 --- a/source/globals.cpp +++ b/source/globals.cpp @@ -336,7 +336,7 @@ void pythonpath_init(const char *name,const char *value) if ( value != NULL ) { int len = snprintf(global_pythonpath,sizeof(global_pythonpath)-1,"%.*s",(int)sizeof(global_pythonpath)-2,value); - snprintf(global_pythonpath+len,sizeof(global_pythonpath)-1-len,":%.*s",(int)(sizeof(global_pythonpath)-2),pythonpath); + snprintf(global_pythonpath+len,sizeof(global_pythonpath)-1-len,":%.*s",(int)(sizeof(global_pythonpath)-3),pythonpath); } else { @@ -1794,7 +1794,7 @@ DEPRECATED const char *global_pid(char *buffer, int size) **/ const char *GldGlobals::getvar(const char *name, char *buffer, size_t size) { - char temp[1024]; + char temp[2048]; size_t len = 0; GLOBALVAR *var = NULL; struct { diff --git a/source/gridlabd.h b/source/gridlabd.h index 96b47bb92..7573f19cd 100644 --- a/source/gridlabd.h +++ b/source/gridlabd.h @@ -1598,13 +1598,13 @@ inline DEPRECATED const char *gl_module_find_transform_function(TRANSFORMFUNCTIO /**@}*/ #ifdef __cplusplus -inline DEPRECATED randomvar *gl_randomvar_getfirst(void) { return callback->randomvar.getnext(NULL); }; -inline DEPRECATED randomvar *gl_randomvar_getnext(randomvar *var) { return callback->randomvar.getnext(var); }; -inline DEPRECATED size_t gl_randomvar_getspec(char *str, size_t size, const randomvar *var) { return callback->randomvar.getspec(str,size,var); }; +inline DEPRECATED randomvar *gl_randomvar_getfirst(void) { return callback->randomvars.getnext(NULL); }; +inline DEPRECATED randomvar *gl_randomvar_getnext(randomvar *var) { return callback->randomvars.getnext(var); }; +inline DEPRECATED size_t gl_randomvar_getspec(char *str, size_t size, const randomvar *var) { return callback->randomvars.getspec(str,size,var); }; #else -#define gl_randomvar_getfirst DEPRECATED (*callback->randomvar.getnext)(NULL) -#define gl_randomvar_getnext DEPRECATED (*callback->randomvar.getnext) /* randomvar *(*randomvar.getnext)(randomvar*) */ -#define gl_randomvar_getspec DEPRECATED (*callback->randomvar.getspec) /* size_t (*randomvar.getspec(char*,size_t,randomvar*) */ +#define gl_randomvar_getfirst DEPRECATED (*callback->randomvars.getnext)(NULL) +#define gl_randomvar_getnext DEPRECATED (*callback->randomvars.getnext) /* randomvar *(*randomvar.getnext)(randomvar*) */ +#define gl_randomvar_getspec DEPRECATED (*callback->randomvars.getspec) /* size_t (*randomvar.getspec(char*,size_t,randomvar*) */ #endif /****************************************************************************** @@ -2447,7 +2447,7 @@ class gld_unit // Method: is_valid // Check whether the unit is valid - inline bool is_valid(void) { return (UNIT*)&core != NULL && core.name[0]!='\0'; }; + inline bool is_valid(void) { return core.name[0]!='\0'; }; public: diff --git a/source/json.cpp b/source/json.cpp index 35438b798..a86ae2491 100644 --- a/source/json.cpp +++ b/source/json.cpp @@ -320,7 +320,7 @@ int GldJsonWriter::write_globals(FILE *fp) /* for each module */ for ( var = global_find(NULL) ; var != NULL ; var = global_getnext(var) ) { - char buffer[1024]; + char buffer[2048]; if ( global_getvar(var->prop->name,buffer,sizeof(buffer)-1) ) // only write globals that can be extracted { KEYWORD *key; diff --git a/source/load.cpp b/source/load.cpp index e69689746..77c2b046f 100755 --- a/source/load.cpp +++ b/source/load.cpp @@ -2871,7 +2871,7 @@ int GldLoader::module_block(PARSER) { char module_name[64]; char fmod[8],mod[54]; - MODULE *module; + MODULE *module = NULL; START; if WHITE ACCEPT; if (LITERAL("module") && WHITE) ACCEPT else REJECT; diff --git a/source/object.h b/source/object.h index c73ca6087..109ac25b3 100644 --- a/source/object.h +++ b/source/object.h @@ -355,7 +355,7 @@ typedef struct s_callbacks { struct { randomvar *(*getnext)(randomvar*); size_t (*getspec)(char *, size_t, const randomvar *); - } randomvar; + } randomvars; struct { unsigned int (*major)(void); unsigned int (*minor)(void); diff --git a/source/odbc++/Makefile.am b/source/odbc++/Makefile.am deleted file mode 100644 index 2e27b3654..000000000 --- a/source/odbc++/Makefile.am +++ /dev/null @@ -1,52 +0,0 @@ -# This file is part of libodbc++. -# -# Copyright (C) 1999-2000 Manush Dodunekov -# -# This library is free software; you can redistribute it and/or -# modify it under the terms of the GNU Library General Public -# License as published by the Free Software Foundation; either -# version 2 of the License, or (at your option) any later version. -# -# This library 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 -# Library General Public License for more details. -# -# You should have received a copy of the GNU Library General Public License -# along with this library; see the file COPYING. If not, write to -# the Free Software Foundation, Inc., 59 Temple Place - Suite 330, -# Boston, MA 02111-1307, USA. - -pkgincludedir=@includedir@/odbc++ - -pkginclude_HEADERS=\ -config.h \ -setup.h \ -types.h \ -threads.h \ -errorhandler.h \ -drivermanager.h \ -connection.h \ -databasemetadata.h \ -statement.h \ -preparedstatement.h \ -callablestatement.h \ -resultset.h \ -resultsetmetadata.h - -config.h: $(CONFIG_HEADER) config.h.in - cat $(srcdir)/config.h.in > $@ - sed -e 's/#\([^ ][^ ]*\) \([^ ][^ ]*\)/#\1 ODBCXX_\2/g' >> $@ < $(CONFIG_HEADER) - - -EXTRA_DIST=config.h.in config-win32.h - -CLEANFILES=config.h - -# nuke our generated config file -dist-hook: - rm -f $(distdir)/config.h - -uninstall-local: - test -d $(DESTDIR)$(pkgincludedir) && \ - rmdir $(DESTDIR)$(pkgincludedir) || true diff --git a/source/odbc++/callablestatement.h b/source/odbc++/callablestatement.h deleted file mode 100644 index e69b15838..000000000 --- a/source/odbc++/callablestatement.h +++ /dev/null @@ -1,168 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_CALLABLESTATEMENT_H -#define __ODBCXX_CALLABLESTATEMENT_H - -#include -#include -#include - -namespace odbc { - - /** A prepared statement suited for stored procedure calls. - * - * A CallableStatement extends the functionality of a - * PreparedStatement, by allowing output parameters. - * - * The ODBC escapes for calling stored procedures and functions - * should be used. A procedure call is prepared like this: - *
-   * std::auto_ptr<CallableStatement> cstmt
-   *    =std::auto_ptr<CallableStatement>(con->prepareCall
-   *     ("{call my_procedure(?,?,?)}"));
-   * 
- * - * And for a function call (a procedure that returns a value), the - * following syntax should be used: - *
-   * std::auto_ptr<CallableStatement> cstmt
-   *    =std::auto_ptr<CallableStatement>(con->prepareCall
-   *     ("{?=call my_function(?,?)}"));
-   * 
- * - * - * All parameters in a CallableStatement are treated - * as input/output parameters, unless they are registered as - * output-only parameters with registerOutParameter(). Note that - * output-only parameters must be registered with their proper - * SQL type prior to executing a CallableStatement. - */ - class ODBCXX_EXPORT CallableStatement : public PreparedStatement { - friend class Connection; - - private: - bool lastWasNull_; - - protected: - CallableStatement(Connection* con, - SQLHSTMT hstmt, - const ODBCXX_STRING& sql, - int resultSetType, - int resultSetConcurrency); - - public: - /** Destructor */ - virtual ~CallableStatement(); - - /** Fetches a parameter as a double - * @param idx The parameter index, starting at 1 - */ - double getDouble(int idx); - - /** Fetches a parameter as a bool - * @param idx The parameter index, starting at 1 - */ - bool getBoolean(int idx); - - /** Fetches a parameter as a signed char - * @param idx The parameter index, starting at 1 - */ - signed char getByte(int idx); - - /** Fetches a parameter as a Bytes object - * @param idx The parameter index, starting at 1 - */ - ODBCXX_BYTES getBytes(int idx); - - /** Fetches a parameter as a Date - * @param idx The parameter index, starting at 1 - */ - Date getDate(int idx); - - /** Fetches a parameter as a float - * @param idx The parameter index, starting at 1 - */ - float getFloat(int idx); - - /** Fetches a parameter as an int - * @param idx The parameter index, starting at 1 - */ - int getInt(int idx); - - /** Fetches a parameter as a Long - * @param idx The parameter index, starting at 1 - */ - Long getLong(int idx); - - /** Fetches a parameter as a short - * @param idx The parameter index, starting at 1 - */ - short getShort(int idx); - - /** Fetches a parameter as a string - * @param idx The parameter index, starting at 1 - */ - ODBCXX_STRING getString(int idx); - - /** Fetches a parameter as a Time - * @param idx The parameter index, starting at 1 - */ - Time getTime(int idx); - - /** Fetches a parameter as a Timestamp - * @param idx The parameter index, starting at 1 - */ - Timestamp getTimestamp(int idx); - - /** Registers an output parameter - * @param idx The parameter index, starting at 1 - * @param sqlType The SQL type of the parameter - * @see Types - */ - void registerOutParameter(int idx, int sqlType) { - this->registerOutParameter(idx,sqlType,0); - } - - /** Registers an output parameter with a given scale - * @param idx The parameter index, starting at 1 - * @param sqlType The SQL type of the parameter - * @param scale The scale of the parameter. - * @see Types - */ - void registerOutParameter(int idx, int sqlType, int scale); - - /** Registers an input only parameter - * @param idx The parameter index, starting at 1 - */ - void registerInParameter(int idx); - - /** Returns true if the last fetched parameter was NULL */ - bool wasNull() { - return lastWasNull_; - } - }; - - -} // namespace odbc - - -#endif // __ODBCXX_CALLABLESTATEMENT_H diff --git a/source/odbc++/config-win32.h b/source/odbc++/config-win32.h deleted file mode 100644 index 14d197ddb..000000000 --- a/source/odbc++/config-win32.h +++ /dev/null @@ -1,101 +0,0 @@ -#if !defined(__ODBCXX_SETUP_H) -# error "Do not include this file directly. Use instead" -#endif - -#define ODBCXX_HAVE_SQL_H -#define ODBCXX_HAVE_SQLEXT_H -#define ODBCXX_HAVE_SQLUCODE_H - -#define ODBCXX_HAVE_CSTDIO -#define ODBCXX_HAVE_CSTDLIB -#define ODBCXX_HAVE_CSTRING -#define ODBCXX_HAVE_CTIME -#define ODBCXX_HAVE_IOSTREAM -#define ODBCXX_HAVE_SSTREAM -#define ODBCXX_HAVE_SET -#define ODBCXX_HAVE_VECTOR - - -#define ODBCXX_ENABLE_THREADS - -#if defined(_MSC_VER) -// MSVC has a rather compliant CXX lib -# define ODBCXX_HAVE_ISO_CXXLIB - -# define ODBCXX_HAVE__ITOA -# define ODBCXX_HAVE__STRICMP -# define ODBCXX_HAVE__SNPRINTF - -# define ODBCXX_HAVE__I64TOA -# define ODBCXX_HAVE__ATOI64 -# define ODBCXX_HAVE__ATOI - -// disable the 'identifier name truncated in debug info' warning -# pragma warning(disable:4786) - -// disable the 'class blah blah should be exported' warning -// don't know if this is dangerous, but it only whines about templated -// and/or inlined classes and it really bothers me =) -# if defined(ODBCXX_DLL) -# pragma warning(disable:4251) -# endif - -# if _MSC_VER <= 1200 -# define ODBCXX_NO_STD_TIME_T -# endif - -#endif // _MSC_VER - - - -#if defined(__BORLANDC__) - -// FIXME: this should check for older versions -# define ODBCXX_HAVE_ISO_CXXLIB - -# if !defined(_RWSTD_NO_EX_SPEC) -# define _RWSTD_NO_EX_SPEC 1 -# endif -// sql.h only defines this for msc, but borland has __int64 as well -# if !defined(ODBCINT64) -# define ODBCINT64 __int64 -# endif - -# define ODBCXX_HAVE_ITOA 1 -# define ODBCXX_HAVE_STRICMP 1 - -#endif // __BORLANDC__ - - -#if defined(__MINGW32__) - -// the MS runtime has those -# if defined(__MSVCRT__) -# define ODBCXX_HAVE__I64TOA -# define ODBCXX_HAVE__ATOI64 -# endif - -#define ODBCXX_HAVE__ITOA -#define ODBCXX_HAVE__STRICMP - -#define ODBCXX_HAVE__SNPRINTF - -// same as with borland -# if !defined(ODBCINT64) -# define ODBCINT64 __int64 -# endif - -#endif // __MINGW32__ - -#define WIN32_LEAN_AND_MEAN - -#if defined(ODBCXX_UNICODE) -# if !defined(_UNICODE) -# define _UNICODE -# endif -# if defined(_MBCS) -# undef _MBCS -# endif -#endif - -#include diff --git a/source/odbc++/config.h b/source/odbc++/config.h deleted file mode 100644 index 908e2832f..000000000 --- a/source/odbc++/config.h +++ /dev/null @@ -1,170 +0,0 @@ -#if !defined(__ODBCXX_SETUP_H) -# error "Do not include this file directly. Use instead" -#endif -/* config.h. Generated by configure. */ -/* config.h.in. Generated from configure.ac by autoheader. */ - -/* Defined if threads enabled */ -/* #undef ODBCXX_ENABLE_THREADS */ - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_CSTDIO 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_CSTDLIB 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_CSTRING 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_CTIME 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_DLFCN_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_EXCEPTION 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_INTTYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_IOSTREAM 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_IOSTREAM_H 1 - -/* Defined if using iodbc */ -/* #undef ODBCXX_HAVE_ISQLEXT_H */ - -/* Defined if using iodbc */ -/* #undef ODBCXX_HAVE_ISQL_H */ - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_ISTREAM 1 - -/* Defined if using iodbc */ -/* #undef ODBCXX_HAVE_LIBIODBC */ - -/* defined if using unixodbc */ -#define ODBCXX_HAVE_LIBODBC - -/* Define to 1 if you have the `localtime_r' function. */ -/* #undef ODBCXX_HAVE_LOCALTIME_R */ - -/* Define if we have long long */ -#define ODBCXX_HAVE_LONG_LONG 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_MEMORY_H 1 - -/* Define to 1 if you have the `pthread_create' function. */ -/* #undef ODBCXX_HAVE_PTHREAD_CREATE */ - -/* Defined if pthreads are available */ -/* #undef ODBCXX_HAVE_PTHREAD_H */ - -/* Define to 1 if you have the header file. */ -/* #undef ODBCXX_HAVE_READLINE_HISTORY_H */ - -/* Define to 1 if you have the header file. */ -/* #undef ODBCXX_HAVE_READLINE_READLINE_H */ - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SET 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SET_H 1 - -/* Define to 1 if you have the `snprintf' function. */ -#define ODBCXX_HAVE_SNPRINTF 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SQLEXT_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SQLUCODE_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SQL_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SSTREAM 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STDINT_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STDLIB_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STRING 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STRINGS_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STRING_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STRSTREAM 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_STRSTREAM_H 1 - -/* Define to 1 if you have the `strtoll' function. */ -#define ODBCXX_HAVE_STRTOLL 1 - -/* Define to 1 if you have the `strtoq' function. */ -#define ODBCXX_HAVE_STRTOQ 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SYS_STAT_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_SYS_TYPES_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_UNISTD_H 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_VECTOR 1 - -/* Define to 1 if you have the header file. */ -#define ODBCXX_HAVE_VECTOR_H 1 - -/* ODBC version */ -/* #undef ODBCXX_ODBCVER */ - -/* Name of package */ -#define ODBCXX_PACKAGE "" - -/* Define to the address where bug reports for this package should be sent. */ -#define ODBCXX_PACKAGE_BUGREPORT "libodbcxx-devel@lists.sourceforge.net" - -/* Define to the full name of this package. */ -#define ODBCXX_PACKAGE_NAME "libodbcxx" - -/* Define to the full name and version of this package. */ -#define ODBCXX_PACKAGE_STRING "libodbcxx 0.2.4pre1" - -/* Define to the one symbol short name of this package. */ -#define ODBCXX_PACKAGE_TARNAME "libodbc++" - -/* Define to the version of this package. */ -#define ODBCXX_PACKAGE_VERSION "0.2.4pre1" - -/* The size of a `int', as computed by sizeof. */ -#define ODBCXX_SIZEOF_INT 4 - -/* The size of a `long', as computed by sizeof. */ -#define ODBCXX_SIZEOF_LONG 4 - -/* The size of a `long long', as computed by sizeof. */ -#define ODBCXX_SIZEOF_LONG_LONG 8 - -/* Define to 1 if you have the ANSI C header files. */ -#define ODBCXX_STDC_HEADERS 1 - -/* Version number of package */ -#define ODBCXX_VERSION "" diff --git a/source/odbc++/config.h.in b/source/odbc++/config.h.in deleted file mode 100644 index 859705055..000000000 --- a/source/odbc++/config.h.in +++ /dev/null @@ -1,3 +0,0 @@ -#if !defined(__ODBCXX_SETUP_H) -# error "Do not include this file directly. Use instead" -#endif diff --git a/source/odbc++/connection.h b/source/odbc++/connection.h deleted file mode 100644 index efa34c2cd..000000000 --- a/source/odbc++/connection.h +++ /dev/null @@ -1,243 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_CONNECTION_H -#define __ODBCXX_CONNECTION_H - -#include -#include -#include - -namespace odbc { - - class DriverInfo; - class DatabaseMetaData; - class Statement; - class PreparedStatement; - class CallableStatement; - - /** A database connection */ - class ODBCXX_EXPORT Connection : public ErrorHandler { - friend class DriverManager; - friend class Statement; - friend class DatabaseMetaData; - friend class DriverInfo; - - private: - struct PD; - // private data - PD* pd_; - - SQLHDBC hdbc_; - - DatabaseMetaData* metaData_; - DriverInfo* driverInfo_; - - //utilities - SQLUINTEGER _getNumericOption(SQLINTEGER optnum); - ODBCXX_STRING _getStringOption(SQLINTEGER optnum); - void _setNumericOption(SQLINTEGER optnum, SQLUINTEGER value); - void _setStringOption(SQLINTEGER optnum, const ODBCXX_STRING& value); - - SQLHSTMT _allocStmt(); - - //private constructor, called from DriverManager - Connection(SQLHDBC h); - - void _connect(const ODBCXX_STRING& dsn, - const ODBCXX_STRING& user, - const ODBCXX_STRING& password); - - void _connect(const ODBCXX_STRING& connectString); - - void _registerStatement(Statement* stmt); - void _unregisterStatement(Statement* stmt); - - const DriverInfo* _getDriverInfo() const { - return driverInfo_; - } - - public: - /** Transaction isolation constants. - */ - enum TransactionIsolation { - /** The data source does not support transactions */ - TRANSACTION_NONE, - /** Dirty reads, non-repeatable reads and phantom reads can occur. */ - TRANSACTION_READ_UNCOMMITTED, - /** Non-repeatable and phantom reads can occur */ - TRANSACTION_READ_COMMITTED, - /** Phantom reads can occur */ - TRANSACTION_REPEATABLE_READ, - /** Simply no problems */ - TRANSACTION_SERIALIZABLE - }; - - /** Destructor. Closes the connection */ - virtual ~Connection(); - - /** Returns true if autocommit is on */ - bool getAutoCommit(); - - /** Sets the autocommit state of this connection - * @param autoCommit true for on, false for off - */ - void setAutoCommit(bool autoCommit); - - /** Commits the ongoing transaction */ - void commit(); - - /** Rollbacks the ongoing transaction */ - void rollback(); - - /** Returns the current catalog */ - ODBCXX_STRING getCatalog(); - - /** Sets the current catalog */ - void setCatalog(const ODBCXX_STRING& catalog); - - /** Returns the current transaction isolation level */ - TransactionIsolation getTransactionIsolation(); - - /** Sets the current transaction isolation level */ - void setTransactionIsolation(TransactionIsolation isolation); - - /** Returns true if the connection is read only */ - bool isReadOnly(); - - /** Sets the read-only state of this connection */ - void setReadOnly(bool readOnly); - - /** Returns true if ODBC tracing is enabled on this connection - */ - bool getTrace(); - - /** Sets ODBC tracing on or off */ - void setTrace(bool on); - - /** Returns the file ODBC tracing is currently written to */ - ODBCXX_STRING getTraceFile(); - - /** Sets the file ODBC tracing is written to */ - void setTraceFile(const ODBCXX_STRING& s); - - /** Returns meta information for this connection. - * - * Note that the returned object is 'owned' by this - * connection and should in no way be deleted by the caller. - * - * Example: - * DatabaseMetaData* dmd = cnt->getMetaData(); - */ - DatabaseMetaData* getMetaData(); - - - /** Creates a non-prepared statement. - * - * Example: - * std::auto_ptr<Statement> stmt = - * std::auto_ptr<Statement>(cnt->createStatement()); - */ - Statement* createStatement(); - - /** Creates a non-prepared statement. - * - * Example: - * std::auto_ptr<Statement> stmt = - * std::auto_ptr<Statement>(cnt->createStatement(x, y)); - * - * @param resultSetType The type for ResultSets created - * by this statement - * @param resultSetConcurrency The concurrency for ResultSets created - * by this statement - */ - Statement* createStatement(int resultSetType, - int resultSetConcurrency); - - - /** Create a prepared statement. - * - * Example: - * std::auto_ptr<PreparedStatement> pstmt = - * std::auto_ptr<PreparedStatement>(cnt->prepareStatement(s)); - * - * @param sql The string to prepare, optionally containing parameter - * markers (?). - */ - PreparedStatement* prepareStatement(const ODBCXX_STRING& sql); - - /** Create a prepared statement. - * - * Example: - * std::auto_ptr<PreparedStatement> pstmt = - * std::auto_ptr<PreparedStatement>(cnt->prepareStatement(s, x, y)); - * - * @param sql The string to prepare, optionally containing parameter - * markers. - * @param resultSetType The type for ResultSets created - * by this statement - * @param resultSetConcurrency The concurrency for ResultSets created - * by this statement - */ - PreparedStatement* prepareStatement(const ODBCXX_STRING& sql, - int resultSetType, - int resultSetConcurrency); - - /** Create a callable prepared statement. - * - * Example: - * std::auto_ptr<CallableStatement> cstmt = - * std::auto_ptr<CallableStatement>(cnt->prepareCall(s)); - * - * @param sql The string to prepare, optionally containing parameter - * markers for input and/or output parameters - */ - CallableStatement* prepareCall(const ODBCXX_STRING& sql); - - /** Create a callable prepared statement. - * - * Example: - * std::auto_ptr<CallableStatement> cstmt = - * std::auto_ptr<CallableStatement>(cnt->prepareCall(s, x, y)); - * - * @param sql The string to prepare, optionally containing parameter - * markers for input and/or output parameters - * @param resultSetType The type for ResultSets created - * by this statement - * @param resultSetConcurrency The concurrency for ResultSets created - * by this statement - */ - CallableStatement* prepareCall(const ODBCXX_STRING& sql, - int resultSetType, - int resultSetConcurrency); - - /** Translate a given SQL string into this data sources' own - * SQL grammar. - */ - ODBCXX_STRING nativeSQL(const ODBCXX_STRING& sql); - }; - - - -} // namespace odbc - - -#endif // __ODBCXX_CONNECTION_H diff --git a/source/odbc++/databasemetadata.h b/source/odbc++/databasemetadata.h deleted file mode 100644 index 85ab85910..000000000 --- a/source/odbc++/databasemetadata.h +++ /dev/null @@ -1,1349 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_DATABASEMETADATA_H -#define __ODBCXX_DATABASEMETADATA_H - -#include -#include -#include - -namespace odbc { - - class ResultSet; - class DriverInfo; - - /** Provides several tons of information about a data source. - * - * @warning The column names in ResultSets returned by methods of - * DatabaseMetaData can differ depending on what ODBC version - * the current driver supports. To avoid problems, columns should - * be referenced by number, and not by name. Also note that - * ODBC version 2 drivers do not return some of the specified - * columns. - */ - class ODBCXX_EXPORT DatabaseMetaData { - friend class Connection; - friend class DriverInfo; - - private: - Connection* connection_; - - DatabaseMetaData(Connection* c); - ~DatabaseMetaData(); - - const DriverInfo* _getDriverInfo() const { - return connection_->_getDriverInfo(); - } - - SQLUSMALLINT _getNumeric16(int what); - SQLUINTEGER _getNumeric32(int what); - - ODBCXX_STRING _getStringInfo(int what); - bool _ownXXXAreVisible(int type, int what); - -#if ODBCVER >= 0x0300 - // returns all CA1 or-ed together - SQLUINTEGER _getAllCursorAttributes1(); -#endif - - public: - - /** Returns the Connection this came from */ - Connection* getConnection() { - return connection_; - } - - /** Constants for the ResultSet returned by getBestRowIdentifier */ - enum { - bestRowTemporary = SQL_SCOPE_CURROW, - bestRowTransaction = SQL_SCOPE_TRANSACTION, - bestRowSession = SQL_SCOPE_SESSION - }; - - /** Constants for the ResultSet returned by getBestRowIdentifier */ - enum { - bestRowUnknown = SQL_PC_UNKNOWN, - bestRowPseudo = SQL_PC_PSEUDO, - bestRowNotPseudo = SQL_PC_NOT_PSEUDO - }; - - - /** Version column constants for getVersionColumns() - * @see #getVersionColumns() - */ - enum { - versionColumnNotPseudo = SQL_PC_NOT_PSEUDO, - versionColumnPseudo = SQL_PC_PSEUDO, - versionColumnUnknown = SQL_PC_UNKNOWN - }; - - - /** Nullability constants for the resultset returned by getTypes() - * @see getTypes() - */ - enum { - typeNoNulls = SQL_NO_NULLS, - typeNullable = SQL_NULLABLE, - typeNullableUnknown = SQL_NULLABLE_UNKNOWN - }; - - /** Nullability constants for the resultset returned by - * getColumns(). - * @see getColumns() - */ - enum { - columnNoNulls = SQL_NO_NULLS, - columnNullable = SQL_NULLABLE, - columnNullableUnknown = SQL_NULLABLE_UNKNOWN - }; - - /** Searchability constants */ - enum { - /** Column is unsearchable */ - typePredNone = SQL_UNSEARCHABLE, - /** Column can only be used in a LIKE clause */ - typePredChar = SQL_LIKE_ONLY, - /** Column can be used in searches, except in LIKE */ - typePredBasic = SQL_ALL_EXCEPT_LIKE, - /** Column is searchable */ - typeSearchable = SQL_SEARCHABLE - }; - - - /** Imported key UPDATE_RULE and DELETE_RULE constants. - * @see getImportedKeys() - */ -#if ODBCVER >= 0x0300 - enum { - importedKeyCascade = SQL_CASCADE, - importedKeySetNull = SQL_SET_NULL, - importedKeySetDefault = SQL_SET_DEFAULT, - importedKeyNoAction = SQL_NO_ACTION, - importedKeyRestrict = SQL_RESTRICT - }; -#else - // workaround mode on - enum { - importedKeyCascade = SQL_CASCADE, - importedKeySetNull = SQL_SET_NULL, - importedKeyRestrict = SQL_RESTRICT, - importedKeyNoAction = SQL_RESTRICT, - importedKeySetDefault - }; - -#endif - -#if ODBCVER >= 0x0300 -#if !defined(SQL_NOT_DEFERRABLE) -# warning "Your sqlext.h is missing SQL_NOT_DEFERRABLE, consider upgrading" -# define SQL_NOT_DEFERRABLE 7 -#endif - /** Imported key DEFERRABILITY constants */ - enum { - importedKeyInitiallyDeferred = SQL_INITIALLY_DEFERRED, - importedKeyInitiallyImmediate = SQL_INITIALLY_IMMEDIATE, - importedKeyNotDeferrable = SQL_NOT_DEFERRABLE - }; -#endif - - /** Index type constants */ - enum { - tableIndexClustered = SQL_INDEX_CLUSTERED, - tableIndexHashed = SQL_INDEX_HASHED, - tableIndexOther = SQL_INDEX_OTHER, - tableIndexStatistic = SQL_TABLE_STAT - }; - - /** Procedure column type constants for getProcedureColumns() - * @see #getProcedureColumns() - */ - enum { - procedureColumnIn = SQL_PARAM_INPUT, - procedureColumnInOut = SQL_PARAM_INPUT_OUTPUT, - procedureColumnOut = SQL_PARAM_OUTPUT, - procedureColumnResult = SQL_RESULT_COL, - procedureColumnReturn = SQL_RETURN_VALUE, - procedureColumnUnknown = SQL_PARAM_TYPE_UNKNOWN - }; - - /** Procedure column nullability constants for getProcedureColumns() - * @see #getProcedureColumns() - */ - enum { - procedureNoNulls = SQL_NO_NULLS, - procedureNullable = SQL_NULLABLE, - procedureNullableUnknown = SQL_NULLABLE_UNKNOWN - }; - - /** Procedure type constants for PROCEDURE_TYPE in getProcedures() - * @see #getProcedures() - */ - enum { - procedureReturnsResult = SQL_PT_FUNCTION, - procedureNoResult = SQL_PT_PROCEDURE, - procedureResultUnknown = SQL_PT_UNKNOWN - }; - - - - /** Returns the name of the database product. - */ - ODBCXX_STRING getDatabaseProductName(); - - /** Returns the version of the database product as a string. - */ - ODBCXX_STRING getDatabaseProductVersion(); - - /** Returns the name of the ODBC driver used. - */ - ODBCXX_STRING getDriverName(); - - /** Returns the version of the ODBC driver used. - */ - ODBCXX_STRING getDriverVersion(); - - /** Returns the major ODBC version of the driver used. */ - int getDriverMajorVersion(); - - /** Returns the minor ODBC version of the driver used. */ - int getDriverMinorVersion(); - - /** Returns the string that can be used to quote identifiers. - * If the data source doesn't support it, returns an empty string. - */ - ODBCXX_STRING getIdentifierQuoteString(); - - /** Returns the term for catalog used by the data source. - * Can be for example "directory" or "database". - */ - ODBCXX_STRING getCatalogTerm(); - - /** Returns the term for schema used by the data source, - * for example "owner" or just "schema". - */ - ODBCXX_STRING getSchemaTerm(); - - /** Returns the term for table used by the data source. - */ - ODBCXX_STRING getTableTerm(); - - /** Returns the term the data source uses for a procedure, - * for example "stored procedure". - */ - ODBCXX_STRING getProcedureTerm(); - - /** Returns the user name of the connection. - */ - ODBCXX_STRING getUserName(); - - /** Returns the string used to separate a catalog - * in a fully qualified identifier. - * - * For example Oracle would return a "@", while - * mysql would say ".". - */ - ODBCXX_STRING getCatalogSeparator(); - - /** Returns true if the catalog is positioned at the - * beginning of a fully qualified identifier. - * - * For example mysql would say true, while oracle would say false. - */ - bool isCatalogAtStart(); - - /** Returns a comma-separated list of all non-ODBC keywords specific - * to this data source. - */ - ODBCXX_STRING getSQLKeywords(); - - - /** Returns true if the data source supports transactions. - */ - bool supportsTransactions(); - - /** Returns the default transaction isolation level - * @see Connection - */ - int getDefaultTransactionIsolation(); - - /** Returns true if the data source supports the specified transaction - * isolation level. - * @param lev The isolation level to check for - */ - bool supportsTransactionIsolationLevel(int lev); - - /** Checks if the data source supports both DML and DDL in transactions - * - * @return true if the data source supports both data manipulation - * (eg. UPDATE, INSERT) and data definition - * (eg. CREATE TABLE) within a transaction. - * - * - * If this method returns true, - * supportsDataManipulationTransactionsOnly(), - * dataDefinitionCausesTransactionCommit() and - * dataDefinitionIgnoredInTransactions() all return false. - */ - bool supportsDataDefinitionAndDataManipulationTransactions(); - - /** Checks if the data source only supports DML in transactions - * - * @return true if the data source only supports data manipulation - * (eg. UPDATE, INSERT) within a transaction. - * - * Attempts to use data definition - * (eg. CREATE TABLE) in a transaction will trigger an - * error. - * - * If this method returns true, - * supportsDataDefinitionAndDataManipulationTransactions(), - * dataDefinitionCausesTransactionCommit() and - * dataDefinitionIgnoredInTransactions() all return false. - */ - bool supportsDataManipulationTransactionsOnly(); - - /** Checks if DDL in a transaction will cause the transaction to be committed - * - * @return true if the data source only supports data manipulation - * (eg. UPDATE, INSERT) within a transaction - * and any data definition (eg. CREATE TABLE) will cause - * the transaction to be committed. - * - * If this method returns true, - * supportsDataDefinitionAndDataManipulationTransactions(), - * supportsDataManipulationTransactionsOnly() and - * dataDefinitionIgnoredInTransactions() all return false. - */ - bool dataDefinitionCausesTransactionCommit(); - - /** Checks if DDL in a transaction is ignored - * - * @return true if the data source only supports data manipulation - * (eg. UPDATE, INSERT) within a transaction - * and any data definition (eg. CREATE TABLE) will be - * ignored. - * - * If this method returns true, - * supportsDataDefinitionAndDataManipulationTransactions(), - * supportsDataManipulationTransactionsOnly() and - * dataDefinitionCausesTransactionCommit() all return false. - */ - bool dataDefinitionIgnoredInTransactions(); - - - /** - */ - bool supportsTableCorrelationNames(); - - /** - */ - bool supportsDifferentTableCorrelationNames(); - - /** - */ - bool supportsOrderByUnrelated(); - - /** - */ - bool supportsExpressionsInOrderBy(); - - /** Returns true if the data source and the driver can handle - * open cursors (eg. ResultSets) across a commit, or false if - * they are invalidated. - */ - bool supportsOpenCursorsAcrossCommit(); - - - /** Returns true if the data source and the driver can handle - * open cursors (eg. ResultSets) across a rollback, or false if - * they are invalidated. - */ - bool supportsOpenCursorsAcrossRollback(); - - - /** Returns true if the data source and the driver can handle - * open statements across a commit, or false if - * they are invalidated. - */ - bool supportsOpenStatementsAcrossCommit(); - - /** Returns true if the data source and the driver can handle - * open statements across a rollback, or false if - * they are invalidated. - */ - bool supportsOpenStatementsAcrossRollback(); - - /** Returns true if the data source supports the given - * result set type. - * @param type The type to check for - * @see ResultSet - */ - bool supportsResultSetType(int type); - - /** Returns true if the data source supports the given - * result set concurrency for the given result set type. - * @param type The type to check for. - * @param concurrency The concurrency level to check for. - * @see ResultSet - */ - bool supportsResultSetConcurrency(int type, int concurrency); - - - /** Returns true if catalogs are supported in DML */ - bool supportsCatalogsInDataManipulation(); - - /** Returns true if catalogs are supported in procedure call statements */ - bool supportsCatalogsInProcedureCalls(); - - /** Returns true if catalogs are supported in CREATE/ALTER TABLE statements */ - bool supportsCatalogsInTableDefinitions(); - - /** Returns true if catalogs are supported in index definitions */ - bool supportsCatalogsInIndexDefinitions(); - - /** Returns true if catalogs are supported in privilege definition statements */ - bool supportsCatalogsInPrivilegeDefinitions(); - - - /** Returns true if schemas are supported in DML */ - bool supportsSchemasInDataManipulation(); - - /** Returns true if schemas are supported in procedure call statements */ - bool supportsSchemasInProcedureCalls(); - - /** Returns true if schemas are supported in CREATE/ALTER TABLE statements */ - bool supportsSchemasInTableDefinitions(); - - /** Returns true if schemas are supported in index definitions */ - bool supportsSchemasInIndexDefinitions(); - - /** Returns true if schemas are supported in privilege definition statements */ - bool supportsSchemasInPrivilegeDefinitions(); - - - /** Returns true if NULL plus a non-NULL value yields NULL. - */ - bool nullPlusNonNullIsNull(); - - /** Returns true if the data source supports column aliasing, for example - * SELECT COLUMN1 [AS] C1 FROM TABLE - */ - bool supportsColumnAliasing(); - - /** Returns true if the CONVERT function is supported by the data source. - */ - bool supportsConvert(); - - /** Returns true if CONVERT between fromType and toType is supported. - */ - bool supportsConvert(int fromType, int toType); - - /** Returns true if ALTER TABLE with drop column is supported. - */ - bool supportsAlterTableWithDropColumn(); - - /** Returns true if ALTER TABLE with add column is supported. - */ - bool supportsAlterTableWithAddColumn(); - - /** Returns the extra characters beyond A-Z, a-z, 0-9 and _ that can - * be used in unquoted identifier names. - */ - ODBCXX_STRING getExtraNameCharacters(); - - /** Returns the string that can be used to escape wildcard characters. - */ - ODBCXX_STRING getSearchStringEscape(); - - /** Returns a comma-separated list of all time and date functions supported. - */ - ODBCXX_STRING getTimeDateFunctions(); - - /** Returns a comma-separated list of all system functions supported. - */ - ODBCXX_STRING getSystemFunctions(); - - /** Returns a comma-separated list of all string functions supported. - */ - ODBCXX_STRING getStringFunctions(); - - /** Returns a comma-separated list of all numeric functions supported. - */ - ODBCXX_STRING getNumericFunctions(); - - /** Returns true if the escape character is supported in LIKE clauses. - */ - bool supportsLikeEscapeClause(); - - /** Returns true if a query can return multiple ResultSets. - */ - bool supportsMultipleResultSets(); - - /** Returns true if multiple transactions can be open at once - * on different connections. - */ - bool supportsMultipleTransactions(); - - /** Returns true if columns can be defined as non-nullable. - */ - bool supportsNonNullableColumns(); - - /** Returns true if the data source supports ODBC minimum SQL grammar. - */ - bool supportsMinimumSQLGrammar(); - - /** Returns true if the data source supports the core ODBC SQL grammar. - */ - bool supportsCoreSQLGrammar(); - - /** Returns true if the data source supports the ODBC extended SQL grammar. - */ - bool supportsExtendedSQLGrammar(); - - - /** Returns true if the data source supports the ANSI92 entry level - * SQL grammar. - */ - bool supportsANSI92EntryLevelSQL(); - - /** Returns true if the data source supports the ANSI92 intermediate level - * SQL grammar. - */ - bool supportsANSI92IntermediateSQL(); - - /** Returns true if the data source supports the full ANSI92 SQL grammar. - */ - bool supportsANSI92FullSQL(); - - /** Checks if the data source supports positioned delete - * - * @return true if ("DELETE WHERE CURRENT OF ...") - * is supported - */ - bool supportsPositionedDelete(); - - /** Checks if the data source supports positioned update - * - * @return true if ("UPDATE ... WHERE CURRENT OF ...") - * is supported - */ - bool supportsPositionedUpdate(); - - /** Checks if the data source supports - * - * @return true if ("SELECT ... FOR UPDATE") - * is supported - */ - bool supportsSelectForUpdate(); - - - /** Returns true if the data source supports the SQL Integrity - * Enhancement Facility. - */ - bool supportsIntegrityEnhancementFacility(); - - /** Whether the data source supports batch updates - */ - bool supportsBatchUpdates(); - - /** Returns true if the data source supports subqueries in comparisons - */ - bool supportsSubqueriesInComparisons(); - - /** Returns true if the data source supports subqueries in - * "EXISTS" expressions. - */ - bool supportsSubqueriesInExists(); - - /** Returns true if the data source supports subqueries in - * "IN" expressions. - */ - bool supportsSubqueriesInIns(); - - /** Returns true if the data source supports subqueries in - * quantified expressions. - */ - bool supportsSubqueriesInQuantifieds(); - - - /** Returns true if the data source supports correlated subqueries - */ - bool supportsCorrelatedSubqueries(); - - /** Returns true if updated rows are available with their new - * values in the ResultSet. - * @param type The type of ResultSet of interest - */ - bool ownUpdatesAreVisible(int type); - - /** Returns true if deleted rows dissapear from a ResultSet - * @param type The type of ResultSet of interest - */ - bool ownDeletesAreVisible(int type); - - /** Returns true if inserted rows become available in a ResultSet - * @param type The type of ResultSet of interest - */ - bool ownInsertsAreVisible(int type); - - /** Returns true if rows updated by others are visible - * with their new values. - * @param type The type of ResultSet of interest - */ - bool othersUpdatesAreVisible(int type); - - /** Returns true if rows deleted by others disapear - * from a ResultSet. - * @param type The type of ResultSet of interest - */ - bool othersDeletesAreVisible(int type); - - /** Returns true if rows inserted by others become available in - * a ResultSet. - * @param type The type of ResultSet of interest - */ - bool othersInsertsAreVisible(int type); - - /** Returns true if a deleted row can be detected with - * ResultSet::rowDeleted(). - * @param type The type of ResultSet of interest - */ - bool deletesAreDetected(int type); - - /** Returns true if an inserted row can be detected with - * ResultSet::rowInserted(). - * @param type The type of ResultSet of interest - */ - bool insertsAreDetected(int type); - - /** Returns true if ResultSet::rowUpdated can determine whether - * a row has been updated. - * @param type The type of ResultSet of interest - */ - bool updatesAreDetected(int type); - - - /** Returns the max number of hex characters allowed in an inline binary - * literal. - */ - int getMaxBinaryLiteralLength(); - - /** Returns the maximum length of an inline character string. - */ - int getMaxCharLiteralLength(); - - /** Returns the maximum length of a column name. - */ - int getMaxColumnNameLength(); - - /** Returns the maximum number of columns this data source can have in - * a GROUP BY clause. - */ - int getMaxColumnsInGroupBy(); - - /** Returns the maximum number of columns allowed in an index. - */ - int getMaxColumnsInIndex(); - - /** Returns the maximum number of columns this data source can have in - * an ORDER BY clause. - */ - int getMaxColumnsInOrderBy(); - - /** Returns the maximum number of columns this data source can SELECT. - */ - int getMaxColumnsInSelect(); - - /** Returns the maximum number of columns a table can consist of. - */ - int getMaxColumnsInTable(); - - /** Returns the maximum length of a cursor name. - */ - int getMaxCursorNameLength(); - - /** Returns the maximum length of an index in bytes. - */ - int getMaxIndexLength(); - - /** Returns the maximum length of a schema name. - */ - int getMaxSchemaNameLength(); - - /** Returns the maximum length of a procedure name. - */ - int getMaxProcedureNameLength(); - - /** Returns the maximum length of a catalog name. - */ - int getMaxCatalogNameLength(); - - /** Returns the maximum size of a row in bytes. - */ - int getMaxRowSize(); - - /** Returns true if the value returned by getMaxRowSize() includes - * BLOBs. - */ - bool doesMaxRowSizeIncludeBlobs(); - - - /** Returns the maximum length of a statement (query). - */ - int getMaxStatementLength(); - - /** Returns the maximum length of a table name. - */ - int getMaxTableNameLength(); - - /** Returns the maximum number of tables that can be joined at once. - * @return zero if unknown. - */ - int getMaxTablesInSelect(); - - /** Returns the maximum length of a username. - */ - int getMaxUserNameLength(); - - /** Returns the maximum number of connections we can have open - * to this data source. - */ - int getMaxConnections(); - - /** Returns the maximim number of statements that can be open - * on this connection. - */ - int getMaxStatements(); - - - /** Returns true if the data source supports case sensitive - * mixed case identifiers. - */ - bool supportsMixedCaseIdentifiers(); - - /** Returns true if the data source supports case sensitive - * mixed case quoted identifiers. - */ - bool supportsMixedCaseQuotedIdentifiers(); - - /** Returns true if the data source supports some form of - * stored procedures. - */ - bool supportsStoredProcedures(); - - - /** Returns true if the data source supports the - * GROUP BY clause. - */ - bool supportsGroupBy(); - - /** Returns true if the columns in a GROUP BY clause are independent - * of the selected ones. - */ - bool supportsGroupByUnrelated(); - - /** Returns true if the columns in a GROUP BY don't have to be - * selected. - */ - bool supportsGroupByBeyondSelect(); - - - /** Returns true if the data source supports UNION joins. - */ - bool supportsUnion(); - - /** Returns true if the data source supports UNION ALL joins. - */ - bool supportsUnionAll(); - - /** Returns true if the data source supports some form of - * outer joins. - */ - bool supportsOuterJoins(); - - /** Returns true if the data source fully supports outer joins. - */ - bool supportsFullOuterJoins(); - - /** Returns true if the data source only supports certain types of - * outer joins. - */ - bool supportsLimitedOuterJoins(); - - /** Returns true if the data source uses a file for each table */ - bool usesLocalFilePerTable(); - - /** Returns true if the data source uses local files */ - bool usesLocalFiles(); - - /** Returns true if NULL values are sorted first, regardless of - * the sort order. - */ - bool nullsAreSortedAtStart(); - - /** Returns true if NULL values are sorted last, regardless of - * the sort order. - */ - bool nullsAreSortedAtEnd(); - - /** Returns true if NULL values are sorted high. - */ - bool nullsAreSortedHigh(); - - /** Returns true if NULL values are sorted low. - */ - bool nullsAreSortedLow(); - - /** Returns true if all procedures returned by getProcedures() are callable - * by the current user. - */ - bool allProceduresAreCallable(); - - /** Returns true if all tables returned by getTables() are selectable by - * the current user. - */ - bool allTablesAreSelectable(); - - /** Returns true if the data source or the current connection is in - * read-only mode. - */ - bool isReadOnly(); - - /** Returns true if the data source treats identifiers as case - * insensitive and stores them in lower case. - */ - bool storesLowerCaseIdentifiers(); - - /** Returns true if the data source treats quoted identifiers as case - * insensitive and stores them in lower case. - */ - bool storesLowerCaseQuotedIdentifiers(); - - /** Returns true if the data source treats identifiers as case - * insensitive and stores them in mixed case. - */ - bool storesMixedCaseIdentifiers(); - - /** Returns true if the data source treats quoted identifiers as case - * insensitive and stores them in mixed case. - */ - bool storesMixedCaseQuotedIdentifiers(); - - /** Returns true if the data source treats identifiers as case - * insensitive and stores them in upper case. - */ - bool storesUpperCaseIdentifiers(); - - /** Returns true if the data source treats quoted identifiers as case - * insensitive and stores them in upper case. - */ - bool storesUpperCaseQuotedIdentifiers(); - - - /** Fetches a list of data types supported by this data source. - * - * The returned ResultSet is ordered by DATA_TYPE and then - * by how closely the type maps to the corresponding ODBC SQL type. - * It contains the following columns: - *
    - *
  1. TYPE_NAME - string - native type name - *
  2. DATA_TYPE - short - SQL data type from Types - *
  3. COLUMN_SIZE - int - maximum precision - *
  4. LITERAL_PREFIX - string - prefix used to quote a literal. - * Can be NULL. - *
  5. LITERAL_SUFFIX - string - suffix used to quote a literal. - * Can be NULL. - *
  6. CREATE_PARAMS - string - comma separated possible list of - * parameters to creating a column of this type - *
  7. NULLABLE - short - whether this type can contain NULLs: - *
      - *
    • typeNoNulls - no - *
    • typeNullable - yes, can be nullable - *
    • typeNullableUnknown - nobody knows - *
    - *
  8. CASE_SENSITIVE - bool - whether this type is case sensitive - *
  9. SEARCHABLE - bool - whether this type can be searched, eg - * used in WHERE-clauses: - *
      - *
    • typePredNone - no - *
    • typePredChar - yes, but only with a LIKE - * predicate - *
    • typePredBasic - yes, except in a LIKE - * predicate - *
    • typeSearchable - yes - *
    - *
  10. UNSIGNED_ATTRIBUTE - bool - true if this type is unsigned - *
  11. FIXED_PREC_SCALE - bool - whether this type has predefined fixed - * precision and scale (eg is useful for money) - *
  12. AUTO_UNIQUE_VALUE - bool - whether this type can be used for an - * autoincrementing value. NULL if not applicable. - *
  13. LOCAL_TYPE_NAME - string - localized native type name. Can be - * NULL. - *
  14. MINIMUM_SCALE - short - minimum supported scale, if applicable - *
  15. MAXIMUM_SCALE - short - maximum supported scale, if applicable - *
  16. SQL_DATA_TYPE - short - unused - *
  17. SQL_DATETIME_SUB - short - unused - *
  18. NUM_PREC_RADIX - int - radix, if applicable - *
- */ - ResultSet* getTypeInfo(); - - /** Fetches the available columns in a catalog. - * - * The returned ResultSet has the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. COLUMN_NAME - string - column name - *
  5. COLUMN_TYPE - short - see Types - *
  6. TYPE_NAME - string - the name of the type. Data source - * dependent. - *
  7. COLUMN_SIZE - int - column size. For character and date - * types, this is the maximum number of characters. For numeric types - * this is the precision. - *
  8. BUFFER_LENGTH - not used - *
  9. DECIMAL_DIGITS - int - the number of fractional digits. - *
  10. NUM_PREC_RADIX - int - radix - *
  11. NULLABLE - int - whether the column allows NULLs - *
      - *
    • columnNoNulls - might not allow NULLs - *
    • columnNullable - definitely allows NULLs - *
    • columnNullableUnknown - nullability is unknown - *
    - *
  12. REMARKS - string - comments on the column (can be NULL) - *
  13. COLUMN_DEF - string - default value (can be NULL) - *
  14. SQL_DATA_TYPE - short - - *
  15. SQL_DATETIME_SUB - short - - *
  16. CHAR_OCTET_LENGTH - int - for character data types the maximum - * number of bytes in the column - *
  17. ORDINAL_POSITION - int - 1-based index in the table - *
  18. IS_NULLABLE - string - "NO" means in no way - * nullable, "YES" means possibly nullable. Empty string means - * nobody knows. - *
- */ - ResultSet* getColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schemaPattern, - const ODBCXX_STRING& tableNamePattern, - const ODBCXX_STRING& columnNamePattern); - - - /** Fetches the available tables in the data source. - * The returned ResultSet has the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. TABLE_TYPE - string - table type - *
  5. REMARKS - string - comments on the table - *
- * @param catalog the catalog name - * @param schemaPattern schema name search pattern - * @param tableNamePattern table name search pattern - * @param types a list of table types. An empty list returns all table types. - */ - ResultSet* getTables(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schemaPattern, - const ODBCXX_STRING& tableNamePattern, - const std::vector& types); - - /** Fetches a list of access rights for tables in a catalog. - * - * A table privilege applies to one or more columns in a table. - * Do not assume that this privilege is valid for all columns. - * - * The returned ResultSet is ordered by - * TABLE_CAT, TABLE_SCHEM, TABLE_NAME - * and PRIVILEGE. It contains the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. GRANTOR - string - grantor (can be NULL). If - * GRANTEE owns the object, GRANTOR is - * "SYSTEM". - *
  5. GRANTEE - string - grantee - *
  6. PRIVILEGE - string - one of "SELECT", - * "INSERT", "UPDATE", "DELETE", - * "REFERENCES" or a data source specific value - *
  7. IS_GRANTABLE - string - "YES" if GRANTEE - * can grant this privilege to other users. "NO" if not. - * NULL if unknown. - *
- */ - ResultSet* getTablePrivileges(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schemaPattern, - const ODBCXX_STRING& tableNamePattern); - - - /** Fetches a list of access rights for a table's columns. - * - * The returned ResultSet is ordered by - * COLUMN_NAME and PRIVILEGE. - * It contains the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. COLUMN_NAME - string - column name - *
  5. GRANTOR - string - grantor (can be NULL). If - * GRANTEE owns the object, GRANTOR is - * "SYSTEM". - *
  6. GRANTEE - string - grantee - *
  7. PRIVILEGE - string - one of "SELECT", - * "INSERT", "UPDATE", "DELETE", - * "REFERENCES" or a data source specific value - *
  8. IS_GRANTABLE - string - "YES" if GRANTEE - * can grant this privilege to other users. "NO" if not. - * NULL if unknown. - *
- */ - ResultSet* getColumnPrivileges(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table, - const ODBCXX_STRING& columnNamePattern); - - /** Fetches a list of primary keys for a table. - * - * The returned ResultSet is ordered by - * TABLE_CAT, TABLE_SCHEM, TABLE_NAME - * and KEY_SEQ. It contains the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. COLUMN_NAME - string - column name - *
  5. KEY_SEQ - string - sequence number in primary key (1-based) - *
  6. PK_NAME - string - primary key (constraint) name. - * Can be NULL. - *
- */ - ResultSet* getPrimaryKeys(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table); - - - /** Fetches a list of indices and statistics for a table. - * - * The returned ResultSet is ordered by - * NON_UNIQUE, TYPE, INDEX_QUALIFIER, - * INDEX_NAME and ORDINAL_POSITION. - * It contains the following columns: - *
    - *
  1. TABLE_CAT - string - table catalog (can be NULL) - *
  2. TABLE_SCHEM - string - table schema (can be NULL) - *
  3. TABLE_NAME - string - table name - *
  4. NON_UNIQUE - bool - true if index values can - * be non-unique. NULL if TYPE is - * tableIndexStatistic - *
  5. INDEX_QUALIFIER - string - index catalog, NULL - * if TYPE is tableIndexStatistic - *
  6. INDEX_NAME - string - index name, NULL - * if TYPE is tableIndexStatistic - *
  7. TYPE - short - index type: - *
      - *
    • tableIndexStatistic - no real index - a statistic for the table - *
    • tableIndexClustered - this index is clustered - *
    • tableIndexHashed - this index is hashed - *
    • tableIndexOther - this is some other kind of index - *
    - *
  8. ORDINAL_POSITION - short - column sequence number in index (1-based). - * NULL if TYPE is tableIndexStatistic. - *
  9. COLUMN_NAME - string - column name. - * NULL if TYPE is tableIndexStatistic. - *
  10. ASC_OR_DESC - string - "A" for ascending, - * "D" for descending index. NULL if TYPE - * is tableIndexStatistic. - *
  11. CARDINALITY - int - If TYPE is - * tableIndexStatistic, the number of rows in the - * table. Otherwise, the number of unique values in the index. - *
  12. PAGES - int - Number of pages used for the table if - * TYPE is tableIndexStatistic. Otherwise - * the number of pages used for the index. - *
  13. FILTER_CONDITION - string - filter condition (if any) - *
- * @param catalog the catalog name - * @param schema the schema name - * @param table the table name - * @param unique whether only unique indices should be looked at - * @param approximate whether only accurate values should be retrieved - */ - ResultSet* getIndexInfo(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table, - bool unique, bool approximate); - - /** Figures out in which way a foreign key table references a - * primary key table. Returns it's findings in a ResultSet, ordered - * by FKTABLE_CAT, FKTABLE_SCHEM, - * FKTABLE_NAME and KEY_SEQ. The - * ResultSet contains the following columns: - *
    - *
  1. PKTABLE_CAT - string - primary key table catalog - *
  2. PKTABLE_SCHEM - string - primary key table schema - *
  3. PKTABLE_NAME - string - primary key table name - *
  4. PKCOLUMN_NAME - string - primary key column name - *
  5. FKTABLE_CAT - string - foreign key table catalog - *
  6. FKTABLE_SCHEM - string - foreign key table schema - *
  7. FKTABLE_NAME - string - foreign key table name - *
  8. FKCOLUMN_NAME - string - foreign key column name - *
  9. KEY_SEQ - short - column sequence number in key (1-based) - *
  10. UPDATE_RULE - short - what happens to the foreign key - * when the primary is updated: - *
      - *
    • importedKeyNoAction - nothing happends since - * the primary key can not be updated - *
    • importedKeyCascade - change imported key to - * match the primary key - *
    • importedKeySetNull - update the imported key to - * NULL - *
    • importedKeySetDefault - update the impored key to - * it's default value - *
    • importedKeyRestrict - same as - * importedKeyNoAction - *
    - *
  11. DELETE_RULE - short - what happens to the foreign key - * when the primary is deleted: - *
      - *
    • importedKeyNoAction - nothing happends since - * the primary key can not be deleted - *
    • importedKeyCascade - imported key is deleted as well - *
    • importedKeySetNull - imported key is set - * to NULL - *
    • importedKeySetDefault - imported key is set to it's - * default value - *
    • importedKeyRestrict - same as - * importedKeyNoAction - *
    - *
- */ - ResultSet* getCrossReference(const ODBCXX_STRING& primaryCatalog, - const ODBCXX_STRING& primarySchema, - const ODBCXX_STRING& primaryTable, - const ODBCXX_STRING& foreignCatalog, - const ODBCXX_STRING& foreignSchema, - const ODBCXX_STRING& foreignTable); - - /** Fetches a list of columns that are foreign keys to other tables' - * primary keys. - * - * The returned ResultSet is identical to the one - * returned by getCrossReference(), except it's ordered by - * PKTABLE_CAT, PKTABLE_SCHEM, - * PKTABLE_NAME and KEY_SEQ. - */ - ResultSet* getImportedKeys(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table) { - return this->getCrossReference(ODBCXX_STRING_CONST(""), - ODBCXX_STRING_CONST(""), - ODBCXX_STRING_CONST(""), - catalog, - schema, - table); - } - - /** Fetches a list of columns that reference a table's primary - * keys. - * - * The returned ResultSet is identical to the one returned - * by getCrossReference(). - */ - ResultSet* getExportedKeys(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table) { - return this->getCrossReference(catalog, - schema, - table, - ODBCXX_STRING_CONST(""), - ODBCXX_STRING_CONST(""), - ODBCXX_STRING_CONST("")); - } - - /** Returns available procedures in a catalog. - * - * The returned ResultSet is ordered by - * PROCEDURE_CAT, PROCEDURE_SCHEM and - * PROCEDURE_NAME. It contains the following columns: - *
    - *
  1. PROCEDURE_CAT - string - the procedure catalog - *
  2. PROCEDURE_SCHEM - string - the procedure schema - *
  3. PROCEDURE_NAME - string - the procedure name - *
  4. NUM_INPUT_PARAMS - reserved for future use - *
  5. NUM_OUTPUT_PARAMS - reserved for future use - *
  6. NUM_RESULT_SETS - reserved for future use - *
  7. REMARKS - string - comments on the procedure - *
  8. PROCEDURE_TYPE - short - the procedure type: - *
      - *
    • procedureResultUnknown - can possibly return - * a result, but nobody is sure - *
    • procedureNoResult - does not return a result - *
    • procedureReturnsResult - returns a result - *
    - *
- */ - ResultSet* getProcedures(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schemaPattern, - const ODBCXX_STRING& procedureNamePattern); - - /** Returns available procedure columns in a catalog. - * - * The returned ResultSet is ordered by - * PROCEDURE_CAT, PROCEDURE_SCHEM, - * PROCEDURE_NAME and COLUMN_NAME. - * It contains the following columns: - *
    - *
  1. PROCEDURE_CAT - string - the procedure catalog - *
  2. PROCEDURE_SCHEM - string - the procedure schema - *
  3. PROCEDURE_NAME - string - the procedure name - *
  4. COLUMN_NAME - string - the column name - *
  5. COLUMN_TYPE - short - the column type - *
      - *
    • procedureColumnUnknown - beats the driver - *
    • procedureColumnIn - IN parameter - *
    • procedureColumnInOut - IN OUT parameter - *
    • procedureColumnOut - OUT parameter - *
    • procedureColumnReturn - procedure return value - * (eg. this procedure is actually a function) - *
    • procedureColumnResult - this column is part of a - * ResultSet this procedure returns - *
    - *
  6. DATA_TYPE - int - SQL type of the column - *
  7. TYPE_NAME - string - native type name - *
  8. COLUMN_SIZE - int - the precision of the column - *
  9. BUFFER_LENGTH - int - nothing of interest - *
  10. DECIMAL_DIGITS - short - scale, if applicable - *
  11. NUM_PREC_RADIX - short - radix, if applicable - *
  12. NULLABLE - short - whether the column is nullable - *
      - *
    • procedureNoNulls - not nullable - *
    • procedureNullable - nullable - *
    • procedureNullableUnknown - nobody knows - *
    - *
  13. REMARKS - string - comments on the column - *
- * - * Note: more columns can be returned depending on the driver. - */ - ResultSet* getProcedureColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schemaPattern, - const ODBCXX_STRING& procedureNamePattern, - const ODBCXX_STRING& columnNamePattern); - - - /** Returns the optimal set of columns that identifies a row. - * - * The returned ResultSet is ordered by SCOPE and has - * the following columns: - *
    - *
  1. SCOPE - short - scope of this result: - *
      - *
    • bestRowTemporary - temporary, only while - * a ResultSet is using the row - *
    • bestRowTransaction - valid until the - * current transaction ends - *
    • bestRowSession - valid through the whole - * session - until the connection is closed - *
    - *
  2. COLUMN_NAME - string - the column name - *
  3. DATA_TYPE - short - the type of the column from Types - *
  4. TYPE_NAME - string - native type name (data source dependent) - *
  5. COLUMN_SIZE - int - the size (precision) of the column. - *
  6. BUFFER_LENGTH - int - unused - *
  7. DECIMAL_DIGITS - short - scale if applicable. - * Can be NULL. - *
  8. PSEUDO_COLUMN - short - whether this is a pseudo column: - *
      - *
    • bestRowUnknown - it is unknown whether this is a pseudo - * column - *
    • bestRowNotPseudo - it is definitely not a pseudo column - *
    • bestRowPseudo - it is definitely a pseudo column - *
    - *
- * @param catalog the catalog name - * @param schema the schema name - * @param table the table name - * @param scope the scope of interest, same values as the SCOPE column. - * @param nullable whether nullable columns should be included - */ - ResultSet* getBestRowIdentifier(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table, - int scope, - bool nullable); - - /** Returns a list of columns for a table that are automatically updated - * when anything in a row is updated. - * - * The returned ResultSet has the following unordered columns: - *
    - *
  1. SCOPE - short - unused - *
  2. COLUMN_NAME - string - the column name - *
  3. DATA_TYPE - short - the type of the column from Types - *
  4. TYPE_NAME - string - native type name (data source dependent) - *
  5. COLUMN_SIZE - int - the size (precision) of the column. - *
  6. BUFFER_LENGTH - int - unused - *
  7. DECIMAL_DIGITS - short - scale if applicable. - * Can be NULL. - *
  8. PSEUDO_COLUMN - short - whether this is a pseudo column: - *
      - *
    • versionColumnUnknown - it is unknown whether this is a pseudo - * column - *
    • versionColumnNotPseudo - it is definitely not a pseudo column - *
    • versionColumnPseudo - it is definitely a pseudo column - *
    - *
- */ - ResultSet* getVersionColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table); - - - - /** Fetches the table types the database supports. - * - * The returned ResultSet is the same as with getTables(), except - * that all columns but TABLE_TYPE contain NULL values. - */ - ResultSet* getTableTypes(); - - /** Returns a list of available schemas in the database. - * - * The returned ResultSet is the same as with getTables(), except - * that all columns but TABLE_SCHEM contain NULL values. - */ - ResultSet* getSchemas(); - - /** Returns a list of available catalogs in the database. - * - * The returned ResultSet is the same as with getTables(), except - * that all columns but TABLE_CAT are NULL values. - */ - ResultSet* getCatalogs(); - }; - - -} // namespace odbc - - -#endif // __ODBCXX_DATABASEMETADATA_H diff --git a/source/odbc++/drivermanager.h b/source/odbc++/drivermanager.h deleted file mode 100644 index ca6fc6845..000000000 --- a/source/odbc++/drivermanager.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_DRIVERMANAGER_H -#define __ODBCXX_DRIVERMANAGER_H - -#include - -#include - -/** The namespace where all libodbc++ classes reside */ -namespace odbc { - - class Connection; - class ErrorHandler; - - /** An ODBC Driver with it's information. - */ - class ODBCXX_EXPORT Driver { - private: - ODBCXX_STRING description_; - std::vector attributes_; - - Driver(const Driver&); //forbid - Driver& operator=(const Driver&); //forbid - - public: - /** Constructor */ - Driver(const ODBCXX_STRING& description, - const std::vector& attributes) - :description_(description), attributes_(attributes) {} - - /** Destructor */ - virtual ~Driver() {} - - /** Return a description of the driver */ - const ODBCXX_STRING& getDescription() const { - return description_; - } - - /** Return a list of keys that can appear in a connect string using this driver */ - const std::vector& getAttributes() const { - return attributes_; - } - }; - - /** A list of Drivers. Actually an STL vector */ - typedef CleanVector DriverList; - - - /** A Data Source */ - class ODBCXX_EXPORT DataSource { - private: - ODBCXX_STRING name_; - ODBCXX_STRING description_; - - public: - /** Constructor */ - DataSource(const ODBCXX_STRING& name, const ODBCXX_STRING& description) - :name_(name), description_(description) {} - - /** Destructor */ - virtual ~DataSource() {} - - /** Return the name of the data source */ - const ODBCXX_STRING& getName() const { - return name_; - } - - /** Return the description (if any) of the datasource */ - const ODBCXX_STRING& getDescription() const { - return description_; - } - }; - - /** A list of datasources. Behaves like an std::vector */ - typedef CleanVector DataSourceList; - - - /** The DriverManager. - */ - class ODBCXX_EXPORT DriverManager { - private: - static SQLHENV henv_; - static ErrorHandler* eh_; - static int loginTimeout_; - - static void _checkInit(); - static Connection* _createConnection(); - - // forbid - DriverManager(); - - public: - - /** Opens a connection by it's DSN, a username and a password */ - static Connection* getConnection(const ODBCXX_STRING& dsn, - const ODBCXX_STRING& user, - const ODBCXX_STRING& password); - - /** Opens a connection using an ODBC connect string. - * @param connectString Usually something like "DSN=db;uid=user;pwd=password" - */ - static Connection* getConnection(const ODBCXX_STRING& connectString); - - /** Gets the current login timeout in seconds. - * @return The current login timeout in seconds, or 0 if disabled. - */ - static int getLoginTimeout(); - - /** Sets the login timeout in seconds - * @param seconds The number of seconds to wait for a connection - * to open. Set to 0 to disable. - */ - static void setLoginTimeout(int seconds); - - /** Fetch a list of all available data sources - */ - static DataSourceList* getDataSources(); - - /** Fetch a list of the available drivers - */ - static DriverList* getDrivers(); - - /** Should be called before an application is to exit - * and after all connections have been closed. - */ - static void shutdown(); - }; - - - -} // namespace odbc - - -#endif // __ODBCXX_DRIVERMANAGER_H diff --git a/source/odbc++/errorhandler.h b/source/odbc++/errorhandler.h deleted file mode 100644 index 35b3325fd..000000000 --- a/source/odbc++/errorhandler.h +++ /dev/null @@ -1,136 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_ERRORHANDLER_H -#define __ODBCXX_ERRORHANDLER_H - -#include -#include -#include - -namespace odbc { - - /** Base class for everything that might contain warnings */ - class ODBCXX_EXPORT ErrorHandler { - friend class DriverManager; - friend class DataStreamBuf; - friend class DataStream; - private: - // private data - struct PD; - PD* pd_; - - WarningList* warnings_; - bool collectWarnings_; - - //the maxumum number of warnings to contain at a time - enum { - MAX_WARNINGS=128 - }; - - protected: - void _postWarning(SQLWarning* w); - - -#if ODBCVER < 0x0300 - void _checkErrorODBC2(SQLHENV henv, - SQLHDBC hdbc, - SQLHSTMT hstmt, - SQLRETURN r, - const ODBCXX_STRING& what); -#else - - void _checkErrorODBC3(SQLINTEGER handleType, - SQLHANDLE h, - SQLRETURN r, const ODBCXX_STRING& what); -#endif //ODBCVER < 0x0300 - - void _checkStmtError(SQLHSTMT hstmt, - SQLRETURN r, const ODBCXX_CHAR_TYPE* what=ODBCXX_STRING_CONST("")) { - - if(r==SQL_SUCCESS_WITH_INFO || r==SQL_ERROR) { -#if ODBCVER < 0x0300 - - this->_checkErrorODBC2(SQL_NULL_HENV, SQL_NULL_HDBC, hstmt, - r,ODBCXX_STRING_C(what)); -#else - - this->_checkErrorODBC3(SQL_HANDLE_STMT,hstmt,r,ODBCXX_STRING_C(what)); - -#endif - } - } - - void _checkConError(SQLHDBC hdbc, - SQLRETURN r, - const ODBCXX_CHAR_TYPE* what=ODBCXX_STRING_CONST("")) { - if(r==SQL_SUCCESS_WITH_INFO || r==SQL_ERROR) { -#if ODBCVER < 0x0300 - - this->_checkErrorODBC2(SQL_NULL_HENV, hdbc, SQL_NULL_HSTMT, r, - ODBCXX_STRING_C(what)); - -#else - - this->_checkErrorODBC3(SQL_HANDLE_DBC, hdbc, r, ODBCXX_STRING_C(what)); - -#endif - } - } - - void _checkEnvError(SQLHENV henv, - SQLRETURN r, - const ODBCXX_CHAR_TYPE* what=ODBCXX_STRING_CONST("")) { - if(r==SQL_SUCCESS_WITH_INFO || r==SQL_ERROR) { -#if ODBCVER < 0x0300 - - this->_checkErrorODBC2(henv,SQL_NULL_HDBC,SQL_NULL_HSTMT,r, - ODBCXX_STRING_C(what)); - -#else - - this->_checkErrorODBC3(SQL_HANDLE_ENV,henv,r,ODBCXX_STRING_C(what)); - -#endif - } - } - - /** Constructor */ - ErrorHandler(bool collectWarnings =true); - - public: - /** Clears all the warnings stored in this object */ - void clearWarnings(); - - /** Fetches all the warnings in this object. - * The caller is responsive for deleteing the - * returned object. - */ - WarningList* getWarnings(); - - /** Destructor */ - virtual ~ErrorHandler(); - }; - - -} // namespace odbc - -#endif diff --git a/source/odbc++/preparedstatement.h b/source/odbc++/preparedstatement.h deleted file mode 100644 index 1abe38655..000000000 --- a/source/odbc++/preparedstatement.h +++ /dev/null @@ -1,222 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - - -#ifndef __ODBCXX_PREPAREDSTATEMENT_H -#define __ODBCXX_PREPAREDSTATEMENT_H - -#include -#include -#include - -#if defined(ODBCXX_HAVE_ISO_CXXLIB) -# include -#else -# include -#endif - -namespace odbc { - - class Rowset; - - /** A prepared statement. - * - * A prepared statement is precompiled by the driver and/or datasource, - * and can be executed multiple times with different parameters. - * - * Parameters are set using the setXXX methods. Note that it's advisable - * to use the set method compatible with the parameter's SQL type - for - * example, for a Types::DATE, setDate() should - * be used. - * Question marks ("?") are used in the SQL statement - * to represent a parameter, for example: - *
-   * std::auto_ptr<PreparedStatement> pstmt
-   *    =std::auto_ptr<PreparedStatement>(con->prepareStatement
-   *    ("INSERT INTO SOMETABLE(AN_INTEGER_COL,A_VARCHAR_COL) VALUES(?,?)"));
-   * pstmt->setInt(1,10);
-   * pstmt->setString(2,"Hello, world!");
-   * int affectedRows=pstmt->executeUpdate();
-   * 
- * @see Connection::prepareStatement() - */ - - class ODBCXX_EXPORT PreparedStatement : public Statement { - friend class Connection; - - private: - void _prepare(); - void _setupParams(); - - protected: - ODBCXX_STRING sql_; - //here we store the parameters - Rowset* rowset_; - size_t numParams_; - std::vector directions_; - int defaultDirection_; - bool paramsBound_; - - PreparedStatement(Connection* con, - SQLHSTMT hstmt, - const ODBCXX_STRING& sql, - int resultSetType, - int resultSetConcurrency, - int defaultDirection =SQL_PARAM_INPUT); - - void _bindParams(); - void _unbindParams(); - - void _checkParam(int idx, - int* allowed, int numAllowed, - int defPrec, int defScale); - - public: - /** Destructor */ - virtual ~PreparedStatement(); - - /** Clears the parameters. - * - * The set of parameters stays around until they are set again. - * To explicitly clear them (and thus release buffers held by the - * driver), this method should be called. - */ - void clearParameters(); - - /** Executes this statement. - * @return True if the result is a ResultSet, false if it's an - * update count or unknown. - */ - bool execute(); - - /** Executes this statement, assuming it returns a ResultSet. - * - * Example: - * std::auto_ptr<ResultSet> rs = - * std::auto_ptr<ResultSet>(pstmt->executeQuery(s)); - * - */ - ResultSet* executeQuery(); - - /** Executes this statement, assuming it returns an update count */ - int executeUpdate(); - - /** Sets a parameter value to a double - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setDouble(int idx, double val); - - /** Sets a parameter value to a bool - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setBoolean(int idx, bool val); - - /** Sets a parameter value to signed char - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setByte(int idx, signed char val); - - - /** Sets a parameter value to a chunk of bytes - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setBytes(int idx, const ODBCXX_BYTES& val); - - /** Sets a parameter value to a Date - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setDate(int idx, const Date& val); - - /** Sets a parameter value to a float - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setFloat(int idx, float val); - - - /** Sets a parameter value to an int - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setInt(int idx, int val); - - /** Sets a parameter value to a Long - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setLong(int idx, Long val); - - /** Sets a parameter value to a short - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setShort(int idx, short val); - - /** Sets a parameter value to a string - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setString(int idx, const ODBCXX_STRING& val); - - /** Sets a parameter value to a Time - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setTime(int idx, const Time& val); - - /** Sets a parameter value to a Timestamp - * @param idx The parameter index, starting at 1 - * @param val The value to set - */ - void setTimestamp(int idx, const Timestamp& val); - - /** Sets a parameter value to an ascii stream. - * @param idx The parameter index, starting at 1 - * @param s The stream to assign - * @param len The number of bytes available in the stream - */ - void setAsciiStream(int idx, ODBCXX_STREAM* s, int len); - - /** Sets a parameter value to a binary stream. - * @param idx The parameter index, starting at 1 - * @param s The stream to assign - * @param len The number of bytes available in the stream - */ - void setBinaryStream(int idx, ODBCXX_STREAM* s, int len); - - - /** Sets a parameter value to NULL - * @param idx The parameter index, starting at 1 - * @param sqlType The SQL type of the parameter - * @see Types - */ - void setNull(int idx, int sqlType); - }; - - -} // namespace odbc - -#endif // __ODBCXX_PREPAREDSTATEMENT_H diff --git a/source/odbc++/resultset.h b/source/odbc++/resultset.h deleted file mode 100644 index 38174e092..000000000 --- a/source/odbc++/resultset.h +++ /dev/null @@ -1,625 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_RESULTSET_H -#define __ODBCXX_RESULTSET_H - -#include -#include -#include -#include - - -namespace odbc { - - class ResultSetMetaData; - class Statement; - class Rowset; - - /** A result set */ - class ODBCXX_EXPORT ResultSet : public ErrorHandler { - friend class Statement; - friend class ResultSetMetaData; - - private: - Statement* statement_; - SQLHSTMT hstmt_; - bool ownStatement_; - - - int currentFetchSize_; - int newFetchSize_; - - Rowset* rowset_; - SQLUSMALLINT* rowStatus_; - SQLUINTEGER rowsInRowset_; - - //tells us if the columns are bound right now - bool colsBound_; - bool streamedColsBound_; - - //the position in the rowset last time we did a bind - unsigned int bindPos_; - - //meta data - it's always there since we need info from it - ResultSetMetaData* metaData_; - - int location_; - - bool lastWasNull_; - - int rowBeforeInsert_; - int locBeforeInsert_; - - ResultSet(Statement* stmt,SQLHSTMT hstmt, bool ownStmt); - - //driver info - const DriverInfo* _getDriverInfo() const { - return statement_->_getDriverInfo(); - } - - //private utils - void _applyFetchSize(); - //this makes sure there is a rowset - void _resetRowset(); - - //this should be called before any call to SQLExtendedFetch - void _prepareForFetch(); - //this performs a possibly scrolled fetch with fetchType to rownum - void _doFetch(int fetchType, int rowNum); - - //this should be called after the position in the rowset changes - SQLRETURN _applyPosition(int mode =SQL_POSITION); - - //these bind/unbind all non-streamed columns - void _bindCols(); - void _unbindCols(); - - //these bind/unbind all streamed columns - void _bindStreamedCols(); - void _unbindStreamedCols(); - - //this sends all needed data from streamed columns - //to be called from insertRow and updateRow - void _handleStreams(SQLRETURN r); - - - public: - /** Destructor */ - virtual ~ResultSet(); - - //remember to update DatabaseMetaData when changing those values - - /** ResultSet concurrency constants. - */ - enum { - /** The ResultSet is read only */ - CONCUR_READ_ONLY, - /** The ResultSet is updatable */ - CONCUR_UPDATABLE - }; - - - /** ResultSet type constants - */ - enum { - /** The result set only goes forward. */ - TYPE_FORWARD_ONLY, - /** The result set is scrollable, but the data in it is not - * affected by changes in the database. - */ - TYPE_SCROLL_INSENSITIVE, - /** The result set is scrollable and sensitive to database changes */ - TYPE_SCROLL_SENSITIVE - }; - - /** Moves the cursor to a specific row in this result set. - * If row is negative, the actual row number is calculated from the - * end of the result set. Calling absolute(0) is - * equivalent to calling beforeFirst() - * @return true if the cursor is in the result set - */ - bool absolute(int row); - - /** Moves the cursor inside the result set relative to the current row. - * Negative values are allowed. This call is illegal if there is no - * current row. - * @return true if the cursor is in the result set - */ - bool relative(int rows); - - /** Places the cursor after the last row in the result set */ - void afterLast(); - - /** Places the cursor before the first row in the result set */ - void beforeFirst(); - - /** Checks if the cursor is after the last row in the result set */ - bool isAfterLast(); - - /** Checks if the cursor is before the first row in the result set */ - bool isBeforeFirst(); - - /** Checks if the cursor is on the first row in the result set */ - bool isFirst(); - - /** Checks if the cursor is on the last row in the result set. - */ - bool isLast(); - - /** Returns the current row number. - * @return The current row number in the result set, or 0 - * if it can't be determined. - */ - int getRow(); - - /** Moves to the next row in the result set - * @return true if the cursor is in the result set - */ - bool next(); - - /** Moves to the previous row in the result set - * @return true if the cursor is in the result set - */ - bool previous(); - - /** Moves to the first row in the result set - * @return true if the cursor is in the result set - */ - bool first(); - - /** Moves to the last row in the result set - * @return true if the cursor is in the result set - */ - bool last(); - - /** Moves the cursor to the 'insert row' of this result set. - * @warning The only valid methods while on the insert row - * are updateXXX(), insertRow() and moveToCurrentRow(). - * @see moveToCurrentRow() - */ - void moveToInsertRow(); - - /** Moves the cursor back to where it was before it was moved - * to the insert row - */ - void moveToCurrentRow(); - - /** Refreshes the current row */ - void refreshRow(); - - /** Deletes the current row */ - void deleteRow(); - - /** Inserts the current row. - * Only valid while on the insert row. - * @see moveToInsertRow() - */ - void insertRow(); - - /** Updates the current row. */ - void updateRow(); - - /** Cancels any updates done to the current row */ - void cancelRowUpdates(); - - /** Returns meta data about this result set - * @see ResultSetMetaData - */ - ResultSetMetaData* getMetaData() { - return metaData_; - } - - /** Find a column index by the column's name */ - int findColumn(const ODBCXX_STRING& colName); - - /** Checks if the current row is deleted */ - bool rowDeleted(); - - /** Checks if the current row was inserted */ - bool rowInserted(); - - /** Checks if the current row was updated */ - bool rowUpdated(); - - /** Gets the type of this result set */ - int getType(); - - /** Gets the concurrency of this result set */ - int getConcurrency(); - - - /** Gets this result set's current fetch size */ - int getFetchSize() { - return newFetchSize_; - } - - /** Sets this result set's fetch size (doesn't apply immediately) */ - void setFetchSize(int fetchSize); - - /** Gets the cursor name associated with this result set */ - ODBCXX_STRING getCursorName(); - - /** Gets the Statement that created this result set */ - Statement* getStatement() { - return statement_; - } - - /** Gets a column's value as a double - * @param idx The column index, starting at 1 - */ - double getDouble(int idx); - - /** Gets a column's value as a bool - * @param idx The column index, starting at 1 - */ - bool getBoolean(int idx); - - /** Gets a column's value as a signed char - * @param idx The column index, starting at 1 - */ - signed char getByte(int idx); - - /** Gets a column's value as a chunk of bytes. - * - * @param idx The column index, starting at 1 - */ - ODBCXX_BYTES getBytes(int idx); - - /** Gets a column's value as a Date - * @param idx The column index, starting at 1 - */ - Date getDate(int idx); - - /** Gets a column's value as a float - * @param idx The column index, starting at 1 - */ - float getFloat(int idx); - - /** Gets a column's value as an int - * @param idx The column index, starting at 1 - */ - int getInt(int idx); - - /** Gets a column's value as a Long - * @param idx The column index, starting at 1 - */ - Long getLong(int idx); - - /** Gets a column's value as a short - * @param idx The column index, starting at 1 - */ - short getShort(int idx); - - /** Gets a column's value as a string - * @param idx The column index, starting at 1 - */ - ODBCXX_STRING getString(int idx); - - /** Gets a column's value as a Time - * @param idx The column index, starting at 1 - */ - Time getTime(int idx); - - /** Gets a column's value as a Timestamp - * @param idx The column index, starting at 1 - */ - Timestamp getTimestamp(int idx); - - /** Gets a column's value as a double - * @param colName The name of the column - */ - double getDouble(const ODBCXX_STRING& colName); - - /** Gets a column's value as a bool - * @param colName The name of the column - */ - bool getBoolean(const ODBCXX_STRING& colName); - - /** Gets a column's value as a signed char - * @param colName The name of the column - */ - signed char getByte(const ODBCXX_STRING& colName); - - - /** Gets a column's value as a chunk of bytes. - * @param colName The name of the column - */ - ODBCXX_BYTES getBytes(const ODBCXX_STRING& colName); - - /** Gets a column's value as a Date - * @param colName The name of the column - */ - Date getDate(const ODBCXX_STRING& colName); - - /** Gets a column's value as a float - * @param colName The name of the column - */ - float getFloat(const ODBCXX_STRING& colName); - - /** Gets a column's value as an int - * @param colName The name of the column - */ - int getInt(const ODBCXX_STRING& colName); - - /** Gets a column's value as a Long - * @param colName The name of the column - */ - Long getLong(const ODBCXX_STRING& colName); - - /** Gets a column's value as a short - * @param colName The name of the column - */ - short getShort(const ODBCXX_STRING& colName); - - /** Gets a column's value as a string - * @param colName The name of the column - */ - ODBCXX_STRING getString(const ODBCXX_STRING& colName); - - /** Gets a column's value as a Time - * @param colName The name of the column - */ - Time getTime(const ODBCXX_STRING& colName); - - /** Gets a column's value as a Timestamp - * @param colName The name of the column - */ - Timestamp getTimestamp(const ODBCXX_STRING& colName); - - - /** Fetches a column's value as a stream. - * Note that the stream is owned by the result set - * and should in no case be deleted by the caller. - * Also, the returned stream is only valid while the - * cursor remains on this position. - * @param idx The column index, starting at 1 - */ - ODBCXX_STREAM* getAsciiStream(int idx); - - /** Fetches a column's value as a stream. - * Note that the stream is owned by the result set - * and should in no case be deleted by the caller. - * Also, the returned stream is only valid while the - * cursor remains on this position. - * @param colName The column name - */ - ODBCXX_STREAM* getAsciiStream(const ODBCXX_STRING& colName); - - /** Fetches a column's value as a stream. - * Note that the stream is owned by the result set - * and should in no case be deleted by the caller. - * Also, the returned stream is only valid while the - * cursor remains on this position. - * @param idx The column index, starting at 1 - */ - ODBCXX_STREAM* getBinaryStream(int idx); - - /** Fetches a column's value as a stream. - * Note that the stream is owned by the result set - * and should in no case be deleted by the caller. - * Also, the returned stream is only valid while the - * cursor remains on this position. - * @param colName The column name - */ - ODBCXX_STREAM* getBinaryStream(const ODBCXX_STRING& colName); - - /** Checks if the last fetched column value was NULL. - * Note that if this is true, the returned value was undefined. - */ - bool wasNull() { - return lastWasNull_; - } - - /** Sets the value of a column to a double - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateDouble(int idx, double val); - - /** Sets the value of a column to a bool - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateBoolean(int idx, bool val); - - /** Sets the value of a column to a signed char - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateByte(int idx, signed char val); - - - /** Sets the value of a column to a chunk of bytes - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateBytes(int idx, const ODBCXX_BYTES& val); - - /** Sets the value of a column to a Date - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateDate(int idx, const Date& val); - - /** Sets the value of a column to a float - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateFloat(int idx, float val); - - /** Sets the value of a column to an int - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateInt(int idx, int val); - - /** Sets the value of a column to a Long - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateLong(int idx, Long val); - - /** Sets the value of a column to a short - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateShort(int idx, short val); - - /** Sets the value of a column to a string - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateString(int idx, const ODBCXX_STRING& val); - - /** Sets the value of a column to a Time - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateTime(int idx, const Time& val); - - /** Sets the value of a column to a Timestamp - * @param idx The column index, starting at 1 - * @param val The value to set - */ - void updateTimestamp(int idx, const Timestamp& val); - - /** Sets the value of a column to NULL - * @param idx The column index, starting at 1 - */ - void updateNull(int idx); - - - /** Sets the value of a column to a double - * @param colName The name of the column - * @param val The value to set - */ - void updateDouble(const ODBCXX_STRING& colName, double val); - - /** Sets the value of a column to a bool - * @param colName The name of the column - * @param val The value to set - */ - void updateBoolean(const ODBCXX_STRING& colName, bool val); - - /** Sets the value of a column to a signed char - * @param colName The name of the column - * @param val The value to set - */ - void updateByte(const ODBCXX_STRING& colName, signed char val); - - /** Sets the value of a column to a chunk of bytes - * @param colName The name of the column - * @param val The value to set - */ - void updateBytes(const ODBCXX_STRING& colName, - const ODBCXX_BYTES& val); - - - /** Sets the value of a column to a Date - * @param colName The name of the column - * @param val The value to set - */ - void updateDate(const ODBCXX_STRING& colName, const Date& val); - - /** Sets the value of a column to a float - * @param colName The name of the column - * @param val The value to set - */ - void updateFloat(const ODBCXX_STRING& colName, float val); - - /** Sets the value of a column to an int - * @param colName The name of the column - * @param val The value to set - */ - void updateInt(const ODBCXX_STRING& colName, int val); - - /** Sets the value of a column to a Long - * @param colName The name of the column - * @param val The value to set - */ - void updateLong(const ODBCXX_STRING& colName, Long val); - - /** Sets the value of a column to a short - * @param colName The name of the column - * @param val The value to set - */ - void updateShort(const ODBCXX_STRING& colName, short val); - - /** Sets the value of a column to a string - * @param colName The name of the column - * @param val The value to set - */ - void updateString(const ODBCXX_STRING& colName, const ODBCXX_STRING& val); - - /** Sets the value of a column to a Time - * @param colName The name of the column - * @param val The value to set - */ - void updateTime(const ODBCXX_STRING& colName, const Time& val); - - /** Sets the value of a column to a Timestamp - * @param colName The name of the column - * @param val The value to set - */ - void updateTimestamp(const ODBCXX_STRING& colName, const Timestamp& val); - - /** Sets the value of a column to a stream - * @param idx The column index, starting at 1 - * @param s The stream to assign - * @param len The number of bytes in the stream - */ - void updateAsciiStream(int idx, ODBCXX_STREAM* s, int len); - - /** Sets the value of a column to the contens of a stream - * @param colName The column name - * @param s The stream to assign - * @param len The number of bytes in the stream - */ - void updateAsciiStream(const ODBCXX_STRING& colName, ODBCXX_STREAM* s, int len); - - - /** Sets the value of a column to the contens of a stream - * @param idx The column index, starting at 1 - * @param s The stream to assign - * @param len The number of bytes in the stream - */ - void updateBinaryStream(int idx, ODBCXX_STREAM* s, int len); - - /** Sets the value of a column to the contens of a stream - * @param colName The column name - * @param s The stream to assign - * @param len The number of bytes in the stream - */ - void updateBinaryStream(const ODBCXX_STRING& colName, ODBCXX_STREAM* s, int len); - - /** Sets the value of a column to NULL - * @param colName The column name - */ - void updateNull(const ODBCXX_STRING& colName); - }; - - - -} // namespace odbc - - -#endif // __ODBCXX_RESULTSET_H diff --git a/source/odbc++/resultsetmetadata.h b/source/odbc++/resultsetmetadata.h deleted file mode 100644 index b9be4e238..000000000 --- a/source/odbc++/resultsetmetadata.h +++ /dev/null @@ -1,182 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_RESULTSETMETADATA_H -#define __ODBCXX_RESULTSETMETADATA_H - -#include -#include -#include - -namespace odbc { - - class ResultSet; - class DriverInfo; - - /** Provides meta data about a result set */ - class ODBCXX_EXPORT ResultSetMetaData { - friend class ResultSet; - friend class Statement; - private: - ResultSet* resultSet_; - - int numCols_; - std::vector colNames_; - std::vector colTypes_; - std::vector colPrecisions_; - std::vector colScales_; -#if ODBCVER >= 0x0300 - std::vector colLengths_; -#endif - - //internal stuff - bool needsGetData_; - - //yes, both constructor and destructor are meant to be private - ResultSetMetaData(ResultSet* rs); - ~ResultSetMetaData() {} - - //driver info - const DriverInfo* _getDriverInfo() const { - return resultSet_->_getDriverInfo(); - } - - //these fetch info about a column - int _getNumericAttribute(unsigned int col, SQLUSMALLINT attr); - ODBCXX_STRING _getStringAttribute(unsigned int col, SQLUSMALLINT attr, unsigned int maxlen =255); - - //this loads the above values - void _fetchColumnInfo(); - - public: - /** Nullability constants */ - enum { - columnNoNulls = SQL_NO_NULLS, - columnNullable = SQL_NULLABLE, - columnNullableUnknown = SQL_NULLABLE_UNKNOWN - }; - - /** Fetch the number of columns in this result set */ - int getColumnCount() const; - - /** Get the name of a column - * @param column The column index, starting at 1 - */ - const ODBCXX_STRING& getColumnName(int column) const; - - /** Get the SQL type of a column - * @param column The column index, starting at 1 - * @see Types - */ - int getColumnType(int column) const; - - /** Get the precision of a column - * @param column The column index, starting at 1 - */ - int getPrecision(int column) const; - - /** Get the scale of a column - * @param column The column index, starting at 1 - */ - int getScale(int column) const; - - /** Get the display size of a column. - * @param column The column index, starting at 1 - */ - int getColumnDisplaySize(int column); - - /** Get the catalog name for a column. - * @param column The column index, starting at 1 - */ - ODBCXX_STRING getCatalogName(int column); - - /** Get the label (if any) for a column. - * @param column The column index, starting at 1 - */ - ODBCXX_STRING getColumnLabel(int column); - - /** Get the name of a columns SQL type - * @param column The column index, starting at 1 - */ - ODBCXX_STRING getColumnTypeName(int column); - - /** Get the schema name for a column - * @param column The column index, starting at 1 - */ - ODBCXX_STRING getSchemaName(int column); - - /** Get the table name for a column - * @param column The column index, starting at 1 - */ - ODBCXX_STRING getTableName(int column); - - /** Check if a column is autoincrementing - * @param column The column index, starting at 1 - */ - bool isAutoIncrement(int column); - - /** Check if a column is case sensitive - * @param column The column index, starting at 1 - */ - bool isCaseSensitive(int column); - - /** Check if a column can be a currency (eg fixed precision) - * @param column The column index, starting at 1 - */ - bool isCurrency(int column); - - /** Check if a column can be updated - * @param column The column index, starting at 1 - */ - bool isDefinitelyWritable(int column); - - /** Check if a column can be set to NULL - * @param column The column index, starting at 1 - */ - int isNullable(int column); - - /** Check if a column is read only - * @param column The column index, starting at 1 - */ - bool isReadOnly(int column); - - /** Check if a column can be used in a where-clause - * @param column The column index, starting at 1 - */ - bool isSearchable(int column); - - /** Check if a column is signed - * @param column The column index, starting at 1 - */ - bool isSigned(int column); - - /** Check if a column is 'probably' writeable - * @param column The column index, starting at 1 - */ - bool isWritable(int column); - }; - - - -} // namespace odbc - - -#endif // __ODBCXX_RESULTSETMETADATA_H diff --git a/source/odbc++/setup.h b/source/odbc++/setup.h deleted file mode 100644 index ce37c89ed..000000000 --- a/source/odbc++/setup.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_SETUP_H -#define __ODBCXX_SETUP_H - -#if defined(__WIN32__) && !defined(WIN32) -# define WIN32 1 -#endif - -#if !defined(WIN32) -# include -#else -# include -#endif - - -#if defined(IN_ODBCXX) && defined(ODBCXX_ENABLE_THREADS) -# if !defined(_REENTRANT) -# define _REENTRANT 1 -# endif -# if !defined(_THREAD_SAFE) -# define _THREAD_SAFE 1 -# endif -#endif - -// set the UNICODE define activate wide versions of ODBC functions -#if defined(ODBCXX_UNICODE) -# if !defined(UNICODE) -# define UNICODE -# endif -#else -# if defined(UNICODE) -# undef UNICODE -# endif -#endif - -// check whether we use strstream or stringstream -#if defined(IN_ODBCXX) -# if defined(ODBCXX_UNICODE) -# define ODBCXX_SSTREAM std::wstringstream -# else -# if defined(ODBCXX_HAVE_SSTREAM) -# define ODBCXX_SSTREAM std::stringstream -# else -# define ODBCXX_SSTREAM std::strstream -# endif -# endif -#endif - -// check if ODBCVER is forced to something -#if defined(ODBCXX_ODBCVER) -# define ODBCVER ODBCXX_ODBCVER -#endif - -// this can confuse our Types::CHAR -#ifdef CHAR -#undef CHAR -#endif - -// NDEBUG and cassert -#if defined(IN_ODBCXX) -# if !defined(ODBCXX_DEBUG) -# define NDEBUG -# endif -# include -#endif - -// this should do the trick -#if defined(__GNUC__) && __GNUC__>=3 -# define ODBCXX_HAVE_ISO_CXXLIB -#endif - - -#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__MINGW32__) -# if defined(ODBCXX_DLL) -# if defined(IN_ODBCXX) -# define ODBCXX_EXPORT __declspec(dllexport) -# else -# define ODBCXX_EXPORT __declspec(dllimport) -# endif -# endif -#endif - -#if !defined(ODBCXX_EXPORT) -# define ODBCXX_EXPORT -#endif - -#if defined(_MSC_VER) || defined(__MINGW32__) -# define ODBCXX_DUMMY_RETURN(x) return (x) -#else -# define ODBCXX_DUMMY_RETURN(x) ((void)0) -#endif - - -// environment abstractions - -#if defined(ODBCXX_QT) - -# define ODBCXX_STRING QString -# define ODBCXX_STRING_C(s) QString::fromLocal8Bit(s) -# define ODBCXX_STRING_CL(s,l) QString::fromLocal8Bit(s,l) -# define ODBCXX_STRING_LEN(s) s.length() -# define ODBCXX_STRING_DATA(s) s.local8Bit().data() -# define ODBCXX_STRING_CSTR(s) s.local8Bit().data() - -# define ODBCXX_STREAM QIODevice - -# define ODBCXX_BYTES QByteArray -# define ODBCXX_BYTES_SIZE(b) b.size() -# define ODBCXX_BYTES_DATA(b) b.data() -# define ODBCXX_BYTES_C(buf,len) QByteArray().duplicate(buf,len) - -#else - -# if defined(ODBCXX_UNICODE) - -# define ODBCXX_STRING std::wstring -# define ODBCXX_STRING_C(s) std::wstring(s) -# define ODBCXX_STRING_CL(s,l) std::wstring(s,l) -# define ODBCXX_STRING_LEN(s) s.length() -# define ODBCXX_STRING_DATA(s) s.data() -# define ODBCXX_STRING_CSTR(s) s.c_str() - -# define ODBCXX_STREAM std::wistream -# define ODBCXX_STREAMBUF std::wstreambuf - -# define ODBCXX_BYTES odbc::Bytes -# define ODBCXX_BYTES_SIZE(b) b.getSize() -# define ODBCXX_BYTES_DATA(b) b.getData() -# define ODBCXX_BYTES_C(buf,len) odbc::Bytes((wchar_t*)buf,(size_t)len) - -# else - -# define ODBCXX_STRING std::string -# define ODBCXX_STRING_C(s) std::string(s) -# define ODBCXX_STRING_CL(s,l) std::string(s,l) -# define ODBCXX_STRING_LEN(s) s.length() -# define ODBCXX_STRING_DATA(s) s.data() -# define ODBCXX_STRING_CSTR(s) s.c_str() - -# define ODBCXX_STREAM std::istream -# define ODBCXX_STREAMBUF std::streambuf - -# define ODBCXX_BYTES odbc::Bytes -# define ODBCXX_BYTES_SIZE(b) b.getSize() -# define ODBCXX_BYTES_DATA(b) b.getData() -# define ODBCXX_BYTES_C(buf,len) odbc::Bytes((signed char*)buf,(size_t)len) - -# endif // ODBCXX_UNICODE - -#endif // ODBCXX_QT - -#if defined(ODBCXX_UNICODE) -# define ODBCXX_CHAR_TYPE wchar_t -# define ODBCXX_SIGNED_CHAR_TYPE wchar_t -# define ODBCXX_SQLCHAR SQLWCHAR -# define ODBCXX_STRING_CONST(s) L ## s -# define ODBCXX_COUT std::wcout -# define ODBCXX_CERR std::wcerr -# define ODBCXX_STRTOL wcstol -#else -# define ODBCXX_CHAR_TYPE char -# define ODBCXX_SIGNED_CHAR_TYPE signed char -# define ODBCXX_SQLCHAR SQLCHAR -# define ODBCXX_STRING_CONST(s) s -# define ODBCXX_COUT std::cout -# define ODBCXX_CERR std::cerr -# define ODBCXX_STRTOL strtol -#endif - -#endif // __ODBCXX_SETUP_H diff --git a/source/odbc++/statement.h b/source/odbc++/statement.h deleted file mode 100644 index 2f4c72064..000000000 --- a/source/odbc++/statement.h +++ /dev/null @@ -1,271 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_STATEMENT_H -#define __ODBCXX_STATEMENT_H - -#include -#include -#include -#include - -namespace odbc { - - class ResultSet; - class DriverInfo; - - /** A simple non-prepared statement */ - class ODBCXX_EXPORT Statement : public ErrorHandler { - friend class Connection; - friend class ResultSet; - friend class DatabaseMetaData; - - protected: - Connection* connection_; - SQLHSTMT hstmt_; - int lastExecute_; - - const DriverInfo* _getDriverInfo() const { - return connection_->_getDriverInfo(); - } - - private: - ResultSet* currentResultSet_; - - int fetchSize_; - int resultSetType_; - int resultSetConcurrency_; - - //used internally - enum StatementState { - STATE_CLOSED, - STATE_OPEN - }; - - StatementState state_; - - std::vector batches_; - - void _registerResultSet(ResultSet* rs); - void _unregisterResultSet(ResultSet* rs); - - void _applyResultSetType(); - - ResultSet* _getTypeInfo(); - ResultSet* _getTables(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName, - const ODBCXX_STRING& types); - - ResultSet* _getTablePrivileges(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName); - - ResultSet* _getColumnPrivileges(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName, - const ODBCXX_STRING& columnName); - - ResultSet* _getPrimaryKeys(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName); - - ResultSet* _getColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName, - const ODBCXX_STRING& columnName); - - ResultSet* _getIndexInfo(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& tableName, - bool unique, bool approximate); - - ResultSet* _getCrossReference(const ODBCXX_STRING& pc, - const ODBCXX_STRING& ps, - const ODBCXX_STRING& pt, - const ODBCXX_STRING& fc, - const ODBCXX_STRING& fs, - const ODBCXX_STRING& ft); - - - ResultSet* _getProcedures(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& procName); - - ResultSet* _getProcedureColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& procName, - const ODBCXX_STRING& colName); - - ResultSet* _getSpecialColumns(const ODBCXX_STRING& catalog, - const ODBCXX_STRING& schema, - const ODBCXX_STRING& table, - int what,int scope,int nullable); - - protected: - Statement(Connection* con, SQLHSTMT hstmt, - int resultSetType, int resultSetConcurrency); - - //utilities - SQLUINTEGER _getNumericOption(SQLINTEGER optnum); - ODBCXX_STRING _getStringOption(SQLINTEGER optnum); - - void _setNumericOption(SQLINTEGER optnum, SQLUINTEGER value); - void _setStringOption(SQLINTEGER optnum, const ODBCXX_STRING& value); - -#if ODBCVER >= 0x0300 - SQLPOINTER _getPointerOption(SQLINTEGER optnum); - void _setPointerOption(SQLINTEGER optnum, SQLPOINTER value); -#endif - - //this returns true if we have a result set pending - bool _checkForResults(); - - //this _always_ returns a ResultSet. If hideMe is true, this statement - //becomes 'owned' by the ResultSet - ResultSet* _getResultSet(bool hideMe =false); - - //this is called before a Statement (or any of the derived classes) - //is executed - void _beforeExecute(); - - //this is called after a successeful execution - void _afterExecute(); - - - public: - /** Destructor. Destroys/closes this statement as well as - * all created resultsets. - */ - virtual ~Statement(); - - /** Returns the connection that created this statement */ - Connection* getConnection(); - - - /** Cancel an ongoing operation that was executed in another thread */ - void cancel(); - - /** Execute a given SQL statement. - * The statement can return multiple results. To get to the - * next result after processing the first one, getMoreResults() should - * be called. - * @param sql The string to execute - * @return true if a resultset is available - */ - virtual bool execute(const ODBCXX_STRING& sql); - - /** Execute an SQL statement, expected to return a resultset. - * - * Example: - * std::auto_ptr<ResultSet> rs = - * std::auto_ptr<ResultSet>(stmt->executeQuery(s)); - * - * @param sql The string to execute - * @return A ResultSet object. - */ - virtual ResultSet* executeQuery(const ODBCXX_STRING& sql); - - /** Execute an SQL statement, expected to return an update count. - * @return The number of affected rows - */ - virtual int executeUpdate(const ODBCXX_STRING& sql); - - /** Fetch the current result as an update count. - * - * @return the current result's update count (affected rows), or -1 - * if the result is a ResultSet or if there are no more results. - */ - int getUpdateCount(); - - /** Fetch the current result as a ResultSet */ - ResultSet* getResultSet(); - - /** Check if there are more results available on this - * statment. - * @return True if this statement has more results to offer. - */ - bool getMoreResults(); - - /** Set the cursor name for this statement */ - void setCursorName(const ODBCXX_STRING& name); - - /** Fetch the current fetch size (also called rowset size) for - * resultsets created by this statement. - */ - int getFetchSize() { - return fetchSize_; - } - - /** Set the current fetch size for resultsets created by this statement */ - void setFetchSize(int size); - - /** Get the concurrency type for resultsets created by this statement */ - int getResultSetConcurrency() { - return resultSetConcurrency_; - } - - /** Get the type for resultsets created by this statement */ - int getResultSetType() { - return resultSetType_; - } - - /** Get the query timeout for this statement */ - int getQueryTimeout(); - /** Set the query timeout for this statement */ - void setQueryTimeout(int seconds); - - /** Get the maximum number of rows to return in a resultset */ - int getMaxRows(); - /** Set the maximum number of rows to return in a resultset */ - void setMaxRows(int maxRows); - - /** Get the maximum field size for resultsets create by this statement */ - int getMaxFieldSize(); - /** Set the maximum field size for resultsets create by this statement */ - void setMaxFieldSize(int maxFieldSize); - - /** Sets escape processing on or off - * - * For PreparedStatements, the command has been parsed on - * creation, so this setting won't really have any effect. - */ - void setEscapeProcessing(bool on); - - /** Gets the current escape processing setting - * @return true if escape processing is on, false - * otherwise - */ - bool getEscapeProcessing(); - - /** Closes all result sets from this execution. This is useful if - * you don't wish to iterate through all remaining results, or if - * your driver does not auto-close cursors. */ - void close(); - - }; - - - -} // namespace odbc - - -#endif // __ODBCXX_STATEMENT_H diff --git a/source/odbc++/threads.h b/source/odbc++/threads.h deleted file mode 100644 index 641741140..000000000 --- a/source/odbc++/threads.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_THREADS_H -#define __ODBCXX_THREADS_H - -#include - -#if defined(ODBCXX_ENABLE_THREADS) - -#if !defined(WIN32) -# include -#endif - -namespace odbc { - - class ODBCXX_EXPORT Mutex { - private: -#if !defined(WIN32) - pthread_mutex_t mutex_; -#else - CRITICAL_SECTION mutex_; -#endif - - Mutex(const Mutex&); - Mutex& operator=(const Mutex&); - - public: - explicit Mutex(); - ~Mutex(); - - void lock(); - void unlock(); - }; - - class ODBCXX_EXPORT Locker { - private: - Mutex& m_; - public: - Locker(Mutex& m) - :m_(m) { - m_.lock(); - } - - ~Locker() { - m_.unlock(); - } - }; - -} //namespace odbc - -// macro used all over the place -#define ODBCXX_LOCKER(mut) odbc::Locker _locker(mut) - -#else // !ODBCXX_ENABLE_THREADS - -#define ODBCXX_LOCKER(mut) ((void)0) - -#endif - -#endif // __ODBCXX_THREADS_H diff --git a/source/odbc++/types.h b/source/odbc++/types.h deleted file mode 100644 index bdca0b159..000000000 --- a/source/odbc++/types.h +++ /dev/null @@ -1,823 +0,0 @@ -/* - This file is part of libodbc++. - - Copyright (C) 1999-2000 Manush Dodunekov - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Library General Public - License as published by the Free Software Foundation; either - version 2 of the License, or (at your option) any later version. - - This library 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 - Library General Public License for more details. - - You should have received a copy of the GNU Library General Public License - along with this library; see the file COPYING. If not, write to - the Free Software Foundation, Inc., 59 Temple Place - Suite 330, - Boston, MA 02111-1307, USA. -*/ - -#ifndef __ODBCXX_TYPES_H -#define __ODBCXX_TYPES_H - -#include - -#include - -#if !defined(ODBCXX_QT) -# include -# else -# include -#endif - -#include -#if defined(ODBCXX_NO_STD_TIME_T) -namespace std { - using ::time_t; -}; -#endif - -#if defined(ODBCXX_QT) -class QIODevice; -#endif - -#if defined(ODBCXX_HAVE_ISQL_H) && defined(ODBCXX_HAVE_ISQLEXT_H) -# include -# include -#elif defined(ODBCXX_HAVE_SQL_H) && defined(ODBCXX_HAVE_SQLEXT_H) -# include -# include -#else -# error "Whoops. Can not recognize the ODBC subsystem." -#endif - -#if defined(ODBCXX_HAVE_SQLUCODE_H) -# include -#endif - -// fixups for current iODBC, which kindly doesn't provide SQL_TRUE and -// SQL_FALSE macros - -#if !defined(SQL_TRUE) -# define SQL_TRUE 1 -#endif - -#if !defined(SQL_FALSE) -# define SQL_FALSE 0 -#endif - -// MS ODBC SDK misses this in some releases -#if ODBCVER >= 0x0300 && !defined(SQL_NOT_DEFERRABLE) -# define SQL_NOT_DEFERRABLE 7 -#endif - - -// Setup our ODBC3_C (odbc3 conditional) macro -#if ODBCVER >= 0x0300 - -# define ODBC3_C(odbc3_value,old_value) odbc3_value - -#else - -# define ODBC3_C(odbc3_value,old_value) old_value - -#endif - - -// ODBC3_DC (odbc3 dynamic conditional) -// Every context using this macro should provide -// a this->_getDriverInfo() method returning -// a const DriverInfo* - -#if ODBCVER >= 0x0300 - -# define ODBC3_DC(odbc3_value,old_value) \ -(this->_getDriverInfo()->getMajorVersion()>=3?odbc3_value:old_value) - -#else - -# define ODBC3_DC(odbc3_value,old_value) old_value - -#endif - -#if defined(ODBCXX_HAVE_INTTYPES_H) -# include -#endif - -#include - - -namespace odbc { - - // We want Long to be at least 64 bits - -#if defined(WIN32) - - typedef __int64 Long; - -#elif defined(ODBCXX_HAVE_INTTYPES_H) - - typedef int64_t Long; - -#else - -# if ODBCXX_SIZEOF_INT == 8 - - typedef int Long; - -# elif ODBCXX_SIZEOF_LONG == 8 - - typedef long Long; - -# elif ODBCXX_SIZEOF_LONG_LONG == 8 - - typedef long long Long; - -# else - -# error "Can't find an appropriate at-least-64-bit integer" - -# endif - -#endif - - - //constants: - //how much we try to fetch with each SQLGetData call - const int GETDATA_CHUNK_SIZE=4*1024; - //how much we write with each SQLPutData call - const int PUTDATA_CHUNK_SIZE=GETDATA_CHUNK_SIZE; - - //how much we read/write in string<->stream conversion - //better names for those? - const int STRING_TO_STREAM_CHUNK_SIZE=1024; - const int STREAM_TO_STRING_CHUNK_SIZE=STRING_TO_STREAM_CHUNK_SIZE; - - - - - - /** SQL type constants - */ - struct Types { - /** Type constants - */ - enum SQLType { - /** An SQL BIGINT */ - BIGINT = SQL_BIGINT, - /** An SQL BINARY (fixed length) */ - BINARY = SQL_BINARY, - /** An SQL BIT */ - BIT = SQL_BIT, - /** An SQL CHAR (fixed length) */ - CHAR = SQL_CHAR, - /** An SQL DATE */ - DATE = ODBC3_C(SQL_TYPE_DATE,SQL_DATE), - /** An SQL DECIMAL (precision,scale) */ - DECIMAL = SQL_DECIMAL, - /** An SQL DOUBLE */ - DOUBLE = SQL_DOUBLE, - /** An SQL FLOAT */ - FLOAT = SQL_FLOAT, - /** An SQL INTEGER */ - INTEGER = SQL_INTEGER, - /** An SQL LONGVARBINARY (variable length, huge) */ - LONGVARBINARY = SQL_LONGVARBINARY, - /** An SQL LONGVARCHAR (variable length, huge) */ - LONGVARCHAR = SQL_LONGVARCHAR, - /** An SQL NUMERIC (precision,scale) */ - NUMERIC = SQL_NUMERIC, - /** An SQL REAL */ - REAL = SQL_REAL, - /** An SQL SMALLINT */ - SMALLINT = SQL_SMALLINT, - /** An SQL TIME */ - TIME = ODBC3_C(SQL_TYPE_TIME,SQL_TIME), - /** An SQL TIMESTAMP */ - TIMESTAMP = ODBC3_C(SQL_TYPE_TIMESTAMP,SQL_TIMESTAMP), - /** An SQL TINYINT */ - TINYINT = SQL_TINYINT, - /** An SQL VARBINARY (variable length less than 256) */ - VARBINARY = SQL_VARBINARY, - /** An SQL VARCHAR (variable length less than 256) */ - VARCHAR = SQL_VARCHAR -#if defined(ODBCXX_HAVE_SQLUCODE_H) - , - /** A wide SQL CHAR (fixed length less than 256) */ - WCHAR = SQL_WCHAR, - /** A wide SQL VARCHAR (variable length less than 256) */ - WVARCHAR = SQL_WVARCHAR, - /** A wide SQL LONGVARCHAR (variable length, huge) */ - WLONGVARCHAR = SQL_WLONGVARCHAR -#endif - }; - }; - - -#if !defined(ODBCXX_QT) - /** A chunk of bytes. - * - * Used for setting and getting binary values. - * @warning This class uses reference counting. An instance that is - * referred to from different threads is likely to cause trouble. - */ - class ODBCXX_EXPORT Bytes { - private: - struct Rep { - ODBCXX_SIGNED_CHAR_TYPE* buf_; - size_t len_; - int refCount_; - Rep(const ODBCXX_SIGNED_CHAR_TYPE* b, size_t l) - :len_(l), refCount_(0) { - if(len_>0) { - buf_=new ODBCXX_SIGNED_CHAR_TYPE[len_]; - memcpy((void*)buf_,(void*)b,len_); - } else { - buf_=NULL; - } - } - ~Rep() { - delete [] buf_; - } - }; - - Rep* rep_; - public: - /** Default constructor */ - Bytes() - :rep_(new Rep(NULL,0)) { - rep_->refCount_++; - } - - /** Constructor */ - Bytes(const ODBCXX_SIGNED_CHAR_TYPE* data, size_t dataLen) - :rep_(new Rep(data,dataLen)) { - rep_->refCount_++; - } - - /** Copy constructor */ - Bytes(const Bytes& b) - :rep_(b.rep_) { - rep_->refCount_++; - } - - /** Assignment */ - Bytes& operator=(const Bytes& b) { - if(--rep_->refCount_==0) { - delete rep_; - } - rep_=b.rep_; - rep_->refCount_++; - return *this; - } - - /** Comparison */ - bool operator==(const Bytes& b) const { - if (getSize()!=b.getSize()) - return false; - for(size_t i=0;irefCount_==0) { - delete rep_; - } - } - - /** Returns a pointer to the data */ - const ODBCXX_SIGNED_CHAR_TYPE* getData() const { - return rep_->buf_; - } - - /** Returns the size of the data */ - size_t getSize() const { - return rep_->len_; - } - }; -#endif - - /** An SQL DATE */ - class ODBCXX_EXPORT Date { - protected: - int year_; - int month_; - int day_; - - virtual void _invalid(const ODBCXX_CHAR_TYPE* what, int value); - - int _validateYear(int y) { - return y; - } - - int _validateMonth(int m) { - if(m<1 || m>12) { - this->_invalid(ODBCXX_STRING_CONST("month"),m); - } - return m; - } - - int _validateDay(int d) { - if(d<1 || d>31) { - this->_invalid(ODBCXX_STRING_CONST("day"),d); - } - return d; - } - - public: - /** Constructor. - */ - Date(int year, int month, int day) { - this->setYear(year); - this->setMonth(month); - this->setDay(day); - } - - /** Constructor. - * - * Sets this date to today. - */ - explicit Date(); - - /** Constructor. - * - * Sets this date to the specified time_t value. - */ - Date(std::time_t t) { - this->setTime(t); - } - - /** Constructor. - * - * Sets this date to the specified string in the YYYY-MM-DD format. - */ - Date(const ODBCXX_STRING& str) { - this->parse(str); - } - - /** Copy constructor */ - Date(const Date& d) - :year_(d.year_), - month_(d.month_), - day_(d.day_) {} - - /** Assignment operator */ - Date& operator=(const Date& d) { - year_=d.year_; - month_=d.month_; - day_=d.day_; - return *this; - } - - /** Destructor */ - virtual ~Date() {} - - /** Sets this date to the specified time_t value */ - virtual void setTime(std::time_t t); - - /** Returns the time_t value of 00:00:00 at this date */ - std::time_t getTime() const; - - /** Sets this date from a string in the YYYY-MM-DD format */ - void parse(const ODBCXX_STRING& str); - - /** Gets the year of this date */ - int getYear() const { - return year_; - } - - /** Gets the month of this date */ - int getMonth() const { - return month_; - } - - /** Gets the monthday of this date */ - int getDay() const { - return day_; - } - - /** Sets the year of this date */ - void setYear(int year) { - year_=this->_validateYear(year); - } - - /** Sets the month of this date */ - void setMonth(int month) { - month_=this->_validateMonth(month); - } - - /** Sets the day of this date */ - void setDay(int day) { - day_=this->_validateDay(day); - } - - /** Gets the date as a string in the YYYY-MM-DD format */ - virtual ODBCXX_STRING toString() const; - }; - - /** An SQL TIME */ - class ODBCXX_EXPORT Time { - protected: - int hour_; - int minute_; - int second_; - - virtual void _invalid(const ODBCXX_CHAR_TYPE* what, int value); - - int _validateHour(int h) { - if(h<0 || h>23) { - this->_invalid(ODBCXX_STRING_CONST("hour"),h); - } - return h; - } - - int _validateMinute(int m) { - if(m<0 || m>59) { - this->_invalid(ODBCXX_STRING_CONST("minute"),m); - } - return m; - } - - int _validateSecond(int s) { - if(s<0 || s>61) { - this->_invalid(ODBCXX_STRING_CONST("second"),s); - } - return s; - } - - public: - /** Constructor */ - Time(int hour, int minute, int second) { - this->setHour(hour); - this->setMinute(minute); - this->setSecond(second); - } - - /** Constructor. - * - * Sets the time to now. - */ - explicit Time(); - - /** Constructor. - * - * Sets the time to the specified time_t value. - */ - Time(std::time_t t) { - this->setTime(t); - } - - /** Constructor. - * - * Sets the time to the specified string in the HH:MM:SS format. - */ - Time(const ODBCXX_STRING& str) { - this->parse(str); - } - - /** Copy constructor */ - Time(const Time& t) - :hour_(t.hour_), - minute_(t.minute_), - second_(t.second_) {} - - /** Assignment operator */ - Time& operator=(const Time& t) { - hour_=t.hour_; - minute_=t.minute_; - second_=t.second_; - return *this; - } - - /** Destructor */ - virtual ~Time() {} - - /** Sets the time to the specified time_t value */ - virtual void setTime(std::time_t t); - - /** Returns the time_t value of 1970-01-01 at this time */ - std::time_t getTime() const; - - /** Sets this time from a string in the HH:MM:SS format */ - void parse(const ODBCXX_STRING& str); - - /** Gets the hour of this time */ - int getHour() const { - return hour_; - } - - /** Gets the minute of this time */ - int getMinute() const { - return minute_; - } - - /** Gets the second of this time */ - int getSecond() const { - return second_; - } - - /** Sets the hour of this time */ - void setHour(int h) { - hour_=this->_validateHour(h); - } - - /** Sets the minute of this time */ - void setMinute(int m) { - minute_=this->_validateMinute(m); - } - - /** Sets the second of this time */ - void setSecond(int s) { - second_=this->_validateSecond(s); - } - - virtual ODBCXX_STRING toString() const; - }; - - - /** An SQL TIMESTAMP - */ - class ODBCXX_EXPORT Timestamp : public Date, public Time { - private: - int nanos_; - - virtual void _invalid(const ODBCXX_CHAR_TYPE* what, int value); - - int _validateNanos(int n) { - if(n<0) { - this->_invalid(ODBCXX_STRING_CONST("nanoseconds"),n); - } - return n; - } - - public: - /** Constructor */ - Timestamp(int year, int month, int day, - int hour, int minute, int second, - int nanos =0) - :Date(year,month,day), Time(hour,minute,second) { - this->setNanos(nanos); - } - - /** Constructor. - * - * Sets the timestamp to now. - */ - explicit Timestamp(); - - /** Constructor. - * - * Sets this timestamp to the specified time_t value. - */ - Timestamp(std::time_t t) { - this->setTime(t); - } - - /** Constructor. - * - * Sets this timestamp from a YYYY-MM-DD HH:MM:SS[.NNN...] format - */ - Timestamp(const ODBCXX_STRING& s) { - this->parse(s); - } - - - /** Copy constructor */ - Timestamp(const Timestamp& t) - :Date(t),Time(t),nanos_(t.nanos_) {} - - /** Assignment operator */ - Timestamp& operator=(const Timestamp& t) { - Date::operator=(t); - Time::operator=(t); - nanos_=t.nanos_; - return *this; - } - - /** Destructor */ - virtual ~Timestamp() {} - - /** Sets this timestamp to the specified time_t value */ - virtual void setTime(std::time_t t); - - /** Gets the time_t value of this timestamp */ - virtual std::time_t getTime() const { - return Date::getTime()+Time::getTime(); - } - - /** Set this timestamp from a YYYY-MM-DD HH:MM:SS[.NNN...] format - */ - void parse(const ODBCXX_STRING& s); - - /** Gets the nanoseconds value of this timestamp */ - int getNanos() const { - return nanos_; - } - - /** Sets the nanoseconds value of this timestamp */ - void setNanos(int nanos) { - nanos_=this->_validateNanos(nanos); - } - - virtual ODBCXX_STRING toString() const; - }; - - - //this is used for several 'lists of stuff' below - //expects T to be a pointer-to-something, and - //the contents will get deleted when the vector - //itself is deleted - template class CleanVector : public std::vector { - private: - CleanVector(const CleanVector&); //forbid - CleanVector& operator=(const CleanVector&); //forbid - - public: - explicit CleanVector() {} - virtual ~CleanVector() { - typename std::vector::iterator i=this->begin(); - typename std::vector::iterator end=this->end(); - while(i!=end) { - delete *i; - ++i; - } - this->clear(); - } - }; - - - /** Used internally - represents the result of an SQLError call - */ - class ODBCXX_EXPORT DriverMessage { - friend class ErrorHandler; - - private: - ODBCXX_CHAR_TYPE state_[SQL_SQLSTATE_SIZE+1]; - ODBCXX_CHAR_TYPE description_[SQL_MAX_MESSAGE_LENGTH]; - SQLINTEGER nativeCode_; - - DriverMessage() {} -#if ODBCVER < 0x0300 - static DriverMessage* fetchMessage(SQLHENV henv, - SQLHDBC hdbc, - SQLHSTMT hstmt); -#else - static DriverMessage* fetchMessage(SQLINTEGER handleType, - SQLHANDLE h, - int idx); -#endif - - public: - virtual ~DriverMessage() {} - - const ODBCXX_CHAR_TYPE* getSQLState() const { - return state_; - } - - const ODBCXX_CHAR_TYPE* getDescription() const { - return description_; - } - - int getNativeCode() const { - return nativeCode_; - } - }; - - - /** The exception thrown when errors occur inside the library. - */ - class SQLException : public std::exception { - private: - ODBCXX_STRING reason_; - ODBCXX_STRING sqlState_; - int errorCode_; -#if defined(ODBCXX_UNICODE) - std::string reason8_; -#elif defined(ODBCXX_QT) - QCString reason8_; -#endif - public: - /** Constructor */ - SQLException(const ODBCXX_STRING& reason =ODBCXX_STRING_CONST(""), - const ODBCXX_STRING& sqlState =ODBCXX_STRING_CONST(""), - int vendorCode =0) - :reason_(reason), - sqlState_(sqlState), - errorCode_(vendorCode) -#if defined(ODBCXX_UNICODE) -{ - const size_t length =sizeof(wchar_t)*reason_.size(); - char* temp =new char[length+1]; - wcstombs(temp,reason_.c_str(),length); - reason8_ =temp; - delete[] temp; -} -#else -# if defined(ODBCXX_QT) - ,reason8_(reason.local8Bit()) -# endif -{} -#endif - - /** Copy from a DriverMessage */ - SQLException(const DriverMessage& dm) - :reason_(dm.getDescription()), - sqlState_(dm.getSQLState()), - errorCode_(dm.getNativeCode()) {} - - /** Destructor */ - virtual ~SQLException() throw() {} - - /** Get the vendor error code of this exception */ - int getErrorCode() const { - return errorCode_; - } - - /** Gets the SQLSTATE of this exception. - * - * Consult your local ODBC reference for SQLSTATE values. - */ - const ODBCXX_STRING& getSQLState() const { - return sqlState_; - } - - /** Gets the description of this message */ - const ODBCXX_STRING& getMessage() const { - return reason_; - } - - - /** Gets the description of this message */ - virtual const char* what() const throw() { - // the conversion from QString involves a temporary, which - // doesn't survive this scope. So here, we do a conditional -#if defined(ODBCXX_QT) - return reason8_.data(); -#else -# if defined(ODBCXX_UNICODE) - return reason8_.c_str(); -# else - return reason_.c_str(); -# endif -#endif - } - }; - - - /** Represents an SQL warning. - * - * Contains the same info as an SQLException. - */ - class SQLWarning : public SQLException { - - SQLWarning(const SQLWarning&); //forbid - SQLWarning& operator=(const SQLWarning&); //forbid - - public: - /** Constructor */ - SQLWarning(const ODBCXX_STRING& reason = ODBCXX_STRING_CONST(""), - const ODBCXX_STRING& sqlState = ODBCXX_STRING_CONST(""), - int vendorCode =0) - :SQLException(reason,sqlState,vendorCode) {} - - /** Copy from a DriverMessage */ - SQLWarning(const DriverMessage& dm) - :SQLException(dm) {} - - /** Destructor */ - virtual ~SQLWarning() throw() {} - }; - - typedef CleanVector WarningList; - - - template class Deleter { - private: - T* ptr_; - bool isArray_; - - Deleter(const Deleter&); - Deleter& operator=(const Deleter&); - - public: - explicit Deleter(T* ptr, bool isArray =false) - :ptr_(ptr), isArray_(isArray) {} - ~Deleter() { - if(!isArray_) { - delete ptr_; - } else { - delete[] ptr_; - } - } - }; - -} // namespace odbc - - -#endif // __ODBCXX_TYPES_H diff --git a/subcommands/autotest/test_geodata.txt b/subcommands/autotest/test_geodata.txt index 3871eb883..aba86c038 100644 --- a/subcommands/autotest/test_geodata.txt +++ b/subcommands/autotest/test_geodata.txt @@ -101,7 +101,7 @@ location,latitude,longitude,id,distance latitude,longitude,id,distance 37.4205,-122.2046,0,0.0 37.5205,-122.3046,1,14196.0 -# geodata merge -D distance ./path_example.csv +# geodata merge -D distance ../path_example.csv id,latitude,longitude,configuration,pole_height,distance 0,37.41505,-122.20565,flat3,54,0.0 1,37.4147,-122.20849,sideT,60,254.0 @@ -140,7 +140,7 @@ id,latitude,longitude,configuration,pole_height,distance 34,37.39161,-122.2786,2pole,69,7593.0 35,37.39171,-122.28139,3pole,48,7839.0 36,37.38806,-122.28844,tower,69,8583.0 -# geodata merge -D distance ./path_example.csv -r 100 +# geodata merge -D distance ../path_example.csv -r 100 position,latitude,longitude,configuration,pole_height,id,distance,heading 0,37.41505,-122.20565,flat3,54.0,0.0,0.0,0.0 100,37.41491,-122.20677,,,,100.0,263.0 @@ -162,8 +162,8 @@ position,latitude,longitude,configuration,pole_height,id,distance,heading 1426,37.41307,-122.2216,,,,1426.0,262.9 1490,37.41298,-122.22232,sideT,48.0,8.0,1490.0,262.9 1590,37.41285,-122.22344,,,,1590.0,263.1 -1690,37.41271,-122.22456,sideT,63.0,9.0,1690.0,263.1 1690,37.41271,-122.22456,,,,1690.0,263.1 +1690,37.41271,-122.22456,sideT,63.0,9.0,1690.0,263.1 1790,37.41257,-122.22568,,,,1790.0,262.9 1890,37.41243,-122.2268,,,,1890.0,262.9 1941,37.41236,-122.22736,sideT,54.0,10.0,1941.0,262.9 @@ -190,16 +190,16 @@ position,latitude,longitude,configuration,pole_height,id,distance,heading 3753,37.40566,-122.24446,,,,3753.0,143.8 3759,37.40562,-122.24443,vert3,51.0,18.0,3759.0,143.8 3859,37.40474,-122.24422,,,,3859.0,166.7 -3878,37.40456,-122.24418,vert3,60.0,19.0,3879.0,166.7 -3978,37.40366,-122.24426,,,,3979.0,185.4 +3878,37.40456,-122.24418,vert3,60.0,19.0,3878.0,166.7 +3978,37.40366,-122.24426,,,,3978.0,185.4 4009,37.40339,-122.24429,vert3,60.0,20.0,4009.0,185.4 4109,37.40254,-122.24466,,,,4109.0,203.4 4115,37.40249,-122.24468,vert3,60.0,21.0,4115.0,203.4 4215,37.40175,-122.24532,,,,4215.0,220.9 -4267,37.40136,-122.24566,vert3,66.0,22.0,4268.0,220.9 -4367,37.40095,-122.24666,,,,4368.0,247.6 -4467,37.40053,-122.24767,,,,4468.0,247.6 -4567,37.40012,-122.24867,,,,4568.0,247.6 +4267,37.40136,-122.24566,vert3,66.0,22.0,4267.0,220.9 +4367,37.40095,-122.24666,,,,4367.0,247.6 +4467,37.40053,-122.24767,,,,4467.0,247.6 +4567,37.40012,-122.24867,,,,4567.0,247.6 4627,37.39987,-122.24927,3pole,48.0,23.0,4627.0,247.6 4727,37.39974,-122.25039,,,,4727.0,263.6 4793,37.39966,-122.25113,2pole,54.0,24.0,4793.0,263.6 @@ -217,8 +217,8 @@ position,latitude,longitude,configuration,pole_height,id,distance,heading 5897,37.39888,-122.26359,,,,5897.0,266.0 5977,37.39882,-122.26449,3pole,54.0,27.0,5977.0,266.0 6077,37.39874,-122.26562,,,,6077.0,266.1 -6119,37.39871,-122.2661,2pole,45.0,28.0,6120.0,266.1 -6219,37.39863,-122.26723,,,,6220.0,266.1 +6119,37.39871,-122.2661,2pole,45.0,28.0,6119.0,266.1 +6219,37.39863,-122.26723,,,,6219.0,266.1 6250,37.39861,-122.26757,3pole,54.0,29.0,6250.0,266.1 6350,37.39783,-122.26814,,,,6350.0,216.5 6450,37.39706,-122.26872,,,,6450.0,216.5 @@ -246,8 +246,8 @@ position,latitude,longitude,configuration,pole_height,id,distance,heading 8340,37.38926,-122.28613,,,,8340.0,242.6 8440,37.38876,-122.28708,,,,8440.0,242.6 8540,37.38827,-122.28803,,,,8540.0,242.6 -8583,37.38806,-122.28844,tower,69.0,36.0,8584.0,242.6 -# geodata merge -D distance ./path_example.csv -k position +8583,37.38806,-122.28844,tower,69.0,36.0,8583.0,242.6 +# geodata merge -D distance ../path_example.csv -k position position,latitude,longitude,configuration,pole_height,id,distance,heading 0,37.41505,-122.20565,flat3,54,0,0.0,0.0 254,37.4147,-122.20849,sideT,60,1,254.0,263.0 @@ -286,7 +286,7 @@ position,latitude,longitude,configuration,pole_height,id,distance,heading 7593,37.39161,-122.2786,2pole,69,34,7593.0,258.5 7840,37.39171,-122.28139,3pole,48,35,7840.0,272.1 8583,37.38806,-122.28844,tower,69,36,8583.0,242.6 -# geodata merge -D distance ./path_example.csv -k location +# geodata merge -D distance ../path_example.csv -k location location,latitude,longitude,configuration,pole_height,id,distance 9q9hg5hw3yyf,37.41505,-122.20565,flat3,54,0,0.0 9q9hg54krv95,37.4147,-122.20849,sideT,60,1,254.0 @@ -325,7 +325,7 @@ location,latitude,longitude,configuration,pole_height,id,distance 9q9h9qzmyj73,37.39161,-122.2786,2pole,69,34,7593.0 9q9h9qvqmpfy,37.39171,-122.28139,3pole,48,35,7840.0 9q9h9q230zd1,37.38806,-122.28844,tower,69,36,8583.0 -# geodata merge -D distance ./path_example.csv -k latitude,longitude +# geodata merge -D distance ../path_example.csv -k latitude,longitude latitude,longitude,configuration,pole_height,id,distance 37.41505,-122.20565,flat3,54,0,0.0 37.4147,-122.20849,sideT,60,1,254.0