Exemplo n.º 1
0
        public static SoqlBooleanExpression ClassRestriction(SoqlPathExpression path, SchemaInfo schema, ClassInfo classInfo)
        {
            // returns no additional filter clause for parent (master-parent) class
            if (classInfo.InheritsFromClass == null)
                return null;

            SoqlExpressionCollection literals = new SoqlExpressionCollection();

            foreach (ClassInfo subclass in classInfo.GetSubclassesForSchema(schema))
            {
                if (subclass.SubclassSelectorValue != null)
                {
                    literals.Add(new SoqlLiteralExpression(subclass.SubclassSelectorValue));
                }
            }
            if (classInfo.SubclassSelectorValue != null)
            {
                literals.Add(new SoqlLiteralExpression(classInfo.SubclassSelectorValue));
            }

            // returns false when class is abstract (no SubClassSelectorValue) and there is no subclasses
            if (literals.Count == 0)
                return new SoqlBooleanLiteralExpression(false);

            SoqlBooleanExpression restriction = new SoqlBooleanInExpression(
                new SoqlPathExpression(path, classInfo.SubclassSelectorField.Name),
                literals
            );

            return restriction;
        }
        static void Resolve(SchemaInfo schema, HashSet<ClassInfo> affectedClasses)
        {
            // add subclasses
            foreach (ClassInfo ci in affectedClasses.ToArray())
            {
                foreach (ClassInfo sci in schema.GetSubclasses(ci))
                    affectedClasses.Add(sci);
            }

            schema.Resolve(affectedClasses);
        }
Exemplo n.º 3
0
        public static void ProcessIncludes(SchemaInfo resultSchema, List<IncludeInfo> includes, string baseDirectoryForIncludes)
        {
            if (includes == null)
                return;

            foreach (IncludeInfo ii in includes)
            {
                string includeFileName = Path.Combine(baseDirectoryForIncludes, ii.SchemaFile);
                SchemaInfo includedSchema = ReadAndValidateSchema(new XmlTextReader(includeFileName), Path.GetDirectoryName(includeFileName), ii);
                resultSchema.MergeIncludedSchema(includedSchema);
                includedSchema.AssemblyName = ii.AssemblyName;
                includedSchema.Namespace = ii.Namespace;
                ii.Schema = includedSchema;
            }
        }
Exemplo n.º 4
0
        internal void Resolve(SchemaInfo schemaInfo)
        {
            relationInfo = schemaInfo.FindRelationByName(Relation);
            if (relationInfo == null)
                throw new SoodaSchemaException("Relation " + Relation + " not found.");

            if (ForeignField != null)
            {
                if (relationInfo.Table.Fields[0].Name == ForeignField)
                    MasterField = 1;
                else
                    MasterField = 0;
            }
            if (MasterField == -1)
                throw new SoodaConfigException("You need to set either masterField or foreignField in <collectionManyToMany name='" + this.Name + "' />");
        }
        public override SchemaInfo GetSchemaFromDatabase(ISchemaImporterOptions options)
        {
            _options = options;
            using (SqlConnection conn = new SqlConnection(options.ConnectionString))
            {
                SqlDataAdapter dataAdapter;

                conn.Open();
                Console.WriteLine("Loading tables...");
                dataAdapter = new SqlDataAdapter(SqlStrings.TablesQuery, conn);
                dataAdapter.Fill(dataSet, "Tables");

                Console.WriteLine("Loading datatypes...");
                dataAdapter.SelectCommand.CommandText = "exec sp_datatype_info";
                dataAdapter.Fill(dataSet, "DataTypes");

                Console.WriteLine("Loading columns...");
                dataAdapter.SelectCommand.CommandText = "exec sp_Columns @table_name='%'";
                dataAdapter.Fill(dataSet, "Columns");

                Console.WriteLine("Loading primary keys...");
                dataAdapter.SelectCommand.CommandText = SqlStrings.PrimaryKeysQuery;
                dataAdapter.Fill(dataSet, "PrimaryKeys");

                Console.WriteLine("Loading foreign keys...");
                dataAdapter.SelectCommand.CommandText = SqlStrings.ForeignKeysQuery;
                dataAdapter.Fill(dataSet, "ForeignKeys");
            }

            SchemaInfo si = new SchemaInfo();

            foreach (DataRow dr in dataSet.Tables["Tables"].Rows)
            {
                DumpTable(si, (string)dr["TABLE_OWNER"], (string)dr["TABLE_NAME"]);
            }

            DumpForeignKeys(si);

            if (_haveIdentityColumns)
                Console.WriteLine("WARNING: Identity columns are not supported. Sooda will not use them, but will provide its own pre-generated key.");

            return si;
        }
Exemplo n.º 6
0
        public void GenerateDatabaseSchema(CodeNamespace nspace, SchemaInfo schema)
        {
            CDILContext context = new CDILContext();
            context["OutNamespace"] = Project.OutputNamespace;

            CodeTypeDeclaration databaseSchemaClass = CDILParser.ParseClass(CDILTemplate.Get("DatabaseSchema.cdil"), context);

            CodeArrayCreateExpression cace = new CodeArrayCreateExpression("ISoodaObjectFactory");
            OutputFactories(cace, Project.OutputNamespace, schema);

            CodeTypeConstructor ctc = new CodeTypeConstructor();
            ctc.Statements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(null, "_theSchema"),
                        new CodeMethodInvokeExpression(null,"LoadSchema")));

            databaseSchemaClass.Members.Add(ctc);

            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Statements.Add(
                    new CodeAssignStatement(
                        new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), "_factories"), cace));

            databaseSchemaClass.Members.Add(ctor);

            nspace.Types.Add(databaseSchemaClass);
        }
Exemplo n.º 7
0
        private void OutputFactories(CodeArrayCreateExpression cace, string ns, SchemaInfo schema)
        {
            //foreach (IncludeInfo ii in schema.Includes)
            //{
            //    if ((ii.Schema != null) && (ii.AssemblyName != null) && (ii.AssemblyName != ""))
            //        OutputFactories(cace, ii.Namespace, ii.Schema);
            //}

            foreach (ClassInfo ci in schema.Classes)
            {
                string nameSpace = string.IsNullOrEmpty(ci.Schema.Namespace) ? ns : ci.Schema.Namespace;
                cace.Initializers.Add(new CodePropertyReferenceExpression(new CodeTypeReferenceExpression(nameSpace + ".Stubs." + ci.Name + "_Factory"), "TheFactory"));
            }
        }
Exemplo n.º 8
0
 public void Include(SchemaInfo schema)
 {
 }
Exemplo n.º 9
0
        public override IDataReader LoadMatchingPrimaryKeys(SchemaInfo schemaInfo, ClassInfo classInfo, SoodaWhereClause whereClause, SoodaOrderBy orderBy, int startIdx, int pageCount)
        {
            try
            {
                SoqlQueryExpression queryExpression = new SoqlQueryExpression();
                foreach (FieldInfo fi in classInfo.GetPrimaryKeyFields())
                {
                    queryExpression.SelectExpressions.Add(new SoqlPathExpression(fi.Name));
                    queryExpression.SelectAliases.Add("");

                }
                if (schemaInfo.GetSubclasses(classInfo).Count > 0)
                {
                    queryExpression.SelectExpressions.Add(new SoqlPathExpression(classInfo.SubclassSelectorField.Name));
                    queryExpression.SelectAliases.Add("");
                }
                queryExpression.StartIdx = startIdx;
                queryExpression.PageCount = pageCount;
                queryExpression.From.Add(classInfo.Name);
                queryExpression.FromAliases.Add("");
                if (whereClause != null && whereClause.WhereExpression != null)
                {
                    queryExpression.WhereClause = whereClause.WhereExpression;
                }

                if (orderBy != null)
                {
                    queryExpression.SetOrderBy(orderBy);
                }

                string query = SoqlToSql(queryExpression, schemaInfo, false);

                IDbCommand cmd = Connection.CreateCommand();
                try
                {
                    cmd.CommandTimeout = CommandTimeout;
                }
                catch (NotSupportedException e)
                {
                    logger.Debug("CommandTimeout not supported. {0}", e.Message);
                }

                if (Transaction != null)
                    cmd.Transaction = this.Transaction;

                SqlBuilder.BuildCommandWithParameters(cmd, false, query, whereClause.Parameters, false);

                return TimedExecuteReader(cmd);
            }
            catch (Exception ex)
            {
                logger.Error("Exception in LoadMatchingPrimaryKeys: {0}", ex);
                throw;
            }
        }
Exemplo n.º 10
0
        private void DumpTable(SchemaInfo schemaInfo, string owner, string table)
        {
            Console.WriteLine("Dumping table {0}.{1}", owner, table);

            ClassInfo ci = new ClassInfo();
            ci.Name = MakePascalCase(table);

            TableInfo ti = new TableInfo();
            ci.LocalTables = new List<TableInfo>();
            ti.DBTableName = table;
            ci.LocalTables.Add(ti);

            foreach (DataRow r in dataSet.Tables["Columns"].Select("TABLE_NAME='" + table + "' and TABLE_OWNER='" + owner + "'", "ORDINAL_POSITION"))
            {
                try
                {
                    string columnName = r["COLUMN_NAME"].ToString();

                    FieldInfo fi = new FieldInfo();
                    fi.Name = MakePascalCase(columnName);
                    fi.DBColumnName = columnName;
                    GetSoodaFieldAttributes(fi, r, false);
                    ti.Fields.Add(fi);
                }
                catch (Exception ex)
                {
                    Console.WriteLine("WARNING: {0}", ex.Message);
                }
            }

            bool hasPrimaryKey = false;

            foreach (DataRow r in dataSet.Tables["PrimaryKeys"].Select("TABLE_NAME='" + table + "' and TABLE_OWNER='" + owner + "'"))
            {
                string column = Convert.ToString(r["COLUMN_NAME"]);
                foreach (FieldInfo fi in ti.Fields)
                {
                    if (0 == String.Compare(fi.DBColumnName, column, true))
                    {
                        fi.IsPrimaryKey = true;
                        hasPrimaryKey = true;
                    }
                }
            }
            if (!hasPrimaryKey)
            {
                Console.WriteLine("WARNING: Created artificial primary key from the first column of the " + ti.DBTableName + " table. This may be incorrect.");
                ti.Fields[0].IsPrimaryKey = true;
            }
            schemaInfo.Classes.Add(ci);
        }
Exemplo n.º 11
0
        internal void MergeIncludedSchema(SchemaInfo includedSchema)
        {
            // merge classes, relations and datasources

            if (includedSchema.Classes != null)
            {
                Dictionary <string, ClassInfo> classNames = new Dictionary <string, ClassInfo>();
                foreach (ClassInfo nci in includedSchema.Classes)
                {
                    classNames.Add(nci.Name, nci);
                }

                List <ClassInfo> newClasses = new List <ClassInfo>();
                if (this.Classes != null)
                {
                    foreach (ClassInfo ci in this.Classes)
                    {
                        newClasses.Add(ci);
                        ClassInfo ci2;
                        if (classNames.TryGetValue(ci.Name, out ci2))
                        {
                            ci.Merge(ci2);
                            classNames.Remove(ci.Name);
                        }
                    }
                }

                foreach (ClassInfo ci in classNames.Values)
                {
                    newClasses.Add(ci);
                }

                this.Classes = newClasses;
            }

            if (includedSchema.Relations != null)
            {
                List <RelationInfo> newRelations = new List <RelationInfo>();

                foreach (RelationInfo ci in includedSchema.Relations)
                {
                    newRelations.Add(ci);
                }

                if (this.Relations != null)
                {
                    foreach (RelationInfo ci in this.Relations)
                    {
                        newRelations.Add(ci);
                    }
                }

                this.Relations = newRelations;
            }

            if (includedSchema.DataSources != null)
            {
                Dictionary <string, DataSourceInfo> sourceNames = new Dictionary <string, DataSourceInfo>();

                List <DataSourceInfo> newDataSources = new List <DataSourceInfo>();

                if (this.DataSources != null)
                {
                    foreach (DataSourceInfo ci in this.DataSources)
                    {
                        newDataSources.Add(ci);
                        sourceNames.Add(ci.Name, ci);
                    }
                }

                foreach (DataSourceInfo ci in includedSchema.DataSources)
                {
                    DataSourceInfo di;
                    if (sourceNames.TryGetValue(ci.Name, out di))
                    {
                        di.EnableDynamicFields |= ci.EnableDynamicFields;
                    }
                    else
                    {
                        newDataSources.Add(ci);
                    }
                }

                this.DataSources = newDataSources;
            }
        }
Exemplo n.º 12
0
 public void Include(SchemaInfo schema)
 {
 }
Exemplo n.º 13
0
 public StringCollection GetBackRefCollections(SchemaInfo schema)
 {
     return schema.GetBackRefCollections(this);
 }
Exemplo n.º 14
0
 private void RemoveReferencePrimaryKeys(SchemaInfo si)
 {
     // for classes, primary keys which are references are not supported
     foreach (ClassInfo ci in si.Classes)
     {
         foreach (FieldInfo fi in ci.UnifiedFields)
         {
             if (fi.IsPrimaryKey)
                 fi.References = null;
         }
     }
 }
Exemplo n.º 15
0
        private void AutoDetectRelations(SchemaInfo si)
        {
            foreach (ClassInfo ci in new ArrayList(si.Classes))
            {
                if (ci.LocalTables[0].Fields.Count != 2)
                    continue;

                if (!(ci.LocalTables[0].Fields[0].IsPrimaryKey && ci.LocalTables[0].Fields[1].IsPrimaryKey))
                    continue;

                if (ci.LocalTables[0].Fields[0].References == null || ci.LocalTables[0].Fields[1].References == null)
                    continue;

                RelationInfo ri = new RelationInfo();
                ri.Name = ci.Name;
                ri.Table.DBTableName = ci.LocalTables[0].DBTableName;
                ri.Table.Fields.Add(ci.LocalTables[0].Fields[0]);
                ri.Table.Fields.Add(ci.LocalTables[0].Fields[1]);
                si.Relations.Add(ri);

                Console.WriteLine("Converting {0} to a relation", ci.Name);
                si.Classes.Remove(ci);
            }
        }
Exemplo n.º 16
0
        private void AutoDetectCollections(SchemaInfo si)
        {
            int counter = 0;
            foreach (ClassInfo ci in si.Classes)
            {
                foreach (FieldInfo fi in ci.LocalTables[0].Fields)
                {
                    if (fi.ReferencedClass != null)
                    {
                        ArrayList al = new ArrayList();
                        if (fi.ReferencedClass.Collections1toN != null)
                        {
                            al.AddRange(fi.ReferencedClass.Collections1toN);
                        }
                        CollectionOnetoManyInfo coll = new CollectionOnetoManyInfo();
                        coll.Name = "CollectionOf" + ci.Name + "" + counter++;
                        coll.ClassName = ci.Name;
                        coll.ForeignFieldName = fi.Name;
                        al.Add(coll);

                        fi.ReferencedClass.Collections1toN = (CollectionOnetoManyInfo[])al.ToArray(typeof(CollectionOnetoManyInfo));
                        // ci.Collections1toN
                    }
                }
            }
            foreach (RelationInfo ri in si.Relations)
            {
                CollectionManyToManyInfo mm;
                ArrayList al;

                al = new ArrayList();
                if (ri.Table.Fields[0].ReferencedClass.CollectionsNtoN != null)
                    al.AddRange(ri.Table.Fields[0].ReferencedClass.CollectionsNtoN);

                mm = new CollectionManyToManyInfo();
                mm.Name = "CollectionOf" + ri.Table.Fields[1].ReferencedClass.Name + "" + counter++;
                mm.Relation = ri.Name;
                mm.ForeignField = ri.Table.Fields[0].Name;
                al.Add(mm);

                ri.Table.Fields[0].ReferencedClass.CollectionsNtoN = (CollectionManyToManyInfo[])al.ToArray(typeof(CollectionManyToManyInfo));

                al = new ArrayList();
                if (ri.Table.Fields[1].ReferencedClass.CollectionsNtoN != null)
                    al.AddRange(ri.Table.Fields[1].ReferencedClass.CollectionsNtoN);

                mm = new CollectionManyToManyInfo();
                mm.Name = "CollectionOf" + ri.Table.Fields[0].ReferencedClass.Name + "" + al.Count;
                mm.Relation = ri.Name;
                mm.ForeignField = ri.Table.Fields[1].Name;
                al.Add(mm);

                ri.Table.Fields[1].ReferencedClass.CollectionsNtoN = (CollectionManyToManyInfo[])al.ToArray(typeof(CollectionManyToManyInfo));

            }
        }
Exemplo n.º 17
0
        public override IDataReader LoadRefObjectList(SchemaInfo schema, RelationInfo relationInfo, int masterColumn, object masterValue, out TableInfo[] tables)
        {
            try
            {
                if (masterColumn == 0)
                    tables = relationInfo.GetRef1ClassInfo().UnifiedTables[0].ArraySingleton;
                else
                    tables = relationInfo.GetRef2ClassInfo().UnifiedTables[0].ArraySingleton;

                string query = GetLoadRefObjectSelectStatement(relationInfo, masterColumn);

                IDbCommand cmd = Connection.CreateCommand();
                try
                {
                    cmd.CommandTimeout = CommandTimeout;
                }
                catch (NotSupportedException e)
                {
                    logger.Debug("CommandTimeout not supported. {0}", e.Message);
                }

                if (Transaction != null)
                    cmd.Transaction = this.Transaction;

                SqlBuilder.BuildCommandWithParameters(cmd, false, query, new object[] { masterValue }, false);
                return TimedExecuteReader(cmd);
            }
            catch (Exception ex)
            {
                logger.Error("Exception in LoadRefObjectList: {0}", ex);
                throw;
            }
        }
Exemplo n.º 18
0
 public override IDataReader ExecuteQuery(Sooda.QL.SoqlQueryExpression query, SchemaInfo schema, object[] parameters)
 {
     try
     {
         string queryText = SoqlToSql(query, schema, false);
         return ExecuteRawQuery(queryText, parameters);
     }
     catch (Exception ex)
     {
         logger.Error("Exception in ExecuteQuery: {0}", ex);
         throw;
     }
 }
Exemplo n.º 19
0
        public override IDataReader LoadObjectList(SchemaInfo schemaInfo, ClassInfo classInfo, SoodaWhereClause whereClause, SoodaOrderBy orderBy, int startIdx, int pageCount, SoodaSnapshotOptions options, out TableInfo[] tables)
        {
            try
            {
                Queue<_QueueItem> queue = new Queue<_QueueItem>();

                List<TableInfo> tablesArrayList = new List<TableInfo>(classInfo.UnifiedTables.Count);
                SoqlQueryExpression queryExpression = new SoqlQueryExpression();
                queryExpression.StartIdx = startIdx;
                queryExpression.PageCount = pageCount;
                queryExpression.From.Add(classInfo.Name);
                queryExpression.FromAliases.Add("");
                foreach (TableInfo ti in classInfo.UnifiedTables)
                {
                    tablesArrayList.Add(ti);
                    foreach (FieldInfo fi in ti.Fields)
                    {
                        SoqlPathExpression pathExpr = new SoqlPathExpression(fi.Name);
                        queryExpression.SelectExpressions.Add(pathExpr);
                        queryExpression.SelectAliases.Add("");

                        if (fi.ReferencedClass != null && fi.PrefetchLevel > 0 && ((options & SoodaSnapshotOptions.PrefetchRelated) != 0))
                        {
                            _QueueItem item = new _QueueItem();
                            item.classInfo = fi.ReferencedClass;
                            item.level = fi.PrefetchLevel;
                            item.prefix = pathExpr;
                            queue.Enqueue(item);
                        }
                    }
                }

                while (queue.Count > 0)
                {
                    _QueueItem it = queue.Dequeue();

                    foreach (TableInfo ti in it.classInfo.UnifiedTables)
                    {
                        tablesArrayList.Add(ti);

                        foreach (FieldInfo fi in ti.Fields)
                        {
                            // TODO - this relies on the fact that path expressions
                            // are never reconstructed or broken. We simply share previous prefix
                            // perhaps it's cleaner to Clone() the expression here

                            SoqlPathExpression extendedExpression = new SoqlPathExpression(it.prefix, fi.Name);

                            queryExpression.SelectExpressions.Add(extendedExpression);
                            queryExpression.SelectAliases.Add("");

                            if (it.level >= 1 && fi.PrefetchLevel > 0 && fi.ReferencedClass != null)
                            {
                                _QueueItem newItem = new _QueueItem();
                                newItem.classInfo = fi.ReferencedClass;
                                newItem.prefix = extendedExpression;
                                newItem.level = it.level - 1;
                                queue.Enqueue(newItem);
                            }
                        }
                    }
                }

                if (whereClause != null && whereClause.WhereExpression != null)
                {
                    queryExpression.WhereClause = whereClause.WhereExpression;
                }

                if (orderBy != null)
                {
                    queryExpression.SetOrderBy(orderBy);
                }

                string query = SoqlToSql(queryExpression, schemaInfo, false);

                IDbCommand cmd = Connection.CreateCommand();

                try
                {
                    cmd.CommandTimeout = CommandTimeout;
                }
                catch (NotSupportedException e)
                {
                    logger.Debug("CommandTimeout not supported. {0}", e.Message);
                }

                if (Transaction != null)
                    cmd.Transaction = this.Transaction;

                SqlBuilder.BuildCommandWithParameters(cmd, false, query, whereClause.Parameters, false);

                tables = tablesArrayList.ToArray();
                return TimedExecuteReader(cmd);
            }
            catch (Exception ex)
            {
                logger.Error("Exception in LoadObjectList: {0}", ex);
                throw;
            }
        }
Exemplo n.º 20
0
 static bool DynamicFieldsEnabled(SchemaInfo schema)
 {
     return(schema.DataSources.Any(ds => ds.EnableDynamicFields));
 }
Exemplo n.º 21
0
 public StringCollection GetBackRefCollections(SchemaInfo schema)
 {
     return(schema.GetBackRefCollections(this));
 }
Exemplo n.º 22
0
 internal void ResolveReferences(SchemaInfo schema)
 {
     if (References == null)
         return;
     ClassInfo ci = schema.FindClassByName(References);
     if (ci == null)
         throw new SoodaSchemaException("Class " + References + " not found.");
     DataType = ci.GetFirstPrimaryKeyField().DataType;
     ReferencedClass = ci;
 }
Exemplo n.º 23
0
        internal void MergeIncludedSchema(SchemaInfo includedSchema)
        {
            // merge classes, relations and datasources

            if (includedSchema.Classes != null)
            {
                Dictionary<string, ClassInfo> classNames = new Dictionary<string, ClassInfo>();
                foreach (ClassInfo nci in includedSchema.Classes)
                    classNames.Add(nci.Name, nci);

                List<ClassInfo> newClasses = new List<ClassInfo>();
                if (this.Classes != null)
                {
                    foreach (ClassInfo ci in this.Classes)
                    {
                        newClasses.Add(ci);
                        ClassInfo ci2;
                        if (classNames.TryGetValue(ci.Name, out ci2))
                        {
                            ci.Merge(ci2);
                            classNames.Remove(ci.Name);
                        }
                    }
                }

                foreach (ClassInfo ci in classNames.Values)
                {
                    newClasses.Add(ci);
                }

                this.Classes = newClasses;
            }

            if (includedSchema.Relations != null)
            {
                List<RelationInfo> newRelations = new List<RelationInfo>();

                foreach (RelationInfo ci in includedSchema.Relations)
                {
                    newRelations.Add(ci);
                }

                if (this.Relations != null)
                {
                    foreach (RelationInfo ci in this.Relations)
                    {
                        newRelations.Add(ci);
                    }
                }

                this.Relations = newRelations;
            }

            if (includedSchema.DataSources != null)
            {
                Dictionary<string, DataSourceInfo> sourceNames = new Dictionary<string, DataSourceInfo>();

                List<DataSourceInfo> newDataSources = new List<DataSourceInfo>();

                if (this.DataSources != null)
                {
                    foreach (DataSourceInfo ci in this.DataSources)
                    {
                        newDataSources.Add(ci);
                        sourceNames.Add(ci.Name, ci);
                    }
                }

                foreach (DataSourceInfo ci in includedSchema.DataSources)
                {
                    DataSourceInfo di;
                    if (sourceNames.TryGetValue(ci.Name, out di))
                        di.EnableDynamicFields |= ci.EnableDynamicFields;
                    else
                        newDataSources.Add(ci);
                }

                this.DataSources = newDataSources;
            }
        }
Exemplo n.º 24
0
        public virtual void GenerateDdlForSchema(SchemaInfo schema, TextWriter tw)
        {
            Dictionary<string, TableInfo> tables = new Dictionary<string, TableInfo>();
            Dictionary<string, string> processed = new Dictionary<string, string>();

            while (processed.Count < schema.Classes.Count)
            {
                foreach (ClassInfo ci in schema.Classes)
                {
                    if (!processed.ContainsKey(ci.Name))
                    {
                        bool isInherited = ci.InheritsFromClass != null;
                        if (!isInherited || processed.ContainsKey(ci.InheritsFromClass.Name))
                        {
                            foreach (TableInfo ti in ci.UnifiedTables)
                            {
                                UnifyTable(tables, ti, isInherited);
                            }
                            processed.Add(ci.Name, ci.Name);
                        }
                    }
                }
            }

            foreach (RelationInfo ri in schema.Relations)
            {
                UnifyTable(tables, ri.Table, false);
            }

            List<string> names = new List<string>();

            foreach (TableInfo ti in tables.Values)
            {
                names.Add(ti.DBTableName);
            }

            names.Sort();

            foreach (string s in names)
            {
                tw.WriteLine("--- table {0}", s);
                SqlBuilder.GenerateCreateTable(tw, tables[s], this.CreateTable, null);
            }

            foreach (string s in names)
            {
                SqlBuilder.GeneratePrimaryKey(tw, tables[s], this.CreateIndex, null);
            }

            foreach (string s in names)
            {
                SqlBuilder.GenerateForeignKeys(tw, tables[s], null);
            }

            foreach (string s in names)
            {
                SqlBuilder.GenerateIndices(tw, tables[s], this.CreateIndex, null);
            }

            if (schema.GetDataSourceInfo(Name).EnableDynamicFields)
                SqlBuilder.GenerateSoodaDynamicField(tw, null);
        }
Exemplo n.º 25
0
        private void DumpForeignKeys(SchemaInfo schemaInfo)
        {
            DataRow[] fkeys = dataSet.Tables["ForeignKeys"].Select("1=1", "SOURCE_TABLE_NAME, FKEY_NAME");

            for (int i = 0; i < fkeys.Length; ++i)
            {
                DataRow r = fkeys[i];
                string curSrcTableOwner = r["SOURCE_TABLE_OWNER"].ToString();
                string curSrcTableName = r["SOURCE_TABLE_NAME"].ToString();
                string curSrcColumnName = r["SOURCE_COLUMN_NAME"].ToString();
                string curDstTableOwner = r["DEST_TABLE_OWNER"].ToString();
                string curDstTableName = r["DEST_TABLE_NAME"].ToString();
                string curDstColumnName = r["DEST_COLUMN_NAME"].ToString();

                foreach (ClassInfo sourceTable in schemaInfo.Classes)
                {
                    if (sourceTable.LocalTables[0].DBTableName == curSrcTableName)
                    {
                        foreach (FieldInfo fi in sourceTable.LocalTables[0].Fields)
                        {
                            if (fi.DBColumnName == curSrcColumnName)
                            {
                                fi.References = MakePascalCase(curDstTableName);
                                break;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 26
0
 internal void ResolveInheritance(SchemaInfo schema)
 {
     if (InheritFrom != null)
     {
         InheritsFromClass = schema.FindClassByName(InheritFrom);
     }
     else
     {
         InheritsFromClass = null;
     }
 }
Exemplo n.º 27
0
        internal void ResolveCollections(SchemaInfo schema)
        {
            if (CollectionsNtoN != null)
            {
                foreach (CollectionManyToManyInfo cinfo in CollectionsNtoN)
                {
                    cinfo.Resolve(schema);
                }
            }

            if (Collections1toN != null)
            {
                foreach (CollectionOnetoManyInfo cinfo in Collections1toN)
                {
                    ClassInfo ci = schema.FindClassByName(cinfo.ClassName);
                    if (ci == null)
                        throw new SoodaSchemaException("Collection " + Name + "." + cinfo.Name + " cannot find class " + cinfo.ClassName);

                    FieldInfo fi = ci.FindFieldByName(cinfo.ForeignFieldName);

                    if (fi == null)
                        throw new SoodaSchemaException("Collection " + Name + "." + cinfo.Name + " cannot find field " + cinfo.ClassName + "." + cinfo.ForeignFieldName);

                    schema.AddBackRefCollection(fi, cinfo.Name);
                    cinfo.ForeignField2 = fi;
                    cinfo.Class = ci;
                }
            }
        }
Exemplo n.º 28
0
 private string SoqlToSql(SoqlQueryExpression queryExpression, SchemaInfo schemaInfo, bool generateColumnAliases)
 {
     StringWriter sw = new StringWriter();
     SoqlToSqlConverter converter = new SoqlToSqlConverter(sw, schemaInfo, SqlBuilder);
     converter.IndentOutput = this.IndentQueries;
     converter.GenerateColumnAliases = generateColumnAliases;
     converter.UpperLike = this.UpperLike;
     //logger.Trace("Converting {0}", queryExpression);
     converter.ConvertQuery(queryExpression);
     string query = sw.ToString();
     //logger.Trace("Converted as {0}", query);
     return query;
 }
Exemplo n.º 29
0
 public List<ClassInfo> GetSubclassesForSchema(SchemaInfo schema)
 {
     return schema.GetSubclasses(this);
 }
Exemplo n.º 30
0
        public void Run()
        {
            try
            {
                if (Project.SchemaFile == null)
                    throw new SoodaCodeGenException("No schema file specified.");

                if (Project.OutputPath == null)
                    throw new SoodaCodeGenException("No Output path specified.");

                if (Project.OutputNamespace == null)
                    throw new SoodaCodeGenException("No Output namespace specified.");

                CodeDomProvider codeProvider = GetCodeProvider(Project.Language);
                _codeProvider = codeProvider;

                CodeDomProvider codeGenerator = codeProvider;
                CodeDomProvider csharpCodeGenerator = GetCodeProvider("c#");
                _codeGenerator = codeGenerator;
                _csharpCodeGenerator = csharpCodeGenerator;

                _fileExtensionWithoutPeriod = _codeProvider.FileExtension;
                if (_fileExtensionWithoutPeriod.StartsWith("."))
                    _fileExtensionWithoutPeriod = _fileExtensionWithoutPeriod.Substring(1);

                Output.Verbose("Loading schema file {0}...", Project.SchemaFile);
                _schema = SchemaManager.ReadAndValidateSchema(
                    new XmlTextReader(Project.SchemaFile),
                    Path.GetDirectoryName(Project.SchemaFile)
                    );
                if (string.IsNullOrEmpty(_schema.Namespace))
                    _schema.Namespace = Project.OutputNamespace;

                StringCollection inputFiles = new StringCollection();
                StringCollection rewrittenOutputFiles = new StringCollection();
                StringCollection shouldBePresentOutputFiles = new StringCollection();

                GetInputAndOutputFiles(inputFiles, rewrittenOutputFiles, shouldBePresentOutputFiles);

                bool doRebuild = false;

                if (MinDate(shouldBePresentOutputFiles) == DateTime.MaxValue)
                    doRebuild = true;

                if (MaxDate(inputFiles) > MinDate(rewrittenOutputFiles))
                    doRebuild = true;

                if (!RebuildIfChanged)
                    doRebuild = true;

                if (RewriteProjects)
                    doRebuild = true;

                if (!doRebuild)
                {
                    Output.Info("Not rebuilding.");
                    return;
                }
                /*
                foreach (string s in inputFiles)
                {
                    Output.Verbose("IN: {0}", s);
                }
                foreach (string s in outputFiles)
                {
                    Output.Verbose("OUT: {0}", s);
                }
                */

                if (Project.AssemblyName == null)
                    Project.AssemblyName = Project.OutputNamespace;

                Output.Verbose("Loaded {0} classes, {1} relations...", _schema.LocalClasses.Count, _schema.Relations.Count);
                LoadExternalProjects();
                CreateOutputDirectories(rewrittenOutputFiles);
                CreateOutputDirectories(shouldBePresentOutputFiles);

                string stubsFileName;

                Output.Verbose("CodeProvider:      {0}", codeProvider.GetType().FullName);
                Output.Verbose("Source extension:  {0}", codeProvider.FileExtension);
                foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                {
                    Output.Verbose("Project:           {0} ({1})", epi.ProjectType, epi.ActualProjectFile);
                }
                Output.Verbose("Output Path:       {0}", Project.OutputPath);
                Output.Verbose("Namespace:         {0}", Project.OutputNamespace);

                // write skeleton files
                _codeGeneratorOptions = new CodeGeneratorOptions();
                _codeGeneratorOptions.BracingStyle = "C";
                _codeGeneratorOptions.IndentString = "    ";
                WriteSkeletonClasses();

                // write stubs
                _codeGeneratorOptions.BracingStyle = "Block";
                _codeGeneratorOptions.IndentString = "  ";
                _codeGeneratorOptions.BlankLinesBetweenMembers = false;

                if (Project.SeparateStubs)
                {
                    WriteMiniSkeleton();
                    WriteMiniStubs();
                }

                SerializeSchema();

                // codeGenerator = csharpCodeGenerator;

                if (Project.SeparateStubs)
                {
                    stubsFileName = Path.Combine(Project.OutputPath, "Stubs/_Stubs.csx");
                }
                else if (Project.FilePerNamespace)
                {
                    string fname = "_Stubs." + _fileExtensionWithoutPeriod;
                    stubsFileName = Path.Combine(Project.OutputPath, fname);

                    foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                    {
                        epi.ProjectProvider.AddCompileUnit(fname);
                    }

                    fname = "_Stubs." + Project.OutputNamespace + ".TypedQueries." + _fileExtensionWithoutPeriod;
                    foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                    {
                        epi.ProjectProvider.AddCompileUnit(fname);
                    }

                    fname = "_Stubs." + Project.OutputNamespace + ".Stubs." + _fileExtensionWithoutPeriod;
                    foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                    {
                        epi.ProjectProvider.AddCompileUnit(fname);
                    }
                }
                else
                {
                    string fname = "_Stubs." + _fileExtensionWithoutPeriod;
                    foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                    {
                        epi.ProjectProvider.AddCompileUnit(fname);
                    }
                    stubsFileName = Path.Combine(Project.OutputPath, fname);
                }

                CodeCompileUnit ccu = new CodeCompileUnit();
                CodeAttributeDeclaration cad = new CodeAttributeDeclaration("Sooda.SoodaObjectsAssembly");
                cad.Arguments.Add(new CodeAttributeArgument(new CodeTypeOfExpression(Project.OutputNamespace + "._DatabaseSchema")));
                ccu.AssemblyCustomAttributes.Add(cad);

                CodeNamespace nspace = null;
                if (Project.WithSoql || Project.LoaderClass)
                {
                    nspace = CreateBaseNamespace(_schema);
                    ccu.Namespaces.Add(nspace);
                }
                if (Project.WithSoql)
                {
                    Output.Verbose("    * list wrappers");
                    foreach (ClassInfo ci in _schema.LocalClasses)
                    {
                        GenerateListWrapper(nspace, ci);
                    }
                }
                if (Project.LoaderClass)
                {
                    Output.Verbose("    * loader class");
                    foreach (ClassInfo ci in _schema.LocalClasses)
                    {
                        GenerateLoaderClass(nspace, ci);
                    }
                }

                Output.Verbose("    * database schema");
                // stubs namespace
                nspace = CreateStubsNamespace(_schema);
                ccu.Namespaces.Add(nspace);

                Output.Verbose("    * class stubs");
                foreach (ClassInfo ci in _schema.LocalClasses)
                {
                    GenerateClassStub(nspace, ci, false);
                }
                Output.Verbose("    * class factories");
                foreach (ClassInfo ci in _schema.LocalClasses)
                {
                    GenerateClassFactory(nspace, ci);
                }
                Output.Verbose("    * N-N relation stubs");
                foreach (RelationInfo ri in _schema.LocalRelations)
                {
                    GenerateRelationStub(nspace, ri);
                }

                if (Project.WithTypedQueryWrappers)
                {
                    Output.Verbose("    * typed query wrappers (internal)");
                    foreach (ClassInfo ci in _schema.LocalClasses)
                    {
                        GenerateTypedInternalQueryWrappers(nspace, ci);
                    }

                    nspace = CreateTypedQueriesNamespace(_schema);
                    ccu.Namespaces.Add(nspace);

                    Output.Verbose("    * typed query wrappers");
                    foreach (ClassInfo ci in _schema.LocalClasses)
                    {
                        GenerateTypedPublicQueryWrappers(nspace, ci);
                    }
                }

                if (Project.FilePerNamespace)
                {
                    foreach (CodeNamespace ns in ccu.Namespaces)
                    {
                        using (StringWriter sw = new StringWriter())
                        {
                            Output.Verbose("Writing code...");
                            codeGenerator.GenerateCodeFromNamespace(ns, sw, _codeGeneratorOptions);
                            Output.Verbose("Done.");

                            string resultString = sw.ToString();
                            resultString = resultString.Replace("[System.ParamArrayAttribute()] ", "params ");

                            string fileName = "_Stubs." + ns.Name + "." + _fileExtensionWithoutPeriod;
                            foreach (ExternalProjectInfo epi in Project.ExternalProjects)
                            {
                                epi.ProjectProvider.AddCompileUnit(fileName);
                            }

                            using (TextWriter tw = new StreamWriter(Path.Combine(Project.OutputPath, fileName)))
                            {
                                tw.Write(resultString);
                            }
                        }
                    }
                    ccu.Namespaces.Clear();
                }

                nspace = CreateBaseNamespace(_schema);
                ccu.Namespaces.Add(nspace);

                GenerateDatabaseSchema(nspace, _schema);

                using (StringWriter sw = new StringWriter())
                {
                    Output.Verbose("Writing code...");
                    codeGenerator.GenerateCodeFromCompileUnit(ccu, sw, _codeGeneratorOptions);
                    Output.Verbose("Done.");

                    string resultString = sw.ToString();
                    resultString = resultString.Replace("[System.ParamArrayAttribute()] ", "params ");

                    using (TextWriter tw = new StreamWriter(stubsFileName))
                    {
                        tw.Write(resultString);
                    }
                }

                SaveExternalProjects();

                return;
            }
            catch (SoodaCodeGenException e)
            {
                throw e;
            }
            catch (SoodaSchemaException e)
            {
                throw new SoodaCodeGenException("Schema validation error.", e);
            }
            catch (ApplicationException e)
            {
                throw new SoodaCodeGenException("Error generating code.", e);
            }
            catch (Exception e)
            {
                throw new SoodaCodeGenException("Unexpected error.", e);
            }
        }
Exemplo n.º 31
0
        internal void Resolve(SchemaInfo schema)
        {
            if (parentSchema == null)
                parentSchema = schema;

            OuterReferences = new List<FieldInfo>();

            // local fields - a sum of all tables local to the class

            LocalFields = new List<FieldInfo>();
            int localOrdinal = 0;
            int count = 0;
            foreach (TableInfo table in LocalTables)
            {
                foreach (FieldInfo fi in table.Fields)
                {
                    // add all fields from the root table + all non-key fields
                    // from other tables

                    if (table.OrdinalInClass == 0 || !fi.IsPrimaryKey)
                    {
                        // Console.WriteLine("Adding local field {0} to class {1}", fi.Name, Name);
                        LocalFields.Add(fi);
                        fi.ClassLocalOrdinal = localOrdinal++;
                    }
                }
                count++;
            }

            if (SubclassSelectorFieldName == null && InheritsFromClass != null)
            {
                for (ClassInfo ci = this; ci != null; ci = ci.InheritsFromClass)
                {
                    if (ci.SubclassSelectorFieldName != null)
                    {
                        SubclassSelectorFieldName = ci.SubclassSelectorFieldName;
                        break;
                    }
                }
            }

            UnifiedCollections = new List<CollectionBaseInfo>();
            LocalCollections = new List<CollectionBaseInfo>();
            for (ClassInfo ci = this; ci != null; ci = ci.InheritsFromClass)
            {
                if (ci.Collections1toN != null)
                {
                    foreach (CollectionOnetoManyInfo c in ci.Collections1toN)
                    {
                        UnifiedCollections.Add(c);
                        if (ci == this)
                            LocalCollections.Add(c);
                    }
                }

                if (ci.CollectionsNtoN != null)
                {
                    foreach (CollectionManyToManyInfo c in ci.CollectionsNtoN)
                    {
                        UnifiedCollections.Add(c);
                        if (ci == this)
                            LocalCollections.Add(c);
                    }
                }
            }

            // all inherited fields + local fields

            UnifiedFields = new List<FieldInfo>();

            int unifiedOrdinal = 0;
            foreach (TableInfo ti in UnifiedTables)
            {
                foreach (FieldInfo fi in ti.Fields)
                {
                    if (ti.OrdinalInClass == 0 || !fi.IsPrimaryKey)
                    {
                        UnifiedFields.Add(fi);
                        fi.ClassUnifiedOrdinal = unifiedOrdinal++;
                    }
                }
            }

            _orderedFieldNames = new string[UnifiedFields.Count];
            for (int i = 0; i < UnifiedFields.Count; ++i)
            {
                _orderedFieldNames[i] = UnifiedFields[i].Name;
            }

            if (SubclassSelectorFieldName != null)
            {
                SubclassSelectorField = FindFieldByName(SubclassSelectorFieldName);
                if (SubclassSelectorField == null)
                    throw new SoodaSchemaException("subclassSelectorField points to invalid field name " + SubclassSelectorFieldName + " in " + Name);
            }
            else if (InheritFrom != null)
            {
                throw new SoodaSchemaException(String.Format("Must use subclassSelectorFieldName when defining inherited class '{0}'", this.Name));
            }
            if (SubclassSelectorStringValue != null)
            {
                // TODO - allow other types based on the field type
                //
                if (SubclassSelectorField == null)
                    throw new SoodaSchemaException("subclassSelectorField is invalid");
                switch (SubclassSelectorField.DataType)
                {
                    case FieldDataType.Integer:
                        SubclassSelectorValue = Convert.ToInt32(SubclassSelectorStringValue);
                        break;

                    case FieldDataType.String:
                        SubclassSelectorValue = SubclassSelectorStringValue;
                        break;

                    default:
                        throw new SoodaSchemaException("Field data type not supported for subclassSelectorValue: " + SubclassSelectorField.DataType);
                }
            }

            List<FieldInfo> pkFields = new List<FieldInfo>();
            foreach (FieldInfo fi in UnifiedFields)
            {
                if (fi.IsPrimaryKey)
                    pkFields.Add(fi);
            }
            _primaryKeyFields = pkFields.ToArray();
        }
Exemplo n.º 32
0
 CodeNamespace CreatePartialNamespace(SchemaInfo schema)
 {
     CodeNamespace nspace = new CodeNamespace(Project.OutputNamespace);
     return nspace;
 }
Exemplo n.º 33
0
        internal void ResolveReferences(SchemaInfo schema)
        {
            // logger.Debug("ResolveReferences({0})", this.Name);
            foreach (FieldInfo fi in UnifiedFields)
            {
                // logger.Debug("unifiedField: {0}", fi.Name);
                fi.ResolveReferences(schema);
            }

            foreach (FieldInfo fi in LocalFields)
            {
                fi.ParentClass = this;
                // logger.Debug("localField: {0}", fi.Name);
                if (fi.ReferencedClass != null)
                {
                    // logger.Debug("Is a reference to {0} with ondelete = {1}", fi.ReferencedClass.Name, fi.DeleteAction);
                    fi.ReferencedClass.OuterReferences.Add(fi);
                }
            }
        }
Exemplo n.º 34
0
 CodeNamespace CreateStubsNamespace(SchemaInfo schema)
 {
     CodeNamespace nspace = new CodeNamespace(Project.OutputNamespace + ".Stubs");
     nspace.Imports.Add(new CodeNamespaceImport("System"));
     nspace.Imports.Add(new CodeNamespaceImport("System.Collections"));
     nspace.Imports.Add(new CodeNamespaceImport("System.Diagnostics"));
     nspace.Imports.Add(new CodeNamespaceImport("System.Data"));
     nspace.Imports.Add(new CodeNamespaceImport("Sooda"));
     nspace.Imports.Add(new CodeNamespaceImport("Sooda.ObjectMapper"));
     nspace.Imports.Add(new CodeNamespaceImport(Project.OutputNamespace.Replace(".", "") + " = " + Project.OutputNamespace));
     AddImportsFromIncludedSchema(nspace, schema.Includes, false);
     AddImportsFromIncludedSchema(nspace, schema.Includes, true);
     return nspace;
 }