Ejemplo n.º 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;
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 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;
 }
Ejemplo n.º 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();
        }
Ejemplo n.º 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;
 }
Ejemplo n.º 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();
 }
Ejemplo n.º 7
0
 public ColumnAttribute(string name, SqlType type, int size, int scale)
 {
     this.name = name;
     this.type = type;
     this.size = size;
     this.scale = scale;
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 9
0
 public override bool CanCastTo(SqlType destType)
 {
     return destType is StringType ||
            destType is NumericType ||
            destType is BinaryType ||
            destType is BooleanType;
 }
Ejemplo n.º 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;
             }
     }
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 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");
     }
 }
Ejemplo n.º 15
0
 public FunctionInfo(ObjectName routineName, RoutineParameter[] parameters, SqlType returnType, FunctionType functionType)
     : base(routineName, parameters)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Ejemplo n.º 16
0
        public ReturnTypeVisitor(IQueryContext queryContext, IVariableResolver variableResolver)
        {
            this.queryContext = queryContext;
            this.variableResolver = variableResolver;

            sqlType = PrimitiveTypes.Null();
        }
Ejemplo n.º 17
0
 public FunctionInfo(ObjectName routineName, SqlType returnType, FunctionType functionType)
     : base(routineName)
 {
     ReturnType = returnType;
     FunctionType = functionType;
     AssertUnboundAtEnd();
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 19
0
        public override bool IsComparable(SqlType type)
        {
            var otherType = type as SpatialType;
            if (otherType == null)
                return false;

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

            return comparable && typeName.Equals(userType.typeName);
        }
Ejemplo n.º 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);
 }
Ejemplo n.º 24
0
        public IColumnInfoBuilder HavingType(SqlType value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            type = value;
            return this;
        }
Ejemplo n.º 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;
 }
Ejemplo n.º 26
0
        public IColumnBuilder OfType(SqlType type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            columnType = type;
            return this;
        }
Ejemplo n.º 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;
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 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;
        }
Ejemplo n.º 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);
     }
 }
Ejemplo n.º 31
0
 protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
 {
     base.InitializeParameter(dbParam, name, sqlType);
     SetVariableLengthParameterSize(dbParam, sqlType);
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 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));
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 35
0
 public OneTestsWithFunLogic(SqlType testFlavour)
     : base(testFlavour)
 {
 }
Ejemplo n.º 36
0
 public MappedJoinTests(SqlType testFlavour)
     : base(testFlavour)
 {
 }
Ejemplo n.º 37
0
 public static SqlType DateTimeOffset()
 {
     return(SqlType.Type("datetimeoffset"));
 }
Ejemplo n.º 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();
        }
Ejemplo n.º 39
0
 public static SqlType DateTime()
 {
     return(SqlType.Type("datetime"));
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 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;
 }
Ejemplo n.º 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)));
 }
Ejemplo n.º 44
0
 /****   Date & Time   ****/
 public static SqlType SmallDateTime()
 {
     return(SqlType.Type("smalldatetime"));
 }
Ejemplo n.º 45
0
 /****   Exact Numerics   ****/
 public static SqlType Bit()
 {
     return(SqlType.Type("bit"));
 }
Ejemplo n.º 46
0
        protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
        {
            base.InitializeParameter(dbParam, name, sqlType);

            if (sqlType.LengthDefined)
            {
                dbParam.Size = sqlType.Length;
            }
        }
Ejemplo n.º 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.");
        }
Ejemplo n.º 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());
        }
Ejemplo n.º 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;
                }
            }
Ejemplo n.º 50
0
 public static SqlType Real()
 {
     return(SqlType.ApproximateNumeric("real", 24));
 }
Ejemplo n.º 51
0
 public AbstractCharType(SqlType sqlType)
     : base(sqlType)
 {
 }
Ejemplo n.º 52
0
 public static SqlType Xml()
 {
     return(SqlType.Type("xml"));
 }
Ejemplo n.º 53
0
 internal static string GetParameterType(this SqlType SqlType, int?Size)
 {
     return((Size != null && !SqlType.IsFixedSize()) ? $"{nonFixedSizeSqlType[SqlType]}({Size})" : map_SqlType_PrmTypeStr[SqlType]);
 }
Ejemplo n.º 54
0
 public static SqlType NVarChar(SqlTextLength options)
 {
     return(SqlType.TextType("nvarchar", options.CharacterLength));
 }
Ejemplo n.º 55
0
 internal static bool IsFixedSize(this SqlType SqlType)
 {
     return(!nonFixedSizeSqlType.ContainsKey(SqlType));
 }
Ejemplo n.º 56
0
 public static SqlType Time()
 {
     return(SqlType.Type("time"));
 }
Ejemplo n.º 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);
        }
Ejemplo n.º 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)));
 }
Ejemplo n.º 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;
 }
Ejemplo n.º 60
0
 public DateTimeType(SqlType sqlTypeDateTime) : base(sqlTypeDateTime)
 {
 }