Пример #1
0
 public static string GetBuilderName(SqlType sql, string tableName)
 {
     string result = GetModel(sql, tableName) ?? tableName;
     result = result.Substring(0, 1).ToLower() + result.Substring(1);
     result += "Builder";
     return result;
 }
Пример #2
0
        public bool RunSprocs(DirectoryInfo directory, SqlType dialect, DatabaseTable table)
        {
            if (table == null)
            {
                Message = "No table";
                return false;
            }

            var gen = new DdlGeneratorFactory(dialect).ProcedureGenerator(table);
            if (gen == null)
            {
                //there is no sproc provider (SQLite)
                Message = @"There is no sproc generator";
                return false;
            }
            var path = Path.Combine(directory.FullName, table.Name + "_sprocs.sql");
            try
            {
                gen.WriteToScript(path);
                Message = @"Wrote " + path;
                return true;
            }
            catch (Exception exception)
            {
                Message =
                    @"An error occurred while creating the script.\n" + exception.Message;
            }
            return false;
        }
Пример #3
0
 public bool RunTableDdl(DirectoryInfo directory, SqlType dialect)
 {
     var tg = new DdlGeneratorFactory(dialect).AllTablesGenerator(_databaseSchema);
     tg.IncludeSchema = false;
     string txt;
     try
     {
         txt = tg.Write();
     }
     catch (Exception exception)
     {
         Message =
             @"An error occurred while creating the script.\n" + exception.Message;
         return false;
     }
     try
     {
         var path = Path.Combine(directory.FullName, "table.sql");
         File.WriteAllText(path, txt);
         Message = @"Wrote " + path;
         return true;
     }
     catch (Exception exception)
     {
         Message =
             @"An IO error occurred while writing the file.\n" + exception.Message;
     }
     return false;
 }
Пример #4
0
        public IndexCollation(SqlType type, CollationColumn[] columns, string function)
        {
            if (columns.Length == 0)
                throw new ArgumentException("Cannot create an empty collation.", "columns");

            if (columns.Length > 1) {
                if (!(type is SqlCompositeType))
                    throw new ArgumentException("Composite indexes must be represented by composite-type");

                SqlCompositeType ctype = (SqlCompositeType) type;
                if (ctype.PartCount != columns.Length)
                    throw new ArgumentException("Composite type size different to the number of columns given", "columns");
            }

            // Can't contain identical columns
            for (int i = 0; i < columns.Length; ++i) {
                for (int n = 0; n < columns.Length; ++n) {
                    if (i != n && columns[i].ColumnName.Equals(columns[n].ColumnName))
                        throw new ArgumentException("Repeat column '" + columns[i] +"' name");
                }
            }

            this.type = type;
            this.function = function;
            this.columns = (CollationColumn[]) columns.Clone();
        }
Пример #5
0
 public virtual TableColumn Add(string columnName, SqlType columnType, bool notNull)
 {
     CheckNotReadOnly();
     TableColumn column = new TableColumn(table, -1, columnName, columnType, notNull);
     columns.Add(column);
     return column;
 }
Пример #6
0
 public Table(string schema, string table, string alias, SqlType sqlType = SqlType.SqlServer)
 {
     this.SchemaName = schema;
     this.TableName = table;
     this.Alias = alias;
     this.formatModel = sqlType.BuildFormatSystemModel();
 }
Пример #7
0
 public ColumnAttribute(string name, SqlType type, int size, int scale)
 {
     this.name = name;
     this.type = type;
     this.size = size;
     this.scale = scale;
 }
Пример #8
0
        public override DataObject CastTo(DataObject value, SqlType destType)
        {
            var bValue = ((SqlBoolean) value.Value);
            if (destType is StringType) {
                var s = Convert.ToString(bValue);
                // TODO: Provide a method in StringType to build a string specific to the type
                return new DataObject(destType, new SqlString(s));
            }
            if (destType is NumericType) {
                SqlNumber num;
                if (bValue == SqlBoolean.Null) {
                    num = SqlNumber.Null;
                } else if (bValue) {
                    num = SqlNumber.One;
                } else {
                    num = SqlNumber.Zero;
                }

                return new DataObject(destType, num);
            }
            if (destType is BinaryType) {
                var bytes = (byte[]) Convert.ChangeType(bValue, typeof (byte[]), CultureInfo.InvariantCulture);
                return new DataObject(destType, new SqlBinary(bytes));
            }
            if (destType is BooleanType)
                return value;

            return base.CastTo(value, destType);
        }
Пример #9
0
 public override bool CanCastTo(SqlType destType)
 {
     return destType is StringType ||
            destType is NumericType ||
            destType is BinaryType ||
            destType is BooleanType;
 }
Пример #10
0
 /// <summary>
 /// トランザクション付きコマンドの取得
 /// </summary>
 /// <param name="dao"></param>
 /// <param name="tx"></param>
 /// <param name="serverType"></param>
 /// <returns></returns>
 public static DbCommand CommandTransaction(this IDao dao, DbTransaction tx, SqlType serverType)
 {
     switch (serverType)
     {
         case SqlType.SqlServer:
             {
                 var command = new SqlCommand();
                 command.Connection = (SqlConnection)dao.Con;
                 command.Transaction = (SqlTransaction)tx;
                 if (log.IsInfoEnabled)
                 {
                     log.Info("command type is SqlCommand.");
                 }
                 return command;
             }
         default:
             {
                 if (log.IsErrorEnabled)
                 {
                     log.Error("Don't supported command type. Type is " + Enum.GetName(typeof(SqlType), serverType));
                 }
                 return null;
             }
     }
 }
Пример #11
0
 public RoutineParameter(string name, SqlType type, ParameterDirection direction, ParameterAttributes attributes)
 {
     Attributes = attributes;
     Direction = direction;
     Type = type;
     Name = name;
 }
 public SqlWriterCommonTest(SqlType sqlType, DatabaseTable table, DbProviderFactory factory, string connectionString)
 {
     _connectionString = connectionString;
     _factory = factory;
     _table = table;
     _sqlType = sqlType;
 }
Пример #13
0
 public static SchemaExtendedReader Create(string connectionString, SqlType sqlType)
 {
     SchemaExtendedReader schemaReader;
     switch (sqlType)
     {
         case SqlType.Oracle:
             schemaReader = new OracleSchemaReader(connectionString, "System.Data.OracleClient");
             break;
         case SqlType.SqlServer:
             schemaReader = new SqlAzureOrSqlServerSchemaReader(connectionString, "System.Data.SqlClient");
             break;
         case SqlType.SqlServerCe:
             schemaReader = new SqlServerCeSchemaReader(connectionString, "System.Data.SqlServerCe.4.0");
             break;
         case SqlType.MySql:
             schemaReader = new MySqlSchemaReader(connectionString, "MySql.Data.MySqlClient");
             break;
         case SqlType.PostgreSql:
             schemaReader = new PostgreSqlSchemaReader(connectionString, "Npgsql");
             break;
         case SqlType.Db2:
             schemaReader = new Db2SchemaReader(connectionString, "IBM.Data.DB2");
             break;
         case SqlType.SQLite:
             schemaReader = new SchemaExtendedReader(connectionString, "System.Data.SQLite");
             break;
         default:
             throw new ArgumentOutOfRangeException("sqlType", "Not a recognized SqlType");
     }
     return schemaReader;
 }
Пример #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DatabaseSchema"/> class.
 /// </summary>
 /// <param name="connectionString">The connection string.</param>
 /// <param name="sqlType">Type of the provider</param>
 public DatabaseSchema(string connectionString, SqlType sqlType)
     :this(connectionString, null)
 {
     switch (sqlType)
     {
         case SqlType.SqlServer:
             Provider = "System.Data.SqlClient";
             break;
         case SqlType.Oracle:
             Provider = "System.Data.OracleClient";
             break;
         case SqlType.MySql:
             Provider = "MySql.Data.MySqlClient";
             break;
         case SqlType.SQLite:
             Provider = "System.Data.SQLite";
             break;
         case SqlType.SqlServerCe:
             Provider = "System.Data.SqlServerCe.4.0";
             break;
         case SqlType.PostgreSql:
             Provider = "Npgsql";
             break;
         case SqlType.Db2:
             Provider = "IBM.Data.DB2";
             break;
         default:
             throw new ArgumentOutOfRangeException("sqlType");
     }
 }
Пример #15
0
 public FunctionInfo(ObjectName routineName, RoutineParameter[] parameters, SqlType returnType, FunctionType functionType)
     : base(routineName, parameters)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Пример #16
0
        public ReturnTypeVisitor(IQueryContext queryContext, IVariableResolver variableResolver)
        {
            this.queryContext = queryContext;
            this.variableResolver = variableResolver;

            sqlType = PrimitiveTypes.Null();
        }
Пример #17
0
 public FunctionInfo(ObjectName routineName, SqlType returnType, FunctionType functionType)
     : base(routineName)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Пример #18
0
        public static bool IsPrimitive(SqlType sqlType)
        {
            if (sqlType == SqlType.Numeric ||
                sqlType == SqlType.TinyInt ||
                sqlType == SqlType.SmallInt ||
                sqlType == SqlType.Integer ||
                sqlType == SqlType.BigInt ||
                sqlType == SqlType.Real ||
                sqlType == SqlType.Double ||
                sqlType == SqlType.Float ||
                sqlType == SqlType.Decimal)
                return true;

            if (sqlType == SqlType.BigInt ||
                sqlType == SqlType.Boolean)
                return true;

            if (sqlType == SqlType.Char ||
                sqlType == SqlType.VarChar ||
                sqlType == SqlType.LongVarChar ||
                sqlType == SqlType.String ||
                sqlType == SqlType.Clob)
                return true;

            if (sqlType == SqlType.Binary ||
                sqlType == SqlType.VarBinary ||
                sqlType == SqlType.LongVarBinary ||
                sqlType == SqlType.Blob)
                return true;

            return false;
        }
Пример #19
0
        public override bool IsComparable(SqlType type)
        {
            var otherType = type as SpatialType;
            if (otherType == null)
                return false;

            return IsComparable(otherType);
        }
Пример #20
0
 public static GenSqlDALBase CreateInstance(SqlType sql)
 {
     if (GlobalService.DbType == DatabaseType.SqlServer)
     {
         return new SqlServer.SqlGenSqlDAL(sql);
     }
     return null;
 }
Пример #21
0
 internal MemberMapping(TypeMapping typeMapping, string memberName, string columnName, SqlType columnType, bool notNull)
 {
     TypeMapping = typeMapping;
     MemberName = memberName;
     ColumnName = columnName;
     ColumnType = columnType;
     NotNull = notNull;
 }
Пример #22
0
        public override bool IsComparableTo(SqlType type)
        {
            SqlUserType userType = (SqlUserType) type;
            if (userType == null)
                return false;

            return comparable && typeName.Equals(userType.typeName);
        }
Пример #23
0
 public AliasTableNameExpression(Expression child, TableName alias, SqlType returnType)
     : base(ExpressionType.AliasTableName)
 {
     SetArgument("child", child);
     SetArgument("alias", alias);
     if (returnType != null)
         SetArgument("return_type", returnType);
 }
Пример #24
0
        public IColumnInfoBuilder HavingType(SqlType value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            type = value;
            return this;
        }
Пример #25
0
 /// <summary>
 /// The Constructors if the type does require a size.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="type"></param>
 /// <param name="notNull"></param>
 private QueryResultColumn(string name, SqlType type, bool notNull)
 {
     Name = name;
     Type = type;
     IsNotNull = notNull;
     IsUnique = false;
     UniqueGroup = -1;
 }
Пример #26
0
        public IColumnBuilder OfType(SqlType type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            columnType = type;
            return this;
        }
Пример #27
0
 public static string GetModel(SqlType sql, string table)
 {
     foreach (var m in sql.MyModels)
     {
         if (m.ColumnSetName.Value.Equals(table))
             return m.Name.Value;
     }
     return null;
 }
Пример #28
0
 public static bool IsPagerQuery(SqlType sql)
 {
     if (sql.HasPagerContentTable() && sql.HasPagerRecordCountTable())
     {
         return (!string.IsNullOrWhiteSpace(sql.PagerContentTable.Value) &&
             !string.IsNullOrWhiteSpace(sql.PagerRecordCountTable.Value));
     }
     return false;
 }
Пример #29
0
        public ExternalFunctionInfo(ObjectName functionName, RoutineParameter[] parameters, SqlType returnType,
			ExternalRef externalRef)
            : base(functionName, parameters, returnType, FunctionType.Static)
        {
            if (externalRef == null)
                throw new ArgumentNullException("externalRef");

            ExternalRef = externalRef;
        }
Пример #30
0
 public SqlCreate(string tableName, SqlType sqlType)
 {
     this.tableName = tableName;
     this.sqlType = sqlType;
     if (sqlType == SqlType.UPDATE)
     {
         this.updateBuilder.AppendFormat("UPDATE {0} SET ", tableName);
     }
 }
Пример #31
0
 protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
 {
     base.InitializeParameter(dbParam, name, sqlType);
     SetVariableLengthParameterSize(dbParam, sqlType);
 }
Пример #32
0
 /// <summary>
 /// Allows access to the basic <see cref="Dialect.GetSelectClauseNullString"/>
 /// implementation...
 /// </summary>
 /// <param name="sqlType">The <see cref="SqlType"/> mapping type</param>
 /// <returns> The appropriate select cluse fragment </returns>
 public virtual string GetBasicSelectClauseNullString(SqlType sqlType)
 {
     return(base.GetSelectClauseNullString(sqlType));
 }
Пример #33
0
 /// <summary>
 /// Construct a new <see cref="QueryType"/> instance from
 /// </summary>
 protected virtual QueryType NewType(SqlType type, bool isNotNull, int length, short precision, short scale)
 {
     return(new SqlQueryType(type, isNotNull, length, precision, scale));
 }
Пример #34
0
        /// <summary>
        /// Gets the <see cref="QueryType"/> for a know database type.
        /// This API does not parse the type name.
        /// Arguments to the type are specified by the <see cref="P:args"/> parameter.
        /// </summary>
        /// <param name="typeName">The base name of a type in the databases language.</param>
        /// <param name="args">Any additional arguments (like length of a text type)</param>
        /// <param name="isNotNull">Determines if the type cannot be null.</param>
        public virtual QueryType GetQueryType(string typeName, string[] args, bool isNotNull)
        {
            if (String.Compare(typeName, "rowversion", StringComparison.OrdinalIgnoreCase) == 0)
            {
                typeName = "Timestamp";
            }

            if (String.Compare(typeName, "numeric", StringComparison.OrdinalIgnoreCase) == 0)
            {
                typeName = "Decimal";
            }

            if (String.Compare(typeName, "sql_variant", StringComparison.OrdinalIgnoreCase) == 0)
            {
                typeName = "Variant";
            }

            SqlType dbType = this.GetSqlType(typeName);

            int   length    = 0;
            short precision = 0;
            short scale     = 0;

            switch (dbType)
            {
            case SqlType.Binary:
            case SqlType.Char:
            case SqlType.Image:
            case SqlType.NChar:
            case SqlType.NVarChar:
            case SqlType.VarBinary:
            case SqlType.VarChar:
                if (args == null || args.Length < 1)
                {
                    length = 80;
                }
                else if (string.Compare(args[0], "max", StringComparison.OrdinalIgnoreCase) == 0)
                {
                    length = Int32.MaxValue;
                }
                else
                {
                    length = Int32.Parse(args[0]);
                }
                break;

            case SqlType.Money:
                if (args == null || args.Length < 1)
                {
                    precision = 29;
                }
                else
                {
                    precision = Int16.Parse(args[0], NumberFormatInfo.InvariantInfo);
                }
                if (args == null || args.Length < 2)
                {
                    scale = 4;
                }
                else
                {
                    scale = Int16.Parse(args[1], NumberFormatInfo.InvariantInfo);
                }
                break;

            case SqlType.Decimal:
                if (args == null || args.Length < 1)
                {
                    precision = 29;
                }
                else
                {
                    precision = Int16.Parse(args[0], NumberFormatInfo.InvariantInfo);
                }
                if (args == null || args.Length < 2)
                {
                    scale = 0;
                }
                else
                {
                    scale = Int16.Parse(args[1], NumberFormatInfo.InvariantInfo);
                }
                break;

            case SqlType.Float:
            case SqlType.Real:
                if (args == null || args.Length < 1)
                {
                    precision = 29;
                }
                else
                {
                    precision = Int16.Parse(args[0], NumberFormatInfo.InvariantInfo);
                }
                break;
            }

            return(NewType(dbType, isNotNull, length, precision, scale));
        }
Пример #35
0
 public OneTestsWithFunLogic(SqlType testFlavour)
     : base(testFlavour)
 {
 }
Пример #36
0
 public MappedJoinTests(SqlType testFlavour)
     : base(testFlavour)
 {
 }
Пример #37
0
 public static SqlType DateTimeOffset()
 {
     return(SqlType.Type("datetimeoffset"));
 }
Пример #38
0
        public void Configure(IType type, IDictionary <string, string> parms, Dialect dialect)
        {
            tableName   = PropertiesHelper.GetString(TableParamName, parms, DefaultTableName);
            columnName  = PropertiesHelper.GetString(ColumnParamName, parms, DefaultColumnName);
            whereColumn = PropertiesHelper.GetString(WhereColumn, parms, DefaultWhereColumnName);
            whereValue  = PropertiesHelper.GetString(WhereValue, parms, string.Empty);
            max_lo      = PropertiesHelper.GetInt64(MaxLo, parms, Int16.MaxValue);
            lo          = max_lo + 1;
            returnClass = type.ReturnedClass;

            if (string.IsNullOrEmpty(whereValue))
            {
                log.Error("wherevalue for SingleTableHiLoGenerator is empty");
                throw new InvalidOperationException("wherevalue is empty");
            }

            whereValues.Add(whereValue);

            var schemaName  = PropertiesHelper.GetString(PersistentIdGeneratorParmsNames.Schema, parms, null);
            var catalogName = PropertiesHelper.GetString(PersistentIdGeneratorParmsNames.Catalog, parms, null);

            if (tableName.IndexOf('.') < 0)
            {
                tableName = dialect.Qualify(catalogName, schemaName, tableName);
            }

            var selectBuilder = new SqlStringBuilder(100);

            selectBuilder.Add("select " + columnName)
            .Add(" from " + dialect.AppendLockHint(LockMode.Upgrade, tableName))
            .Add(" where ")
            .Add(whereColumn).Add("=").Add(whereValue);

            selectBuilder.Add(dialect.ForUpdateString);

            query = selectBuilder.ToString();

            columnType = type as PrimitiveType;
            if (columnType == null)
            {
                log.Error("Column type for TableGenerator is not a value type");
                throw new ArgumentException("type is not a ValueTypeType", "type");
            }

            // build the sql string for the Update since it uses parameters
            if (type is Int16Type)
            {
                columnSqlType = SqlTypeFactory.Int16;
            }
            else if (type is Int64Type)
            {
                columnSqlType = SqlTypeFactory.Int64;
            }
            else
            {
                columnSqlType = SqlTypeFactory.Int32;
            }
            wherecolumnSqlType = SqlTypeFactory.GetString(255);

            parameterTypes = new[] { columnSqlType, columnSqlType };

            var builder = new SqlStringBuilder(100);

            builder.Add("update " + tableName + " set ")
            .Add(columnName).Add("=").Add(Parameter.Placeholder)
            .Add(" where ")
            .Add(columnName).Add("=").Add(Parameter.Placeholder)
            .Add(" and ")
            .Add(whereColumn).Add("=").Add(whereValue);

            updateSql = builder.ToSqlString();
        }
Пример #39
0
 public static SqlType DateTime()
 {
     return(SqlType.Type("datetime"));
 }
Пример #40
0
        protected override void InitializeParameter(DbParameter dbParam, string name, SqlType sqlType)
        {
            var convertedSqlType = sqlType;

            if (convertedSqlType.DbType == DbType.Currency)
            {
                convertedSqlType = new SqlType(DbType.Decimal);
            }

            base.InitializeParameter(dbParam, name, convertedSqlType);
        }
Пример #41
0
 /// <summary>
 /// Initialize a new instance of the ImmutableType class using a
 /// <see cref="SqlType"/>.
 /// </summary>
 /// <param name="sqlType">The underlying <see cref="SqlType"/>.</param>
 protected ImmutableType(SqlType sqlType) : base(sqlType)
 {
 }
 public SqlManipulationCore(string strDSN, SqlType sqlType)
 {
     _sqlType = sqlType;
     _strDSN  = strDSN;
 }
Пример #43
0
 /// <summary>
 /// Interprets if a parameter is a Clob (for the purposes of setting its default size)
 /// </summary>
 /// <param name="dbParam">The parameter</param>
 /// <param name="sqlType">The <see cref="SqlType" /> of the parameter</param>
 /// <returns>True, if the parameter should be interpreted as a Clob, otherwise False</returns>
 protected static bool IsText(IDbDataParameter dbParam, SqlType sqlType)
 {
     return((sqlType is StringClobSqlType) || ((DbType.String == dbParam.DbType || DbType.StringFixedLength == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MaxSizeForLengthLimitedString)));
 }
Пример #44
0
 /****   Date & Time   ****/
 public static SqlType SmallDateTime()
 {
     return(SqlType.Type("smalldatetime"));
 }
Пример #45
0
 /****   Exact Numerics   ****/
 public static SqlType Bit()
 {
     return(SqlType.Type("bit"));
 }
Пример #46
0
        protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
        {
            base.InitializeParameter(dbParam, name, sqlType);

            if (sqlType.LengthDefined)
            {
                dbParam.Size = sqlType.Length;
            }
        }
Пример #47
0
        /// <summary>
        /// Push down computations to Hyper during Insertion using expressions
        /// </summary>
        /// <param name="exampleDataDir">Path to the directory with example data.</param>
        public override void Execute(string exampleDataDir)
        {
            Console.WriteLine("EXAMPLE - Push down computations to Hyper during Insertion using Expressions");

            // Start the Hyper process with telemetry enabled.
            using (HyperProcess hyper = new HyperProcess(Telemetry.SendUsageDataToTableau))
            {
                // Connect to hyper and create new Hyper file "superstore.hyper".
                // Replaces file if it already exists when CreateMode.CreateAndReplace is set.
                using (Connection connection = new Connection(hyper.Endpoint, "orders.hyper", CreateMode.CreateAndReplace))
                {
                    // The table is called "Extract" and will be created in the "Extract" schema.
                    // This has historically been the default table name and schema for extracts created by Tableau.
                    TableName       extractTable           = new TableName("Extract", "Extract");
                    TableDefinition extractTableDefinition = new TableDefinition(extractTable)
                                                             .AddColumn("Order ID", SqlType.Int(), Nullability.NotNullable)
                                                             .AddColumn("Ship Timestamp", SqlType.Timestamp(), Nullability.NotNullable)
                                                             .AddColumn("Ship Mode", SqlType.Text(), Nullability.NotNullable)
                                                             .AddColumn("Ship Priority", SqlType.Int(), Nullability.NotNullable);

                    // Create the schema and the table
                    connection.Catalog.CreateSchema("Extract");
                    connection.Catalog.CreateTable(extractTableDefinition);

                    // Hyper API's Inserter allows users to transform data during insertion.
                    // To make use of data transformation during insertion, the inserter requires the following inputs
                    //   1. The connection to the Hyper instance containing the table.
                    //   2. The table name or table defintion into which data is inserted.
                    //   3. List of Inserter.ColumnMapping.
                    //       This list informs the inserter how each column in the target table must be tranformed.
                    //       The list must contain all the columns into which data is inserted.
                    //       "Inserter.ColumnMapping" maps a valid SQL expression (if any) to a column in the target table
                    //       For example new Inserter.ColumnMapping("target_column", $"{Sql.EscapeName("colA")}*{Sql.EscapeName("colB")})
                    //       The column "target_column" contains the product of "colA" and "colB" after successful insertion.
                    //       SQL expression string is optional in Inserter.ColumnMapping.
                    //       For a column without any transformation (identity transformation) only the column name is required.
                    //       For example new Inserter.ColumnMapping("no_data_transformation_column")
                    //   4. Inserter Definition, a list of column definitions for all the input values provided during insertion.

                    // Inserter definition contains the column definition for the values that are inserted.
                    List <TableDefinition.Column> inserterDefinition = new List <TableDefinition.Column>();
                    inserterDefinition.Add(new TableDefinition.Column("Order ID", SqlType.Int(), Nullability.NotNullable));
                    inserterDefinition.Add(new TableDefinition.Column("Ship Timestamp Text", SqlType.Text(), Nullability.NotNullable));
                    inserterDefinition.Add(new TableDefinition.Column("Ship Mode", SqlType.Text(), Nullability.NotNullable));
                    inserterDefinition.Add(new TableDefinition.Column("Ship Priority Text", SqlType.Text(), Nullability.NotNullable));

                    // Column 'Order Id' is inserted into "Extract"."Extract" as-is.
                    // Column 'Ship Timestamp' in "Extract"."Extract" of timestamp type is computed from Column 'Ship Timestamp Text' of text type using 'to_timestamp()'.
                    // Column 'Ship Mode' is inserted into "Extract"."Extract" as-is.
                    // Column 'Ship Priority' is "Extract"."Extract" of integer type is computed from Colum 'Ship Priority Text' of text type using 'CASE' statement.
                    string textToTimeStampExpression       = $"to_timestamp({Sql.EscapeName("Ship Timestamp Text")}, {Sql.EscapeStringLiteral("YYYY-MM-DD HH24:MI:SS")})";
                    string shipPriorityAsIntCaseExpression = $"CASE {Sql.EscapeName("Ship Priority Text")}" +
                                                             $" WHEN {Sql.EscapeStringLiteral("Urgent")} THEN 1 " +
                                                             $" WHEN {Sql.EscapeStringLiteral("Medium")} THEN 2 " +
                                                             $" WHEN {Sql.EscapeStringLiteral("Low")} THEN 3 END";

                    List <Inserter.ColumnMapping> columnMappings = new List <Inserter.ColumnMapping>();
                    columnMappings.Add(new Inserter.ColumnMapping("Order ID"));
                    columnMappings.Add(new Inserter.ColumnMapping("Ship Timestamp", textToTimeStampExpression));
                    columnMappings.Add(new Inserter.ColumnMapping("Ship Mode"));
                    columnMappings.Add(new Inserter.ColumnMapping("Ship Priority", shipPriorityAsIntCaseExpression));

                    // Insert data into the "Extract"."Extract" table with expressions.
                    using (Inserter inserter = new Inserter(connection, extractTable, columnMappings, inserterDefinition))
                    {
                        inserter.AddRow(399, "2012-09-13 10:00:00", "Express Class", "Urgent");
                        inserter.AddRow(530, "2012-07-12 14:00:00", "Standard Class", "Low");
                        inserter.Execute();
                    }

                    // ExecuteScalarQuery is for executing a query that returns exactly one row with one column.
                    long count = connection.ExecuteScalarQuery <long>($"SELECT COUNT(*) FROM {extractTable}");
                    Console.WriteLine($"Table {extractTable} has a count of {count} rows");
                }

                Console.WriteLine("The connection to the Hyper file has been closed.");
            }

            Console.WriteLine("The Hyper process has been shut down.");
        }
Пример #48
0
        protected string GenerateSubquery(PersistentClass model, IMapping mapping)
        {
            Dialect.Dialect dialect  = Factory.Dialect;
            Settings        settings = Factory.Settings;

            if (!model.HasSubclasses)
            {
                return(model.Table.GetQualifiedName(dialect, settings.DefaultCatalogName, settings.DefaultSchemaName));
            }

            HashedSet <Column> columns = new HashedSet <Column>();

            foreach (Table table in model.SubclassTableClosureIterator)
            {
                if (!table.IsAbstractUnionTable)
                {
                    foreach (Column column in table.ColumnIterator)
                    {
                        columns.Add(column);
                    }
                }
            }

            StringBuilder buf = new StringBuilder().Append("( ");
            IEnumerable <PersistentClass> siter =
                new JoinedEnumerable <PersistentClass>(new SingletonEnumerable <PersistentClass>(model),
                                                       new SafetyEnumerable <PersistentClass>(model.SubclassIterator));

            foreach (PersistentClass clazz in siter)
            {
                Table table = clazz.Table;
                if (!table.IsAbstractUnionTable)
                {
                    buf.Append("select ");
                    foreach (Column col in columns)
                    {
                        if (!table.ContainsColumn(col))
                        {
                            SqlType sqlType = col.GetSqlTypeCode(mapping);
                            buf.Append(dialect.GetSelectClauseNullString(sqlType)).Append(" as ");
                        }
                        buf.Append(col.Name);
                        buf.Append(StringHelper.CommaSpace);
                    }
                    buf.Append(clazz.SubclassId).Append(" as clazz_");
                    buf.Append(" from ").Append(table.GetQualifiedName(dialect, settings.DefaultCatalogName, settings.DefaultSchemaName));
                    buf.Append(" union ");
                    if (dialect.SupportsUnionAll)
                    {
                        buf.Append("all ");
                    }
                }
            }

            if (buf.Length > 2)
            {
                //chop the last union (all)
                buf.Length -= (dialect.SupportsUnionAll ? 11 : 7);                 //" union " : "all "
            }

            return(buf.Append(" )").ToString());
        }
Пример #49
0
            protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
            {
                base.InitializeParameter(dbParam, name, sqlType);

                if (sqlType.DbType == DbType.Binary)
                {
                    _dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.Image, null);
                    return;
                }

                if (sqlType.Length <= 4000)
                {
                    return;
                }

                switch (sqlType.DbType)
                {
                case DbType.String:
                    _dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.NText, null);
                    break;

                case DbType.AnsiString:
                    _dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.Text, null);
                    break;
                }
            }
Пример #50
0
 public static SqlType Real()
 {
     return(SqlType.ApproximateNumeric("real", 24));
 }
Пример #51
0
 public AbstractCharType(SqlType sqlType)
     : base(sqlType)
 {
 }
Пример #52
0
 public static SqlType Xml()
 {
     return(SqlType.Type("xml"));
 }
Пример #53
0
 internal static string GetParameterType(this SqlType SqlType, int?Size)
 {
     return((Size != null && !SqlType.IsFixedSize()) ? $"{nonFixedSizeSqlType[SqlType]}({Size})" : map_SqlType_PrmTypeStr[SqlType]);
 }
Пример #54
0
 public static SqlType NVarChar(SqlTextLength options)
 {
     return(SqlType.TextType("nvarchar", options.CharacterLength));
 }
Пример #55
0
 internal static bool IsFixedSize(this SqlType SqlType)
 {
     return(!nonFixedSizeSqlType.ContainsKey(SqlType));
 }
Пример #56
0
 public static SqlType Time()
 {
     return(SqlType.Type("time"));
 }
Пример #57
0
        protected virtual DbParameter CloneParameter(DbCommand cmd, DbParameter originalParameter, SqlType originalType)
        {
            var clone = GenerateParameter(cmd, originalParameter.ParameterName, originalType);

            clone.Value = originalParameter.Value;
            return(clone);
        }
Пример #58
0
 /// <summary>
 /// Interprets if a parameter is a Blob (for the purposes of setting its default size)
 /// </summary>
 /// <param name="dbParam">The parameter</param>
 /// <param name="sqlType">The <see cref="SqlType" /> of the parameter</param>
 /// <returns>True, if the parameter should be interpreted as a Blob, otherwise False</returns>
 protected static bool IsBlob(IDbDataParameter dbParam, SqlType sqlType)
 {
     return((sqlType is BinaryBlobSqlType) || ((DbType.Binary == dbParam.DbType) && sqlType.LengthDefined && (sqlType.Length > MaxSizeForLengthLimitedBinary)));
 }
Пример #59
0
 /// <summary>
 /// Initialize a new instance of the NullableType class using a
 /// <see cref="SqlType"/>.
 /// </summary>
 /// <param name="sqlType">The underlying <see cref="SqlType"/>.</param>
 /// <remarks>This is used when the Property is mapped to a single column.</remarks>
 protected NullableType(SqlType sqlType)
 {
     _sqlType = sqlType;
 }
Пример #60
0
 public DateTimeType(SqlType sqlTypeDateTime) : base(sqlTypeDateTime)
 {
 }