Creates table which manages schema version and insert an initial record as version 0.
12995
protected void createTable(){
        sqlManager.executeUpdate(
                new StringSqlResource(String.format("CREATE TABLE %s (VERSION NUMERIC NOT NULL)", tableName)));

        sqlManager.executeUpdate(
                new StringSqlResource(String.format("INSERT INTO %s (0))", tableName)));
    }
376576
def create_temporary_table(from_table, name=None, on_commit=None):
    
    from_table = from_table.__table__ if hasattr(from_table, "__table__") else from_table

    name = name or f"temporary_{from_table.name}"

    # copy the origin table into the metadata with the new name.
    temporary_table = copy_table(from_table, name)

    # change create clause to: CREATE TEMPORARY TABLE
    temporary_table._prefixes = list(from_table._prefixes)
    temporary_table._prefixes.append("TEMPORARY")

    # change post create clause to: ON COMMIT DROP
    if on_commit:
        temporary_table.dialect_options["postgresql"].update(
            on_commit=on_commit,
        )

    temporary_table.insert_many = MethodType(insert_many, temporary_table)
    temporary_table.select_from = MethodType(select_from, temporary_table)
    temporary_table.upsert_into = MethodType(upsert_into, temporary_table)

    return temporary_table
469959
private void generateOnUpgrade(SQLiteDatabaseSchema schema, List<SQLiteEntity> orderedEntities) {
		MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("onUpgrade").addAnnotation(Override.class)
				.addModifiers(Modifier.PUBLIC);
		methodBuilder.addParameter(SQLiteDatabase.class, "database");
		methodBuilder.addParameter(Integer.TYPE, "previousVersion");
		methodBuilder.addParameter(Integer.TYPE, "currentVersion");
		methodBuilder.addJavadoc("onUpgrade\n");

		Collections.reverse(orderedEntities);

		if (schema.isLogEnabled()) {
			// generate log section - BEGIN
			methodBuilder.addComment("log section BEGIN");
			methodBuilder.beginControlFlow("if (this.logEnabled)");

			methodBuilder.addStatement(
					"$T.info(\"Update database '%s' from version %s to version %s\",this.name, previousVersion, currentVersion)",
					Logger.class);

			// generate log section - END
			methodBuilder.endControlFlow();
			methodBuilder.addComment("log section END");
		}

		methodBuilder.addComment("if we have a list of update task, try to execute them");
		methodBuilder.beginControlFlow("if (options.updateTasks != null)");
		methodBuilder.addStatement("$T<$T> tasks = buildTaskList(previousVersion, currentVersion)", List.class,
				SQLiteUpdateTask.class);
		methodBuilder.beginControlFlow("for ($T task : tasks)", SQLiteUpdateTask.class);

		// generate log section - BEGIN
		methodBuilder.addComment("log section BEGIN");
		methodBuilder.beginControlFlow("if (this.logEnabled)");

		methodBuilder.addStatement(
				"$T.info(\"Begin update database from version %s to %s\", previousVersion, previousVersion+1)",
				Logger.class);

		// generate log section - END
		methodBuilder.endControlFlow();
		methodBuilder.addComment("log section END");

		methodBuilder.addStatement("task.execute(database, previousVersion, previousVersion+1)");

		// generate log section - BEGIN
		methodBuilder.addComment("log section BEGIN");
		methodBuilder.beginControlFlow("if (this.logEnabled)");

		methodBuilder.addStatement(
				"$T.info(\"End update database from version %s to %s\", previousVersion, previousVersion+1)",
				Logger.class);

		// generate log section - END
		methodBuilder.endControlFlow();
		methodBuilder.addComment("log section END");

		methodBuilder.addStatement("previousVersion++");
		methodBuilder.endControlFlow();
		methodBuilder.nextControlFlow("else");

		methodBuilder.addComment("drop all tables");
		methodBuilder.addStatement("$T.dropTablesAndIndices(database)", SQLiteUpdateTaskHelper.class);

		// reorder entities
		Collections.reverse(orderedEntities);

		methodBuilder.addCode("\n");
		methodBuilder.addCode("// generate tables\n");

		for (SQLiteEntity item : orderedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");

				methodBuilder.addCode("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL);\n", Logger.class,
						BindTableGenerator.tableClassName(null, item));

				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section END");
			}
			methodBuilder.addCode("database.execSQL($T.CREATE_TABLE_SQL);\n",
					BindTableGenerator.tableClassName(null, item));
		}

		// use generated entities too
		for (GeneratedTypeElement item : schema.generatedEntities) {
			if (schema.isLogEnabled()) {
				// generate log section - BEGIN
				methodBuilder.addComment("log section BEGIN");
				methodBuilder.beginControlFlow("if (this.logEnabled)");
				methodBuilder.addStatement("$T.info(\"DDL: %s\",$T.CREATE_TABLE_SQL)", Logger.class,
						TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
				// generate log section - END
				methodBuilder.endControlFlow();
				methodBuilder.addComment("log section END");
			}
			methodBuilder.addStatement("database.execSQL($T.CREATE_TABLE_SQL)",
					TypeUtility.className(BindTableGenerator.getTableClassName(item.getQualifiedName())));
		}

		methodBuilder.endControlFlow();

		methodBuilder.beginControlFlow("if (options.databaseLifecycleHandler != null)");
		methodBuilder.addStatement(
				"options.databaseLifecycleHandler.onUpdate(database, previousVersion, currentVersion, true)");
		methodBuilder.endControlFlow();

		classBuilder.addMethod(methodBuilder.build());
	}
1309275
function createDatabase(tx) {
    var schema = "clicks (id integer primary key, date text)"
    var sql = "create table if not exists " + schema

    tx.executeSql(sql, null, clearDatabase, sqlError);
}
364475
private void createOrUpdateSchema(Boolean isUpdate)

    {
        createNamespace(isUpdate);
        readExternalProperties();
        Map<Class<?>, EntityType<?>> entityMap = kunderaMetadata.getApplicationMetadata()
                .getMetaModelBuilder(puMetadata.getPersistenceUnitName()).getManagedTypes();
        // iterating all classes of pu to generate schema
        for (Class<?> clazz : entityMap.keySet())
        {
            EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
            if (m != null)
            {
                String tablename = m.getTableName();
                HTableDescriptor hTableDescriptor = getTableDescriptor(clazz, entityMap.get(clazz), tablename);
                String hTableName = HBaseUtils.getHTableName(databaseName, tablename);
                createOrUpdateTable(hTableName, hTableDescriptor);
            }
        }
    }
523655
def install_versioning(self, conn):
        
        logging.info('Creating the versioning table %s', self.version_table)
        conn.executescript(CREATE_VERSIONING % self.version_table)
        self._insert_script(self.read_scripts()[0], conn)
173671
function(db_schema) {

        // add existing object store
        if (schema instanceof ydn.db.schema.EditableDatabase) {
          var editable = /** @type {ydn.db.schema.EditableDatabase} */ (schema);
          for (var i = 0; i < db_schema.stores.length; i++) {
            if (!editable.hasStore(db_schema.stores[i].getName())) {
              editable.addStore(db_schema.stores[i].clone());
            }
          }
        }

        var diff_msg = schema.difference(db_schema, false, true);
        if (diff_msg.length > 0) {
          goog.log.log(me.logger, goog.log.Level.FINER, 'Schema change require for difference in ' +
              diff_msg);

          var on_completed = function(t, e) {
            if (t == ydn.db.base.TxEventTypes.COMPLETE) {
              setDb(db);
            } else {
              goog.log.error(me.logger, 'Fail to update version on ' + db.name + ':' +
                  db.version);
              setDb(null, e);
            }
          };

          var next_version = goog.isNumber(db.version) ? db.version + 1 : 1;

          if (!ydn.db.base.OLD_INDEXEDDB_SUPPORT || 'IDBOpenDBRequest' in goog.global) {
            db.close();
            var req = ydn.db.base.indexedDb.open(
                dbname, /** @type {number} */ (next_version));
            req.onupgradeneeded = function(ev) {
              var db = ev.target.result;
              goog.log.log(me.logger, goog.log.Level.FINER, 're-open for version ' + db.version);
              updateSchema(db, req['transaction'], false);

            };
            req.onsuccess = function(ev) {
              setDb(ev.target.result);
            };
            req.onerror = function(e) {
              goog.log.log(me.logger, goog.log.Level.FINER, me + ': fail.');
              setDb(null);
            };
          } else if (ydn.db.base.OLD_INDEXEDDB_SUPPORT) {
            var ver_request = db.setVersion(next_version + '');

            ver_request.onfailure = function(e) {
              goog.log.warning(me.logger, 'migrating from ' + db.version + ' to ' +
                  next_version + ' failed.');
              setDb(null, e);
            };


            var trans = ver_request['transaction'];
            ver_request.onsuccess = function(e) {

              ver_request['transaction'].oncomplete = tr_on_complete;

              updateSchema(db, ver_request['transaction'], true);
            };

            var tr_on_complete = function(e) {

              // for old format.
              // by reopening the database, we make sure that we are not in
              // version change state since transaction cannot open during
              // version change state.
              // db.close(); // necessary - cause error ?
              var reOpenRequest = ydn.db.base.indexedDb.open(dbname);
              reOpenRequest.onsuccess = function(rev) {
                var db = rev.target.result;
                goog.log.log(me.logger, goog.log.Level.FINER, me + ': OK.');
                setDb(db);
              };

              reOpenRequest.onerror = function(e) {
                goog.log.log(me.logger, goog.log.Level.FINER, me + ': fail.');
                setDb(null);
              };
            };

            if (goog.isDefAndNotNull(ver_request['transaction'])) {
              ver_request['transaction'].oncomplete = tr_on_complete;
            }

          }

        } else {
          setDb(db);
        }
      }
410539
void insert(boolean readOnly, int generation) throws PersistException {
        if (mAllProperties == null) {
            throw new IllegalStateException();
        }

        mStoredLayout.setGeneration(generation);

        if (readOnly) {
            return;
        }

        try {
            mStoredLayout.insert();
        } catch (UniqueConstraintException e) {
            // If existing record logically matches, update to allow replication.
            StoredLayout existing = mStoredLayout.prepare();
            mStoredLayout.copyPrimaryKeyProperties(existing);
            try {
                existing.load();
            } catch (FetchException e2) {
                throw e2.toPersistException();
            }
            if (existing.getGeneration() != generation ||
                !existing.getStorableTypeName().equals(getStorableTypeName()) ||
                !Arrays.equals(existing.getExtraData(), mStoredLayout.getExtraData()))
            {
                throw e;
            }
            mStoredLayout.setVersionNumber(existing.getVersionNumber());
            mStoredLayout.update();
        }

        for (LayoutProperty property : mAllProperties) {
            property.insert();
        }
    }
143039
def _create_table(self):
        '''
        
        '''
        self._cursor.execute('''
            CREATE TABLE IF NOT EXISTS %(name)s ( %(fields)s )
        ''' % {
            'name': self._name,
            'fields': ','.join('%s %s' % (k, v) for (k, v) in self._fields)
        })
        self._connection.commit()
250476
def set_version(db, name, major_version, minor_version):
    
    version = pack_version(major_version, minor_version)
    db.execute(SET_VERSION_SQL, dict(name=name, version=version))
734822
public static void createSchema(Connection connection, String dialect, boolean createSchemaMigrations) {
    if (createSchemaMigrations) {
      executeScript(connection, "org/sonar/db/version/schema_migrations-" + dialect + ".ddl");
    }
    executeScript(connection, "org/sonar/db/version/schema-" + dialect + ".ddl");
    executeScript(connection, "org/sonar/db/version/rows-" + dialect + ".sql");
  }
539846
@Override
    public boolean setVersion(String version) {
        // Update the version column in the database. This is a little weird looking because we want
        // to avoid modifying the database if the version didn't change, and because the row might
        // not exist yet.
        SQLiteStorageEngine storage = store.getStorageEngine();
        boolean hasView;
        Cursor cursor = null;
        try {
            String sql = "SELECT name, version FROM views WHERE name=?";
            String[] args = {name};
            cursor = storage.rawQuery(sql, args);
            hasView = cursor.moveToNext();
        } catch (SQLException e) {
            Log.e(Log.TAG_VIEW, "Error querying existing view name " + name, e);
            return false;
        } finally {
            if (cursor != null)
                cursor.close();
        }

        if (!hasView) {
            // no such record, so insert
            ContentValues insertValues = new ContentValues();
            insertValues.put("name", name);
            insertValues.put("version", version);
            insertValues.put("total_docs", 0);
            storage.insert("views", null, insertValues);
            createIndex();
            return true; // created new view
        }

        ContentValues updateValues = new ContentValues();
        updateValues.put("version", version);
        updateValues.put("lastSequence", 0);
        updateValues.put("total_docs", 0);
        String[] whereArgs = {name, version};
        int rowsAffected = storage.update("views",
                updateValues,
                "name=? AND version!=?",
                whereArgs);
        return (rowsAffected > 0);
    }
137620
def create_upgrades_table(self):
        """"""

        query = """CREATE TABLE IF NOT EXISTS {}
                (
                id serial NOT NULL,
                version character varying(50),
                description character varying(200) NOT NULL,
                type integer NOT NULL,
                script character varying(1000) NOT NULL,
                checksum character varying(32) NOT NULL,
                installed_by character varying(100) NOT NULL,
                installed_on timestamp without time zone NOT NULL DEFAULT now(),
                execution_time integer NOT NULL,
                success boolean NOT NULL,
                PRIMARY KEY (id)
                )
        """.format(self.upgrades_table)

        self.cursor.execute(query)
        self.connection.commit()
108297
def create(cls, object_version, key, value):
        """"""
        assert len(key) < 256
        assert len(value) < 256
        with db.session.begin_nested():
            obj = cls(version_id=as_object_version_id(object_version),
                      key=key,
                      value=value)
            db.session.add(obj)
        return obj
385862
def create_table(cls):
        
        schema_editor = getattr(connection, 'schema_editor', None)
        if schema_editor:
            with schema_editor() as schema_editor:
                schema_editor.create_model(cls)
        else:
            raw_sql, _ = connection.creation.sql_create_model(
                cls,
                no_style(),
                [])
            cls.delete_table()
            cursor = connection.cursor()
            try:
                cursor.execute(*raw_sql)
            finally:
                cursor.close()
636203
public function createInstallationProgressTable()
    {
        Schema::create('tbl_antares_installation', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->unique();
            $table->text('content')->nullable();
        });
    }
1040828
def create_sql(self, insert=False, version=False, version_fieldname=None,
                   fields=None, ec=None, compare=False):
        
        version_fieldname = version_fieldname or 'version'
        #fix when d is empty, orm will not insert record bug 2013/04/07
        if not self._key or insert:
            d = self._get_data(fields, compare=compare)
            if d:
                return rawsql(self.table.insert().values(**d),
                              ec or self.get_engine_name()) + ';'

        else:
            d = self._get_data(fields, compare=compare)
            _key = d.pop(self._primary_field)
            if d:
                _cond = self.table.c[self._primary_field] == self._key
                if version:
                    version_field = self.table.c.get(version_fieldname)
                    if version_field is None:
                        raise KindError("version_fieldname %s is not existed in Model %s" % (version_fieldname, self.__class__.__name__))
                    _version_value = getattr(self, version_fieldname, 0)
                    # setattr(self, version_fieldname, _version_value+1)
                    d[version_fieldname] = _version_value+1
                    _cond = (version_field == _version_value) & _cond

                return rawsql(self.table.update(_cond).values(**d),
                              ec or self.get_engine_name()) + ';'
        return ''