コード例 #1
0
        public int CreateTable(Type ty, CreateFlags createFlags = CreateFlags.None)
        {
            if (Tables == null)
            {
                Tables = new Dictionary <string, TableMapping>();
            }
            TableMapping map;

            if (!Tables.TryGetValue(ty.FullName, out map))
            {
                map = GetMapping(ty, createFlags);
                Tables.Add(ty.FullName, map);
            }

            string query = "create table if not exists \"" + map.TableName + "\"(\n";

            IEnumerable <string> decls = map.Columns.Select(p => Orm.SqlDecl(p, this.StoreDateTimeAsTicks));
            string decl = string.Join(",\n", decls.ToArray());

            query += decl;
            query += ")";

            int count = Execute(query);

            if (count == 0)
            {
                MigrateTable(map);
            }

            Dictionary <string, IndexInfo> indexes = new Dictionary <string, IndexInfo>();

            foreach (TableMapping.Column c in map.Columns)
            {
                foreach (IndexedAttribute i in c.Indices)
                {
                    string    iname = i.Name ?? map.TableName + "_" + c.Name;
                    IndexInfo iinfo;
                    if (!indexes.TryGetValue(iname, out iinfo))
                    {
                        iinfo = new IndexInfo {
                            IndexName = iname,
                            TableName = map.TableName,
                            Unique    = i.Unique,
                            Columns   = new List <IndexedColumn>()
                        };
                        indexes.Add(iname, iinfo);
                    }

                    if (i.Unique != iinfo.Unique)
                    {
                        throw new Exception(
                                  "All the columns in an index must have the same value for their Unique property");
                    }

                    iinfo.Columns.Add(new IndexedColumn {
                        Order      = i.Order,
                        ColumnName = c.Name
                    });
                }
            }

            foreach (string indexName in indexes.Keys)
            {
                IndexInfo index   = indexes[indexName];
                string[]  columns = index.Columns.OrderBy(i => i.Order).Select(i => i.ColumnName).ToArray();
                count += CreateIndex(indexName, index.TableName, columns, index.Unique);
            }

            return(count);
        }