File: OdbcCommandBuilder.cs

package info (click to toggle)
mono 6.12.0.199%2Bdfsg-6
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 1,296,836 kB
  • sloc: cs: 11,181,803; xml: 2,850,076; ansic: 699,709; cpp: 123,344; perl: 59,361; javascript: 30,841; asm: 21,853; makefile: 20,405; sh: 15,009; python: 4,839; pascal: 925; sql: 859; sed: 16; php: 1
file content (327 lines) | stat: -rw-r--r-- 14,388 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
//------------------------------------------------------------------------------
// <copyright file="OdbcCommandBuilder.cs" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Globalization;
using System.Text;


namespace System.Data.Odbc {

    public sealed class OdbcCommandBuilder : DbCommandBuilder {

        public OdbcCommandBuilder() : base() {
            GC.SuppressFinalize(this);
        }

        public OdbcCommandBuilder(OdbcDataAdapter adapter) : this() {
            DataAdapter = adapter;
        }

        [
        DefaultValue(null),
        ResCategoryAttribute(Res.DataCategory_Update),
        ResDescriptionAttribute(Res.OdbcCommandBuilder_DataAdapter), // MDAC 60524
        ]
        new public OdbcDataAdapter DataAdapter {
            get {
                return (base.DataAdapter as OdbcDataAdapter);
            }
            set {
                base.DataAdapter = value;
            }
        }

        private void OdbcRowUpdatingHandler(object sender, OdbcRowUpdatingEventArgs ruevent) {
            RowUpdatingHandler(ruevent);
        }

        new public OdbcCommand GetInsertCommand() {
            return (OdbcCommand) base.GetInsertCommand();
        }
        new public OdbcCommand GetInsertCommand(bool useColumnsForParameterNames) {
            return (OdbcCommand) base.GetInsertCommand(useColumnsForParameterNames);
        }

        new public OdbcCommand GetUpdateCommand() {
            return (OdbcCommand) base.GetUpdateCommand();
        }
        new public OdbcCommand GetUpdateCommand(bool useColumnsForParameterNames) {
            return (OdbcCommand) base.GetUpdateCommand(useColumnsForParameterNames);
        }

        new public OdbcCommand GetDeleteCommand() {
            return (OdbcCommand) base.GetDeleteCommand();
        }
        new public OdbcCommand GetDeleteCommand(bool useColumnsForParameterNames) {
            return (OdbcCommand) base.GetDeleteCommand(useColumnsForParameterNames);
        }

        override protected string GetParameterName(int parameterOrdinal) {
            return "p" + parameterOrdinal.ToString(System.Globalization.CultureInfo.InvariantCulture);
        }
        override protected string GetParameterName(string parameterName) {
            return parameterName;
        }

        override protected string GetParameterPlaceholder(int parameterOrdinal) {
            return "?";
        }

        override protected void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause) {
            OdbcParameter p = (OdbcParameter) parameter;
            object valueType = datarow[SchemaTableColumn.ProviderType];
            p.OdbcType = (OdbcType) valueType;

            object bvalue = datarow[SchemaTableColumn.NumericPrecision];
            if (DBNull.Value != bvalue) {
                byte bval = (byte)(short)bvalue;
                p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0);
            }

            bvalue = datarow[SchemaTableColumn.NumericScale];
            if (DBNull.Value != bvalue) {
                byte bval = (byte)(short)bvalue;
                p.ScaleInternal = ((0xff != bval) ? bval : (byte)0);
            }
        }

        static public void DeriveParameters(OdbcCommand command) {
            // MDAC 65927
            OdbcConnection.ExecutePermission.Demand();

            if (null == command) {
                throw ADP.ArgumentNull("command");
            }
            switch (command.CommandType) {
                case System.Data.CommandType.Text:
                    throw ADP.DeriveParametersNotSupported(command);
                case System.Data.CommandType.StoredProcedure:
                    break;
                case System.Data.CommandType.TableDirect:
                    // CommandType.TableDirect - do nothing, parameters are not supported
                    throw ADP.DeriveParametersNotSupported(command);
                default:
                    throw ADP.InvalidCommandType(command.CommandType);
            }
            if (ADP.IsEmpty(command.CommandText)) {
                throw ADP.CommandTextRequired(ADP.DeriveParameters);
            }

            OdbcConnection connection = command.Connection;

            if (null == connection) {
                throw ADP.ConnectionRequired(ADP.DeriveParameters);
            }

            ConnectionState state = connection.State;

            if (ConnectionState.Open != state) {
                throw ADP.OpenConnectionRequired(ADP.DeriveParameters, state);
            }

            OdbcParameter[] list = DeriveParametersFromStoredProcedure(connection, command);

            OdbcParameterCollection parameters = command.Parameters;
            parameters.Clear();

            int count = list.Length;
            if (0 < count) {
                for(int i = 0; i < list.Length; ++i) {
                    parameters.Add(list[i]);
                }
            }
            }


        // DeriveParametersFromStoredProcedure (
        //  OdbcConnection connection,
        //  OdbcCommand command);
        //
        // Uses SQLProcedureColumns to create an array of OdbcParameters
        //

        static private OdbcParameter[] DeriveParametersFromStoredProcedure(OdbcConnection connection, OdbcCommand command) {
            List<OdbcParameter> rParams = new List<OdbcParameter>();

            // following call ensures that the command has a statement handle allocated
            CMDWrapper cmdWrapper = command.GetStatementHandle();
            OdbcStatementHandle hstmt = cmdWrapper.StatementHandle;
            int cColsAffected;

            // maps an enforced 4-part qualified string as follows
            // parts[0] = null  - ignored but removal would be a run-time breaking change from V1.0
            // parts[1] = CatalogName (optional, may be null)
            // parts[2] = SchemaName (optional, may be null)
            // parts[3] = ProcedureName
            //
            string quote = connection.QuoteChar(ADP.DeriveParameters);
            string[] parts = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quote, quote, '.', 4, true, Res.ODBC_ODBCCommandText, false);          
            if (null == parts[3]) { // match everett behavior, if the commandtext is nothing but whitespace set the command text to the whitespace
                parts[3] = command.CommandText;
            }
            // note: native odbc appears to ignore all but the procedure name
            ODBC32.RetCode retcode = hstmt.ProcedureColumns(parts[1], parts[2], parts[3], null);

            // Note: the driver does not return an error if the given stored procedure does not exist
            // therefore we cannot handle that case and just return not parameters.

            if (ODBC32.RetCode.SUCCESS != retcode) {
                connection.HandleError(hstmt, retcode);
            }

            using (OdbcDataReader reader = new OdbcDataReader(command, cmdWrapper, CommandBehavior.Default)) {
                reader.FirstResult();
                cColsAffected = reader.FieldCount;

                // go through the returned rows and filter out relevant parameter data
                //
                while (reader.Read()) {
                    // devnote: column types are specified in the ODBC Programmer's Reference
                    // COLUMN_TYPE      Smallint    16bit
                    // COLUMN_SIZE      Integer     32bit
                    // DECIMAL_DIGITS   Smallint    16bit
                    // NUM_PREC_RADIX   Smallint    16bit

                    OdbcParameter parameter = new OdbcParameter();

                    parameter.ParameterName = reader.GetString(ODBC32.COLUMN_NAME-1);
                    switch ((ODBC32.SQL_PARAM)reader.GetInt16(ODBC32.COLUMN_TYPE-1)){
                        case ODBC32.SQL_PARAM.INPUT:
                            parameter.Direction = ParameterDirection.Input;
                            break;
                        case ODBC32.SQL_PARAM.OUTPUT:
                            parameter.Direction = ParameterDirection.Output;
                            break;

                        case ODBC32.SQL_PARAM.INPUT_OUTPUT:
                            parameter.Direction = ParameterDirection.InputOutput;
                            break;
                        case ODBC32.SQL_PARAM.RETURN_VALUE:
                            parameter.Direction = ParameterDirection.ReturnValue;
                            break;
                        default:
                            Debug.Assert(false, "Unexpected Parametertype while DeriveParamters");
                            break;
                    }
                    parameter.OdbcType = TypeMap.FromSqlType((ODBC32.SQL_TYPE)reader.GetInt16(ODBC32.DATA_TYPE-1))._odbcType;
                    parameter.Size = (int)reader.GetInt32(ODBC32.COLUMN_SIZE-1);
                    switch(parameter.OdbcType){
                        case OdbcType.Decimal:
                        case OdbcType.Numeric:
                            parameter.ScaleInternal = (Byte)reader.GetInt16(ODBC32.DECIMAL_DIGITS-1);
                            parameter.PrecisionInternal = (Byte)reader.GetInt16(ODBC32.NUM_PREC_RADIX-1);
                        break;
                    }
                    rParams.Add (parameter);
                }
            }
            retcode = hstmt.CloseCursor();
            return rParams.ToArray();;
        }

        public override string QuoteIdentifier(string unquotedIdentifier){
            return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
        }
        public string QuoteIdentifier( string unquotedIdentifier, OdbcConnection connection){

            ADP.CheckArgumentNull(unquotedIdentifier, "unquotedIdentifier");

            // if the user has specificed a prefix use the user specified  prefix and suffix
            // otherwise get them from the provider
            string quotePrefix = QuotePrefix;
            string quoteSuffix = QuoteSuffix;
            if (ADP.IsEmpty(quotePrefix) == true) {
                if (connection == null) {
                    // VSTFDEVDIV 479567: use the adapter's connection if QuoteIdentifier was called from 
                    // DbCommandBuilder instance (which does not have an overload that gets connection object)
                    connection = base.GetConnection() as OdbcConnection;
                    if (connection == null) {
                        throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier);
                    }
                }
                quotePrefix = connection.QuoteChar(ADP.QuoteIdentifier);
                quoteSuffix = quotePrefix;
            }

            // by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned."
            // So if a blank is returned the string is returned unchanged. Otherwise the returned string is used
            // to quote the string
            if ((ADP.IsEmpty(quotePrefix) == false) && (quotePrefix != " ")) {
                return ADP.BuildQuotedString(quotePrefix,quoteSuffix,unquotedIdentifier);
            }
            else {
                return unquotedIdentifier;
            }
        }



        override protected void SetRowUpdatingHandler(DbDataAdapter adapter) {
            Debug.Assert(adapter is OdbcDataAdapter, "!OdbcDataAdapter");
            if (adapter == base.DataAdapter) { // removal case
                ((OdbcDataAdapter)adapter).RowUpdating -= OdbcRowUpdatingHandler;
            }
            else { // adding case
                ((OdbcDataAdapter)adapter).RowUpdating += OdbcRowUpdatingHandler;
            }
        }

        public override string UnquoteIdentifier( string quotedIdentifier){
            return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
        }

        public string UnquoteIdentifier(string quotedIdentifier, OdbcConnection connection){

            ADP.CheckArgumentNull(quotedIdentifier, "quotedIdentifier");


            // if the user has specificed a prefix use the user specified  prefix and suffix
            // otherwise get them from the provider
            string quotePrefix = QuotePrefix;
            string quoteSuffix = QuoteSuffix;
            if (ADP.IsEmpty(quotePrefix) == true) {
                if (connection == null) {
                    // VSTFDEVDIV 479567: use the adapter's connection if UnquoteIdentifier was called from 
                    // DbCommandBuilder instance (which does not have an overload that gets connection object)
                    connection = base.GetConnection() as OdbcConnection;
                    if (connection == null) {
                        throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier);
                    }
                }
                quotePrefix = connection.QuoteChar(ADP.UnquoteIdentifier);
                quoteSuffix = quotePrefix;
            }

            String unquotedIdentifier;
            // by the ODBC spec "If the data source does not support quoted identifiers, a blank is returned."
            // So if a blank is returned the string is returned unchanged. Otherwise the returned string is used
            // to unquote the string
            if ((ADP.IsEmpty(quotePrefix) == false) || (quotePrefix != " ")) {
                // ignoring the return value because it is acceptable for the quotedString to not be quoted in this
                // context.
                ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier);
            }
            else {
                unquotedIdentifier = quotedIdentifier;
            }
            return unquotedIdentifier;

        }

    }
}