首页 文章 精选 留言 我的

精选列表

搜索[非自回归核心技术],共10000篇文章
优秀的个人博客,低调大师

IvorySQL 核心技术解读:双 Parser 架构如何定义数据库兼容性?

引言 PostgreSQL 与 Oracle 的语法差异较大,为兼容 Oracle 语法并保持原生 PostgreSQL 语法,IvorySQL 采用了双 Parser 框架,动态切换不同 Parser,实现 Oracle 兼容语法与 PostgreSQL 原生语法的共存。 双 Parser 架构设计总览 双 Parser 的实现目标是在 SQL 和服务器编程语言两个层面兼容 Oracle。通过端口选择或兼容模式设定,实现 Oracle/PG 语法解析的"热切换"。 涉及到的核心模块包括: SQL 解析层,即 Oracle 风格语法树生成; 服务器端编程语言层(通过全新的 PL/iSQL 过程语言实现兼容 Oracle 的 PLSQL) SQL 端词法语法分离 概述 基本做法是新增一套兼容 Oracle 风格的语法和词法,在开启 Oracle 兼容模式时,采用 Oracle 风格的语法分析,生成对应的语法树。 具体实现步骤 在 src/backend/ 目录下新建一个 oracle_Parser 目录,将 src/backend/Parser/ 中的 scan.l 和 gram.y 复制到新目录,并分别重命名为 ora_gram.y 和 ora_scan.l,添加 Oracle 风格的语法和词法分析代码。同时,将 keywords.c 文件复制到该目录,用于存放自定义的关键字。该 oracle_Parser 目录会编译成一个动态库 libParser_oracle.so。当开启 Oracle 兼容模式时,配置文件 ivorysql.conf 将被嵌入到 postgresql.conf 的末尾,并在 ivorysql.conf 中的 shared_preload_libraries 参数中添加 liboracle_Parser,确保数据库启动时自动加载 liboracle_Parser 动态库。 新增 ora_raw_Parser 函数指针,当 libParser_oracle.so 动态库加载时,动态库中的 _PG_init() 函数会将 oracle_raw_Parser() 函数的地址赋值给 ora_raw_Parser,而 _PG_fini() 函数则在兼容模式切换时负责将 ora_raw_Parser 重置为空。 每个后端进程会调用 BackendInitialize() 函数,根据后端进程所连接的端口号设置 port->connmode。如果端口是 Oracle 兼容端口,则将 connmode 设置为 'o',否则设置为 'p'。 在 PostgresMain() 调用 InitIvorysql() 后,如果 port->connmode 为 'o',则调用 SetConfigOption("ivorysql.compatible_mode", "oracle", PGC_USERSET, PGC_S_OVERRIDE)。由于该参数设置了 assign_hook,在 SetConfigOption() 中执行 assign_hook() 时,实际上会调用 assign_compatible_mode(),从而将 sql_raw_Parser 设置为 ora_raw_Parser。 在对 SQL 语句进行分析时,函数 pg_parse_query()->raw_Parser() 通过函数指针 sql_raw_Parser 调用 standard Parser() 或者 ora_raw_Parser()。 下面的图演示了 SQL 语句分析时发生的事情。 服务器端编程语言词法语法分离 概述 与 SQL 端类似,基本做法是新增一套兼容 Oracle 风格的编程语言 PL/iSQL,在开启 Oracle 兼容的情况下,使用 PL/iSQL 语言进行编译。 具体实现步骤 将 PostgreSQL 源码中的 plpgsql 目录复制一份并改名为 plisql,同时将目录内的文件名修改为以 plisql 开头。由于 plpgsql 是一种语言,改造后的 plisql 也将成为一种语言,因此,plpgsql 语言的注册函数如 plpgsql_validator、plpgsql_call_handler、plpgsql_inline_handler 等也需要修改为以 plisql 开头,其他函数名同样按此规则改为以 plisql 开头。 plisql 目录构建为一个插件,initdb 时如果数据库模式是 Oracle,则创建这个插件。这个插件会将 pliSQL 语言注册到数据库的系统表中。 PL/iSQL 本身没有独立的词法解析体系,而是依赖于 SQL 端的词法分析器。因此,为了确保 PL/iSQL 兼容 Oracle 的词法规则,主要的改造是在 plisql_scanner_init 函数中,需调用 ora_scanner_init() 函数,同时,plisql 目录中的 internal_yylex() 函数也应调用 ora_core_yylex()。 PL/iSQL 语法规则在 plisql/src/pl_gram.y 中,兼容 Oracle PLSQL 块的语法规则都在这个模块中实现。 SQL 端创建函数,没有指定 language 的时候,如果当前是兼容 Oracle 模式,则默认 language 是 PL/iSQL,如果是兼容 pg 模式,则默认 language 是 PL/pgSQL。oracle_Parser 中的 ora_gram.y 默认是 PL/iSQL,pg Parser 中的 gram.y 默认是 PL/pgSQL。 匿名块没有指定 language 的时候,如果是兼容 Oracle 模式,默认 PL/iSQL;如果是兼容 pg 模式,则默认 PL/pgSQL。 处理过程的 ExecuteDoStmt 函数同样根据兼容模式来决定默认 language。 下面的图演示了块语句编译分析时发生的事情。 总结 双 Parser 框架作为 IvorySQL 的重要基础,确保同时支持原生 PG 与 Oracle 语法风格,避免两者相互干扰,为 IvorySQL 的兼容特性提供了坚实保障。 IvorySQL 生态大会预告 2025 年 6 月 27 日,IvorySQL 生态大会将在济南盛大开幕,已确认多位全球 PostgreSQL 大咖参与,包括: Bruce Momjian:PG 全球开发小组联合创始人和核心团队成员 Cédric Villemain:法国,Data Bene 创始人&CEO Chris Travers:印度尼西亚,PG 和基础设施专家 Ivan Blinkov:俄罗斯,YDB 副总裁 Michael Meskes:德国,Meskes 董事长(原 Credativ 创始人) Yurii Rashkovskii:加拿大,Omnigres 公司创始人 Álvaro Hernández:西班牙,OnGres 创始人 更多重量级嘉宾正在确认中!目前议题仍在火热征集中,欢迎提交您的议题! 无论你是数据库开发者、架构师还是技术爱好者,这都是与全球顶尖专家面对面交流的绝佳机会。6 月 27 日,相约济南,共同探索 PostgreSQL 的无限可能! 本文由博客一文多发平台 OpenWrite 发布!

优秀的个人博客,低调大师

《Spring源码解析(三)》从源码深处体验Spring核心技术--IOC容器初体验

开局经验之谈:可能从这一篇文章开始,小伙伴们都会有点晕车的感觉了,但是这个系列并不是只是介绍下 spring 表面的一些肤浅的东西,本系列的目的是为了让大家从源码层次深入理解 Spring,这也是大家在未来的求职道路上的一个重要的涨薪手段,希望小伙伴都不要放弃,结合源码多看几遍,努力一定会有收获。 本文即开始带领大家研读Spring5源码,如果还没有构建Spirng5源码工程的话,可以先去《Spring源码解析(二)》构建 Spring5 源码工程,开启研读Spring源码之路 学习如何构建Spring5源码工程。 认识 IOC 与 DI 「IOC(Inversion of Control)控制反转」:所谓控制反转,就是把原先我们代码里面需要实现的对象创建、依赖的代码,反转给容器来帮忙实现。那么必然的我们需要创建一个容器,同时需要一种描述来让容器知道需要创建的对象与对象的关系。 这个描述最具体表现就是我们所看到的配置文件。 「DI(Dependency Injection)依赖注入」:就是指对象是被动接受依赖类而不是自己主动去找,换句话说就是指对象不是从容器中查找它依赖的类,而是在容器实例化对象的时候主动将它依赖的类注入给它。 如何设计IOC和DI,我们先来思考下面四个问题? 1、对象和对象的关系怎么表示? 可以用 xml,properties 文件等语义化配置文件表示。 2、描述对象关系的文件存放在哪里? 可能是 classpath,filesystem,或者是 URL 网络资源,servletContext 等。 回到正题,有了配置文件,还需要对配置文件解析。 3、不同的配置文件对对象的描述不一样,如标准的,自定义声明式的,如何统一? 在内部需要有一个统一的关于对象的定义,所有外部的描述都必须转化成统一的描述定义。 4、如何对不同的配置文件进行解析? 需要对不同的配置文件语法,采用不同的解析器。 Spring 核心容器类图 1、BeanFactory Spring Bean 的创建是典型的工厂模式,这一系列的 Bean 工厂,也即 IOC 容器为开发者管理对象间的依赖关系提供了很多便利和基础服务,在 Spring 中有许多的 IOC 容器的实现供用户选择和使用,其相互关系如下: 其中 BeanFactory 作为最顶层的一个接口类,它定义了 IOC 容器的基本功能规范 BeanFactory 有三 个重要的子类:ListableBeanFactory、HierarchicalBeanFactory 和 AutowireCapableBeanFactory。 但是从类图中我们可以发现最终的默认实现类是 DefaultListableBeanFactory,它实现了所有的接口。 那为何要定义这么多层次的接口呢? 查阅这些接口的源码和说明发现,每个接口都有它使用的场合,它主要是为了区分在 Spring 内部在操作过程中对象的传递和转化过程时,对对象的数据访问所做的限制。 例如 ListableBeanFactory 接口表示这些 Bean 是可列表化的,而 HierarchicalBeanFactory 表示的是这些 Bean 是有继承关系的,也就是每个 Bean 有可能有父 Bean。 AutowireCapableBeanFactory 接口定义 Bean 的自动装配规则。这三个接口共同定义了 Bean 的集合、Bean 之间的关系、以及 Bean 行为。 最基本的 IOC 容器接口 BeanFactory,来看一下它的源码: public interface BeanFactory { //对FactoryBean的转义定义,因为如果使用bean的名字检索FactoryBean得到的对象是工厂生成的对象, //如果需要得到工厂本身,需要转义 String FACTORY_BEAN_PREFIX = "&"; //根据bean的名字,获取在IOC容器中得到bean实例 Object getBean(String name) throws BeansException; //根据bean的名字和Class类型来得到bean实例,增加了类型安全验证机制。 <T> T getBean(String name, @Nullable Class<T> requiredType) throws BeansException; Object getBean(String name, Object... args) throws BeansException; <T> T getBean(Class<T> requiredType) throws BeansException; <T> T getBean(Class<T> requiredType, Object... args) throws BeansException; //提供对bean的检索,看看是否在IOC容器有这个名字的bean boolean containsBean(String name); //根据bean名字得到bean实例,并同时判断这个bean是不是单例 boolean isSingleton(String name) throws NoSuchBeanDefinitionException; boolean isPrototype(String name) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException; boolean isTypeMatch(String name, @Nullable Class<?> typeToMatch) throws NoSuchBeanDefinitionException; //得到bean实例的Class类型 @Nullable Class<?> getType(String name) throws NoSuchBeanDefinitionException; //得到bean的别名,如果根据别名检索,那么其原名也会被检索出来 String[] getAliases(String name); } 在 BeanFactory 里只对 IOC 容器的基本行为作了定义,根本不关心你的 Bean 是如何定义怎样加载的。 正如我们只关心工厂里得到什么的产品对象,至于工厂是怎么生产这些对象的,这个基本的接口不关心。 而要知道工厂是如何产生对象的,我们需要看具体的 IOC 容器实现,Spring 提供了许多 IOC 容器的 实现 。 比 如 GenericApplicationContext , ClasspathXmlApplicationContext 等 。 ApplicationContext 是 Spring 提供的一个高级的 IOC 容器,它除了能够提供 IOC 容器的基本功能外,还为用户提供了以下的附加服务。 从 ApplicationContext 接口的实现,我们看出其特点: 1、支持信息源,可以实现国际化。(实现 MessageSource 接口) 2、访问资源。(实现 ResourcePatternResolver 接口,后面章节会讲到) 3、支持应用事件。(实现 ApplicationEventPublisher 接口) 2、BeanDefinition SpringIOC 容器管理了我们定义的各种 Bean 对象及其相互的关系,Bean 对象在 Spring 实现中是以 BeanDefinition 来描述的,其继承体系如下: 3、BeanDefinitionReader Bean 的解析过程非常复杂,功能被分的很细,因为这里需要被扩展的地方很多,必须保证有足够的灵活性,以应对可能的变化。 Bean 的解析主要就是对 Spring 配置文件的解析。这个解析过程主要通过 BeanDefintionReader 来完成,最后看看 Spring 中 BeanDefintionReader 的类结构图: 通过本章内容的分析,我们对 Spring 框架体系有了一个基本的宏观了解,希望小伙伴们好好理解,最好在脑海中形成画面,为以后的学习打下良好的铺垫。 Web IOC 容器初体验 我们还是从大家最熟悉的 DispatcherServlet 开始,我们最先想到的还是 DispatcherServlet 的 init()方法。我们发现在 DispatherServlet 中并没有找到 init()方法。 但是经过探索,往上追索在其父类 HttpServletBean 中找到了我们想要的 init()方法,如下: /** * Map config parameters onto bean properties of this servlet, and * invoke subclass initialization. * @throws ServletException if bean properties are invalid (or required * properties are missing), or if subclass initialization fails. */ @Override public final void init() throws ServletException { if (logger.isDebugEnabled()) { logger.debug("Initializing servlet '" + getServletName() + "'"); } // Set bean properties from init parameters. PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties); if (!pvs.isEmpty()) { try { /**定位资源**/ BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this); /**加载配置信息**/ ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext()); bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment())); initBeanWrapper(bw); bw.setPropertyValues(pvs, true); } catch (BeansException ex) { if (logger.isErrorEnabled()) { logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex); } throw ex; } } // Let subclasses do whatever initialization they like. initServletBean(); if (logger.isDebugEnabled()) { logger.debug("Servlet '" + getServletName() + "' configured successfully"); } } 在 init()方法中,真正完成初始化容器动作的逻辑其实在 initServletBean()方法中,我们继续跟进 initServletBean()中的代码在 FrameworkServlet 类中: protected final void initServletBean() throws ServletException { getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'"); if (this.logger.isInfoEnabled()) { this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started"); } long startTime = System.currentTimeMillis(); try { this.webApplicationContext = initWebApplicationContext(); initFrameworkServlet(); }catch (ServletException ex) { this.logger.error("Context initialization failed", ex); throw ex; }catch (RuntimeException ex) { this.logger.error("Context initialization failed", ex); throw ex; } if (this.logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " + elapsedTime + " ms"); } } 在上面的代码中终于看到了我们似曾相识的代码 initWebAppplicationContext(),继续跟进: /** * Initialize and publish the WebApplicationContext for this servlet. * <p>Delegates to {@link #createWebApplicationContext} for actual creation * of the context. Can be overridden in subclasses. * @return the WebApplicationContext instance * @see #FrameworkServlet(WebApplicationContext) * @see #setContextClass * @see #setContextConfigLocation */ protected WebApplicationContext initWebApplicationContext() { /**先从ServletContext中获得父容器WebApplicationContext**/ WebApplicationContext rootContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext()); /**声明子容器**/ WebApplicationContext wac = null; /**建立父,子容器之间的关联关系**/ if (this.webApplicationContext != null) { // A context instance was injected at construction time -&gt; use it wac = this.webApplicationContext; if (wac instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac; if (!cwac.isActive()) { // The context has not yet been refreshed -&gt; provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -&gt; set // the root application context (if any; may be null) as the parent cwac.setParent(rootContext); } configureAndRefreshWebApplicationContext(cwac); } } } /**先去ServletContext中查找Web容器的引用是否存在,并创建默认的空IOC容器**/ if (wac == null) { // No context instance was injected at construction time -&gt; see if one // has been registered in the servlet context. If one exists, it is assumed // that the parent context (if any) has already been set and that the // user has performed any initialization such as setting the context id wac = findWebApplicationContext(); } /**给上一步创建好的IOC容器赋值**/ if (wac == null) { // No context instance is defined for this servlet -&gt; create a local one wac = createWebApplicationContext(rootContext); } /**触发onRefresh方法**/ if (!this.refreshEventReceived) { // Either the context is not a ConfigurableApplicationContext with refresh // support or the context injected at construction time had already been // refreshed -&gt; trigger initial onRefresh manually here. onRefresh(wac); } if (this.publishContext) { // Publish the context as a servlet context attribute. String attrName = getServletContextAttributeName(); getServletContext().setAttribute(attrName, wac); if (this.logger.isDebugEnabled()) { this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]"); } } return wac; } /** * Retrieve a {@code WebApplicationContext} from the {@code ServletContext} * attribute with the {@link #setContextAttribute configured name}. The * {@code WebApplicationContext} must have already been loaded and stored in the * {@code ServletContext} before this servlet gets initialized (or invoked). * </p><p>Subclasses may override this method to provide a different * {@code WebApplicationContext} retrieval strategy. * @return the WebApplicationContext for this servlet, or {@code null} if not found * @see #getContextAttribute() */ @Nullable protected WebApplicationContext findWebApplicationContext() { String attrName = getContextAttribute(); if (attrName == null) { return null; } WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName); if (wac == null) { throw new IllegalStateException("No WebApplicationContext found: initializer not registered?"); } return wac; } /** * Instantiate the WebApplicationContext for this servlet, either a default * {@link org.springframework.web.context.support.XmlWebApplicationContext} * or a {@link #setContextClass custom context class}, if set. * </p><p>This implementation expects custom contexts to implement the * {@link org.springframework.web.context.ConfigurableWebApplicationContext} * interface. Can be overridden in subclasses. * </p><p>Do not forget to register this servlet instance as application listener on the * created context (for triggering its {@link #onRefresh callback}, and to call * {@link org.springframework.context.ConfigurableApplicationContext#refresh()} * before returning the context instance. * @param parent the parent ApplicationContext to use, or {@code null} if none * @return the WebApplicationContext for this servlet * @see org.springframework.web.context.support.XmlWebApplicationContext */ protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) { Class<!--?--> contextClass = getContextClass(); if (this.logger.isDebugEnabled()) { this.logger.debug("Servlet with name '" + getServletName() + "' will try to create custom WebApplicationContext context of class '" + contextClass.getName() + "'" + ", using parent context [" + parent + "]"); } if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { throw new ApplicationContextException( "Fatal initialization error in servlet with name '" + getServletName() + "': custom WebApplicationContext class [" + contextClass.getName() + "] is not of type ConfigurableWebApplicationContext"); } ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); wac.setEnvironment(getEnvironment()); wac.setParent(parent); String configLocation = getContextConfigLocation(); if (configLocation != null) { wac.setConfigLocation(configLocation); } configureAndRefreshWebApplicationContext(wac); return wac; } protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) { if (ObjectUtils.identityToString(wac).equals(wac.getId())) { // The application context id is still set to its original default value // -&gt; assign a more useful id based on available information if (this.contextId != null) { wac.setId(this.contextId); } else { // Generate default id... wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName()); } } wac.setServletContext(getServletContext()); wac.setServletConfig(getServletConfig()); wac.setNamespace(getNamespace()); wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener())); // The wac environment's #initPropertySources will be called in any case when the context // is refreshed; do it eagerly here to ensure servlet property sources are in place for // use in any post-processing or initialization that occurs below prior to #refresh ConfigurableEnvironment env = wac.getEnvironment(); if (env instanceof ConfigurableWebEnvironment) { ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig()); } postProcessWebApplicationContext(wac); applyInitializers(wac); wac.refresh(); } 从上面的代码中可以看出,在 configAndRefreshWebApplicationContext()方法中,调用 refresh()方法,这个是真正启动 IOC 容器的入口,后面会详细介绍。 IOC 容器初始化以后,最后调用了 DispatcherServlet 的 onRefresh()方法,在 onRefresh()方法中又是直接调用 initStrategies()方法初始化 SpringMVC 的九大组件: /** * This implementation calls {@link #initStrategies}. */ @Override protected void onRefresh(ApplicationContext context) { initStrategies(context); } /** * Initialize the strategy objects that this servlet uses. * </p><p>May be overridden in subclasses in order to initialize further strategy objects. */ /**初始化策略**/ protected void initStrategies(ApplicationContext context) { /**多文件上传的组件**/ initMultipartResolver(context); /**初始化本地语言环境**/ initLocaleResolver(context); /**初始化模板处理器**/ initThemeResolver(context); /**handlerMapping**/ initHandlerMappings(context); /**初始化参数适配器**/ initHandlerAdapters(context); /**初始化异常拦截器**/ initHandlerExceptionResolvers(context); /**初始化视图预处理器**/ initRequestToViewNameTranslator(context); /**初始化视图转化器**/ initViewResolvers(context); initFlashMapManager(context); } 本文带领大家把IOC的源码流程大致走了一遍,后续会有详细介绍,IOC是Spring源码的重中之重,我们将分多个篇幅来进行讲解。 Spring Cloud 微服务精彩系列 阿里面试官问我:到底知不知道什么是Eureka,这次,我没沉默 万字详解Ribbon架构,针对面试高频题多角度细说Ribbon 什么是Hystrix,阿里技术最终面,遗憾的倒在Hystrix面前! 2万字好文全方位深入学习SpringCloud Fegin,面试不在彷徨 Zuul,听说SpringCloud不准备要我了,可是为什么面试还要天天问我? 全网最全讲解 SpringCloudGateway,认真看完这一篇就够了!

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

用户登录
用户注册