Пример #1
0
        public void CanCheckCirculars()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table A
	ref A # will not be circular
	ref C # will be circular
	ref D # will not be circular
table B
	ref A #will be circular
table C
	ref D # will no be circular
	ref B # will be circular
table D
	
");

            Assert.True(model.IsValid);
            Assert.False(model["a"]["a"].GetIsCircular(), "(-)a->a (self links are not treats as circular for model)");
            Assert.True(model["a"]["c"].GetIsCircular(), "(+)a->c");
            Assert.False(model["a"]["d"].GetIsCircular(), "(-)a->c");
            Assert.True(model["b"]["a"].GetIsCircular(), "(+)b->a");
            Assert.False(model["c"]["d"].GetIsCircular(), "(-)c->d");
            Assert.True(model["c"]["b"].GetIsCircular(), "(+)c->b");
            //проверяем, что ранги сформированы максимально адекватно исходя из алгоритма обхода
            Assert.AreEqual(4, model["d"].Rank);
            Assert.AreEqual(4, model["b"].Rank);
            Assert.AreEqual(3, model["c"].Rank);
            Assert.AreEqual(1, model["a"].Rank);
        }
Пример #2
0
        public void CanGenerateTableWithSystemName(string name)
        {
            var code  = @"
class " + name + @" prototype=dbtable
	ref "     + name + @"
";
            var model = PersistentModel.Compile(code);
            var t     = model[name];
            var mwr   = new TableWriter(t)
            {
                Dialect     = DbDialect.SqlServer,
                NoDelimiter = true,
                NoComment   = true,
                Mode        = ScriptMode.Create
            };
            var scr = mwr.ToString();

            Console.WriteLine(scr);
            //Console.WriteLine("------------------  for copy-paste --------------------------");
            //Console.WriteLine(scr.Replace("\"","\"\"").Replace("\""+name+"\"","\"{0}\"").Replace("_"+name+"_","_{0}_"));
            Assert.AreEqual(string.Format(@"CREATE TABLE ""dbo"".""{0}"" (
	""id"" int NOT NULL CONSTRAINT dbo_{0}_id_pk PRIMARY KEY DEFAULT (NEXT VALUE FOR ""dbo"".""{0}_seq""),
	""{0}"" int NOT NULL CONSTRAINT dbo_{0}_{0}_{0}_id_fk FOREIGN KEY REFERENCES ""dbo"".""{0}"" (""id"") DEFAULT 0
) ON SECONDARY;
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""{0}"" where ""id""=0)  INSERT INTO ""dbo"".""{0}"" (""id"") VALUES (0);
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""{0}"" where ""id""=-1)  INSERT INTO ""dbo"".""{0}"" (""id"", ""{0}"") VALUES (-1, -1);
".Trim(), name), scr.Trim());
        }
        public void BasicSelfTagResolutionOptions()
        {
            var model = PersistentModel.Compile(@"
class a prototype=dbtable resolve
	string Tag resolve
");
            var code  = new ResolveTagOptionsWriter(model)
            {
                WithHeader = false
            }.ToString().Replace("\"", "\"\"");

            Console.WriteLine(code);
            Assert.AreEqual(@"
using System;
namespace Orm{
	///<summary>Options for tag resolution in model</summary>
	public partial class ResolveTagOptions {
		///<summary>Defult instance for full resolution</summary>
		public static readonly ResolveTagOptions Default  = new ResolveTagOptions();
		///<summary>Default instance for resolution on only one level</summary>
		public static readonly ResolveTagOptions SelfOnly = new ResolveTagOptions{
		};
		///<summary>aTag can be used in resolution</summary>
		public bool aTag = true;
	}
}
".Trim(), code.Trim());
        }
Пример #4
0
        public void ComputeAsFieldWriter()
        {
            var model  = PersistentModel.Compile(SimpleModelWithComputeBy);
            var master = model["master"];
            var mwr    = new TableWriter(master)
            {
                Dialect     = DbDialect.SqlServer,
                NoDelimiter = true,
                NoComment   = true,
                Mode        = ScriptMode.Create
            };

            var scr = mwr.ToString();

            Console.WriteLine(scr.Replace("\"", "\"\""));
            Assert.AreEqual(@"CREATE TABLE ""dbo"".""master"" (
	""id"" int NOT NULL CONSTRAINT dbo_master_id_pk PRIMARY KEY DEFAULT (NEXT VALUE FOR ""dbo"".""master_seq""),
	""code"" nvarchar(255) NOT NULL CONSTRAINT dbo_master_code_unq UNIQUE DEFAULT '',
	""code2"" AS (code+'a')
) ON SECONDARY;
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""master"" where ""id""=0)  INSERT INTO ""dbo"".""master"" (""id"", ""code"") VALUES (0, '/');
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""master"" where ""id""=-1)  INSERT INTO ""dbo"".""master"" (""id"", ""code"") VALUES (-1, 'ERR');
EXECUTE sp_addextendedproperty N'MS_Description', 'Код', N'SCHEMA', N'dbo', N'TABLE', N'master', N'COLUMN', 'code';
EXECUTE sp_addextendedproperty N'MS_Description', 'Код2', N'SCHEMA', N'dbo', N'TABLE', N'master', N'COLUMN', 'code2';
".Trim(), scr.Trim());
        }
Пример #5
0
        public void CloneableOptionsWriterWithRefs()
        {
            var model = PersistentModel.Compile(@"
class a prototype=dbtable cloneable
class b prototype=dbtable cloneable
	ref a reverse
");
            var code  = new CloneOptionsWriter(model)
            {
                WithHeader = false
            }.ToString().Replace("\"", "\"\"");

            Console.WriteLine(code);

            Assert.AreEqual(@"
using System;
namespace Orm{
	///<summary>Options for cloning in model</summary>
	public partial class CloneOptions {
		///<summary>Defult instance</summary>
		public static readonly CloneOptions Default = new CloneOptions();
		///<summary>abs must be cloned</summary>
		public bool abs = false;
		///<summary>ba must be cloned</summary>
		public bool ba = false;
	}
}
".Trim(), code.Trim());
        }
Пример #6
0
        public void CanParseTableFunction()
        {
            var model = PersistentModel.Compile(SimplestTableFunction);

            Assert.True(model.IsValid, "Модель должна быть валидна");
            var b = model["B"];

            Assert.NotNull(b, "А где B?");
            var a = model["A"];

            Assert.NotNull(b, "А где A?");
            var geta = b.SqlObjects.FirstOrDefault(_ => _.Name == "GetA") as SqlFunction;

            Assert.NotNull(geta, "Функция должна быть прочитана и инициализирована");
            var dt = geta.ReturnType;

            Assert.True(dt.IsTable, "Тип данных должен быть табличным");
            Assert.AreEqual(a, dt.TargetType, "Тип возвращаемой таблицы должен быть A");
            var arg = geta.Arguments["code"];

            Assert.NotNull(arg, "Должен был считать аргумент @id");
            Assert.True(arg.DataType.IsIdRef, "Тип аргумента должен быть ссылкой на Id");
            Assert.AreEqual(b, arg.DataType.TargetType, "Тип ссылки по ID должен быть B");
            Assert.AreEqual(SqlMethodOptions.IsMethod, geta.SqlMethod);
        }
Пример #7
0
        private void Start()
        {
            race = GameObject.Find("Race").GetComponent <Race>();

            pModel = PersistentModel.Instance;

            stop = false;

            m_Topspeed = m_CurrentTopspeed = 70;

            m_WheelMeshLocalRotations = new Quaternion[4];
            for (int i = 0; i < 4; i++)
            {
                m_WheelMeshLocalRotations[i] = m_WheelMeshes[i].transform.localRotation;
            }
            m_WheelColliders[0].attachedRigidbody.centerOfMass = m_CentreOfMassOffset;

            m_MaxHandbrakeTorque = float.MaxValue;

            m_Rigidbody     = GetComponent <Rigidbody>();
            m_CurrentTorque = m_FullTorqueOverAllWheels - (m_TractionControl * m_FullTorqueOverAllWheels);

            this.skidMarksController = GameObject.Find("SkidMarksController").GetComponent <Skidmarks>();

            // right
            m_WheelColliders[2].gameObject.GetComponent <WheelSkid>().rb = m_Rigidbody;
            m_WheelColliders[2].gameObject.GetComponent <WheelSkid>().skidmarksController = this.skidMarksController;

            // left wheel
            m_WheelColliders[3].gameObject.GetComponent <WheelSkid>().rb = m_Rigidbody;
            m_WheelColliders[3].gameObject.GetComponent <WheelSkid>().skidmarksController = this.skidMarksController;
        }
Пример #8
0
        /// <summary>
        ///     Формирует SQL-объект
        /// </summary>
        /// <param name="model"></param>
        /// <param name="cls"></param>
        /// <param name="bscls"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public virtual SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml)
        {
            Table   = cls;
            Model   = model;
            BSClass = bscls;
            if (null == Model && null != cls)
            {
                Model = cls.Model;
            }
            Definition = xml;
            if (null != xml)
            {
                Name         = xml.ChooseAttr("sqlname", "code");
                Comment      = xml.Attr("name");
                External     = xml.GetSmartValue("external");
                ExternalBody = xml.GetSmartValue("externalbody");
                Dialect      = DbDialect.Ansi;
                string dialect = xml.GetSmartValue("dialect");
                if (!string.IsNullOrWhiteSpace(dialect))
                {
                    Dialect = dialect.To <DbDialect>();
                }
                Body = xml.Value;
            }


            return(this);
        }
Пример #9
0
        public void SimpleReferenceSupport()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table X
table Y
	ref X
");

            Assert.True(model.IsValid);
            var x = model["dbo.x"];
            var y = model["dbo.y"];

            Console.WriteLine(x.Rank);
            Console.WriteLine(y.Rank);
            Assert.Greater(x.Rank, y.Rank, "ранг таблицы X должен быть больше, так как от нее зависит  Y");
            var reference = y["x"];

            Assert.True(reference.IsReference);
            Assert.AreEqual(x, reference.ReferenceClass);
            Assert.AreEqual(x["id"].DataType, reference.DataType);
            Assert.True(x.ReverseFields.ContainsKey(reference.ReverseCollectionName));
            Assert.AreEqual("Ys", reference.ReverseCollectionName);
            Assert.AreEqual(x.ReverseFields[reference.ReverseCollectionName], reference);
            Assert.False(reference.GetIsCircular());
            Assert.False(reference.IsReverese, "по умолчанию бэк коллекций не указывается");
        }
Пример #10
0
        string GetScript(string code, ScriptMode mode = ScriptMode.Create, DbDialect dialect = DbDialect.SqlServer, bool print = true)
        {
            var model = PersistentModel.Compile(code);

            if (!model.IsValid)
            {
                Assert.Fail("invalid model");
            }
            var sb = new StringBuilder();

            foreach (var w in model.GetWriters(dialect, mode))
            {
                w.NoComment = true;
                var str = w.ToString();
                if (!string.IsNullOrWhiteSpace(str))
                {
                    sb.AppendLine(str);
                }
            }
            var result = sb.ToString();

            if (print)
            {
                Console.WriteLine(result.Replace("\"", "\"\""));
            }
            return(result.Trim());
        }
Пример #11
0
        public void CanFilterGenerationTypesWithExclude()
        {
            var model = PersistentModel.Compile(new GenerationOptions {
                ExcludeSqlObjectTypes = SqlObjectType.Function
            }, @"
class a prototype=dbtable 
	int Get1 : (
		return 1
	)
");
            var script = model.GetScript(DbDialect.SqlServer, ScriptMode.Create);

            Console.WriteLine(script.Replace("\"", "\"\""));
            Assert.AreEqual(@"
-- begin command ScriptWriter

SET NOCOUNT ON
GO
IF OBJECT_ID('__ensurefg') IS NOT NULL DROP PROC __ensurefg
GO
 CREATE PROCEDURE __ensurefg @n nvarchar(255),@filecount int = 1, @filesize int = 100, @withidx bit = 0, @isdefault bit = 0 AS begin declare @q nvarchar(max) set @filesize = isnull(@filesize,100) if @filesize <=3 set @filesize =3 set @filecount = ISNULL(@filecount,1) if @filecount < 1 set @filecount= 1 set @withidx = isnull(@withidx,0) set @isdefault = isnull(@isdefault,0) set @q = 'ALTER DATABASE '+DB_NAME()+' ADD FILEGROUP '+@n BEGIN TRY exec sp_executesql @q END TRY BEGIN CATCH END CATCH declare @basepath nvarchar(255) set @basepath = reverse((Select top 1 filename from sys.sysfiles)) set @basepath = REVERSE( RIGHT( @basepath, len(@basepath)-CHARINDEX('\',@basepath)+1)) declare @c int set @c = @filecount while @c >= 1 begin BEGIN TRY set @q='ALTER DATABASE '+DB_NAME()+' ADD FILE ( NAME = N'''+DB_NAME()+'_'+@n+cast(@c as nvarchar(255))+''', FILENAME = N'''+ @basepath+DB_NAME()+'_'+@n+cast(@c as nvarchar(255))+'.ndf'' , SIZE = '+cast(@filesize as nvarchar(255))+'MB , FILEGROWTH = 5% ) TO FILEGROUP ['+@n+']' exec sp_executesql @q END TRY BEGIN CATCH END CATCH set @c = @c - 1 end IF @isdefault = 1 BEGIN set @q='ALTER DATABASE '+DB_NAME()+' MODIFY FILEGROUP '+@n+' DEFAULT ' BEGIN TRY exec sp_executesql @q END TRY BEGIN CATCH END CATCH end IF @withidx = 1 BEGIN set @n = @n +'IDX' exec __ensurefg @n, @filecount,@filesize,0,0 END end 
GO

GO

-- begin command FileGroupWriter
exec __ensurefg @n='SECONDARY', @filecount=1, @filesize=10, @withidx=0, @isdefault=1
GO

-- begin command SequenceWriter
begin try
CREATE SEQUENCE ""dbo"".""a_seq"" AS int START WITH 10 INCREMENT BY 10;
end try begin catch print ERROR_MESSAGE() end catch
GO

-- begin command TableWriter
CREATE TABLE ""dbo"".""a"" (
	""id"" int NOT NULL CONSTRAINT dbo_a_id_pk PRIMARY KEY DEFAULT (NEXT VALUE FOR ""dbo"".""a_seq"")
) ON SECONDARY;
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""a"" where ""id""=0)  INSERT INTO ""dbo"".""a"" (""id"") VALUES (0);
IF NOT EXISTS (SELECT TOP 1 * FROM ""dbo"".""a"" where ""id""=-1)  INSERT INTO ""dbo"".""a"" (""id"") VALUES (-1);

GO

-- begin command SqlTriggerWriter
IF OBJECT_ID('""dbo"".""aPreventDeletionOfSystemDefinedRows""') IS NOT NULL DROP TRIGGER ""dbo"".""aPreventDeletionOfSystemDefinedRows"";
GO
CREATE TRIGGER ""dbo"".""aPreventDeletionOfSystemDefinedRows"" ON ""dbo"".""a"" INSTEAD OF DELETE AS BEGIN
delete ""dbo"".""a"" from deleted d join ""dbo"".""a"" on ""dbo"".""a"".id = d.id where ""dbo"".""a"".id not in (0,-1)
END;
GO

-- begin command ScriptWriter

IF OBJECT_ID('__ensurefg') IS NOT NULL DROP PROC __ensurefg

GO
".Trim(), script.Trim());
        }
Пример #12
0
        public void CanResolveTableByPartialName()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table A");

            Assert.NotNull(model.Resolve("a"));
        }
Пример #13
0
        public void CanApplyFileGroup()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a filegroup=TEST
");

            Assert.AreEqual("TEST", model["a"].AllocationInfo.FileGroupName);
        }
Пример #14
0
        public void CanReadExternal()
        {
            File.WriteAllText("CanReadExternal.sql", "--echo x");
            var model  = PersistentModel.Compile(@"class X prototype=dbscript external=CanReadExternal.sql");
            var script = model.ExtendedScripts.First(_ => _.Name == "X");

            Console.WriteLine(script.Text);
            Assert.AreEqual("--echo x", script.Text);
        }
Пример #15
0
 /// <summary>
 ///     Перекрыть для настройки DBObject из XML
 /// </summary>
 /// <param name="bscls"></param>
 /// <param name="xml"></param>
 /// <param name="model"></param>
 /// <param name="cls"></param>
 public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml)
 {
     base.Setup(model, cls, bscls, xml);
     WithIndex = xml.Attr("withidx", "0").ToBool();
     FileSize  = xml.Attr("filesize", "10").ToInt();
     FileCount = xml.Attr("filecount", "1").ToInt();
     IsDefault = xml.Attr("isdefault", "0").ToBool();
     return(this);
 }
Пример #16
0
        public void CanApplyDefaultFileGroup()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a
");

            Assert.AreEqual("SECONDARY", model["a"].AllocationInfo.FileGroupName);
        }
Пример #17
0
        /// <summary>
        /// </summary>
        /// <param name="context"></param>
        public override void Execute(IBSharpContext context)
        {
            if (!context.ExtendedData.ContainsKey(DefaultModelName))
            {
                var gopts = new GenerationOptions();
                gopts.IncludeSqlObjectTypes = SqlObjectType.All;
                gopts.ExcludeSqlObjectTypes = SqlObjectType.None;

                var conds = context.Compiler.GetConditions();
                if (conds.ContainsKey("EX_ALL"))
                {
                    gopts.ExcludeSqlObjectTypes = SqlObjectType.All;
                }
                if (conds.Any(_ => _.Key.StartsWith("DO_")))
                {
                    gopts.IncludeSqlObjectTypes = SqlObjectType.None;
                    gopts.ExcludeSqlObjectTypes = SqlObjectType.All;
                }
                if (conds.ContainsKey("DO_DYN"))
                {
                    gopts.IncludeSqlObjectTypes = SqlObjectType.Function | SqlObjectType.ClrTrigger | SqlObjectType.Procedure;
                    gopts.ExcludeSqlObjectTypes = SqlObjectType.All;
                }
                foreach (var c in context.Compiler.GetConditions())
                {
                    if (c.Key.StartsWith("DO_") || c.Key.StartsWith("EX_"))
                    {
                        if (c.Key == "EX_ALL")
                        {
                            continue;
                        }
                        if (c.Key == "DO_DYN")
                        {
                            continue;
                        }
                        var type = c.Key.Substring(3);
                        var tp   = type.To <SqlObjectType>(true);
                        if (tp != SqlObjectType.None)
                        {
                            if (c.Key.StartsWith("DO_"))
                            {
                                gopts.IncludeSqlObjectTypes |= tp;
                            }
                            else
                            {
                                gopts.ExcludeSqlObjectTypes |= tp;
                            }
                        }
                    }
                }
                PersistentModel model = new PersistentModel {
                    GenerationOptions = gopts
                }.Setup(context);
                context.ExtendedData[DefaultModelName] = model;
            }
        }
Пример #18
0
        public void SqlCallsWrapper()
        {
            var code     = @"
require data
class a prototype=dbtable 
    void X 'Bla-bla' cs-wrap=scalar cs-return=long
        @id=long : (
            SELECT 1;
        )
    void Y 'Ta-da' cs-wrap=multiplereader 
        @id=long : (
            SELECT 1;
            SELECT 2;
        )";
            var model    = PersistentModel.Compile(code);
            var table    = model["a"];
            var function = table.GetObject <SqlFunction>("X");

            Assert.NotNull(function);
            var writer = new PokoObjectCacheWriter(table)
            {
                DoWriteClassWrapper   = false,
                DoWriteModelLink      = false,
                DoWriteSqlMethods     = false,
                DoWriteTableQuery     = false,
                DoWriteObjectWrappers = true
            };
            var result = writer.ToString();

            Console.WriteLine(result);
            var simpleResult = Regex.Replace(result, @"\s", "").Replace("\"", "'");

            Assert.AreEqual(simpleResult, Regex.Replace(@"		private DbCommandWrapper _XWrapper = new DbCommandWrapper{ObjectName='dbo.aX',Notation=DbCallNotation.Scalar};
		///<summary>Bla-bla</summary>
		public Int64 XGeneric (object parameters) {
			var command = _XWrapper.Clone(parameters,GetConnection());
			var result = DbCommandExecutor.Default.GetResultSync(command);
			var convertedResult = result.To<Int64>();
			return convertedResult;
		}
		///<summary>Bla-bla</summary>
		public Int64 X (Int64 id = default(Int64)){
			return XGeneric (new{id});
		}
		private DbCommandWrapper _YWrapper = new DbCommandWrapper{ObjectName='dbo.aY',Notation=DbCallNotation.MultipleReader};
		///<summary>Ta-da</summary>
		public object YGeneric (object parameters) {
			var command = _YWrapper.Clone(parameters,GetConnection());
			var result = DbCommandExecutor.Default.GetResultSync(command);
			return result;
		}
		///<summary>Ta-da</summary>
		public object Y (Int64 id = default(Int64)){
			return YGeneric (new{id});
		}"        , @"\s", ""));
        }
Пример #19
0
        public void NotMappedPartitionedFieldIsError()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a 
	partitioned with=X
");

            Assert.False(model.IsValid);
        }
Пример #20
0
        public void CanDetectNonValidTableRef()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a
	ref b
");

            Assert.False(model.IsValid);
        }
Пример #21
0
 /// <summary>
 ///     Формирует глобальные объекты уровня базы данных
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public static IEnumerable <SqlObject> CreateDatabaseWide(PersistentModel model)
 {
     foreach (SqlObject schema in GenerateSchemas(model))
     {
         yield return(schema);
     }
     foreach (SqlObject fgroup in GenerateFileGroups(model))
     {
         yield return(fgroup);
     }
 }
Пример #22
0
        public void CanReadScriptWithParameters()
        {
            var model  = PersistentModel.Compile(@"class X prototype=dbscript position=before dialect=postgres mode=drop : '--echo 2'");
            var script = model.ExtendedScripts.First(_ => _.Name == "X");

            Assert.AreEqual("X", script.Name);
            Assert.AreEqual(DbDialect.PostGres, script.DbDialect);
            Assert.AreEqual(ScriptMode.Drop, script.Mode);
            Assert.AreEqual(ScriptPosition.Before, script.Position);
            Assert.AreEqual("--echo 2", script.Text);
        }
Пример #23
0
        public void CanReadSimpleScript()
        {
            var model  = PersistentModel.Compile(@"class X prototype=dbscript : --echo");
            var script = model.ExtendedScripts.First(_ => _.Name == "X");

            Assert.AreEqual("X", script.Name);
            Assert.AreEqual(DbDialect.Ansi, script.DbDialect);
            Assert.AreEqual(ScriptMode.Create, script.Mode);
            Assert.AreEqual(ScriptPosition.After, script.Position);
            Assert.AreEqual("--echo", script.Text);
        }
Пример #24
0
        public void BestPracticeFileGroupSecondaryAlwaysExistsAndMappedAsDefault()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a 
");
            var fg    = model.DatabaseSqlObjects.OfType <FileGroup>().FirstOrDefault(_ => _.Name == "SECONDARY");

            Assert.NotNull(fg);
            Assert.True(fg.IsDefault);
        }
Пример #25
0
        public void CanApplyFileGroupWithAttrToCustomName()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
class X.TEST sqlname=T2
table a filegroup=^X.TEST
");

            Assert.AreEqual("T2", model["a"].AllocationInfo.FileGroupName);
            Assert.AreEqual(model.DatabaseSqlObjects[0], model["a"].AllocationInfo.FileGroup);
        }
Пример #26
0
        public void SchemasAreConfiguredToCreate()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a schema=Test
");

            Assert.True(model.IsValid);
            Assert.AreEqual("\"test\".\"a\"", model["a"].FullSqlName);
            Assert.AreEqual("test", model["a"].Schema);
            Assert.NotNull(model.DatabaseSqlObjects.OfType <Schema>().FirstOrDefault(_ => _.Name == "test"));
        }
Пример #27
0
        public void AutoGenerateFileGroup()
        {
            var model = PersistentModel.Compile(@"
class table prototype=dbtable abstract
table a filegroup=test	
");
            var a     = model["a"].AllocationInfo;

            Assert.AreEqual("TEST", a.FileGroupName);
            Assert.NotNull(a.FileGroup);
            Assert.True(model.DatabaseSqlObjects.Contains(a.FileGroup));
        }
Пример #28
0
 /// <summary>
 ///     Формирует SQL-объект
 /// </summary>
 /// <param name="model"></param>
 /// <param name="cls"></param>
 /// <param name="bscls"></param>
 /// <param name="xml"></param>
 /// <returns></returns>
 public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml)
 {
     base.Setup(model, cls, bscls, xml);
     TableName = cls.FullSqlName;
     Name      = xml.Attr("code");
     Schema    = cls.Schema;
     Insert    = xml.GetSmartValue("insert").ToBool();
     Update    = xml.GetSmartValue("update").ToBool();
     Delete    = xml.GetSmartValue("delete").ToBool();
     Before    = xml.GetSmartValue("before").ToBool();
     return(this);
 }
Пример #29
0
        public void CannotRefereneUnknownViewWithThis()
        {
            var model = PersistentModel.Compile(@"
class a prototype=dbtable
    view x from='this.Zzz'	
");
            var e     = Assert.Throws <Exception>(() => {
                new SqlViewWriter(model["a"].SqlObjects.OfType <SqlView>().First()).ToString();
            });

            StringAssert.Contains("Zzz", e.Message);
        }
Пример #30
0
    public override void PreInitialize()
    {
        pModel = PersistentModel.Instance;

        _isGameScreenOverlay          = true;
        isLoadingRequiredBeforeDraw   = true;
        showProgressLoadingPanel      = true;
        showSmallProgressLoadingPanel = false;

        builder = new StringBuilder(10, 16);

        base.PreInitialize();
    }
Пример #31
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="cls"></param>
		/// <param name="bscls"></param>
		/// <param name="xml"></param>
		public override SqlObject Setup(PersistentModel model, PersistentClass cls, IBSharpClass bscls, XElement xml){
			base.Setup(model, cls, bscls, xml);
			if (null != xml){
				Start = xml.Attr("start", "10").ToInt();
				Step = xml.Attr("step", "10").ToInt();
			}
			Name = cls.Name + "_SEQ";
			Schema = cls.Schema;
			IsCyclic = cls.CyclicId;
			if (null != cls.PrimaryKey){
				DataType = cls.PrimaryKey.DataType;
			}
			else{
				DataType = cls.DataTypeMap["int"];
			}
			return this;
		}
Пример #32
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="cls"></param>
		/// <param name="definition"></param>
		/// <returns></returns>
		public SqlScript Setup(PersistentModel model, IBSharpClass cls, XElement definition){
			Model = model;
			MyClass = cls;
			Definition = definition;
			Name = definition.Attr("code");
			Comment = definition.Attr("name");
			External = definition.Attr("external");
			Position = definition.Attr("position", "After").To<ScriptPosition>();
			Mode = definition.Attr("mode", "Create").To<ScriptMode>();
			DbDialect = definition.Attr("dialect", "Ansi").To<DbDialect>();
			if (string.IsNullOrWhiteSpace(definition.Value) && string.IsNullOrWhiteSpace(External)){
				External = Name;
			}
			if (!string.IsNullOrWhiteSpace(External) && !External.EndsWith(".sql")){
				External += ".sql";
			}

			XElement[] subscripts = definition.Elements("script").ToArray();
			if (0 == subscripts.Length){
				
				if (string.IsNullOrWhiteSpace(External) ){
					Text = definition.Value;
				}
				else{
					Text = model.ResolveExternalContent(definition, External);
				}

			}
			else{
				foreach (XElement subscriptdef in definition.Elements("script")){
					var subscript = new SqlScript();
					subscript.Parent = this;
					subscript.Setup(Model, cls, subscriptdef);
					SubScripts.Add(subscript);
				}
			}
			return this;
		}
Пример #33
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="output"></param>
		public ExtendedModelWriter(PersistentModel model, TextWriter output = null) : base(model, output){
		}
Пример #34
0
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="output"></param>
		protected CodeWriterBase(PersistentModel model, TextWriter output)
			: this(output){
			Model = model;
		}
		/// <summary>
		/// </summary>
		/// <param name="model"></param>
		/// <param name="output"></param>
		public ResolveTagFacilityWriter(PersistentModel model, TextWriter output = null)
			: base(model, output){
		}