示例#1
0
        public bool InsertIdentity <T>(T entity) where T : class, new()
        {
            ColumnProperty identity = SchemaCache.GetColumns <T>().FirstOrDefault(t => t.Identity);

            if (!identity)
            {
                throw new InvalidOperationException();
            }
            IEnumerable <ColumnProperty> fields = SchemaCache.GetColumns <T>().Where(t => !t.Identity);
            string            sql        = $"INSERT INTO {typeof(T).GetTableName()} ({ string.Join(",", fields.Select(t => $"{t.Name}")) }) VALUES({ string.Join(",", fields.Select(t => $"@{t.Name}")) });SELECT LAST_INSERT_ID();";
            DynamicParameters parameters = new DynamicParameters();

            foreach (ColumnProperty field in fields)
            {
                parameters.Add($"@{field.Name}", field.Property.GetValue(entity).GetSafeValue(field.Property.PropertyType));
            }
            object value = this.db.ExecuteScalar(CommandType.Text, sql, parameters);

            if (value == null || value == DBNull.Value)
            {
                return(false);
            }
            identity.Property.SetValue(entity, Convert.ChangeType(value, identity.Property.PropertyType));
            return(true);
        }
示例#2
0
        internal DynamicMetadataProvider(ProviderSpecificSchema informationSchema, InformationSchemaMapping?informationSchemaMapping)
        {
            InformationSchema         = informationSchema;
            _informationSchemaMapping = informationSchemaMapping;

            _schemaCache = SchemaCacheFactory.Create(informationSchema, _informationSchemaMapping?.Tables);
        }
示例#3
0
        public IDataReader ReadData <T>(params Expression <Func <T, object> >[] fields) where T : class, new()
        {
            string field = string.Join(",", SchemaCache.GetColumns(fields).Select(t => $"{t.Name}"));
            string sql   = $"SELECT {field} FROM {typeof(T).GetTableName()};";

            return(db.ReadData(CommandType.Text, sql));
        }
        internal DynamicMetadataProvider(ProviderSpecificSchema informationSchema, InformationSchemaSettings informationSchemaSettings)
        {
            InformationSchema          = informationSchema;
            _informationSchemaSettings = informationSchemaSettings;

            _schemaCache = SchemaCacheFactory.Create(informationSchema, _informationSchemaSettings);
        }
        internal DynamicMetadataProvider(ProviderSpecificSchema informationSchema, InformationSchemaMapping?informationSchemaMapping)
        {
            InformationSchema         = informationSchema;
            _informationSchemaMapping = informationSchemaMapping;

            _schemaCache = new SchemaCache(informationSchema);
            _schemaCache.Initialize(_informationSchemaMapping?.Tables);
        }
示例#6
0
 public TValue ReadInfo <T, TValue>(Expression <Func <T, TValue> > field, Expression <Func <T, bool> > condition) where T : class, new()
 {
     using (IExpressionCondition expression = db.GetExpressionCondition(condition))
     {
         string conditionSql = expression.ToCondition(out DynamicParameters parameters);
         string sql          = $"SELECT  { SchemaCache.GetColumnProperty(field).Name } FROM {typeof(T).GetTableName()} {conditionSql}  LIMIT 0,1;";
         object value        = db.ExecuteScalar(CommandType.Text, sql, parameters);
         if (value == null)
         {
             return(default);
示例#7
0
        public IDataReader ReadData <T>(Expression <Func <T, bool> > condition, params Expression <Func <T, object> >[] fields) where T : class, new()
        {
            string field = string.Join(",", SchemaCache.GetColumns(fields).Select(t => $"{t.Name}"));

            using (IExpressionCondition expression = db.GetExpressionCondition(condition))
            {
                string conditionSql = expression.ToCondition(out DynamicParameters parameters);
                string sql          = $"SELECT {field} FROM {typeof(T).GetTableName()} {conditionSql};";
                return(db.ReadData(CommandType.Text, sql, parameters));
            }
        }
示例#8
0
        /// <summary>
        /// 获取DataSet
        /// </summary>
        public DataSet GetDataSet <T>(Expression <Func <T, bool> > condition, params Expression <Func <T, object> >[] fields) where T : class, new()
        {
            string field = string.Join(",", SchemaCache.GetColumns(fields).Select(t => $"[{t.Name}]"));

            using (ExpressionCondition expression = db.GetExpressionCondition(condition))
            {
                string conditionSql = expression.ToCondition(out DynamicParameters parameters);
                string sql          = $"SELECT {field} FROM [{typeof(T).GetTableName()}] {conditionSql}";
                return(db.GetDataSet(CommandType.Text, sql, parameters.ToDbParameter()));
            }
        }
示例#9
0
        public bool Insert <T>(T entity) where T : class, new()
        {
            IEnumerable <ColumnProperty> fields = SchemaCache.GetColumns <T>().Where(t => !t.Identity);
            string            sql        = $"INSERT INTO {typeof(T).GetTableName()} ({ string.Join(",", fields.Select(t => $"{t.Name}")) }) VALUES({ string.Join(",", fields.Select(t => $"@{t.Name}")) });";
            DynamicParameters parameters = new DynamicParameters();

            foreach (ColumnProperty field in fields)
            {
                parameters.Add($"@{field.Name}", field.Property.GetValue(entity).GetSafeValue(field.Property.PropertyType));
            }
            return(this.db.ExecuteNonQuery(CommandType.Text, sql, parameters) == 1);
        }
示例#10
0
        /// <summary>
        /// 获取一行值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="precate"></param>
        /// <returns></returns>
        public SQLResult Info <T>(T obj, params Expression <Func <T, object> >[] precate) where T : class, new()
        {
            Dictionary <ColumnProperty, object> condition = obj.GetCondition(precate);
            string tableName = obj.GetTableName();
            IEnumerable <ColumnProperty> fields = SchemaCache.GetColumns <T>();
            string sql = $"SELECT TOP 1 { string.Join(",", fields.Select(t => string.Format("[{0}]", t.Name))) } FROM [{tableName}] WHERE { string.Join(" AND ", condition.Select(t => $"[{t.Key.Name}] = @{t.Key.Property.Name}")) }";

            DbParameter[] parameters = condition.Select(t => new SqlParameter($"@{t.Key.Property.Name}", t.Value)).ToArray();
            return(new SQLResult()
            {
                CommandText = sql,
                Prameters = parameters
            });
        }
示例#11
0
        public bool Delete <T>(T entity) where T : class, new()
        {
            DynamicParameters parameters = new DynamicParameters();

            Stack <string> where = new Stack <string>();
            foreach (ColumnProperty column in SchemaCache.GetColumns <T>().Where(t => t.IsKey))
            {
                where.Push($"[{column.Name}]=@{column.Name}");
                parameters.Add(column.Name, column.Property.GetValue(entity));
            }
            string sql = $"DELETE FROM {typeof(T).GetTableName()} WHERE {string.Join(" AND ", where)};";

            return(db.ExecuteNonQuery(CommandType.Text, sql, parameters) > 0);
        }
示例#12
0
        public RecordStorageEngine(DatabaseLayout databaseLayout, Config config, PageCache pageCache, FileSystemAbstraction fs, LogProvider logProvider, LogProvider userLogProvider, TokenHolders tokenHolders, SchemaState schemaState, ConstraintSemantics constraintSemantics, JobScheduler scheduler, TokenNameLookup tokenNameLookup, LockService lockService, IndexProviderMap indexProviderMap, IndexingService.Monitor indexingServiceMonitor, DatabaseHealth databaseHealth, ExplicitIndexProvider explicitIndexProvider, IndexConfigStore indexConfigStore, IdOrderingQueue explicitIndexTransactionOrdering, IdGeneratorFactory idGeneratorFactory, IdController idController, Monitors monitors, RecoveryCleanupWorkCollector recoveryCleanupWorkCollector, OperationalMode operationalMode, VersionContextSupplier versionContextSupplier)
        {
            this._tokenHolders   = tokenHolders;
            this._schemaState    = schemaState;
            this._lockService    = lockService;
            this._databaseHealth = databaseHealth;
            this._explicitIndexProviderLookup      = explicitIndexProvider;
            this._indexConfigStore                 = indexConfigStore;
            this._constraintSemantics              = constraintSemantics;
            this._explicitIndexTransactionOrdering = explicitIndexTransactionOrdering;

            this._idController = idController;
            StoreFactory factory = new StoreFactory(databaseLayout, config, idGeneratorFactory, pageCache, fs, logProvider, versionContextSupplier);

            _neoStores = factory.OpenAllNeoStores(true);

            try
            {
                _schemaCache   = new SchemaCache(constraintSemantics, Collections.emptyList(), indexProviderMap);
                _schemaStorage = new SchemaStorage(_neoStores.SchemaStore);

                NeoStoreIndexStoreView neoStoreIndexStoreView = new NeoStoreIndexStoreView(lockService, _neoStores);
                bool readOnly = config.Get(GraphDatabaseSettings.read_only) && operationalMode == OperationalMode.single;
                monitors.AddMonitorListener(new LoggingMonitor(logProvider.GetLog(typeof(NativeLabelScanStore))));
                _labelScanStore = new NativeLabelScanStore(pageCache, databaseLayout, fs, new FullLabelStream(neoStoreIndexStoreView), readOnly, monitors, recoveryCleanupWorkCollector);

                _indexStoreView        = new DynamicIndexStoreView(neoStoreIndexStoreView, _labelScanStore, lockService, _neoStores, logProvider);
                this._indexProviderMap = indexProviderMap;
                _indexingService       = IndexingServiceFactory.createIndexingService(config, scheduler, indexProviderMap, _indexStoreView, tokenNameLookup, Iterators.asList(_schemaStorage.loadAllSchemaRules()), logProvider, userLogProvider, indexingServiceMonitor, schemaState, readOnly);

                _integrityValidator = new IntegrityValidator(_neoStores, _indexingService);
                _cacheAccess        = new BridgingCacheAccess(_schemaCache, schemaState, tokenHolders);

                _explicitIndexApplierLookup = new Org.Neo4j.Kernel.Impl.Api.ExplicitIndexApplierLookup_Direct(explicitIndexProvider);

                _labelScanStoreSync = new WorkSync <Supplier <LabelScanWriter>, LabelUpdateWork>(_labelScanStore.newWriter);

                _commandReaderFactory = new RecordStorageCommandReaderFactory();
                _indexUpdatesSync     = new WorkSync <IndexingUpdateService, IndexUpdatesWork>(_indexingService);

                _denseNodeThreshold = config.Get(GraphDatabaseSettings.dense_node_threshold);
                _recordIdBatchSize  = config.Get(GraphDatabaseSettings.record_id_batch_size);
            }
            catch (Exception failure)
            {
                _neoStores.close();
                throw failure;
            }
        }
示例#13
0
 internal RecordStorageReader(TokenHolders tokenHolders, SchemaStorage schemaStorage, NeoStores neoStores, IndexingService indexService, SchemaCache schemaCache, System.Func <IndexReaderFactory> indexReaderFactory, System.Func <LabelScanReader> labelScanReaderSupplier, RecordStorageCommandCreationContext commandCreationContext)
 {
     this._tokenHolders           = tokenHolders;
     this._neoStores              = neoStores;
     this._schemaStorage          = schemaStorage;
     this._indexService           = indexService;
     this._nodeStore              = neoStores.NodeStore;
     this._relationshipStore      = neoStores.RelationshipStore;
     this._relationshipGroupStore = neoStores.RelationshipGroupStore;
     this._propertyStore          = neoStores.PropertyStore;
     this._counts      = neoStores.Counts;
     this._schemaCache = schemaCache;
     this._indexReaderFactorySupplier = indexReaderFactory;
     this._labelScanReaderSupplier    = labelScanReaderSupplier;
     this._commandCreationContext     = commandCreationContext;
 }
示例#14
0
        public bool Exists <T>(T entity) where T : class, new()
        {
            IEnumerable <ColumnProperty> fields = SchemaCache.GetColumns <T>(t => t.IsKey);

            if (!fields.Any())
            {
                throw new Exception($"{ typeof(T).GetTableName() } No primary key");
            }
            string            sql        = $"SELECT 0 WHERE EXISTS(SELECT 0 FROM {typeof(T).GetTableName()} WHERE { string.Join(" AND ", fields.Select(t => $"{t.Name}=@{t.Name}")) });";
            DynamicParameters parameters = new DynamicParameters();

            foreach (ColumnProperty column in fields)
            {
                parameters.Add($"@{column.Name}", column.Property.GetValue(entity));
            }
            return(db.ExecuteScalar(CommandType.Text, sql, parameters) != null);
        }
示例#15
0
        public static object GetReaderData(this IDataReader reader, object source)
        {
            //映射数据库中的字段到实体属性
            IEnumerable <ColumnProperty> propertys = SchemaCache.GetColumns(source.GetType());

            foreach (ColumnProperty property in propertys)
            {
                //对实体属性进行设值
                object value = reader[property.Name];
                if (value == null)
                {
                    continue;
                }
                property.Property.SetValue(source, value);
            }
            return(source);
        }
示例#16
0
        /// <summary>
        /// 读取一个字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="TValue"></typeparam>
        /// <param name="field"></param>
        /// <param name="condition"></param>
        /// <returns></returns>
        public IEnumerable <TValue> ReadList <T, TValue>(Expression <Func <T, TValue> > field, Expression <Func <T, bool> > condition) where T : class, new()
        {
            string        fieldName = SchemaCache.GetColumnProperty(field).Name;
            List <TValue> list      = new List <TValue>();

            using (ExpressionCondition expression = db.GetExpressionCondition(condition))
            {
                string      conditionSql = expression.ToCondition(out DynamicParameters parameters);
                string      sql          = $"SELECT {fieldName} FROM [{typeof(T).GetTableName()}] {conditionSql}";
                IDataReader reader       = db.ReadData(CommandType.Text, sql, parameters);
                while (reader.Read())
                {
                    list.Add((TValue)reader[0]);
                }
                if (!reader.IsClosed)
                {
                    reader.Close();
                }
            }
            return(list);
        }
示例#17
0
 public SchemaFacts()
 {
     _cache = new MemoryCache(new MemoryCacheOptions());
     _sut   = new SchemaCache(_cache);
 }
 public MongoDbProjectionVisitorScalarTests(MongoResource resource)
 {
     _cache = new SchemaCache(resource);
 }
 public MongoDbProjectionObjectTests(MongoResource resource)
 {
     _cache = new SchemaCache(resource);
 }
 internal StorageSchemaReaderSnapshot(SchemaCache schema, RecordStorageReader reader)
 {
     this._schema = schema;
     this._reader = reader;
 }
 /// <summary>
 /// Look up schema on schema cache, if not present add a new key.
 /// </summary>
 /// <param name="type"></param>
 /// <returns></returns>
 private static string GetOrSaveSchemaReference(Type type)
 {
     return(SchemaCache.AddSchema(type));
 }