additional SQL functions to the database
434841
def _init_sqlite_functions(self):
        """"""

        self.connection.create_function("sqrt", 1,sqlfunctions._sqrt)
        self.connection.create_function("sqr", 1,sqlfunctions._sqr)
        self.connection.create_function("periodic", 1,sqlfunctions._periodic)
        self.connection.create_function("pow", 2,sqlfunctions._pow)
        self.connection.create_function("match",2,sqlfunctions._match)
        self.connection.create_function("regexp",2,sqlfunctions._regexp)
        self.connection.create_function("fformat",2,sqlfunctions._fformat)
        self.connection.create_aggregate("std",1,sqlfunctions._Stdev)
        self.connection.create_aggregate("stdN",1,sqlfunctions._StdevN)
        self.connection.create_aggregate("median",1,sqlfunctions._Median)
        self.connection.create_aggregate("array",1,sqlfunctions._NumpyArray)
        self.connection.create_aggregate("histogram",4,sqlfunctions._NumpyHistogram)
        self.connection.create_aggregate("distribution",4,sqlfunctions._NormedNumpyHistogram)
        self.connection.create_aggregate("meanhistogram",5,sqlfunctions._MeanHistogram)
        self.connection.create_aggregate("stdhistogram",5,sqlfunctions._StdHistogram)
        self.connection.create_aggregate("minhistogram",5,sqlfunctions._MinHistogram)
        self.connection.create_aggregate("maxhistogram",5,sqlfunctions._MaxHistogram)
        self.connection.create_aggregate("medianhistogram",5,sqlfunctions._MedianHistogram)
        self.connection.create_aggregate("zscorehistogram",5,sqlfunctions._ZscoreHistogram)
849194
function(db) {
		var methods_uuid = uuid();
		debug.assert(methods_uuid).is('uuid');

		return db.query('CREATE SEQUENCE methods_seq')
			.query(['CREATE TABLE IF NOT EXISTS methods (',
					"	id uuid PRIMARY KEY NOT NULL default uuid_generate_v5('"+methods_uuid+"', nextval('methods_seq'::regclass)::text),",
					'	types_id uuid REFERENCES types,',
					'	type text NOT NULL,',
					'	name text NOT NULL,',
					'	body text NOT NULL,',
					'	meta json NOT NULL,',
					'	active BOOLEAN DEFAULT TRUE,',
					'	created timestamptz NOT NULL default now(),',
					'	modified timestamptz NOT NULL default now(),',
					'	CONSTRAINT active_not_false CHECK(active != false)',
					')'
				].join('\n'))
			.query('ALTER SEQUENCE methods_seq OWNED BY methods.id')
			.query('CREATE INDEX methods_types_id ON methods (types_id)')
			.query('CREATE INDEX methods_types_id_name ON methods (types_id,name)')
			.query('CREATE INDEX methods_type ON methods (type)')
			.query('CREATE INDEX methods_type_name ON methods (type,name)')
			.query('CREATE UNIQUE INDEX ON methods USING btree(types_id, name, active nulls LAST);')
			.query('CREATE TRIGGER methods_modified BEFORE UPDATE ON methods FOR EACH ROW EXECUTE PROCEDURE moddatetime (modified)')
			.query(
				[
	'CREATE OR REPLACE FUNCTION ensure_only_one_active_row_trigger()',
	'RETURNS trigger',
	'AS $function$',
	'BEGIN',
	  // Disable the currently enabled row
	"  IF (TG_OP = 'UPDATE') THEN",
	     // Nothing to do if updating the row currently enabled'
	"    IF (OLD.active = true AND OLD.name = NEW.name) THEN",
	'      RETURN NEW;',
	'    END IF;',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, OLD.name);",
	"    IF (OLD.name != NEW.name) THEN",
	"      EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'    END IF;',
	'  ELSE',
	"    EXECUTE format('UPDATE %I.%I SET active = null WHERE active = true AND name = %L;', TG_TABLE_SCHEMA, TG_TABLE_NAME, NEW.name);",
	'  END IF;',
	   // Enable new row
	'  NEW.active := true;',
	'  RETURN NEW;',
	'END;',
	'$function$',
	'LANGUAGE plpgsql'
				].join('\n')
			)
			.query('CREATE TRIGGER methods_only_one_active_row'+
				' BEFORE INSERT OR UPDATE OF active ON methods'+
				' FOR EACH ROW WHEN (NEW.active = true)'+
				' EXECUTE PROCEDURE ensure_only_one_active_row_trigger()'
			);
	}
622212
protected function appendExtraFieldsToQuery()
    {
        $finalized = [];

        foreach ($this->extraFields as $field => $spec) {
            $obj = Injector::inst()->create($spec);

            if ($obj instanceof DBComposite) {
                $this->_compositeExtraFields[$field] = [];

                // append the composite field names to the select
                foreach ($obj->compositeDatabaseFields() as $subField => $subSpec) {
                    $col = $field . $subField;
                    $finalized[] = $col;

                    // cache
                    $this->_compositeExtraFields[$field][] = $subField;
                }
            } else {
                $finalized[] = $field;
            }
        }

        $this->dataQuery->addSelectFromTable($this->joinTable, $finalized);
    }
1329529
def build_insert(table_name, attributes):
    
    sql = "INSERT INTO %s" %(table_name)
    column_str = u""
    value_str = u""
    for index, (key, value) in enumerate(attributes.items()):
        if index > 0:
            column_str += u","
            value_str += u","
        column_str += key
        value_str += value_to_sql_str(value)
    sql = sql + u"(%s) VALUES(%s)" %(column_str, value_str)
    return sql
183325
def exec_query(sql, name = 'SQL', binds = [])
      # NOTE: we allow to execute SQL as requested returning a results.
      # e.g. this allows to use SQLServer's EXEC with a result set ...
      sql = to_sql(sql, binds) if sql.respond_to?(:to_sql)

      sql = repair_special_columns(sql)
      if prepared_statements?
        log(sql, name, binds) { @connection.execute_query(sql, binds) }
      else
        log(sql, name) { @connection.execute_query(sql) }
      end
    end
455221
def insert_function(self, fname, ftype):
        ""
        index = self.insert_id(fname, SharedData.KINDS.FUNCTION, [SharedData.KINDS.GLOBAL_VAR, SharedData.KINDS.FUNCTION], ftype)
        self.table[index].set_attribute("Params",0)
        return index
255287
def update_sql(table, filter, updates):
    '''
    
    '''
    where_keys, where_vals = _split_dict(filter)
    up_keys, up_vals = _split_dict(updates)
    changes = _pairs(up_keys, sep=', ')
    where = _pairs(where_keys, start=len(up_keys) + 1)
    sql = 'UPDATE {} SET {} WHERE {}'.format(
        table, changes, where)
    return sql, up_vals + where_vals
1135797
void appendSql(String tableName, StringBuilder sb, List<ArgumentHolder> columnArgList) throws SQLException {
		if (clauseStackLevel == 0) {
			throw new IllegalStateException("No where clauses defined.  Did you miss a where operation?");
		}
		if (clauseStackLevel != 1) {
			throw new IllegalStateException(
					"Both the \"left-hand\" and \"right-hand\" clauses have been defined.  Did you miss an AND or OR?");
		}
		if (needsFuture != null) {
			throw new IllegalStateException(
					"The SQL statement has not been finished since there are previous operations still waiting for clauses.");
		}

		// we don't pop here because we may want to run the query multiple times
		peek().appendSql(databaseType, tableName, sb, columnArgList);
	}
590822
def _condition_as_sql(self, qn, connection):
        '''
        
        '''
        def escape(value):
            if isinstance(value, bool):
                value = str(int(value))
            if isinstance(value, six.string_types):
                # Escape params used with LIKE
                if '%' in value:
                    value = value.replace('%', '%%')
                # Escape single quotes
                if "'" in value:
                    value = value.replace("'", "''")
                # Add single quote to text values
                value = "'" + value + "'"
            return value

        sql, param = self.condition.query.where.as_sql(qn, connection)
        param = map(escape, param)

        return sql % tuple(param)
435655
function generateAddFieldSql( $table, $field_name, $added_field, $params )
    {
        return $this->OtherSchema->generateAddFieldSql( $table, $field_name, $added_field, $params );
    }
423015
function prepareSqlQuery( &$fd, &$buffer )
    {

        $sqlQueryArray = array();
        while( count( $sqlQueryArray ) == 0 && !feof( $fd ) )
        {
            $buffer  .= fread( $fd, 4096 );
            if ( $buffer )
            {
                // Fix SQL file by deleting all comments and newlines
                // eZDebug::writeDebug( $buffer, "read data" );
                $sqlQuery = preg_replace( array( "/^#.*\n" . "/m",
                                                 "#^/\*.*\*/\n" . "#m",
                                                 "/^--.*\n" . "/m",
                                                 "/\n|\r\n|\r/m" ),
                                          array( "",
                                                 "",
                                                 "",
                                                 "\n" ),
                                          $buffer );
//            eZDebug::writeDebug( $sqlQuery, "read data" );

                // Split the query into an array
                $sqlQueryArray = preg_split( "/;\n/m", $sqlQuery );

                if ( preg_match( '/;\n/m', $sqlQueryArray[ count( $sqlQueryArray ) -1 ] ) )
                {
                    $buffer = '';
                }
                else
                {
                    $buffer = $sqlQueryArray[ count( $sqlQueryArray ) -1 ];
                    array_splice( $sqlQueryArray, count( $sqlQueryArray ) -1 , 1 );
                }
            }
            else
            {
                return $sqlQueryArray;

            }
        }
        return $sqlQueryArray;
    }
336251
static public function IsFunctionSQL( string & $sql ) : bool {
    
        $ret = false;
        
        // echo "\n IsFunctionSQL( {$sql} ) ";
        
        $str = \rstoetter\cSQL\cSQL::RemoveAlias( $sql );
    
        if ( ( $pos = self::PositionEndFunctionSQL( $str ) ) != -1 ) {
        
            // echo "\n pos ')' is " . $pos . '->\'' . substr( $str, $pos ) . '\'';
        
            
            if ( $pos == strlen( $str ) -1 ) {
                $ret = true;
            } else {
            
            
                $str = trim( substr( $sql, $pos + 1 ) );
                if ( 
                    ( $str == '' ) ||
                    ( $str == ';' )
                ) {
                    $ret = true;
                }
            }
        }
        
        
        // echo "\n IsFunctionSQL( ) returns " . ( $ret ? 'true' : 'false' );
        
        return $ret;
    
    }
269444
def form_query(self, columns, options={}):
        
        from_cl = 'FROM'

        direct = options.get('direct', self.direct)
        if direct:
            if columns != '*':
                raise ProgrammingError("Column lists cannot be specified for a direct function call.")
            columns = ''
            from_cl = ''

        if len(self.args) >= 1:
            replace = ['%s' for x in range(len(self.args))]
            func = "%s(" % self.query_base + ",".join(replace) + ")"
        else:
            func = "%s()" % self.query_base

        return "SELECT %s %s %s" % (columns, from_cl, func)
525780
def compile(self):
        
        params = self.column_params + self.join_params + self.params
        if self.limit and self.limit >= 0:
            self.sql_limit = 'LIMIT ?'
            params += [self.limit]
        return (self.sql, params, self.keys)
240207
def _loadDB(self):
        """"""
        if not self._validID():
            raise NotFound, self._getID()
        (sql, fields) = self._prepareSQL("SELECT")
        curs = self.cursor()
        curs.execute(sql, self._getID())
        result = curs.fetchone()
        if not result:
            curs.close()
            raise NotFound, self._getID()
        self._loadFromRow(result, fields, curs)
        curs.close()
        self._updated = time.time()
1152156
def install_sql_hook():
    """"""
    try:
        from django.db.backends.utils import CursorWrapper
    except ImportError:
        from django.db.backends.util import CursorWrapper

    try:
        real_execute = CursorWrapper.execute
        real_executemany = CursorWrapper.executemany
    except AttributeError:
        # XXX(mitsuhiko): On some very old django versions (<1.6) this
        # trickery would have to look different but I can't be bothered.
        return

    def record_many_sql(vendor, alias, start, sql, param_list):
        duration = time.time() - start
        for params in param_list:
            record_sql(vendor, alias, start, duration, sql, params)

    def execute(self, sql, params=None):
        start = time.time()
        try:
            return real_execute(self, sql, params)
        finally:
            record_sql(self.db.vendor, getattr(self.db, 'alias', None),
                       start, time.time() - start, sql, params)

    def executemany(self, sql, param_list):
        start = time.time()
        try:
            return real_executemany(self, sql, param_list)
        finally:
            record_many_sql(self.db.vendor, getattr(self.db, 'alias', None),
                            start, sql, param_list)

    CursorWrapper.execute = execute
    CursorWrapper.executemany = executemany
    breadcrumbs.ignore_logger('django.db.backends')
700045
function insertQuerySuccess(resultSet) {
        resultSet.Action = 'inserted';
        resultSet.ID = resultSet.rs.insertId;
        CRUD.stats.writesExecuted++;
        return resultSet;
    }